Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

index.test.ts 29 KB

You have to be logged in to leave a comment. Sign In
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
  1. import fs from 'fs';
  2. import path from 'path';
  3. import { globSync } from 'glob';
  4. import yaml from 'js-yaml';
  5. import { z } from 'zod';
  6. import {
  7. AssertionSchema,
  8. BaseAssertionTypesSchema,
  9. CommandLineOptionsSchema,
  10. isGradingResult,
  11. TestCaseSchema,
  12. TestSuiteConfigSchema,
  13. TestSuiteSchema,
  14. UnifiedConfigSchema,
  15. VarsSchema,
  16. } from '../../src/types';
  17. import type { TestSuite } from '../../src/types';
  18. describe('AssertionSchema', () => {
  19. it('should validate a basic assertion', () => {
  20. const basicAssertion = {
  21. type: 'equals',
  22. value: 'expected value',
  23. };
  24. const result = AssertionSchema.safeParse(basicAssertion);
  25. expect(result.success).toBe(true);
  26. });
  27. it('should validate an assertion with all optional fields', () => {
  28. const fullAssertion = {
  29. type: 'similar',
  30. value: 'expected value',
  31. threshold: 0.8,
  32. weight: 2,
  33. provider: 'openai:gpt-4o-mini',
  34. rubricPrompt: 'Custom rubric prompt',
  35. metric: 'similarity_score',
  36. transform: 'toLowerCase()',
  37. };
  38. const result = AssertionSchema.safeParse(fullAssertion);
  39. expect(result.success).toBe(true);
  40. });
  41. it('should validate all base assertion types', () => {
  42. const baseTypes = BaseAssertionTypesSchema.options;
  43. baseTypes.forEach((type) => {
  44. const assertion = {
  45. type,
  46. value: 'test value',
  47. };
  48. const result = AssertionSchema.safeParse(assertion);
  49. expect(result.success).toBe(true);
  50. });
  51. });
  52. it('should validate "not-" prefixed assertion types', () => {
  53. const notPrefixedAssertion = {
  54. type: 'not-contains',
  55. value: 'unwanted value',
  56. };
  57. const result = AssertionSchema.safeParse(notPrefixedAssertion);
  58. expect(result.success).toBe(true);
  59. });
  60. it('should validate assertions with function values', () => {
  61. const functionAssertion = {
  62. type: 'equals',
  63. value: (output: string) => output === 'expected value',
  64. };
  65. const result = AssertionSchema.safeParse(functionAssertion);
  66. expect(result.success).toBe(true);
  67. });
  68. it('should validate assertions with array values', () => {
  69. const arrayAssertion = {
  70. type: 'contains-all',
  71. value: ['value1', 'value2', 'value3'],
  72. };
  73. const result = AssertionSchema.safeParse(arrayAssertion);
  74. expect(result.success).toBe(true);
  75. });
  76. });
  77. describe('VarsSchema', () => {
  78. it('should validate and transform various types of values', () => {
  79. expect.assertions(9);
  80. const testCases = [
  81. { input: { key: 'string value' }, expected: { key: 'string value' } },
  82. { input: { key: 42 }, expected: { key: 42 } },
  83. { input: { key: true }, expected: { key: true } },
  84. { input: { key: false }, expected: { key: false } },
  85. { input: { key: ['a', 'b', 'c'] }, expected: { key: ['a', 'b', 'c'] } },
  86. { input: { key: [1, 2, 3] }, expected: { key: [1, 2, 3] } },
  87. { input: { key: [true, false] }, expected: { key: [true, false] } },
  88. { input: { key: [{ nested: 'object' }] }, expected: { key: [{ nested: 'object' }] } },
  89. {
  90. input: { key: { arbitrary: 'value', nested: { object: true } } },
  91. expected: { key: { arbitrary: 'value', nested: { object: true } } },
  92. },
  93. ];
  94. testCases.forEach(({ input, expected }) => {
  95. expect(VarsSchema.safeParse(input)).toEqual({ success: true, data: expected });
  96. });
  97. });
  98. it('should throw an error for invalid types', () => {
  99. expect.assertions(4);
  100. const invalidCases = [
  101. { key: null },
  102. { key: undefined },
  103. { key: Symbol('test') },
  104. { key: () => {} },
  105. ];
  106. invalidCases.forEach((invalidInput) => {
  107. expect(() => VarsSchema.parse(invalidInput)).toThrow(z.ZodError);
  108. });
  109. });
  110. });
  111. describe('isGradingResult', () => {
  112. it('should return true for valid grading result object', () => {
  113. const validResult = {
  114. pass: true,
  115. score: 0.8,
  116. reason: 'Test passed',
  117. };
  118. expect(isGradingResult(validResult)).toBe(true);
  119. });
  120. it('should return true for grading result with optional fields', () => {
  121. const resultWithOptional = {
  122. pass: false,
  123. score: 0.2,
  124. reason: 'Test failed',
  125. namedScores: { accuracy: 0.5 },
  126. tokensUsed: { total: 100 },
  127. componentResults: [],
  128. assertion: { type: 'equals', value: 'expected' },
  129. comment: 'Needs improvement',
  130. };
  131. expect(isGradingResult(resultWithOptional)).toBe(true);
  132. });
  133. it('should correctly identify valid GradingResult objects', () => {
  134. const validResults = [
  135. { pass: true, score: 1, reason: 'Perfect' },
  136. { pass: false, score: 0, reason: 'Failed', namedScores: { accuracy: 0 } },
  137. { pass: true, score: 0.5, reason: 'Partial', tokensUsed: { total: 100 } },
  138. { pass: true, score: 1, reason: 'Good', componentResults: [] },
  139. { pass: false, score: 0, reason: 'Bad', assertion: null },
  140. { pass: true, score: 1, reason: 'Excellent', comment: 'Great job!' },
  141. ];
  142. validResults.forEach((result) => {
  143. expect(isGradingResult(result)).toBe(true);
  144. });
  145. });
  146. it('should return false for null', () => {
  147. expect(isGradingResult(null)).toBe(false);
  148. });
  149. it('should return false for non-object', () => {
  150. expect(isGradingResult('not an object')).toBe(false);
  151. expect(isGradingResult(123)).toBe(false);
  152. expect(isGradingResult(undefined)).toBe(false);
  153. });
  154. it('should return false if missing required fields', () => {
  155. expect(isGradingResult({ score: 1, reason: 'test' })).toBe(false);
  156. expect(isGradingResult({ pass: true, reason: 'test' })).toBe(false);
  157. expect(isGradingResult({ pass: true, score: 1 })).toBe(false);
  158. });
  159. it('should correctly identify invalid GradingResult objects', () => {
  160. const invalidResults = [
  161. {},
  162. { pass: 'true', score: 1, reason: 'Invalid pass type' },
  163. { pass: true, score: '1', reason: 'Invalid score type' },
  164. { pass: true, score: 1, reason: 42 },
  165. { pass: true, score: 1, reason: 'Valid', namedScores: 'invalid' },
  166. { pass: true, score: 1, reason: 'Valid', tokensUsed: 'invalid' },
  167. { pass: true, score: 1, reason: 'Valid', componentResults: 'invalid' },
  168. { pass: true, score: 1, reason: 'Valid', assertion: 'invalid' },
  169. { pass: true, score: 1, reason: 'Valid', comment: 42 },
  170. ];
  171. invalidResults.forEach((result) => {
  172. expect(isGradingResult(result)).toBe(false);
  173. });
  174. });
  175. it('should return false if fields have wrong types', () => {
  176. expect(
  177. isGradingResult({
  178. pass: 'true',
  179. score: '0.8',
  180. reason: 123,
  181. }),
  182. ).toBe(false);
  183. });
  184. it('should return false if optional fields have wrong types', () => {
  185. expect(
  186. isGradingResult({
  187. pass: true,
  188. score: 0.8,
  189. reason: 'test',
  190. namedScores: 'invalid',
  191. tokensUsed: 'invalid',
  192. componentResults: 'invalid',
  193. assertion: 'invalid',
  194. comment: 123,
  195. }),
  196. ).toBe(false);
  197. });
  198. });
  199. describe('TestCaseSchema assertScoringFunction', () => {
  200. it('should validate test case with valid file-based scoring function', () => {
  201. const testCase = {
  202. description: 'Test with file scoring',
  203. assertScoringFunction: 'file://path/to/score.js:scoreFunc',
  204. vars: { input: 'test' },
  205. };
  206. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  207. });
  208. it('should validate test case with valid custom scoring function', () => {
  209. const testCase = {
  210. description: 'Test with custom scoring',
  211. assertScoringFunction: async (scores: Record<string, number>) => {
  212. return {
  213. pass: scores.accuracy > 0.8,
  214. score: scores.accuracy,
  215. reason: 'Custom scoring applied',
  216. };
  217. },
  218. vars: { input: 'test' },
  219. };
  220. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  221. });
  222. it('should validate test case with missing assertScoringFunction', () => {
  223. const testCase = {
  224. description: 'No scoring function',
  225. vars: { input: 'test' },
  226. };
  227. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  228. });
  229. it('should validate test case with python file scoring function', () => {
  230. const testCase = {
  231. description: 'Python scoring function',
  232. assertScoringFunction: 'file://path/to/score.py:score_func',
  233. vars: { input: 'test' },
  234. };
  235. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  236. });
  237. it('should validate test case with typescript file scoring function', () => {
  238. const testCase = {
  239. description: 'TypeScript scoring function',
  240. assertScoringFunction: 'file://path/to/score.ts:scoreFunc',
  241. vars: { input: 'test' },
  242. };
  243. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  244. });
  245. it('should validate test case with file path containing dots', () => {
  246. const testCase = {
  247. description: 'File path with dots',
  248. assertScoringFunction: 'file://path/to/my.score.js:myNamespace.scoreFunc',
  249. vars: { input: 'test' },
  250. };
  251. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  252. });
  253. it('should validate test case with absolute file path', () => {
  254. const testCase = {
  255. description: 'Absolute file path',
  256. assertScoringFunction: 'file:///absolute/path/to/score.js:scoreFunc',
  257. vars: { input: 'test' },
  258. };
  259. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  260. });
  261. it('should validate test case with relative file path', () => {
  262. const testCase = {
  263. description: 'Relative file path',
  264. assertScoringFunction: 'file://./relative/path/score.js:scoreFunc',
  265. vars: { input: 'test' },
  266. };
  267. expect(() => TestCaseSchema.parse(testCase)).not.toThrow('Invalid test case schema');
  268. });
  269. });
  270. describe('CommandLineOptionsSchema', () => {
  271. it('should validate options with filterErrorsOnly string', () => {
  272. const options = {
  273. providers: ['provider1'],
  274. output: ['output1'],
  275. filterErrorsOnly: 'true',
  276. };
  277. expect(() => CommandLineOptionsSchema.parse(options)).not.toThrow(
  278. 'Invalid command line options',
  279. );
  280. });
  281. it('should validate options without filterErrorsOnly', () => {
  282. const options = {
  283. providers: ['provider1'],
  284. output: ['output1'],
  285. };
  286. expect(() => CommandLineOptionsSchema.parse(options)).not.toThrow(
  287. 'Invalid command line options',
  288. );
  289. });
  290. it('should validate options with empty filterErrorsOnly string', () => {
  291. const options = {
  292. providers: ['provider1'],
  293. output: ['output1'],
  294. filterErrorsOnly: '',
  295. };
  296. expect(() => CommandLineOptionsSchema.parse(options)).not.toThrow(
  297. 'Invalid command line options',
  298. );
  299. });
  300. it('should validate options with non-boolean filterErrorsOnly string', () => {
  301. const options = {
  302. providers: ['provider1'],
  303. output: ['output1'],
  304. filterErrorsOnly: 'errors-only',
  305. };
  306. expect(() => CommandLineOptionsSchema.parse(options)).not.toThrow(
  307. 'Invalid command line options',
  308. );
  309. });
  310. it('should reject options with non-string filterErrorsOnly', () => {
  311. const options = {
  312. providers: ['provider1'],
  313. output: ['output1'],
  314. filterErrorsOnly: true,
  315. };
  316. expect(() => CommandLineOptionsSchema.parse(options)).toThrow(
  317. 'Expected string, received boolean',
  318. );
  319. });
  320. it('should validate options with filterErrorsOnly and other filter options', () => {
  321. const options = {
  322. providers: ['provider1'],
  323. output: ['output1'],
  324. filterErrorsOnly: 'true',
  325. filterFailing: 'true',
  326. filterFirstN: 5,
  327. filterMetadata: 'meta',
  328. };
  329. expect(() => CommandLineOptionsSchema.parse(options)).not.toThrow(
  330. 'Invalid command line options',
  331. );
  332. });
  333. it('should validate options with filterErrorsOnly and minimal required fields', () => {
  334. const options = {
  335. providers: ['provider1'],
  336. output: ['output1'],
  337. filterErrorsOnly: 'true',
  338. };
  339. expect(() => CommandLineOptionsSchema.parse(options)).not.toThrow(
  340. 'Invalid command line options',
  341. );
  342. });
  343. it('should validate options with all possible filter combinations', () => {
  344. const options = {
  345. providers: ['provider1'],
  346. output: ['output1'],
  347. filterErrorsOnly: 'true',
  348. filterFailing: 'true',
  349. filterFirstN: 10,
  350. filterMetadata: 'metadata',
  351. filterPattern: 'pattern',
  352. filterProviders: 'provider1',
  353. filterSample: 5,
  354. filterTargets: 'target1',
  355. };
  356. expect(() => CommandLineOptionsSchema.parse(options)).not.toThrow(
  357. 'Invalid command line options',
  358. );
  359. });
  360. });
  361. describe('TestSuiteConfigSchema', () => {
  362. const rootDir = path.join(__dirname, '../..');
  363. const configFiles = globSync(`${rootDir}/examples/**/promptfooconfig.{yaml,yml,json}`, {
  364. windowsPathsNoEscape: true,
  365. });
  366. it('should find configuration files', () => {
  367. expect(configFiles.length).toBeGreaterThan(0);
  368. });
  369. describe('env property', () => {
  370. it('should validate config with string env values', () => {
  371. const config = {
  372. providers: ['provider1'],
  373. prompts: ['prompt1'],
  374. env: {
  375. API_KEY: 'abc123',
  376. DEBUG: 'true',
  377. },
  378. };
  379. expect(() => TestSuiteConfigSchema.parse(config)).not.toThrow();
  380. });
  381. it('should validate config with number env values converted to strings', () => {
  382. const config = {
  383. providers: ['provider1'],
  384. prompts: ['prompt1'],
  385. env: {
  386. PORT: 3000,
  387. TIMEOUT: 5000,
  388. },
  389. };
  390. expect(() => TestSuiteConfigSchema.parse(config)).not.toThrow();
  391. });
  392. it('should validate config with boolean env values converted to strings', () => {
  393. const config = {
  394. providers: ['provider1'],
  395. prompts: ['prompt1'],
  396. env: {
  397. DEBUG: true,
  398. VERBOSE: false,
  399. },
  400. };
  401. expect(() => TestSuiteConfigSchema.parse(config)).not.toThrow();
  402. });
  403. it('should validate config with undefined env property', () => {
  404. const config = {
  405. providers: ['provider1'],
  406. prompts: ['prompt1'],
  407. };
  408. expect(() => TestSuiteConfigSchema.parse(config)).not.toThrow();
  409. });
  410. it('should validate env field with primitive values that get transformed to strings', () => {
  411. const customEnvVars = {
  412. CUSTOM_STRING_VALUE: 'string-value',
  413. CUSTOM_NUMBER_VALUE: 42,
  414. CUSTOM_BOOLEAN_TRUE: true,
  415. CUSTOM_BOOLEAN_FALSE: false,
  416. };
  417. const recordSchema = z.record(
  418. z.string(),
  419. z.union([z.string(), z.number(), z.boolean()]).transform(String),
  420. );
  421. const recordResult = recordSchema.safeParse(customEnvVars);
  422. expect(recordResult.success).toBe(true);
  423. const parsedData = recordResult.success ? recordResult.data : {};
  424. expect(parsedData.CUSTOM_STRING_VALUE).toBe('string-value');
  425. expect(parsedData.CUSTOM_NUMBER_VALUE).toBe('42');
  426. expect(parsedData.CUSTOM_BOOLEAN_TRUE).toBe('true');
  427. expect(parsedData.CUSTOM_BOOLEAN_FALSE).toBe('false');
  428. const config = {
  429. providers: [{ id: 'test-provider' }],
  430. prompts: ['test prompt'],
  431. env: customEnvVars,
  432. };
  433. const result = TestSuiteConfigSchema.safeParse(config);
  434. expect(result.success).toBe(true);
  435. const testProvider = result.success
  436. ? {
  437. id: 'test-provider',
  438. config: { someConfig: true },
  439. env: result.data.env,
  440. }
  441. : { id: 'test-provider', config: { someConfig: true } };
  442. expect(Object.keys(testProvider)).toContain('env');
  443. });
  444. });
  445. describe('extensions field', () => {
  446. const minimalConfig = {
  447. providers: ['provider1'],
  448. prompts: ['prompt1'],
  449. };
  450. it('should accept null extensions', () => {
  451. const config = {
  452. ...minimalConfig,
  453. extensions: null,
  454. };
  455. const result = TestSuiteConfigSchema.safeParse(config);
  456. expect(result.success).toBe(true);
  457. });
  458. it('should accept undefined extensions (optional field)', () => {
  459. const config = { ...minimalConfig };
  460. // Explicitly not setting extensions
  461. const result = TestSuiteConfigSchema.safeParse(config);
  462. expect(result.success).toBe(true);
  463. });
  464. it('should accept empty array extensions', () => {
  465. const config = {
  466. ...minimalConfig,
  467. extensions: [],
  468. };
  469. const result = TestSuiteConfigSchema.safeParse(config);
  470. expect(result.success).toBe(true);
  471. });
  472. it('should accept array of extension strings', () => {
  473. const config = {
  474. ...minimalConfig,
  475. extensions: ['file://path/to/extension.js:functionName'],
  476. };
  477. const result = TestSuiteConfigSchema.safeParse(config);
  478. expect(result.success).toBe(true);
  479. });
  480. it('should transform and remove null, undefined, and empty array extensions', () => {
  481. // We need to use UnifiedConfigSchema for transformation tests
  482. // since the transform is applied there
  483. const configs = [
  484. { ...minimalConfig, extensions: null },
  485. { ...minimalConfig }, // undefined extensions
  486. { ...minimalConfig, extensions: [] },
  487. ];
  488. configs.forEach((config) => {
  489. const result = UnifiedConfigSchema.safeParse(config);
  490. expect(result.success).toBe(true);
  491. // Only access data properties if we're sure parsing succeeded
  492. expect(result).toEqual(
  493. expect.objectContaining({
  494. success: true,
  495. data: expect.not.objectContaining({ extensions: expect.anything() }),
  496. }),
  497. );
  498. });
  499. });
  500. it('should keep non-empty extensions arrays', () => {
  501. const config = {
  502. ...minimalConfig,
  503. extensions: ['file://path/to/extension.js:functionName'],
  504. };
  505. const result = UnifiedConfigSchema.safeParse(config);
  506. expect(result.success).toBe(true);
  507. // Only access data properties if we're sure parsing succeeded
  508. expect(result).toEqual(
  509. expect.objectContaining({
  510. success: true,
  511. data: expect.objectContaining({
  512. extensions: ['file://path/to/extension.js:functionName'],
  513. }),
  514. }),
  515. );
  516. });
  517. });
  518. describe('defaultTest validation', () => {
  519. it('should accept string defaultTest starting with file://', () => {
  520. const validConfig = {
  521. providers: ['openai:gpt-4'],
  522. prompts: ['Test prompt'],
  523. tests: [{ vars: { test: 'value' } }],
  524. defaultTest: 'file://path/to/defaultTest.yaml',
  525. };
  526. const result = TestSuiteConfigSchema.safeParse(validConfig);
  527. expect(result.success).toBe(true);
  528. expect(result.data!.defaultTest).toBe('file://path/to/defaultTest.yaml');
  529. });
  530. it('should reject string defaultTest not starting with file://', () => {
  531. const invalidConfig = {
  532. providers: ['openai:gpt-4'],
  533. prompts: ['Test prompt'],
  534. tests: [{ vars: { test: 'value' } }],
  535. defaultTest: 'invalid/path.yaml',
  536. };
  537. const result = TestSuiteConfigSchema.safeParse(invalidConfig);
  538. expect(result.success).toBe(false);
  539. });
  540. it('should accept partial TestCase object for defaultTest', () => {
  541. const validConfig = {
  542. providers: ['openai:gpt-4'],
  543. prompts: ['Test prompt'],
  544. tests: [{ vars: { test: 'value' } }],
  545. defaultTest: {
  546. assert: [{ type: 'contains', value: 'test' }],
  547. vars: { default: true },
  548. threshold: 0.8,
  549. },
  550. };
  551. const result = TestSuiteConfigSchema.safeParse(validConfig);
  552. expect(result.success).toBe(true);
  553. expect(result.data!.defaultTest).toEqual({
  554. assert: [{ type: 'contains', value: 'test' }],
  555. vars: { default: true },
  556. threshold: 0.8,
  557. });
  558. });
  559. it('should accept defaultTest with description field (it will be stripped)', () => {
  560. const configWithDescription = {
  561. providers: ['openai:gpt-4'],
  562. prompts: ['Test prompt'],
  563. tests: [{ vars: { test: 'value' } }],
  564. defaultTest: {
  565. description: 'This will be stripped by omit()',
  566. assert: [{ type: 'equals', value: 'test' }],
  567. },
  568. };
  569. const result = TestSuiteConfigSchema.safeParse(configWithDescription);
  570. expect(result.success).toBe(true);
  571. // The description field should be stripped from the parsed result
  572. expect(result.data!.defaultTest).toEqual({
  573. assert: [{ type: 'equals', value: 'test' }],
  574. });
  575. expect((result.data!.defaultTest as any).description).toBeUndefined();
  576. });
  577. });
  578. for (const file of configFiles) {
  579. it(`should validate ${path.relative(rootDir, file)}`, async () => {
  580. const configContent = fs.readFileSync(file, 'utf8');
  581. const config = yaml.load(configContent) as Record<string, unknown>;
  582. const extendedSchema = TestSuiteConfigSchema.extend({
  583. targets: z.union([TestSuiteConfigSchema.shape.providers, z.undefined()]),
  584. providers: z.union([TestSuiteConfigSchema.shape.providers, z.undefined()]),
  585. ...(typeof config.redteam !== 'undefined' && {
  586. prompts: z.optional(TestSuiteConfigSchema.shape.prompts),
  587. }),
  588. }).refine(
  589. (data) => {
  590. const hasTargets = Boolean(data.targets);
  591. const hasProviders = Boolean(data.providers);
  592. return (hasTargets && !hasProviders) || (!hasTargets && hasProviders);
  593. },
  594. {
  595. message: "Exactly one of 'targets' or 'providers' must be provided, but not both",
  596. },
  597. );
  598. const result = extendedSchema.safeParse(config);
  599. if (!result.success) {
  600. console.error(`Validation failed for ${file}:`, result.error);
  601. }
  602. expect(result.success).toBe(true);
  603. });
  604. }
  605. });
  606. describe('UnifiedConfigSchema extensions handling', () => {
  607. it('should remove null extensions', () => {
  608. const config = {
  609. providers: ['provider1'],
  610. prompts: ['prompt1'],
  611. extensions: null,
  612. };
  613. const parsed = UnifiedConfigSchema.parse(config);
  614. expect(parsed.extensions).toBeUndefined();
  615. });
  616. it('should remove undefined extensions', () => {
  617. const config = {
  618. providers: ['provider1'],
  619. prompts: ['prompt1'],
  620. extensions: undefined,
  621. };
  622. const parsed = UnifiedConfigSchema.parse(config);
  623. expect(parsed.extensions).toBeUndefined();
  624. });
  625. it('should remove empty array extensions', () => {
  626. const config = {
  627. providers: ['provider1'],
  628. prompts: ['prompt1'],
  629. extensions: [],
  630. };
  631. const parsed = UnifiedConfigSchema.parse(config);
  632. expect(parsed.extensions).toBeUndefined();
  633. });
  634. it('should preserve valid extensions array', () => {
  635. const config = {
  636. providers: ['provider1'],
  637. prompts: ['prompt1'],
  638. extensions: ['ext1', 'ext2'],
  639. };
  640. const parsed = UnifiedConfigSchema.parse(config);
  641. expect(parsed.extensions).toEqual(['ext1', 'ext2']);
  642. });
  643. it('should transform targets to providers when only targets is present', () => {
  644. const config = {
  645. targets: ['target1', 'target2'],
  646. prompts: ['prompt1'],
  647. };
  648. const parsed = UnifiedConfigSchema.parse(config);
  649. expect(parsed.providers).toEqual(['target1', 'target2']);
  650. expect(parsed.targets).toBeUndefined();
  651. });
  652. it('should throw an error when both targets and providers are present', () => {
  653. const config = {
  654. providers: ['provider1', 'provider2'],
  655. targets: ['target1', 'target2'],
  656. prompts: ['prompt1'],
  657. };
  658. expect(() => UnifiedConfigSchema.parse(config)).toThrow(
  659. "Exactly one of 'targets' or 'providers' must be provided, but not both",
  660. );
  661. });
  662. });
  663. describe('TestSuiteSchema', () => {
  664. const baseTestSuite: TestSuite = {
  665. providers: [
  666. {
  667. id: () => 'mock-provider',
  668. callApi: () => Promise.resolve({}),
  669. },
  670. ],
  671. prompts: [{ raw: 'Hello, world!', label: 'mock-prompt' }],
  672. };
  673. describe('extensions field', () => {
  674. it('should allow null extensions', () => {
  675. const suite = {
  676. providers: [{ id: () => 'provider1' }],
  677. prompts: [{ raw: 'prompt1', label: 'test' }],
  678. extensions: null,
  679. };
  680. expect(() => TestSuiteSchema.parse(suite)).not.toThrow();
  681. });
  682. it('should allow undefined extensions', () => {
  683. const suite = {
  684. providers: [{ id: () => 'provider1' }],
  685. prompts: [{ raw: 'prompt1', label: 'test' }],
  686. };
  687. expect(() => TestSuiteSchema.parse(suite)).not.toThrow();
  688. });
  689. it('should accept valid Python extension paths', () => {
  690. const validExtensions = [
  691. 'file://path/to/file.py:function_name',
  692. 'file://./relative/path.py:function_name',
  693. 'file:///absolute/path.py:function_name',
  694. ];
  695. validExtensions.forEach((extension) => {
  696. const result = TestSuiteSchema.safeParse({ ...baseTestSuite, extensions: [extension] });
  697. expect(result.success).toBe(true);
  698. });
  699. });
  700. it('should accept valid JavaScript extension paths', () => {
  701. const validExtensions = [
  702. 'file://path/to/file.js:function_name',
  703. 'file://./relative/path.ts:function_name',
  704. 'file:///absolute/path.mjs:function_name',
  705. 'file://path/to/file.cjs:function_name',
  706. ];
  707. validExtensions.forEach((extension) => {
  708. const result = TestSuiteSchema.safeParse({ ...baseTestSuite, extensions: [extension] });
  709. expect(result.success).toBe(true);
  710. });
  711. });
  712. it.each([
  713. ['path/to/file.py:function_name', 'Missing file:// prefix'],
  714. ['file://path/to/file.txt:function_name', 'Invalid file extension'],
  715. ['file://path/to/file.py', 'Missing function name'],
  716. ['file://path/to/file.py:', 'Empty function name'],
  717. ['file://:function_name', 'Missing file path'],
  718. ['file://path/to/file.py:function_name:extra_arg', 'Extra argument'],
  719. ])('should reject invalid extension path: %s (%s)', (extension, reason) => {
  720. const result = TestSuiteSchema.safeParse({ ...baseTestSuite, extensions: [extension] });
  721. expect(result.success).toBe(false);
  722. expect(result.error?.issues[0].message).toMatch(/Extension must/);
  723. });
  724. it('should allow an empty array of extensions', () => {
  725. const result = TestSuiteSchema.safeParse({ ...baseTestSuite, extensions: [] });
  726. expect(result.success).toBe(true);
  727. });
  728. });
  729. describe('defaultTest validation', () => {
  730. it('should accept string defaultTest starting with file://', () => {
  731. const validConfig = {
  732. providers: [
  733. {
  734. id: () => 'openai:gpt-4',
  735. callApi: async () => ({ output: 'test' }),
  736. },
  737. ],
  738. prompts: [{ raw: 'Test prompt', label: 'test' }],
  739. tests: [{ vars: { test: 'value' } }],
  740. defaultTest: 'file://path/to/defaultTest.yaml',
  741. };
  742. const result = TestSuiteSchema.safeParse(validConfig);
  743. expect(result.success).toBe(true);
  744. expect(result.data!.defaultTest).toBe('file://path/to/defaultTest.yaml');
  745. });
  746. it('should reject string defaultTest not starting with file://', () => {
  747. const invalidConfig = {
  748. providers: [
  749. {
  750. id: () => 'openai:gpt-4',
  751. callApi: async () => ({ output: 'test' }),
  752. },
  753. ],
  754. prompts: [{ raw: 'Test prompt', label: 'test' }],
  755. tests: [{ vars: { test: 'value' } }],
  756. defaultTest: 'invalid/path.yaml',
  757. };
  758. const result = TestSuiteSchema.safeParse(invalidConfig);
  759. expect(result.success).toBe(false);
  760. expect(result.error!.errors[0].message).toContain(
  761. 'defaultTest string must start with file://',
  762. );
  763. });
  764. it('should accept object defaultTest', () => {
  765. const validConfig = {
  766. providers: [
  767. {
  768. id: () => 'openai:gpt-4',
  769. callApi: async () => ({ output: 'test' }),
  770. },
  771. ],
  772. prompts: [{ raw: 'Test prompt', label: 'test' }],
  773. tests: [{ vars: { test: 'value' } }],
  774. defaultTest: {
  775. assert: [{ type: 'equals', value: 'test' }],
  776. vars: { foo: 'bar' },
  777. options: { provider: 'openai:gpt-4' },
  778. },
  779. };
  780. const result = TestSuiteSchema.safeParse(validConfig);
  781. expect(result.success).toBe(true);
  782. expect(result.data!.defaultTest).toEqual(
  783. expect.objectContaining({
  784. assert: [{ type: 'equals', value: 'test' }],
  785. vars: { foo: 'bar' },
  786. }),
  787. );
  788. });
  789. it('should accept undefined defaultTest', () => {
  790. const validConfig = {
  791. providers: [
  792. {
  793. id: () => 'openai:gpt-4',
  794. callApi: async () => ({ output: 'test' }),
  795. },
  796. ],
  797. prompts: [{ raw: 'Test prompt', label: 'test' }],
  798. tests: [{ vars: { test: 'value' } }],
  799. };
  800. const result = TestSuiteSchema.safeParse(validConfig);
  801. expect(result.success).toBe(true);
  802. expect(result.data!.defaultTest).toBeUndefined();
  803. });
  804. });
  805. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...