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

javascript.test.ts 22 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
  1. import * as path from 'path';
  2. import { runAssertion } from '../../src/assertions';
  3. import { importModule } from '../../src/esm';
  4. import { OpenAiChatCompletionProvider } from '../../src/providers/openai/chat';
  5. import { isPackagePath, loadFromPackage } from '../../src/providers/packageParser';
  6. import type { Assertion, AtomicTestCase, GradingResult } from '../../src/types';
  7. jest.mock('../../src/redteam/remoteGeneration', () => ({
  8. shouldGenerateRemote: jest.fn().mockReturnValue(false),
  9. }));
  10. jest.mock('proxy-agent', () => ({
  11. ProxyAgent: jest.fn().mockImplementation(() => ({})),
  12. }));
  13. jest.mock('node:module', () => {
  14. const mockRequire: NodeJS.Require = {
  15. resolve: jest.fn() as unknown as NodeJS.RequireResolve,
  16. } as unknown as NodeJS.Require;
  17. return {
  18. createRequire: jest.fn().mockReturnValue(mockRequire),
  19. };
  20. });
  21. jest.mock('../../src/fetch', () => {
  22. const actual = jest.requireActual('../../src/fetch');
  23. return {
  24. ...actual,
  25. fetchWithRetries: jest.fn(actual.fetchWithRetries),
  26. };
  27. });
  28. jest.mock('glob', () => ({
  29. globSync: jest.fn(),
  30. }));
  31. jest.mock('fs', () => ({
  32. readFileSync: jest.fn(),
  33. promises: {
  34. readFile: jest.fn(),
  35. },
  36. }));
  37. jest.mock('../../src/esm', () => ({
  38. importModule: jest.fn().mockImplementation((path, functionName) => {
  39. // Make sure both parameters are captured in the mock call
  40. return Promise.resolve();
  41. }),
  42. __esModule: true,
  43. }));
  44. jest.mock('../../src/database', () => ({
  45. getDb: jest.fn(),
  46. }));
  47. jest.mock('path', () => {
  48. const actualPath = jest.requireActual('path');
  49. return {
  50. ...actualPath,
  51. resolve: jest.fn((basePath, filePath) => actualPath.join(basePath, filePath)),
  52. extname: jest.fn((filePath) => actualPath.extname(filePath)),
  53. join: actualPath.join,
  54. };
  55. });
  56. jest.mock('../../src/cliState', () => ({
  57. basePath: '/base/path',
  58. }));
  59. jest.mock('../../src/matchers', () => {
  60. const actual = jest.requireActual('../../src/matchers');
  61. return {
  62. ...actual,
  63. matchesContextRelevance: jest
  64. .fn()
  65. .mockResolvedValue({ pass: true, score: 1, reason: 'Mocked reason' }),
  66. matchesContextFaithfulness: jest
  67. .fn()
  68. .mockResolvedValue({ pass: true, score: 1, reason: 'Mocked reason' }),
  69. };
  70. });
  71. // Add this mock for packageParser
  72. jest.mock('../../src/providers/packageParser', () => {
  73. const mockIsPackagePath = jest.fn();
  74. const mockLoadFromPackage = jest.fn();
  75. return {
  76. isPackagePath: mockIsPackagePath,
  77. loadFromPackage: mockLoadFromPackage,
  78. __esModule: true, // This is important for proper mocking
  79. };
  80. });
  81. const javascriptStringAssertion: Assertion = {
  82. type: 'javascript',
  83. value: 'output === "Expected output"',
  84. };
  85. const javascriptMultilineStringAssertion: Assertion = {
  86. type: 'javascript',
  87. value: `
  88. if (output === "Expected output") {
  89. return {
  90. pass: true,
  91. score: 0.5,
  92. reason: 'Assertion passed',
  93. };
  94. }
  95. return {
  96. pass: false,
  97. score: 0,
  98. reason: 'Assertion failed',
  99. };`,
  100. };
  101. const javascriptStringAssertionWithNumber: Assertion = {
  102. type: 'javascript',
  103. value: 'output.length * 10',
  104. };
  105. const javascriptBooleanAssertionWithConfig: Assertion = {
  106. type: 'javascript',
  107. value: 'output.length <= context.config.maximumOutputSize',
  108. config: {
  109. maximumOutputSize: 20,
  110. },
  111. };
  112. const javascriptStringAssertionWithNumberAndThreshold: Assertion = {
  113. type: 'javascript',
  114. value: 'output.length * 10',
  115. threshold: 0.5,
  116. };
  117. const javascriptFunctionAssertion: Assertion = {
  118. type: 'javascript',
  119. value: async (output: string) => ({
  120. pass: true,
  121. score: 0.5,
  122. reason: 'Assertion passed',
  123. assertion: null,
  124. }),
  125. };
  126. const javascriptFunctionFailAssertion: Assertion = {
  127. type: 'javascript',
  128. value: async (output: string) => ({
  129. pass: false,
  130. score: 0.5,
  131. reason: 'Assertion failed',
  132. assertion: null,
  133. }),
  134. };
  135. describe('JavaScript file references', () => {
  136. beforeEach(() => {
  137. jest.clearAllMocks();
  138. // Reset all mocks before each test
  139. jest.mocked(importModule).mockReset();
  140. jest.mocked(path.resolve).mockReset();
  141. jest.mocked(isPackagePath).mockReset();
  142. jest.mocked(loadFromPackage).mockReset();
  143. });
  144. it('should handle JavaScript file reference with function name', async () => {
  145. const assertion: Assertion = {
  146. type: 'javascript',
  147. value: 'file:///path/to/assert.js:customFunction',
  148. };
  149. const mockFn = jest.fn((output: string) => true);
  150. jest.mocked(path.resolve).mockReturnValue('/path/to/assert.js');
  151. jest.mocked(path.extname).mockReturnValue('.js');
  152. jest.mocked(isPackagePath).mockReturnValue(false);
  153. // Mock importModule to return the mock function
  154. jest.mocked(importModule).mockImplementationOnce((path, functionName) => {
  155. return Promise.resolve({
  156. customFunction: mockFn,
  157. });
  158. });
  159. const output = 'Expected output';
  160. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  161. const providerResponse = { output };
  162. const result = await runAssertion({
  163. prompt: 'Some prompt',
  164. provider,
  165. assertion,
  166. test: {} as AtomicTestCase,
  167. providerResponse,
  168. });
  169. // Verify the mock was called with both parameters
  170. expect(importModule).toHaveBeenCalledWith('/path/to/assert.js', 'customFunction');
  171. expect(mockFn).toHaveBeenCalledWith(output, {
  172. prompt: 'Some prompt',
  173. vars: {},
  174. test: {},
  175. provider,
  176. providerResponse,
  177. });
  178. expect(result).toMatchObject({
  179. pass: true,
  180. reason: 'Assertion passed',
  181. });
  182. });
  183. it('should handle default export when no function name specified', async () => {
  184. const assertion: Assertion = {
  185. type: 'javascript',
  186. value: 'file:///path/to/assert.js',
  187. };
  188. const mockFn = jest.fn((output: string) => true);
  189. jest.mocked(path.resolve).mockReturnValue('/path/to/assert.js');
  190. jest.mocked(path.extname).mockReturnValue('.js');
  191. jest.mocked(isPackagePath).mockReturnValue(false);
  192. // Mock importModule to return the mock function
  193. jest.mocked(importModule).mockImplementationOnce((path, functionName) => {
  194. return Promise.resolve(mockFn);
  195. });
  196. const output = 'Expected output';
  197. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  198. const providerResponse = { output };
  199. const result = await runAssertion({
  200. prompt: 'Some prompt',
  201. provider,
  202. assertion,
  203. test: {} as AtomicTestCase,
  204. providerResponse,
  205. });
  206. expect(importModule).toHaveBeenCalledWith('/path/to/assert.js', undefined);
  207. expect(mockFn).toHaveBeenCalledWith(output, {
  208. prompt: 'Some prompt',
  209. vars: {},
  210. test: {},
  211. provider,
  212. providerResponse,
  213. });
  214. expect(result).toMatchObject({
  215. pass: true,
  216. reason: 'Assertion passed',
  217. });
  218. });
  219. it('should handle default export object with function', async () => {
  220. const assertion: Assertion = {
  221. type: 'javascript',
  222. value: 'file:///path/to/assert.js',
  223. };
  224. const mockFn = jest.fn((output: string) => true);
  225. jest.mocked(path.resolve).mockReturnValue('/path/to/assert.js');
  226. jest.mocked(path.extname).mockReturnValue('.js');
  227. jest.mocked(isPackagePath).mockReturnValue(false);
  228. // Mock importModule to handle both parameters
  229. const mockImportModule = jest.mocked(importModule);
  230. mockImportModule.mockImplementationOnce((path, functionName) => {
  231. // Return the mock function in a default export object
  232. return Promise.resolve({ default: mockFn });
  233. });
  234. const output = 'Expected output';
  235. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  236. const providerResponse = { output };
  237. const result = await runAssertion({
  238. prompt: 'Some prompt',
  239. provider,
  240. assertion,
  241. test: {} as AtomicTestCase,
  242. providerResponse,
  243. });
  244. expect(importModule).toHaveBeenCalledWith('/path/to/assert.js', undefined);
  245. expect(mockFn).toHaveBeenCalledWith(output, {
  246. prompt: 'Some prompt',
  247. vars: {},
  248. test: {},
  249. provider,
  250. providerResponse,
  251. });
  252. expect(result).toMatchObject({
  253. pass: true,
  254. reason: 'Assertion passed',
  255. });
  256. });
  257. it('should pass when the javascript assertion passes', async () => {
  258. const output = 'Expected output';
  259. const result: GradingResult = await runAssertion({
  260. prompt: 'Some prompt',
  261. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  262. assertion: javascriptStringAssertion,
  263. test: {} as AtomicTestCase,
  264. providerResponse: { output },
  265. });
  266. expect(result).toMatchObject({
  267. pass: true,
  268. reason: 'Assertion passed',
  269. });
  270. });
  271. it('should pass a score through when the javascript returns a number', async () => {
  272. const output = 'Expected output';
  273. const result: GradingResult = await runAssertion({
  274. prompt: 'Some prompt',
  275. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  276. assertion: javascriptStringAssertionWithNumber,
  277. test: {} as AtomicTestCase,
  278. providerResponse: { output },
  279. });
  280. expect(result).toMatchObject({
  281. pass: true,
  282. score: output.length * 10,
  283. reason: 'Assertion passed',
  284. });
  285. });
  286. it('should pass when javascript returns an output string that is smaller than the maximum size threshold', async () => {
  287. const output = 'Expected output';
  288. const result: GradingResult = await runAssertion({
  289. prompt: 'Some prompt',
  290. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  291. assertion: javascriptBooleanAssertionWithConfig,
  292. test: {} as AtomicTestCase,
  293. providerResponse: { output },
  294. });
  295. expect(result).toMatchObject({
  296. pass: true,
  297. score: 1.0,
  298. reason: 'Assertion passed',
  299. });
  300. });
  301. it('should fail when javascript returns an output string that is larger than the maximum size threshold', async () => {
  302. const output = 'Expected output with some extra characters';
  303. const result: GradingResult = await runAssertion({
  304. prompt: 'Some prompt',
  305. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  306. assertion: javascriptBooleanAssertionWithConfig,
  307. test: {} as AtomicTestCase,
  308. providerResponse: { output },
  309. });
  310. expect(result).toMatchObject({
  311. pass: false,
  312. score: 0,
  313. reason: expect.stringContaining('Custom function returned false'),
  314. });
  315. });
  316. it('should pass when javascript returns a number above threshold', async () => {
  317. const output = 'Expected output';
  318. const result: GradingResult = await runAssertion({
  319. prompt: 'Some prompt',
  320. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  321. assertion: javascriptStringAssertionWithNumberAndThreshold,
  322. test: {} as AtomicTestCase,
  323. providerResponse: { output },
  324. });
  325. expect(result).toMatchObject({
  326. pass: true,
  327. score: output.length * 10,
  328. reason: 'Assertion passed',
  329. });
  330. });
  331. it('should fail when javascript returns a number below threshold', async () => {
  332. const output = '';
  333. const result: GradingResult = await runAssertion({
  334. prompt: 'Some prompt',
  335. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  336. assertion: javascriptStringAssertionWithNumberAndThreshold,
  337. test: {} as AtomicTestCase,
  338. providerResponse: { output },
  339. });
  340. expect(result).toMatchObject({
  341. pass: false,
  342. score: output.length * 10,
  343. reason: expect.stringContaining('Custom function returned false'),
  344. });
  345. });
  346. it('should set score when javascript returns false', async () => {
  347. const output = 'Test output';
  348. const assertion: Assertion = {
  349. type: 'javascript',
  350. value: 'output.length < 1',
  351. };
  352. const result: GradingResult = await runAssertion({
  353. prompt: 'Some prompt',
  354. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  355. assertion,
  356. test: {} as AtomicTestCase,
  357. providerResponse: { output },
  358. });
  359. expect(result).toMatchObject({
  360. pass: false,
  361. score: 0,
  362. reason: expect.stringContaining('Custom function returned false'),
  363. });
  364. });
  365. it('should fail when the javascript assertion fails', async () => {
  366. const output = 'Different output';
  367. const result: GradingResult = await runAssertion({
  368. prompt: 'Some prompt',
  369. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  370. assertion: javascriptStringAssertion,
  371. test: {} as AtomicTestCase,
  372. providerResponse: { output },
  373. });
  374. expect(result).toMatchObject({
  375. pass: false,
  376. reason: 'Custom function returned false\noutput === "Expected output"',
  377. });
  378. });
  379. it('should pass when javascript function assertion passes - with vars', async () => {
  380. const output = 'Expected output';
  381. const javascriptStringAssertionWithVars: Assertion = {
  382. type: 'javascript',
  383. value: 'output === "Expected output" && context.vars.foo === "bar"',
  384. };
  385. const result: GradingResult = await runAssertion({
  386. prompt: 'Some prompt',
  387. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  388. assertion: javascriptStringAssertionWithVars,
  389. test: { vars: { foo: 'bar' } } as AtomicTestCase,
  390. providerResponse: { output },
  391. });
  392. expect(result).toMatchObject({
  393. pass: true,
  394. reason: 'Assertion passed',
  395. });
  396. });
  397. it('should fail when the javascript does not match vars', async () => {
  398. const output = 'Expected output';
  399. const javascriptStringAssertionWithVars: Assertion = {
  400. type: 'javascript',
  401. value: 'output === "Expected output" && context.vars.foo === "something else"',
  402. };
  403. const result: GradingResult = await runAssertion({
  404. prompt: 'Some prompt',
  405. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  406. assertion: javascriptStringAssertionWithVars,
  407. test: { vars: { foo: 'bar' } } as AtomicTestCase,
  408. providerResponse: { output },
  409. });
  410. expect(result).toMatchObject({
  411. pass: false,
  412. reason:
  413. 'Custom function returned false\noutput === "Expected output" && context.vars.foo === "something else"',
  414. });
  415. });
  416. it('should pass when the function returns pass', async () => {
  417. const output = 'Expected output';
  418. const result: GradingResult = await runAssertion({
  419. prompt: 'Some prompt',
  420. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  421. assertion: javascriptFunctionAssertion,
  422. test: {} as AtomicTestCase,
  423. providerResponse: { output },
  424. });
  425. expect(result).toMatchObject({
  426. pass: true,
  427. score: 0.5,
  428. reason: 'Assertion passed',
  429. });
  430. });
  431. it('should fail when the function returns fail', async () => {
  432. const output = 'Expected output';
  433. const result: GradingResult = await runAssertion({
  434. prompt: 'Some prompt',
  435. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  436. assertion: javascriptFunctionFailAssertion,
  437. test: {} as AtomicTestCase,
  438. providerResponse: { output },
  439. });
  440. expect(result).toMatchObject({
  441. pass: false,
  442. score: 0.5,
  443. reason: 'Assertion failed',
  444. });
  445. });
  446. it('should pass when the multiline javascript assertion passes', async () => {
  447. const output = 'Expected output';
  448. const result: GradingResult = await runAssertion({
  449. prompt: 'Some prompt',
  450. assertion: javascriptMultilineStringAssertion,
  451. test: {} as AtomicTestCase,
  452. providerResponse: { output },
  453. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  454. });
  455. expect(result).toMatchObject({
  456. pass: true,
  457. reason: 'Assertion passed',
  458. });
  459. });
  460. it('should pass when the multiline javascript assertion fails', async () => {
  461. const output = 'Not the expected output';
  462. const result: GradingResult = await runAssertion({
  463. prompt: 'Some prompt',
  464. assertion: javascriptMultilineStringAssertion,
  465. test: {} as AtomicTestCase,
  466. providerResponse: { output },
  467. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  468. });
  469. expect(result).toMatchObject({
  470. pass: false,
  471. reason: 'Assertion failed',
  472. });
  473. });
  474. it.each([
  475. [
  476. 'boolean',
  477. jest.fn((output: string) => output === 'Expected output'),
  478. true,
  479. 'Assertion passed',
  480. ],
  481. ['number', jest.fn((output: string) => output.length), true, 'Assertion passed'],
  482. [
  483. 'GradingResult',
  484. jest.fn((output: string) => ({ pass: true, score: 1, reason: 'Custom reason' })),
  485. true,
  486. 'Custom reason',
  487. ],
  488. [
  489. 'boolean',
  490. jest.fn((output: string) => output !== 'Expected output'),
  491. false,
  492. 'Custom function returned false',
  493. ],
  494. ['number', jest.fn((output: string) => 0), false, 'Custom function returned false'],
  495. [
  496. 'GradingResult',
  497. jest.fn((output: string) => ({ pass: false, score: 0.1, reason: 'Custom reason' })),
  498. false,
  499. 'Custom reason',
  500. ],
  501. [
  502. 'boolean Promise',
  503. jest.fn((output: string) => Promise.resolve(true)),
  504. true,
  505. 'Assertion passed',
  506. ],
  507. ])(
  508. 'should pass when the file:// assertion with .js file returns a %s',
  509. async (type, mockFn, expectedPass, expectedReason) => {
  510. const output = 'Expected output';
  511. // Mock path.resolve to return a valid path
  512. jest.mocked(path.resolve).mockReturnValue('/mocked/path/to/assert.js');
  513. jest.mocked(path.extname).mockReturnValue('.js');
  514. // Mock isPackagePath to return false for file:// paths
  515. jest.mocked(isPackagePath).mockReturnValue(false);
  516. // Mock importModule to handle both path and functionName
  517. const mockImportModule = jest.mocked(importModule);
  518. mockImportModule.mockImplementation((path, functionName) => {
  519. // Make sure both parameters are captured in the mock
  520. mockImportModule.mock.calls.push([path, functionName]);
  521. return Promise.resolve(mockFn);
  522. });
  523. const fileAssertion: Assertion = {
  524. type: 'javascript',
  525. value: 'file:///path/to/assert.js',
  526. };
  527. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  528. const providerResponse = { output };
  529. const result: GradingResult = await runAssertion({
  530. prompt: 'Some prompt',
  531. provider,
  532. assertion: fileAssertion,
  533. test: {} as AtomicTestCase,
  534. providerResponse,
  535. });
  536. expect(mockFn).toHaveBeenCalledWith(output, {
  537. prompt: 'Some prompt',
  538. vars: {},
  539. test: {},
  540. provider,
  541. providerResponse,
  542. });
  543. expect(result).toMatchObject({
  544. pass: expectedPass,
  545. reason: expect.stringContaining(expectedReason),
  546. });
  547. },
  548. );
  549. it.each([
  550. [
  551. 'boolean',
  552. jest.fn((output: string) => output === 'Expected output'),
  553. true,
  554. 'Assertion passed',
  555. ],
  556. ['number', jest.fn((output: string) => output.length), true, 'Assertion passed'],
  557. [
  558. 'GradingResult',
  559. jest.fn((output: string) => ({ pass: true, score: 1, reason: 'Custom reason' })),
  560. true,
  561. 'Custom reason',
  562. ],
  563. [
  564. 'boolean',
  565. jest.fn((output: string) => output !== 'Expected output'),
  566. false,
  567. 'Custom function returned false',
  568. ],
  569. ['number', jest.fn((output: string) => 0), false, 'Custom function returned false'],
  570. [
  571. 'GradingResult',
  572. jest.fn((output: string) => ({ pass: false, score: 0.1, reason: 'Custom reason' })),
  573. false,
  574. 'Custom reason',
  575. ],
  576. [
  577. 'boolean Promise',
  578. jest.fn((output: string) => Promise.resolve(true)),
  579. true,
  580. 'Assertion passed',
  581. ],
  582. ])(
  583. 'should pass when assertion is a package path',
  584. async (type, mockFn, expectedPass, expectedReason) => {
  585. const output = 'Expected output';
  586. // Mock isPackagePath to return true for package paths
  587. jest.mocked(isPackagePath).mockReturnValue(true);
  588. // Mock loadFromPackage to return the mockFn
  589. jest.mocked(loadFromPackage).mockResolvedValue(mockFn);
  590. const packageAssertion: Assertion = {
  591. type: 'javascript',
  592. value: 'package:@promptfoo/fake:assertionFunction',
  593. };
  594. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  595. const providerResponse = { output };
  596. const result: GradingResult = await runAssertion({
  597. prompt: 'Some prompt',
  598. provider,
  599. assertion: packageAssertion,
  600. test: {} as AtomicTestCase,
  601. providerResponse,
  602. });
  603. expect(mockFn).toHaveBeenCalledWith(output, {
  604. prompt: 'Some prompt',
  605. vars: {},
  606. test: {},
  607. provider,
  608. providerResponse,
  609. });
  610. expect(result).toMatchObject({
  611. pass: expectedPass,
  612. reason: expect.stringContaining(expectedReason),
  613. });
  614. },
  615. );
  616. it('should resolve js paths relative to the configuration file', async () => {
  617. const output = 'Expected output';
  618. const mockFn = jest.fn((output: string) => output === 'Expected output');
  619. // Mock path.resolve to return a valid path
  620. jest.mocked(path.resolve).mockReturnValue('/base/path/path/to/assert.js');
  621. jest.mocked(path.extname).mockReturnValue('.js');
  622. // Mock isPackagePath to return false
  623. jest.mocked(isPackagePath).mockReturnValue(false);
  624. // Mock importModule to return the mockFn
  625. jest.mocked(importModule).mockResolvedValue(mockFn);
  626. const fileAssertion: Assertion = {
  627. type: 'javascript',
  628. value: 'file://./path/to/assert.js',
  629. };
  630. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  631. const providerResponse = { output };
  632. const result: GradingResult = await runAssertion({
  633. prompt: 'Some prompt',
  634. provider,
  635. assertion: fileAssertion,
  636. test: {} as AtomicTestCase,
  637. providerResponse,
  638. });
  639. expect(mockFn).toHaveBeenCalledWith(output, {
  640. prompt: 'Some prompt',
  641. vars: {},
  642. test: {},
  643. provider,
  644. providerResponse,
  645. });
  646. expect(result).toMatchObject({
  647. pass: true,
  648. reason: 'Assertion passed',
  649. });
  650. });
  651. });
Tip!

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

Comments

Loading...