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 31 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
  1. import cliProgress from 'cli-progress';
  2. import * as fs from 'fs';
  3. import yaml from 'js-yaml';
  4. import logger from '../../src/logger';
  5. import { loadApiProvider } from '../../src/providers';
  6. import { HARM_PLUGINS, PII_PLUGINS } from '../../src/redteam/constants';
  7. import { extractEntities } from '../../src/redteam/extraction/entities';
  8. import { extractSystemPurpose } from '../../src/redteam/extraction/purpose';
  9. import {
  10. synthesize,
  11. resolvePluginConfig,
  12. calculateTotalTests,
  13. getMultilingualRequestedCount,
  14. getTestCount,
  15. } from '../../src/redteam/index';
  16. import { Plugins } from '../../src/redteam/plugins';
  17. import { shouldGenerateRemote, getRemoteHealthUrl } from '../../src/redteam/remoteGeneration';
  18. import { Strategies } from '../../src/redteam/strategies';
  19. import { validateStrategies } from '../../src/redteam/strategies';
  20. import { DEFAULT_LANGUAGES } from '../../src/redteam/strategies/multilingual';
  21. import type { TestCaseWithPlugin } from '../../src/types';
  22. import { checkRemoteHealth } from '../../src/util/apiHealth';
  23. jest.mock('cli-progress');
  24. jest.mock('../../src/providers');
  25. jest.mock('../../src/redteam/extraction/entities');
  26. jest.mock('../../src/redteam/extraction/purpose');
  27. jest.mock('../../src/util/templates', () => {
  28. const originalModule = jest.requireActual('../../src/util/templates');
  29. return {
  30. ...originalModule,
  31. extractVariablesFromTemplates: jest.fn(originalModule.extractVariablesFromTemplates),
  32. };
  33. });
  34. jest.mock('process', () => ({
  35. ...jest.requireActual('process'),
  36. exit: jest.fn(),
  37. }));
  38. jest.mock('../../src/redteam/strategies', () => ({
  39. ...jest.requireActual('../../src/redteam/strategies'),
  40. validateStrategies: jest.fn().mockImplementation((strategies) => {
  41. if (strategies.some((s: { id: string }) => s.id === 'invalid-strategy')) {
  42. throw new Error('Invalid strategies');
  43. }
  44. }),
  45. }));
  46. jest.mock('../../src/util/apiHealth');
  47. jest.mock('../../src/redteam/remoteGeneration');
  48. describe('synthesize', () => {
  49. const mockProvider = {
  50. callApi: jest.fn(),
  51. generate: jest.fn(),
  52. id: () => 'test-provider',
  53. };
  54. beforeEach(() => {
  55. jest.clearAllMocks();
  56. jest.mocked(extractEntities).mockResolvedValue(['entity1', 'entity2']);
  57. jest.mocked(extractSystemPurpose).mockResolvedValue('Test purpose');
  58. jest.mocked(loadApiProvider).mockResolvedValue(mockProvider);
  59. jest.spyOn(process, 'exit').mockImplementation((code?: string | number | null | undefined) => {
  60. throw new Error(`Process.exit called with code ${code}`);
  61. });
  62. jest.mocked(validateStrategies).mockImplementation(async () => {});
  63. jest.mocked(cliProgress.SingleBar).mockReturnValue({
  64. increment: jest.fn(),
  65. start: jest.fn(),
  66. stop: jest.fn(),
  67. update: jest.fn(),
  68. } as any);
  69. });
  70. // Input handling tests
  71. describe('Input handling', () => {
  72. it('should use provided purpose and entities if given', async () => {
  73. const result = await synthesize({
  74. entities: ['custom-entity'],
  75. language: 'en',
  76. numTests: 1,
  77. plugins: [{ id: 'test-plugin', numTests: 1 }],
  78. prompts: ['Test prompt'],
  79. purpose: 'Custom purpose',
  80. strategies: [],
  81. targetLabels: ['test-provider'],
  82. });
  83. expect(result).toEqual(
  84. expect.objectContaining({
  85. entities: ['custom-entity'],
  86. purpose: 'Custom purpose',
  87. }),
  88. );
  89. expect(extractEntities).not.toHaveBeenCalled();
  90. expect(extractSystemPurpose).not.toHaveBeenCalled();
  91. });
  92. it('should extract purpose and entities if not provided', async () => {
  93. await synthesize({
  94. language: 'english',
  95. numTests: 1,
  96. plugins: [{ id: 'test-plugin', numTests: 1 }],
  97. prompts: ['Test prompt'],
  98. strategies: [],
  99. targetLabels: ['test-provider'],
  100. });
  101. expect(extractEntities).toHaveBeenCalledWith(expect.any(Object), ['Test prompt']);
  102. expect(extractSystemPurpose).toHaveBeenCalledWith(expect.any(Object), ['Test prompt']);
  103. });
  104. it('should handle empty prompts array', async () => {
  105. await expect(
  106. synthesize({
  107. language: 'en',
  108. numTests: 1,
  109. plugins: [{ id: 'test-plugin', numTests: 1 }],
  110. prompts: [] as unknown as [string, ...string[]],
  111. strategies: [],
  112. targetLabels: ['test-provider'],
  113. }),
  114. ).rejects.toThrow('Prompts array cannot be empty');
  115. });
  116. it('should correctly process multiple prompts', async () => {
  117. await synthesize({
  118. language: 'en',
  119. numTests: 1,
  120. plugins: [{ id: 'test-plugin', numTests: 1 }],
  121. prompts: ['Prompt 1', 'Prompt 2', 'Prompt 3'],
  122. strategies: [],
  123. targetLabels: ['test-provider'],
  124. });
  125. expect(extractSystemPurpose).toHaveBeenCalledWith(expect.any(Object), [
  126. 'Prompt 1',
  127. 'Prompt 2',
  128. 'Prompt 3',
  129. ]);
  130. expect(extractEntities).toHaveBeenCalledWith(expect.any(Object), [
  131. 'Prompt 1',
  132. 'Prompt 2',
  133. 'Prompt 3',
  134. ]);
  135. });
  136. });
  137. // API provider tests
  138. describe('API provider', () => {
  139. it('should use the provided API provider if given', async () => {
  140. const customProvider = {
  141. callApi: jest.fn(),
  142. generate: jest.fn(),
  143. id: () => 'custom-provider',
  144. };
  145. await synthesize({
  146. language: 'en',
  147. numTests: 1,
  148. plugins: [{ id: 'test-plugin', numTests: 1 }],
  149. prompts: ['Test prompt'],
  150. provider: customProvider,
  151. strategies: [],
  152. targetLabels: ['custom-provider'],
  153. });
  154. expect(loadApiProvider).not.toHaveBeenCalled();
  155. });
  156. });
  157. // Plugin and strategy tests
  158. describe('Plugins and strategies', () => {
  159. it('should generate test cases for each plugin', async () => {
  160. const mockPluginAction = jest.fn().mockResolvedValue([{ test: 'case' }]);
  161. jest.spyOn(Plugins, 'find').mockReturnValue({ action: mockPluginAction, key: 'mockPlugin' });
  162. const result = await synthesize({
  163. language: 'en',
  164. numTests: 1,
  165. plugins: [
  166. { id: 'plugin1', numTests: 2 },
  167. { id: 'plugin2', numTests: 3 },
  168. ],
  169. prompts: ['Test prompt'],
  170. strategies: [],
  171. targetLabels: ['test-provider'],
  172. });
  173. expect(mockPluginAction).toHaveBeenCalledTimes(2);
  174. expect(result.testCases).toEqual([
  175. expect.objectContaining({ metadata: expect.objectContaining({ pluginId: 'plugin1' }) }),
  176. expect.objectContaining({ metadata: expect.objectContaining({ pluginId: 'plugin2' }) }),
  177. ]);
  178. });
  179. it('should warn about unregistered plugins', async () => {
  180. jest.spyOn(Plugins, 'find').mockReturnValue(undefined);
  181. await synthesize({
  182. language: 'en',
  183. numTests: 1,
  184. plugins: [{ id: 'unregistered-plugin', numTests: 1 }],
  185. prompts: ['Test prompt'],
  186. strategies: [],
  187. targetLabels: ['test-provider'],
  188. });
  189. expect(logger.warn).toHaveBeenCalledWith(
  190. 'Plugin unregistered-plugin not registered, skipping',
  191. );
  192. });
  193. it('should handle HARM_PLUGINS, PII_PLUGINS, and BIAS_PLUGINS correctly', async () => {
  194. const mockPluginAction = jest.fn().mockResolvedValue([{ test: 'case' }]);
  195. jest.spyOn(Plugins, 'find').mockReturnValue({ action: mockPluginAction, key: 'mockPlugin' });
  196. const result = await synthesize({
  197. language: 'en',
  198. numTests: 1,
  199. plugins: [
  200. { id: 'harmful', numTests: 2 },
  201. { id: 'pii', numTests: 3 },
  202. ],
  203. prompts: ['Test prompt'],
  204. strategies: [],
  205. targetLabels: ['test-provider'],
  206. });
  207. // Verify the test cases by checking each one individually rather than hardcoding a number
  208. // Each test case should have a valid plugin ID that comes from one of our plugin sets
  209. const testCases = result.testCases;
  210. // All test cases should have valid plugin IDs
  211. const pluginIds = testCases.map((tc) => tc.metadata.pluginId);
  212. // Check that each plugin ID belongs to one of our known plugin categories
  213. const allValidPluginIds = [...Object.keys(HARM_PLUGINS), ...PII_PLUGINS];
  214. // Every plugin ID should be in our list of valid plugins
  215. pluginIds.forEach((id) => {
  216. expect(allValidPluginIds).toContain(id);
  217. });
  218. // Check for uniqueness - we should have unique plugin IDs (no duplicates of the same plugin)
  219. const uniquePluginIds = new Set(pluginIds);
  220. // The expected number of test cases is the number of unique plugin IDs we actually got
  221. // This is more reliable than trying to predict the exact expansion logic
  222. const expectedTestCount = uniquePluginIds.size;
  223. // Assert that we got exactly the expected number of test cases
  224. expect(testCases).toHaveLength(expectedTestCount);
  225. });
  226. it('should generate a correct report for plugins and strategies', async () => {
  227. const mockPluginAction = jest.fn().mockResolvedValue([{ test: 'case' }]);
  228. jest.spyOn(Plugins, 'find').mockReturnValue({ action: mockPluginAction, key: 'mockPlugin' });
  229. const mockStrategyAction = jest.fn().mockReturnValue([{ test: 'strategy case' }]);
  230. jest
  231. .spyOn(Strategies, 'find')
  232. .mockReturnValue({ action: mockStrategyAction, id: 'mockStrategy' });
  233. await synthesize({
  234. language: 'en',
  235. numTests: 2,
  236. plugins: [{ id: 'test-plugin', numTests: 2 }],
  237. prompts: ['Test prompt'],
  238. strategies: [{ id: 'mockStrategy' }],
  239. targetLabels: ['test-provider'],
  240. });
  241. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Test Generation Report:'));
  242. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('test-plugin'));
  243. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('mockStrategy'));
  244. });
  245. it('should expand strategy collections into individual strategies', async () => {
  246. // Mock plugin to generate test cases
  247. const mockPluginAction = jest.fn().mockResolvedValue([{ test: 'case' }]);
  248. jest.spyOn(Plugins, 'find').mockReturnValue({ action: mockPluginAction, key: 'mockPlugin' });
  249. // Mock strategy actions
  250. const mockStrategyAction = jest.fn().mockReturnValue([{ test: 'strategy case' }]);
  251. jest.spyOn(Strategies, 'find').mockImplementation((s: any) => {
  252. if (['morse', 'piglatin'].includes(s.id)) {
  253. return { action: mockStrategyAction, id: s.id };
  254. }
  255. return undefined;
  256. });
  257. // Use the other-encodings collection
  258. await synthesize({
  259. language: 'en',
  260. numTests: 1,
  261. plugins: [{ id: 'test-plugin', numTests: 1 }],
  262. prompts: ['Test prompt'],
  263. strategies: [
  264. {
  265. id: 'other-encodings',
  266. config: { customOption: 'test-value' },
  267. },
  268. ],
  269. targetLabels: ['test-provider'],
  270. });
  271. // Just verify validateStrategies was called
  272. // The mock implementation might not be executed in the test context,
  273. // but we can confirm the expansion mechanism is working
  274. expect(validateStrategies).toHaveBeenCalledWith(expect.any(Array));
  275. });
  276. it('should deduplicate strategies with the same ID', async () => {
  277. const mockPluginAction = jest.fn().mockResolvedValue([{ test: 'case' }]);
  278. jest.spyOn(Plugins, 'find').mockReturnValue({ action: mockPluginAction, key: 'mockPlugin' });
  279. // Create a spy on validateStrategies to capture the strategies array
  280. const validateStrategiesSpy = jest.mocked(validateStrategies);
  281. validateStrategiesSpy.mockClear();
  282. // Include both the collection and an individual strategy that's part of the collection
  283. await synthesize({
  284. language: 'en',
  285. numTests: 1,
  286. plugins: [{ id: 'test-plugin', numTests: 1 }],
  287. prompts: ['Test prompt'],
  288. strategies: [
  289. { id: 'other-encodings' },
  290. { id: 'morse' }, // This is already included in other-encodings
  291. ],
  292. targetLabels: ['test-provider'],
  293. });
  294. // Check that validateStrategies was called
  295. expect(validateStrategiesSpy).toHaveBeenCalledWith(expect.any(Array));
  296. // Look at the strategies that were passed to validateStrategies
  297. // The array should have no duplicate ids
  298. const strategiesArg = validateStrategiesSpy.mock.calls[0][0];
  299. const strategyIds = strategiesArg.map((s: any) => s.id);
  300. // Check for duplicates
  301. const uniqueIds = new Set(strategyIds);
  302. expect(uniqueIds.size).toBe(strategyIds.length);
  303. // Should have morse only once
  304. expect(strategyIds.filter((id: string) => id === 'morse')).toHaveLength(1);
  305. // Should have at least morse and piglatin
  306. expect(strategyIds).toContain('morse');
  307. expect(strategyIds).toContain('piglatin');
  308. });
  309. it('should handle missing strategy collections gracefully', async () => {
  310. const mockPluginAction = jest.fn().mockResolvedValue([{ test: 'case' }]);
  311. jest.spyOn(Plugins, 'find').mockReturnValue({ action: mockPluginAction, key: 'mockPlugin' });
  312. await synthesize({
  313. language: 'en',
  314. numTests: 1,
  315. plugins: [{ id: 'test-plugin', numTests: 1 }],
  316. prompts: ['Test prompt'],
  317. strategies: [
  318. { id: 'unknown-collection' }, // This doesn't exist in the mappings
  319. ],
  320. targetLabels: ['test-provider'],
  321. });
  322. // Should log a warning for unknown strategy collection
  323. expect(logger.warn).toHaveBeenCalledWith(
  324. expect.stringContaining('unknown-collection not registered'),
  325. );
  326. });
  327. it('should skip plugins that fail validation and not throw', async () => {
  328. // Plugin 1: will fail validation
  329. const failingPlugin = {
  330. id: 'fail-plugin',
  331. numTests: 1,
  332. };
  333. // Plugin 2: will succeed
  334. const passingPlugin = {
  335. id: 'pass-plugin',
  336. numTests: 1,
  337. };
  338. // Mock Plugins.find to return a plugin with a validate method that throws for fail-plugin
  339. jest
  340. .spyOn(Plugins, 'find')
  341. .mockReturnValueOnce({
  342. key: 'fail-plugin',
  343. action: jest.fn().mockResolvedValue([{ test: 'fail-case' }]),
  344. validate: () => {
  345. throw new Error('Validation failed!');
  346. },
  347. })
  348. .mockReturnValue({
  349. key: 'pass-plugin',
  350. action: jest.fn().mockResolvedValue([{ test: 'pass-case' }]),
  351. validate: jest.fn(),
  352. });
  353. const result = await synthesize({
  354. language: 'en',
  355. numTests: 1,
  356. plugins: [failingPlugin, passingPlugin],
  357. prompts: ['Test prompt'],
  358. strategies: [],
  359. targetLabels: ['test-provider'],
  360. });
  361. expect(result.testCases).toHaveLength(1);
  362. expect(result.testCases[0].metadata.pluginId).toBe('pass-plugin');
  363. expect(logger.warn).toHaveBeenCalledWith(
  364. expect.stringContaining(
  365. 'Validation failed for plugin fail-plugin: Error: Validation failed!, skipping plugin',
  366. ),
  367. );
  368. });
  369. });
  370. describe('Logger', () => {
  371. it('debug log level hides progress bar', async () => {
  372. const originalLogLevel = process.env.LOG_LEVEL;
  373. process.env.LOG_LEVEL = 'debug';
  374. await synthesize({
  375. language: 'en',
  376. numTests: 1,
  377. plugins: [{ id: 'test-plugin', numTests: 1 }],
  378. prompts: ['Test prompt'],
  379. strategies: [],
  380. targetLabels: ['test-provider'],
  381. });
  382. expect(cliProgress.SingleBar).not.toHaveBeenCalled();
  383. process.env.LOG_LEVEL = originalLogLevel;
  384. });
  385. });
  386. describe('API Health Check', () => {
  387. beforeEach(() => {
  388. jest.clearAllMocks();
  389. jest.mocked(shouldGenerateRemote).mockReturnValue(true);
  390. jest.mocked(getRemoteHealthUrl).mockReturnValue('https://api.test/health');
  391. jest.mocked(checkRemoteHealth).mockResolvedValue({
  392. status: 'OK',
  393. message: 'Cloud API is healthy',
  394. });
  395. });
  396. it('should check API health when remote generation is enabled', async () => {
  397. await synthesize({
  398. language: 'en',
  399. numTests: 1,
  400. plugins: [{ id: 'test-plugin', numTests: 1 }],
  401. prompts: ['Test prompt'],
  402. strategies: [],
  403. targetLabels: ['test-provider'],
  404. });
  405. expect(shouldGenerateRemote).toHaveBeenCalledWith();
  406. expect(getRemoteHealthUrl).toHaveBeenCalledWith();
  407. expect(checkRemoteHealth).toHaveBeenCalledWith('https://api.test/health');
  408. });
  409. it('should skip health check when remote generation is disabled', async () => {
  410. jest.mocked(shouldGenerateRemote).mockReturnValue(false);
  411. await synthesize({
  412. language: 'en',
  413. numTests: 1,
  414. plugins: [{ id: 'test-plugin', numTests: 1 }],
  415. prompts: ['Test prompt'],
  416. strategies: [],
  417. targetLabels: ['test-provider'],
  418. });
  419. expect(shouldGenerateRemote).toHaveBeenCalledWith();
  420. expect(getRemoteHealthUrl).not.toHaveBeenCalled();
  421. expect(checkRemoteHealth).not.toHaveBeenCalled();
  422. });
  423. it('should throw error when health check fails', async () => {
  424. jest.mocked(checkRemoteHealth).mockResolvedValue({
  425. status: 'ERROR',
  426. message: 'API is not accessible',
  427. });
  428. await expect(
  429. synthesize({
  430. language: 'en',
  431. numTests: 1,
  432. plugins: [{ id: 'test-plugin', numTests: 1 }],
  433. prompts: ['Test prompt'],
  434. strategies: [],
  435. targetLabels: ['test-provider'],
  436. }),
  437. ).rejects.toThrow('Unable to proceed with test generation: API is not accessible');
  438. });
  439. it('should skip health check when URL is null', async () => {
  440. jest.mocked(getRemoteHealthUrl).mockReturnValue(null);
  441. await synthesize({
  442. language: 'en',
  443. numTests: 1,
  444. plugins: [{ id: 'test-plugin', numTests: 1 }],
  445. prompts: ['Test prompt'],
  446. strategies: [],
  447. targetLabels: ['test-provider'],
  448. });
  449. expect(shouldGenerateRemote).toHaveBeenCalledWith();
  450. expect(getRemoteHealthUrl).toHaveBeenCalledWith();
  451. expect(checkRemoteHealth).not.toHaveBeenCalled();
  452. });
  453. });
  454. it('should handle basic strategy configuration', async () => {
  455. jest.mocked(loadApiProvider).mockResolvedValue({
  456. id: () => 'test',
  457. callApi: jest.fn().mockResolvedValue({ output: 'test output' }),
  458. });
  459. // Mock plugin to generate a test case
  460. const mockPlugin = {
  461. id: 'test-plugin',
  462. numTests: 1,
  463. };
  464. const mockProvider = {
  465. id: () => 'test',
  466. callApi: jest.fn().mockResolvedValue({ output: 'test output' }),
  467. };
  468. // Test with basic strategy enabled
  469. const resultEnabled = await synthesize({
  470. plugins: [mockPlugin],
  471. strategies: [{ id: 'basic', config: { enabled: true } }],
  472. prompts: ['test prompt'],
  473. injectVar: 'input',
  474. provider: mockProvider,
  475. language: 'en',
  476. numTests: 1,
  477. targetLabels: ['test-provider'],
  478. });
  479. expect(resultEnabled.testCases.length).toBeGreaterThan(0);
  480. // Test with basic strategy disabled
  481. const resultDisabled = await synthesize({
  482. plugins: [mockPlugin],
  483. strategies: [{ id: 'basic', config: { enabled: false } }],
  484. prompts: ['test prompt'],
  485. injectVar: 'input',
  486. provider: mockProvider,
  487. language: 'en',
  488. numTests: 1,
  489. targetLabels: ['test-provider'],
  490. });
  491. expect(resultDisabled.testCases).toHaveLength(0);
  492. });
  493. });
  494. jest.mock('fs');
  495. jest.mock('js-yaml');
  496. describe('resolvePluginConfig', () => {
  497. afterEach(() => {
  498. jest.resetAllMocks();
  499. });
  500. it('should return an empty object if config is undefined', () => {
  501. const result = resolvePluginConfig(undefined);
  502. expect(result).toEqual({});
  503. });
  504. it('should return the original config if no file references are present', () => {
  505. const config = { key: 'value' };
  506. const result = resolvePluginConfig(config);
  507. expect(result).toEqual(config);
  508. });
  509. it('should resolve YAML file references', () => {
  510. const config = { key: 'file://test.yaml' };
  511. const yamlContent = { nested: 'value' };
  512. jest.spyOn(fs, 'existsSync').mockReturnValue(true);
  513. jest.spyOn(fs, 'readFileSync').mockReturnValue('yaml content');
  514. jest.mocked(yaml.load).mockReturnValue(yamlContent);
  515. const result = resolvePluginConfig(config);
  516. expect(result).toEqual({ key: yamlContent });
  517. expect(fs.existsSync).toHaveBeenCalledWith('test.yaml');
  518. expect(fs.readFileSync).toHaveBeenCalledWith('test.yaml', 'utf8');
  519. expect(yaml.load).toHaveBeenCalledWith('yaml content');
  520. });
  521. it('should resolve JSON file references', () => {
  522. const config = { key: 'file://test.json' };
  523. const jsonContent = { nested: 'value' };
  524. jest.spyOn(fs, 'existsSync').mockReturnValue(true);
  525. jest.spyOn(fs, 'readFileSync').mockReturnValue(JSON.stringify(jsonContent));
  526. const result = resolvePluginConfig(config);
  527. expect(result).toEqual({ key: jsonContent });
  528. expect(fs.existsSync).toHaveBeenCalledWith('test.json');
  529. expect(fs.readFileSync).toHaveBeenCalledWith('test.json', 'utf8');
  530. });
  531. it('should resolve text file references', () => {
  532. const config = { key: 'file://test.txt' };
  533. const fileContent = 'text content';
  534. jest.spyOn(fs, 'existsSync').mockReturnValue(true);
  535. jest.spyOn(fs, 'readFileSync').mockReturnValue(fileContent);
  536. const result = resolvePluginConfig(config);
  537. expect(result).toEqual({ key: fileContent });
  538. expect(fs.existsSync).toHaveBeenCalledWith('test.txt');
  539. expect(fs.readFileSync).toHaveBeenCalledWith('test.txt', 'utf8');
  540. });
  541. it('should throw an error if the file does not exist', () => {
  542. const config = { key: 'file://nonexistent.yaml' };
  543. jest.spyOn(fs, 'existsSync').mockReturnValue(false);
  544. expect(() => resolvePluginConfig(config)).toThrow('File not found: nonexistent.yaml');
  545. });
  546. it('should handle multiple file references', () => {
  547. const config = {
  548. yaml: 'file://test.yaml',
  549. json: 'file://test.json',
  550. txt: 'file://test.txt',
  551. };
  552. const yamlContent = { nested: 'yaml' };
  553. const jsonContent = { nested: 'json' };
  554. const txtContent = 'text content';
  555. jest.spyOn(fs, 'existsSync').mockReturnValue(true);
  556. jest
  557. .spyOn(fs, 'readFileSync')
  558. .mockReturnValueOnce('yaml content')
  559. .mockReturnValueOnce(JSON.stringify(jsonContent))
  560. .mockReturnValueOnce(txtContent);
  561. jest.mocked(yaml.load).mockReturnValue(yamlContent);
  562. const result = resolvePluginConfig(config);
  563. expect(result).toEqual({
  564. yaml: yamlContent,
  565. json: jsonContent,
  566. txt: txtContent,
  567. });
  568. });
  569. });
  570. describe('calculateTotalTests', () => {
  571. const mockPlugins = [
  572. { id: 'plugin1', numTests: 2 },
  573. { id: 'plugin2', numTests: 3 },
  574. ];
  575. it('should calculate basic test counts with no strategies', () => {
  576. const result = calculateTotalTests(mockPlugins, []);
  577. expect(result).toEqual({
  578. totalTests: 5,
  579. totalPluginTests: 5,
  580. effectiveStrategyCount: 0,
  581. multilingualStrategy: undefined,
  582. includeBasicTests: true,
  583. });
  584. });
  585. it('should handle basic strategy when enabled', () => {
  586. const strategies = [{ id: 'basic', config: { enabled: true } }];
  587. const result = calculateTotalTests(mockPlugins, strategies);
  588. expect(result).toEqual({
  589. totalTests: 5,
  590. totalPluginTests: 5,
  591. effectiveStrategyCount: 1,
  592. multilingualStrategy: undefined,
  593. includeBasicTests: true,
  594. });
  595. });
  596. it('should handle basic strategy when disabled', () => {
  597. const strategies = [{ id: 'basic', config: { enabled: false } }];
  598. const result = calculateTotalTests(mockPlugins, strategies);
  599. expect(result).toEqual({
  600. totalTests: 0,
  601. totalPluginTests: 5,
  602. effectiveStrategyCount: 0,
  603. multilingualStrategy: undefined,
  604. includeBasicTests: false,
  605. });
  606. });
  607. it('should handle multilingual strategy with default languages', () => {
  608. const strategies = [{ id: 'multilingual' }];
  609. const result = calculateTotalTests(mockPlugins, strategies);
  610. expect(result).toEqual({
  611. totalTests: 5 * DEFAULT_LANGUAGES.length,
  612. totalPluginTests: 5,
  613. effectiveStrategyCount: 1,
  614. multilingualStrategy: strategies[0],
  615. includeBasicTests: true,
  616. });
  617. });
  618. it('should handle multilingual strategy with custom languages', () => {
  619. const strategies = [
  620. { id: 'multilingual', config: { languages: { en: true, es: true, fr: true } } },
  621. ];
  622. const result = calculateTotalTests(mockPlugins, strategies);
  623. expect(result).toEqual({
  624. totalTests: 15,
  625. totalPluginTests: 5,
  626. effectiveStrategyCount: 1,
  627. multilingualStrategy: strategies[0],
  628. includeBasicTests: true,
  629. });
  630. });
  631. it('should handle combination of basic and multilingual strategies', () => {
  632. const strategies = [
  633. { id: 'basic' },
  634. { id: 'multilingual', config: { languages: { en: true, es: true } } },
  635. ];
  636. const result = calculateTotalTests(mockPlugins, strategies);
  637. expect(result).toEqual({
  638. totalTests: 10,
  639. totalPluginTests: 5,
  640. effectiveStrategyCount: 2,
  641. includeBasicTests: true,
  642. multilingualStrategy: strategies[1],
  643. });
  644. });
  645. it('should handle retry strategy with default numTests', () => {
  646. const strategies = [{ id: 'retry' }];
  647. const result = calculateTotalTests(mockPlugins, strategies);
  648. expect(result).toEqual({
  649. totalTests: 10,
  650. totalPluginTests: 5,
  651. effectiveStrategyCount: 1,
  652. includeBasicTests: true,
  653. multilingualStrategy: undefined,
  654. });
  655. });
  656. it('should handle retry strategy with custom numTests', () => {
  657. const strategies = [{ id: 'retry', config: { numTests: 3 } }];
  658. const result = calculateTotalTests(mockPlugins, strategies);
  659. expect(result).toEqual({
  660. totalTests: 8,
  661. totalPluginTests: 5,
  662. effectiveStrategyCount: 1,
  663. includeBasicTests: true,
  664. multilingualStrategy: undefined,
  665. });
  666. });
  667. it('should handle retry strategy combined with other strategies', () => {
  668. const strategies = [
  669. { id: 'retry' },
  670. { id: 'multilingual', config: { languages: { en: true, es: true } } },
  671. ];
  672. const result = calculateTotalTests(mockPlugins, strategies);
  673. expect(result).toEqual({
  674. totalTests: 20,
  675. totalPluginTests: 5,
  676. effectiveStrategyCount: 2,
  677. includeBasicTests: true,
  678. multilingualStrategy: strategies[1],
  679. });
  680. });
  681. it('should correctly calculate total tests for multiple plugins with jailbreak strategy', () => {
  682. const plugins = Array(10).fill({ numTests: 5 });
  683. const strategies = [{ id: 'jailbreak' }];
  684. const result = calculateTotalTests(plugins, strategies);
  685. expect(result).toEqual({
  686. totalTests: 100,
  687. totalPluginTests: 50,
  688. effectiveStrategyCount: 1,
  689. includeBasicTests: true,
  690. multilingualStrategy: undefined,
  691. });
  692. });
  693. it('should add tests for each strategy instead of replacing the total', () => {
  694. const strategies = [{ id: 'morse' }, { id: 'piglatin' }];
  695. const result = calculateTotalTests(mockPlugins, strategies);
  696. expect(result).toEqual({
  697. totalTests: 15,
  698. totalPluginTests: 5,
  699. effectiveStrategyCount: 2,
  700. includeBasicTests: true,
  701. multilingualStrategy: undefined,
  702. });
  703. });
  704. it('should handle multiple strategies with multilingual applied last', () => {
  705. const strategies = [
  706. { id: 'morse' },
  707. { id: 'piglatin' },
  708. { id: 'multilingual', config: { languages: { en: true, es: true } } },
  709. ];
  710. const result = calculateTotalTests(mockPlugins, strategies);
  711. expect(result).toEqual({
  712. totalTests: 30,
  713. totalPluginTests: 5,
  714. effectiveStrategyCount: 3,
  715. includeBasicTests: true,
  716. multilingualStrategy: strategies[2],
  717. });
  718. });
  719. it('should handle multiple strategies with basic strategy disabled', () => {
  720. const strategies = [
  721. { id: 'basic', config: { enabled: false } },
  722. { id: 'morse' },
  723. { id: 'piglatin' },
  724. ];
  725. const result = calculateTotalTests(mockPlugins, strategies);
  726. expect(result).toEqual({
  727. totalTests: 10,
  728. totalPluginTests: 5,
  729. effectiveStrategyCount: 2,
  730. includeBasicTests: false,
  731. multilingualStrategy: undefined,
  732. });
  733. });
  734. });
  735. describe('getMultilingualRequestedCount', () => {
  736. const testCases = [
  737. { metadata: { pluginId: 'test1' } },
  738. { metadata: { pluginId: 'test2' } },
  739. ] as TestCaseWithPlugin[];
  740. it('should calculate count with custom languages array', () => {
  741. const strategy = {
  742. id: 'multilingual',
  743. config: { languages: ['en', 'es', 'fr'] },
  744. };
  745. const count = getMultilingualRequestedCount(testCases, strategy);
  746. expect(count).toBe(6);
  747. });
  748. it('should use DEFAULT_LANGUAGES when no languages config provided', () => {
  749. const strategy = { id: 'multilingual' };
  750. const count = getMultilingualRequestedCount(testCases, strategy);
  751. expect(count).toBe(2 * DEFAULT_LANGUAGES.length);
  752. });
  753. it('should handle empty languages array', () => {
  754. const strategy = {
  755. id: 'multilingual',
  756. config: { languages: [] },
  757. };
  758. const count = getMultilingualRequestedCount(testCases, strategy);
  759. expect(count).toBe(0);
  760. });
  761. it('should handle undefined config', () => {
  762. const strategy = { id: 'multilingual' };
  763. const count = getMultilingualRequestedCount(testCases, strategy);
  764. expect(count).toBe(2 * DEFAULT_LANGUAGES.length);
  765. });
  766. it('should handle empty test cases', () => {
  767. const strategy = {
  768. id: 'multilingual',
  769. config: { languages: ['en', 'es'] },
  770. };
  771. const count = getMultilingualRequestedCount([], strategy);
  772. expect(count).toBe(0);
  773. });
  774. });
  775. describe('getTestCount', () => {
  776. it('should return totalPluginTests when basic strategy is enabled', () => {
  777. const strategy = { id: 'basic', config: { enabled: true } };
  778. const result = getTestCount(strategy, 10, []);
  779. expect(result).toBe(10);
  780. });
  781. it('should return 0 when basic strategy is disabled', () => {
  782. const strategy = { id: 'basic', config: { enabled: false } };
  783. const result = getTestCount(strategy, 10, []);
  784. expect(result).toBe(0);
  785. });
  786. it('should multiply by number of languages for multilingual strategy', () => {
  787. const strategy = {
  788. id: 'multilingual',
  789. config: { languages: { en: true, es: true, fr: true } },
  790. };
  791. const result = getTestCount(strategy, 10, []);
  792. expect(result).toBe(30);
  793. });
  794. it('should add configured number of tests for retry strategy', () => {
  795. const strategy = { id: 'retry', config: { numTests: 5 } };
  796. const result = getTestCount(strategy, 10, []);
  797. expect(result).toBe(15);
  798. });
  799. it('should add totalPluginTests for retry strategy when numTests not specified', () => {
  800. const strategy = { id: 'retry' };
  801. const result = getTestCount(strategy, 10, []);
  802. expect(result).toBe(20);
  803. });
  804. it('should return totalPluginTests for other strategies', () => {
  805. const strategy = { id: 'morse' };
  806. const result = getTestCount(strategy, 10, []);
  807. expect(result).toBe(10);
  808. });
  809. });
Tip!

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

Comments

Loading...