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

testCases.test.ts 24 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
  1. import dedent from 'dedent';
  2. import * as fs from 'fs';
  3. import { globSync } from 'glob';
  4. import yaml from 'js-yaml';
  5. import { testCaseFromCsvRow } from '../src/csv';
  6. import { getEnvString } from '../src/envars';
  7. import { fetchCsvFromGoogleSheet } from '../src/googleSheets';
  8. import logger from '../src/logger';
  9. import { loadApiProvider } from '../src/providers';
  10. import {
  11. generatePersonasPrompt,
  12. readStandaloneTestsFile,
  13. readTest,
  14. readTests,
  15. readVarsFiles,
  16. synthesize,
  17. testCasesPrompt,
  18. } from '../src/testCases';
  19. import type { AssertionType, TestCase, TestCaseWithVarsFile } from '../src/types';
  20. jest.mock('proxy-agent', () => ({
  21. ProxyAgent: jest.fn().mockImplementation(() => ({})),
  22. }));
  23. jest.mock('glob', () => ({
  24. globSync: jest.fn(),
  25. }));
  26. jest.mock('../src/providers', () => ({
  27. loadApiProvider: jest.fn(),
  28. }));
  29. jest.mock('../src/fetch');
  30. jest.mock('fs', () => ({
  31. readFileSync: jest.fn(),
  32. writeFileSync: jest.fn(),
  33. statSync: jest.fn(),
  34. readdirSync: jest.fn(),
  35. existsSync: jest.fn(),
  36. mkdirSync: jest.fn(),
  37. promises: {
  38. readFile: jest.fn(),
  39. },
  40. }));
  41. jest.mock('../src/database', () => ({
  42. getDb: jest.fn(),
  43. }));
  44. jest.mock('../src/googleSheets', () => ({
  45. fetchCsvFromGoogleSheet: jest.fn(),
  46. }));
  47. jest.mock('../src/logger');
  48. jest.mock('../src/envars', () => ({
  49. ...jest.requireActual('../src/envars'),
  50. getEnvBool: jest.fn(),
  51. getEnvString: jest.fn().mockImplementation((key, defaultValue) => defaultValue),
  52. }));
  53. describe('readStandaloneTestsFile', () => {
  54. beforeEach(() => {
  55. jest.clearAllMocks();
  56. });
  57. it('should read CSV file and return test cases', async () => {
  58. jest
  59. .mocked(fs.readFileSync)
  60. .mockReturnValue('var1,var2,__expected\nvalue1,value2,expected1\nvalue3,value4,expected2');
  61. const result = await readStandaloneTestsFile('test.csv');
  62. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.csv'), 'utf-8');
  63. expect(result).toEqual([
  64. {
  65. assert: [{ metric: undefined, type: 'equals', value: 'expected1' }],
  66. description: 'Row #1',
  67. options: {},
  68. vars: { var1: 'value1', var2: 'value2' },
  69. },
  70. {
  71. assert: [{ metric: undefined, type: 'equals', value: 'expected2' }],
  72. description: 'Row #2',
  73. options: {},
  74. vars: { var1: 'value3', var2: 'value4' },
  75. },
  76. ]);
  77. });
  78. it('should read CSV file with BOM (Byte Order Mark) and return test cases', async () => {
  79. jest
  80. .mocked(fs.readFileSync)
  81. .mockReturnValue(
  82. '\uFEFFvar1,var2,__expected\nvalue1,value2,expected1\nvalue3,value4,expected2',
  83. );
  84. const result = await readStandaloneTestsFile('test.csv');
  85. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.csv'), 'utf-8');
  86. expect(result).toEqual([
  87. {
  88. assert: [{ metric: undefined, type: 'equals', value: 'expected1' }],
  89. description: 'Row #1',
  90. options: {},
  91. vars: { var1: 'value1', var2: 'value2' },
  92. },
  93. {
  94. assert: [{ metric: undefined, type: 'equals', value: 'expected2' }],
  95. description: 'Row #2',
  96. options: {},
  97. vars: { var1: 'value3', var2: 'value4' },
  98. },
  99. ]);
  100. });
  101. it('should read JSON file and return test cases', async () => {
  102. jest.mocked(fs.readFileSync).mockReturnValue(
  103. JSON.stringify([
  104. { var1: 'value1', var2: 'value2' },
  105. { var1: 'value3', var2: 'value4' },
  106. ]),
  107. );
  108. const result = await readStandaloneTestsFile('test.json');
  109. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.json'), 'utf-8');
  110. expect(result).toEqual([
  111. { assert: [], description: 'Row #1', options: {}, vars: { var1: 'value1', var2: 'value2' } },
  112. { assert: [], description: 'Row #2', options: {}, vars: { var1: 'value3', var2: 'value4' } },
  113. ]);
  114. });
  115. it('should read YAML file and return test cases', async () => {
  116. jest.mocked(fs.readFileSync).mockReturnValue(dedent`
  117. - var1: value1
  118. var2: value2
  119. - var1: value3
  120. var2: value4
  121. `);
  122. const result = await readStandaloneTestsFile('test.yaml');
  123. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.yaml'), 'utf-8');
  124. expect(result).toEqual([
  125. { assert: [], description: 'Row #1', options: {}, vars: { var1: 'value1', var2: 'value2' } },
  126. { assert: [], description: 'Row #2', options: {}, vars: { var1: 'value3', var2: 'value4' } },
  127. ]);
  128. });
  129. it('should read Google Sheets and return test cases', async () => {
  130. const mockFetchCsvFromGoogleSheet = jest.mocked(fetchCsvFromGoogleSheet);
  131. mockFetchCsvFromGoogleSheet.mockResolvedValue([
  132. { var1: 'value1', var2: 'value2', __expected: 'expected1' },
  133. { var1: 'value3', var2: 'value4', __expected: 'expected2' },
  134. ]);
  135. const result = await readStandaloneTestsFile('https://docs.google.com/spreadsheets/d/example');
  136. expect(mockFetchCsvFromGoogleSheet).toHaveBeenCalledWith(
  137. 'https://docs.google.com/spreadsheets/d/example',
  138. );
  139. expect(result).toEqual([
  140. {
  141. assert: [{ metric: undefined, type: 'equals', value: 'expected1' }],
  142. description: 'Row #1',
  143. options: {},
  144. vars: { var1: 'value1', var2: 'value2' },
  145. },
  146. {
  147. assert: [{ metric: undefined, type: 'equals', value: 'expected2' }],
  148. description: 'Row #2',
  149. options: {},
  150. vars: { var1: 'value3', var2: 'value4' },
  151. },
  152. ]);
  153. });
  154. it('should handle file:// prefix in file path', async () => {
  155. jest.mocked(fs.readFileSync).mockReturnValue('var1,var2\nvalue1,value2');
  156. await readStandaloneTestsFile('file://test.csv');
  157. expect(fs.readFileSync).toHaveBeenCalledWith(expect.not.stringContaining('file://'), 'utf-8');
  158. });
  159. it('should return an empty array for unsupported file types', async () => {
  160. await expect(readStandaloneTestsFile('test.txt')).resolves.toEqual([]);
  161. });
  162. it('should read CSV file with default delimiter', async () => {
  163. jest.mocked(getEnvString).mockReturnValue(',');
  164. jest
  165. .mocked(fs.readFileSync)
  166. .mockReturnValue('var1,var2,__expected\nvalue1,value2,expected1\nvalue3,value4,expected2');
  167. const result = await readStandaloneTestsFile('test.csv');
  168. expect(getEnvString).toHaveBeenCalledWith('PROMPTFOO_CSV_DELIMITER', ',');
  169. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.csv'), 'utf-8');
  170. expect(result).toEqual([
  171. {
  172. assert: [{ metric: undefined, type: 'equals', value: 'expected1' }],
  173. description: 'Row #1',
  174. options: {},
  175. vars: { var1: 'value1', var2: 'value2' },
  176. },
  177. {
  178. assert: [{ metric: undefined, type: 'equals', value: 'expected2' }],
  179. description: 'Row #2',
  180. options: {},
  181. vars: { var1: 'value3', var2: 'value4' },
  182. },
  183. ]);
  184. });
  185. it('should read CSV file with custom delimiter', async () => {
  186. jest.mocked(getEnvString).mockReturnValue(';');
  187. jest
  188. .mocked(fs.readFileSync)
  189. .mockReturnValue('var1;var2;__expected\nvalue1;value2;expected1\nvalue3;value4;expected2');
  190. const result = await readStandaloneTestsFile('test.csv');
  191. expect(getEnvString).toHaveBeenCalledWith('PROMPTFOO_CSV_DELIMITER', ',');
  192. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.csv'), 'utf-8');
  193. expect(result).toEqual([
  194. {
  195. assert: [{ metric: undefined, type: 'equals', value: 'expected1' }],
  196. description: 'Row #1',
  197. options: {},
  198. vars: { var1: 'value1', var2: 'value2' },
  199. },
  200. {
  201. assert: [{ metric: undefined, type: 'equals', value: 'expected2' }],
  202. description: 'Row #2',
  203. options: {},
  204. vars: { var1: 'value3', var2: 'value4' },
  205. },
  206. ]);
  207. });
  208. });
  209. describe('readTest', () => {
  210. beforeEach(() => {
  211. jest.clearAllMocks();
  212. });
  213. it('readTest with string input (path to test config)', async () => {
  214. const testPath = 'test1.yaml';
  215. const testContent = {
  216. description: 'Test 1',
  217. vars: { var1: 'value1', var2: 'value2' },
  218. assert: [{ type: 'equals', value: 'value1' }],
  219. };
  220. jest.mocked(fs.readFileSync).mockReturnValueOnce(yaml.dump(testContent));
  221. const result = await readTest(testPath);
  222. expect(fs.readFileSync).toHaveBeenCalledTimes(1);
  223. expect(result).toEqual(testContent);
  224. });
  225. it('readTest with TestCase input', async () => {
  226. const input: TestCase = {
  227. description: 'Test 1',
  228. vars: { var1: 'value1', var2: 'value2' },
  229. assert: [{ type: 'equals', value: 'value1' }],
  230. };
  231. const result = await readTest(input);
  232. expect(result).toEqual(input);
  233. });
  234. it('readTest with invalid input', async () => {
  235. const input: any = 123;
  236. await expect(readTest(input)).rejects.toThrow(
  237. 'Test case must contain one of the following properties: assert, vars, options, metadata, provider, providerOutput, threshold.\n\nInstead got:\n{}',
  238. );
  239. });
  240. it('readTest with TestCase that contains a vars glob input', async () => {
  241. const input: TestCaseWithVarsFile = {
  242. description: 'Test 1',
  243. vars: 'vars/*.yaml',
  244. assert: [{ type: 'equals' as AssertionType, value: 'value1' }],
  245. };
  246. const varsContent1 = { var1: 'value1' };
  247. const varsContent2 = { var2: 'value2' };
  248. jest.mocked(globSync).mockReturnValueOnce(['vars/vars1.yaml', 'vars/vars2.yaml']);
  249. jest
  250. .mocked(fs.readFileSync)
  251. .mockReturnValueOnce(yaml.dump(varsContent1))
  252. .mockReturnValueOnce(yaml.dump(varsContent2));
  253. const result = await readTest(input);
  254. expect(globSync).toHaveBeenCalledTimes(1);
  255. expect(fs.readFileSync).toHaveBeenCalledTimes(2);
  256. expect(result).toEqual({
  257. description: 'Test 1',
  258. vars: { var1: 'value1', var2: 'value2' },
  259. assert: [{ type: 'equals', value: 'value1' }],
  260. });
  261. });
  262. describe('readTest with provider', () => {
  263. it('should load provider when provider is a string', async () => {
  264. const mockProvider = { callApi: jest.fn(), id: jest.fn().mockReturnValue('mock-provider') };
  265. jest.mocked(loadApiProvider).mockResolvedValue(mockProvider);
  266. const testCase: TestCase = {
  267. description: 'Test with string provider',
  268. provider: 'mock-provider',
  269. assert: [{ type: 'equals', value: 'expected' }],
  270. };
  271. const result = await readTest(testCase);
  272. expect(loadApiProvider).toHaveBeenCalledWith('mock-provider');
  273. expect(result.provider).toBe(mockProvider);
  274. });
  275. it('should load provider when provider is an object with id', async () => {
  276. const mockProvider = { callApi: jest.fn(), id: jest.fn().mockReturnValue('mock-provider') };
  277. jest.mocked(loadApiProvider).mockResolvedValue(mockProvider);
  278. const testCase: TestCase = {
  279. description: 'Test with provider object',
  280. provider: {
  281. id: 'mock-provider',
  282. callApi: jest.fn(),
  283. },
  284. assert: [{ type: 'equals', value: 'expected' }],
  285. };
  286. const result = await readTest(testCase);
  287. expect(loadApiProvider).toHaveBeenCalledWith('mock-provider', {
  288. options: { id: 'mock-provider', callApi: expect.any(Function) },
  289. basePath: '',
  290. });
  291. expect(result.provider).toBe(mockProvider);
  292. });
  293. });
  294. });
  295. describe('readTests', () => {
  296. beforeEach(() => {
  297. jest.resetAllMocks();
  298. });
  299. it('readTests with string input (CSV file path)', async () => {
  300. jest
  301. .mocked(fs.readFileSync)
  302. .mockReturnValue('var1,var2,__expected\nvalue1,value2,value1\nvalue3,value4,fn:value5');
  303. const testsPath = 'tests.csv';
  304. const result = await readTests(testsPath);
  305. expect(fs.readFileSync).toHaveBeenCalledTimes(1);
  306. expect(result).toEqual([
  307. {
  308. description: 'Row #1',
  309. vars: { var1: 'value1', var2: 'value2' },
  310. assert: [{ type: 'equals', value: 'value1' }],
  311. options: {},
  312. },
  313. {
  314. description: 'Row #2',
  315. vars: { var1: 'value3', var2: 'value4' },
  316. assert: [{ type: 'javascript', value: 'value5' }],
  317. options: {},
  318. },
  319. ]);
  320. });
  321. it('readTests with string input (CSV file path with file:// prefix)', async () => {
  322. jest
  323. .mocked(fs.readFileSync)
  324. .mockReturnValue('var1,var2,__expected\nvalue1,value2,value1\nvalue3,value4,fn:value5');
  325. const testsPath = 'file://tests.csv';
  326. const result = await readTests(testsPath);
  327. expect(fs.readFileSync).toHaveBeenCalledTimes(1);
  328. expect(result).toEqual([
  329. {
  330. description: 'Row #1',
  331. vars: { var1: 'value1', var2: 'value2' },
  332. assert: [{ type: 'equals', value: 'value1' }],
  333. options: {},
  334. },
  335. {
  336. description: 'Row #2',
  337. vars: { var1: 'value3', var2: 'value4' },
  338. assert: [{ type: 'javascript', value: 'value5' }],
  339. options: {},
  340. },
  341. ]);
  342. });
  343. it('readTests with multiple __expected in CSV', async () => {
  344. jest
  345. .mocked(fs.readFileSync)
  346. .mockReturnValue(
  347. 'var1,var2,__expected1,__expected2,__expected3\nvalue1,value2,value1,value1.2,value1.3\nvalue3,value4,fn:value5,fn:value5.2,fn:value5.3',
  348. );
  349. const testsPath = 'tests.csv';
  350. const result = await readTests(testsPath);
  351. expect(fs.readFileSync).toHaveBeenCalledTimes(1);
  352. expect(result).toEqual([
  353. {
  354. description: 'Row #1',
  355. vars: { var1: 'value1', var2: 'value2' },
  356. assert: [
  357. { type: 'equals', value: 'value1' },
  358. { type: 'equals', value: 'value1.2' },
  359. { type: 'equals', value: 'value1.3' },
  360. ],
  361. options: {},
  362. },
  363. {
  364. description: 'Row #2',
  365. vars: { var1: 'value3', var2: 'value4' },
  366. assert: [
  367. { type: 'javascript', value: 'value5' },
  368. { type: 'javascript', value: 'value5.2' },
  369. { type: 'javascript', value: 'value5.3' },
  370. ],
  371. options: {},
  372. },
  373. ]);
  374. });
  375. it('readTests with array input (TestCase[])', async () => {
  376. const input: TestCase[] = [
  377. {
  378. description: 'Test 1',
  379. vars: { var1: 'value1', var2: 'value2' },
  380. assert: [{ type: 'equals', value: 'value1' }],
  381. },
  382. {
  383. description: 'Test 2',
  384. vars: { var1: 'value3', var2: 'value4' },
  385. assert: [{ type: 'contains-json', value: 'value3' }],
  386. },
  387. ];
  388. const result = await readTests(input);
  389. expect(result).toEqual(input);
  390. });
  391. it('readTests with string array input (paths to test configs)', async () => {
  392. const testsPaths = ['test1.yaml', 'test2.yaml'];
  393. const test1Content = [
  394. {
  395. description: 'Test 1',
  396. vars: { var1: 'value1', var2: 'value2' },
  397. assert: [{ type: 'equals', value: 'value1' }],
  398. },
  399. ];
  400. const test2Content = [
  401. {
  402. description: 'Test 2',
  403. vars: { var1: 'value3', var2: 'value4' },
  404. assert: [{ type: 'contains-json', value: 'value3' }],
  405. },
  406. ];
  407. jest
  408. .mocked(fs.readFileSync)
  409. .mockReturnValueOnce(yaml.dump(test1Content))
  410. .mockReturnValueOnce(yaml.dump(test2Content));
  411. jest.mocked(globSync).mockImplementation((pathOrGlob) => [pathOrGlob].flat());
  412. const result = await readTests(testsPaths);
  413. expect(fs.readFileSync).toHaveBeenCalledTimes(2);
  414. expect(result).toEqual([...test1Content, ...test2Content]);
  415. });
  416. it('readTests with vars glob input (paths to vars configs)', async () => {
  417. const testsPaths = ['test1.yaml'];
  418. const test1Content = [
  419. {
  420. description: 'Test 1',
  421. vars: 'vars1.yaml',
  422. assert: [{ type: 'equals', value: 'value1' }],
  423. },
  424. ];
  425. const vars1Content = {
  426. var1: 'value1',
  427. var2: 'value2',
  428. };
  429. jest
  430. .mocked(fs.readFileSync)
  431. .mockReturnValueOnce(yaml.dump(test1Content))
  432. .mockReturnValueOnce(yaml.dump(vars1Content));
  433. jest.mocked(globSync).mockImplementation((pathOrGlob) => [pathOrGlob].flat());
  434. const result = await readTests(testsPaths);
  435. expect(fs.readFileSync).toHaveBeenCalledTimes(2);
  436. expect(result).toEqual([Object.assign({}, test1Content[0], { vars: vars1Content })]);
  437. });
  438. it('readTests with single TestCase content', async () => {
  439. const testsPaths = ['test1.yaml'];
  440. const test1Content = {
  441. description: 'Test 1',
  442. assert: [{ type: 'equals', value: 'value1' }],
  443. };
  444. jest.mocked(fs.readFileSync).mockReturnValueOnce(yaml.dump(test1Content));
  445. jest.mocked(globSync).mockImplementation((pathOrGlob) => [pathOrGlob].flat());
  446. const result = await readTests(testsPaths);
  447. expect(fs.readFileSync).toHaveBeenCalledTimes(1);
  448. expect(result).toEqual([test1Content]);
  449. });
  450. it('should read tests from a Google Sheets URL', async () => {
  451. const mockFetchCsvFromGoogleSheet =
  452. jest.requireMock('../src/googleSheets').fetchCsvFromGoogleSheet;
  453. mockFetchCsvFromGoogleSheet.mockResolvedValue([
  454. { var1: 'value1', var2: 'value2', __expected: 'expected1' },
  455. { var1: 'value3', var2: 'value4', __expected: 'expected2' },
  456. ]);
  457. const result = await readTests('https://docs.google.com/spreadsheets/d/example');
  458. expect(mockFetchCsvFromGoogleSheet).toHaveBeenCalledWith(
  459. 'https://docs.google.com/spreadsheets/d/example',
  460. );
  461. expect(result).toHaveLength(2);
  462. expect(result[0]).toMatchObject({
  463. description: 'Row #1',
  464. vars: { var1: 'value1', var2: 'value2' },
  465. assert: [{ type: 'equals', value: 'expected1' }],
  466. });
  467. expect(result[1]).toMatchObject({
  468. description: 'Row #2',
  469. vars: { var1: 'value3', var2: 'value4' },
  470. assert: [{ type: 'equals', value: 'expected2' }],
  471. });
  472. });
  473. it('should log a warning for unsupported test format', async () => {
  474. const warnSpy = jest.spyOn(logger, 'warn');
  475. const unsupportedTests = { invalid: 'format' };
  476. await readTests(unsupportedTests as any);
  477. expect(warnSpy).toHaveBeenCalledWith(
  478. expect.stringContaining("Warning: Unsupported 'tests' format in promptfooconfig.yaml."),
  479. );
  480. warnSpy.mockRestore();
  481. });
  482. it('should not log a warning if tests is undefined', async () => {
  483. await readTests(undefined);
  484. expect(logger.warn).not.toHaveBeenCalled();
  485. });
  486. });
  487. describe('testCaseFromCsvRow', () => {
  488. it('should convert a CSV row to a TestCase object', () => {
  489. const csvRow = {
  490. var1: 'value1',
  491. var2: 'value2',
  492. __expected: 'foobar',
  493. __expected1: 'is-json',
  494. __prefix: 'test-prefix',
  495. __suffix: 'test-suffix',
  496. };
  497. const testCase = testCaseFromCsvRow(csvRow);
  498. expect(testCase).toEqual({
  499. vars: {
  500. var1: 'value1',
  501. var2: 'value2',
  502. },
  503. assert: [
  504. {
  505. type: 'equals',
  506. value: 'foobar',
  507. },
  508. {
  509. type: 'is-json',
  510. },
  511. ],
  512. options: {
  513. prefix: 'test-prefix',
  514. suffix: 'test-suffix',
  515. },
  516. });
  517. });
  518. });
  519. describe('readVarsFiles', () => {
  520. it('should read variables from a single YAML file', async () => {
  521. const yamlContent = 'var1: value1\nvar2: value2';
  522. jest.mocked(fs.readFileSync).mockReturnValue(yamlContent);
  523. jest.mocked(globSync).mockReturnValue(['vars.yaml']);
  524. const result = await readVarsFiles('vars.yaml');
  525. expect(result).toEqual({ var1: 'value1', var2: 'value2' });
  526. });
  527. it('should read variables from multiple YAML files', async () => {
  528. const yamlContent1 = 'var1: value1';
  529. const yamlContent2 = 'var2: value2';
  530. jest
  531. .mocked(fs.readFileSync)
  532. .mockReturnValueOnce(yamlContent1)
  533. .mockReturnValueOnce(yamlContent2);
  534. jest.mocked(globSync).mockReturnValue(['vars1.yaml', 'vars2.yaml']);
  535. const result = await readVarsFiles(['vars1.yaml', 'vars2.yaml']);
  536. expect(result).toEqual({ var1: 'value1', var2: 'value2' });
  537. });
  538. });
  539. describe('synthesize', () => {
  540. it('should generate test cases based on prompts and personas', async () => {
  541. let i = 0;
  542. const mockProvider = {
  543. id: () => 'mock-provider',
  544. callApi: jest.fn(() => {
  545. if (i === 0) {
  546. i++;
  547. return Promise.resolve({ output: '{"personas": ["Persona 1", "Persona 2"]}' });
  548. }
  549. return Promise.resolve({ output: '{"vars": [{"var1": "value1"}, {"var2": "value2"}]}' });
  550. }),
  551. };
  552. jest.mocked(loadApiProvider).mockResolvedValue(mockProvider);
  553. const result = await synthesize({
  554. provider: 'mock-provider',
  555. prompts: ['Test prompt'],
  556. tests: [],
  557. numPersonas: 2,
  558. numTestCasesPerPersona: 1,
  559. });
  560. expect(result).toHaveLength(2);
  561. expect(result).toEqual([{ var1: 'value1' }, { var2: 'value2' }]);
  562. });
  563. });
  564. describe('generatePersonasPrompt', () => {
  565. it('should generate a prompt for a single prompt input', () => {
  566. const prompts = ['What is the capital of France?'];
  567. const numPersonas = 3;
  568. const result = generatePersonasPrompt(prompts, numPersonas);
  569. expect(result).toBe(dedent`
  570. Consider the following prompt for an LLM application:
  571. <Prompts>
  572. <Prompt>
  573. What is the capital of France?
  574. </Prompt>
  575. </Prompts>
  576. List up to 3 user personas that would send this prompt. Your response should be JSON of the form {personas: string[]}
  577. `);
  578. });
  579. it('should generate a prompt for multiple prompt inputs', () => {
  580. const prompts = ['What is the capital of France?', 'Who wrote Romeo and Juliet?'];
  581. const numPersonas = 5;
  582. const result = generatePersonasPrompt(prompts, numPersonas);
  583. expect(result).toBe(dedent`
  584. Consider the following prompts for an LLM application:
  585. <Prompts>
  586. <Prompt>
  587. What is the capital of France?
  588. </Prompt>
  589. <Prompt>
  590. Who wrote Romeo and Juliet?
  591. </Prompt>
  592. </Prompts>
  593. List up to 5 user personas that would send these prompts. Your response should be JSON of the form {personas: string[]}
  594. `);
  595. });
  596. });
  597. describe('testCasesPrompt', () => {
  598. it('should generate a test cases prompt with single prompt and no existing tests', () => {
  599. const prompts = ['What is the capital of {{country}}?'];
  600. const persona = 'A curious student';
  601. const tests: TestCase[] = [];
  602. const numTestCasesPerPersona = 3;
  603. const variables = ['country'];
  604. const result = testCasesPrompt(prompts, persona, tests, numTestCasesPerPersona, variables);
  605. expect(result).toBe(dedent`
  606. Consider this prompt, which contains some {{variables}}:
  607. <Prompts>
  608. <Prompt>
  609. What is the capital of {{country}}?
  610. </Prompt>
  611. </Prompts>
  612. This is your persona:
  613. <Persona>
  614. A curious student
  615. </Persona>
  616. Here are some existing tests:
  617. Fully embody this persona and determine a value for each variable, such that the prompt would be sent by this persona.
  618. You are a tester, so try to think of 3 sets of values that would be interesting or unusual to test.
  619. Your response should contain a JSON map of variable names to values, of the form {vars: {country: string}[]}
  620. `);
  621. });
  622. it('should generate a test cases prompt with multiple prompts and existing tests', () => {
  623. const prompts = ['What is the capital of {{country}}?', 'What is the population of {{city}}?'];
  624. const persona = 'A geography enthusiast';
  625. const tests: TestCase[] = [
  626. { vars: { country: 'France', city: 'Paris' } },
  627. { vars: { country: 'Japan', city: 'Tokyo' } },
  628. ];
  629. const numTestCasesPerPersona = 2;
  630. const variables = ['country', 'city'];
  631. const instructions = 'Focus on less known countries and cities.';
  632. const result = testCasesPrompt(
  633. prompts,
  634. persona,
  635. tests,
  636. numTestCasesPerPersona,
  637. variables,
  638. instructions,
  639. );
  640. expect(result).toBe(dedent`
  641. Consider these prompts, which contains some {{variables}}:
  642. <Prompts>
  643. <Prompt>
  644. What is the capital of {{country}}?
  645. </Prompt>
  646. <Prompt>
  647. What is the population of {{city}}?
  648. </Prompt>
  649. </Prompts>
  650. This is your persona:
  651. <Persona>
  652. A geography enthusiast
  653. </Persona>
  654. Here are some existing tests:
  655. <Test>
  656. {
  657. "country": "France",
  658. "city": "Paris"
  659. }
  660. </Test>
  661. <Test>
  662. {
  663. "country": "Japan",
  664. "city": "Tokyo"
  665. }
  666. </Test>
  667. Fully embody this persona and determine a value for each variable, such that the prompt would be sent by this persona.
  668. You are a tester, so try to think of 2 sets of values that would be interesting or unusual to test. Focus on less known countries and cities.
  669. Your response should contain a JSON map of variable names to values, of the form {vars: {country: string, city: string}[]}
  670. `);
  671. });
  672. });
Tip!

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

Comments

Loading...