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

simpleVideo.test.ts 6.6 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
  1. /**
  2. * Test file for simpleVideo strategy
  3. *
  4. * Tests core functionality with proper mocks to avoid depending on fs, ffmpeg, etc.
  5. */
  6. import fs from 'fs';
  7. import logger from '../../../src/logger';
  8. import {
  9. addVideoToBase64,
  10. createProgressBar,
  11. getFallbackBase64,
  12. writeVideoFile,
  13. } from '../../../src/redteam/strategies/simpleVideo';
  14. import type { TestCase } from '../../../src/types';
  15. // Mock for dummy video data
  16. const DUMMY_VIDEO_BASE64 = 'AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAu1tZGF0';
  17. // Mock video generator function
  18. const mockVideoGenerator = jest.fn().mockImplementation(() => {
  19. return Promise.resolve(DUMMY_VIDEO_BASE64);
  20. });
  21. // Mock required dependencies
  22. jest.mock('../../../src/logger', () => ({
  23. level: 'info',
  24. debug: jest.fn(),
  25. info: jest.fn(),
  26. warn: jest.fn(),
  27. error: jest.fn(),
  28. }));
  29. jest.mock('../../../src/cliState', () => ({
  30. webUI: false,
  31. }));
  32. jest.mock('fs', () => ({
  33. writeFileSync: jest.fn(),
  34. existsSync: jest.fn(),
  35. unlinkSync: jest.fn(),
  36. }));
  37. // Mock for progress bar
  38. jest.mock('cli-progress', () => ({
  39. SingleBar: jest.fn().mockImplementation(() => ({
  40. start: jest.fn(),
  41. increment: jest.fn(),
  42. stop: jest.fn(),
  43. })),
  44. Presets: { shades_classic: {} },
  45. }));
  46. describe('simpleVideo strategy', () => {
  47. beforeEach(() => {
  48. jest.clearAllMocks();
  49. mockVideoGenerator.mockClear();
  50. });
  51. describe('getFallbackBase64', () => {
  52. it('converts text to base64', () => {
  53. const input = 'Test text';
  54. const result = getFallbackBase64(input);
  55. // Decode the base64 and verify it matches the original text
  56. const decoded = Buffer.from(result, 'base64').toString();
  57. expect(decoded).toBe(input);
  58. });
  59. });
  60. describe('createProgressBar', () => {
  61. it('creates a progress bar with increment and stop methods', () => {
  62. const progressBar = createProgressBar(10);
  63. expect(progressBar).toHaveProperty('increment');
  64. expect(progressBar).toHaveProperty('stop');
  65. expect(typeof progressBar.increment).toBe('function');
  66. expect(typeof progressBar.stop).toBe('function');
  67. });
  68. it('handles errors when incrementing progress', () => {
  69. const progressBar = createProgressBar(10);
  70. // Call increment and make sure it doesn't throw an error
  71. expect(() => {
  72. progressBar.increment();
  73. }).not.toThrow();
  74. expect(logger.warn).not.toHaveBeenCalled();
  75. });
  76. it('handles errors when stopping progress', () => {
  77. const progressBar = createProgressBar(10);
  78. // Call stop and make sure it doesn't throw an error
  79. expect(() => {
  80. progressBar.stop();
  81. }).not.toThrow();
  82. expect(logger.warn).not.toHaveBeenCalled();
  83. });
  84. });
  85. describe('writeVideoFile', () => {
  86. it('writes a base64 video to a file', async () => {
  87. await writeVideoFile(DUMMY_VIDEO_BASE64, 'test.mp4');
  88. expect(fs.writeFileSync).toHaveBeenCalledWith('test.mp4', expect.any(Buffer));
  89. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Video file written to'));
  90. });
  91. it('throws an error if writing fails', async () => {
  92. const mockError = new Error('Write failed');
  93. jest.mocked(fs.writeFileSync).mockImplementationOnce(() => {
  94. throw mockError;
  95. });
  96. await expect(writeVideoFile(DUMMY_VIDEO_BASE64, 'test.mp4')).rejects.toThrow('Write failed');
  97. expect(logger.error).toHaveBeenCalledWith(
  98. expect.stringContaining('Failed to write video file'),
  99. );
  100. });
  101. });
  102. describe('addVideoToBase64', () => {
  103. it('processes test cases correctly using mock generator', async () => {
  104. // Create a test case
  105. const testCase: TestCase = {
  106. vars: {
  107. prompt: 'test prompt',
  108. },
  109. assert: [
  110. {
  111. type: 'promptfoo:redteam:test',
  112. metric: 'test-metric',
  113. },
  114. ],
  115. };
  116. // Process the test case
  117. const result = await addVideoToBase64([testCase], 'prompt', mockVideoGenerator);
  118. // Verify the structure and content of the result
  119. expect(result).toHaveLength(1);
  120. expect(result[0].vars?.prompt).toBe(DUMMY_VIDEO_BASE64);
  121. expect(result[0].vars?.video_text).toBe('test prompt');
  122. expect(result[0].metadata?.strategyId).toBe('video');
  123. expect(result[0].metadata?.originalText).toBe('test prompt');
  124. expect(result[0].assert?.[0].metric).toBe('test/Video-Encoded');
  125. // Verify the mock generator was called
  126. expect(mockVideoGenerator).toHaveBeenCalledTimes(1);
  127. });
  128. it('throws an error if vars is missing', async () => {
  129. const emptyTestCase = {} as TestCase;
  130. await expect(addVideoToBase64([emptyTestCase], 'prompt', mockVideoGenerator)).rejects.toThrow(
  131. 'Video encoding: testCase.vars is required',
  132. );
  133. });
  134. it('preserves non-redteam assertion metrics', async () => {
  135. const testCase: TestCase = {
  136. vars: {
  137. prompt: 'test prompt',
  138. },
  139. assert: [
  140. {
  141. // @ts-expect-error: Testing non-redteam type
  142. type: 'other',
  143. metric: 'test-metric',
  144. },
  145. ],
  146. };
  147. const result = await addVideoToBase64([testCase], 'prompt', mockVideoGenerator);
  148. expect(result[0].assert?.[0].metric).toBe('test-metric');
  149. });
  150. it('handles multiple test cases', async () => {
  151. const testCases: TestCase[] = [
  152. { vars: { prompt: 'test prompt 1' } },
  153. { vars: { prompt: 'test prompt 2' } },
  154. { vars: { prompt: 'test prompt 3' } },
  155. ];
  156. const result = await addVideoToBase64(testCases, 'prompt', mockVideoGenerator);
  157. expect(result).toHaveLength(3);
  158. expect(mockVideoGenerator).toHaveBeenCalledTimes(3);
  159. });
  160. it('logs debug messages when logger.level is debug', async () => {
  161. // Set logger level to debug
  162. Object.defineProperty(logger, 'level', { get: () => 'debug' });
  163. const testCase: TestCase = {
  164. vars: { prompt: 'test prompt' },
  165. };
  166. await addVideoToBase64([testCase], 'prompt', mockVideoGenerator);
  167. // Verify debug was called
  168. expect(logger.debug).toHaveBeenCalledWith('Processed 1 of 1');
  169. });
  170. it('handles errors during processing', async () => {
  171. const errorCase: TestCase = {
  172. vars: { prompt: 'error prompt' },
  173. };
  174. // Mock generator that throws an error
  175. const errorGenerator = jest.fn().mockImplementation(() => {
  176. throw new Error('Test error');
  177. });
  178. // Expect the function to reject with the error
  179. await expect(addVideoToBase64([errorCase], 'prompt', errorGenerator)).rejects.toThrow(
  180. 'Test error',
  181. );
  182. });
  183. });
  184. });
Tip!

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

Comments

Loading...