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
|
- import * as fs from 'fs';
- import * as yaml from 'js-yaml';
- import * as os from 'os';
- import path from 'path';
- import { doGenerateRedteam } from '../../src/redteam/commands/generate';
- import { doRedteamRun } from '../../src/redteam/shared';
- import { checkRemoteHealth } from '../../src/util/apiHealth';
- import { loadDefaultConfig } from '../../src/util/config/default';
- import FakeDataFactory from '../factories/data/fakeDataFactory';
- jest.mock('../../src/redteam/commands/generate');
- jest.mock('../../src/commands/eval', () => ({
- doEval: jest.fn().mockResolvedValue({
- table: [],
- version: 3,
- createdAt: new Date().toISOString(),
- results: {
- table: [],
- summary: {
- version: 3,
- stats: {
- successes: 0,
- failures: 0,
- tokenUsage: {},
- },
- },
- },
- }),
- }));
- jest.mock('../../src/util/apiHealth');
- jest.mock('../../src/util/config/default');
- jest.mock('../../src/logger', () => ({
- __esModule: true,
- default: {
- debug: jest.fn(),
- info: jest.fn(),
- warn: jest.fn(),
- error: jest.fn(),
- },
- setLogCallback: jest.fn(),
- setLogLevel: jest.fn(),
- }));
- jest.mock('../../src/globalConfig/accounts', () => ({
- getUserEmail: jest.fn(() => 'test@example.com'),
- setUserEmail: jest.fn(),
- getAuthor: jest.fn(() => 'test@example.com'),
- promptForEmailUnverified: jest.fn().mockResolvedValue(undefined),
- checkEmailStatusOrExit: jest.fn().mockResolvedValue(undefined),
- }));
- jest.mock('../../src/telemetry', () => ({
- record: jest.fn().mockResolvedValue(undefined),
- send: jest.fn().mockResolvedValue(undefined),
- saveConsent: jest.fn().mockResolvedValue(undefined),
- }));
- jest.mock('../../src/share', () => ({
- createShareableUrl: jest.fn().mockResolvedValue('http://example.com'),
- }));
- jest.mock('../../src/util', () => ({
- isRunningUnderNpx: jest.fn(() => false),
- setupEnv: jest.fn(),
- }));
- jest.mock('fs');
- jest.mock('js-yaml');
- jest.mock('os');
- describe('doRedteamRun', () => {
- const mockDate = new Date('2023-01-01T00:00:00.000Z');
- let dateNowSpy: jest.SpyInstance;
- beforeEach(() => {
- jest.resetAllMocks();
- dateNowSpy = jest.spyOn(Date, 'now').mockReturnValue(mockDate.getTime());
- jest.mocked(checkRemoteHealth).mockResolvedValue({ status: 'OK', message: 'Healthy' });
- jest.mocked(loadDefaultConfig).mockResolvedValue({
- defaultConfig: {},
- defaultConfigPath: 'promptfooconfig.yaml',
- });
- jest.mocked(fs.existsSync).mockReturnValue(true);
- jest.mocked(os.tmpdir).mockReturnValue('/tmp');
- jest.mocked(fs.mkdirSync).mockImplementation(() => '');
- jest.mocked(fs.writeFileSync).mockImplementation(() => {});
- jest.mocked(yaml.dump).mockReturnValue('mocked-yaml-content');
- jest.mocked(doGenerateRedteam).mockResolvedValue({});
- });
- afterEach(() => {
- jest.resetAllMocks();
- dateNowSpy.mockRestore();
- });
- it('should use default config path when not specified', async () => {
- await doRedteamRun({});
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- config: 'promptfooconfig.yaml',
- }),
- );
- });
- it('should use provided config path when specified', async () => {
- const customConfig = 'custom/config.yaml';
- await doRedteamRun({ config: customConfig });
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- config: customConfig,
- }),
- );
- });
- it('should use provided output path if specified', async () => {
- const outputPath = 'custom/output.yaml';
- await doRedteamRun({ output: outputPath });
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- output: outputPath,
- }),
- );
- });
- it('should locate the out file in the same directory as the config file if output is not specified', async () => {
- // Generate a random directory path
- const dirPath = FakeDataFactory.system.directoryPath();
- const customConfig = `${dirPath}/config.yaml`;
- await doRedteamRun({ config: customConfig });
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- config: customConfig,
- output: path.normalize(`${dirPath}/redteam.yaml`),
- }),
- );
- });
- describe('liveRedteamConfig temporary file handling', () => {
- const mockConfig = {
- prompts: ['Test prompt'],
- vars: {},
- providers: [{ id: 'test-provider' }],
- };
- it('should create timestamped temporary file in current directory when loadedFromCloud is true', async () => {
- await doRedteamRun({
- liveRedteamConfig: mockConfig,
- loadedFromCloud: true,
- });
- const expectedFilename = `redteam-${mockDate.getTime()}.yaml`;
- const expectedPath = path.join('', expectedFilename);
- expect(fs.mkdirSync).toHaveBeenCalledWith(path.dirname(expectedPath), { recursive: true });
- expect(fs.writeFileSync).toHaveBeenCalledWith(expectedPath, 'mocked-yaml-content');
- expect(yaml.dump).toHaveBeenCalledWith(mockConfig);
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- config: expectedPath,
- output: expectedPath,
- }),
- );
- });
- it('should create redteam.yaml file in system temp directory when loadedFromCloud is false', async () => {
- await doRedteamRun({
- liveRedteamConfig: mockConfig,
- loadedFromCloud: false,
- });
- const expectedPath = path.join('/tmp', 'redteam.yaml');
- const expectedFilePrefix = path.join('/tmp', 'redteam-');
- expect(os.tmpdir).toHaveBeenCalledWith();
- expect(fs.mkdirSync).toHaveBeenCalledWith(path.dirname(expectedPath), { recursive: true });
- expect(fs.writeFileSync).toHaveBeenCalledWith(
- expect.stringContaining(expectedFilePrefix),
- 'mocked-yaml-content',
- );
- expect(yaml.dump).toHaveBeenCalledWith(mockConfig);
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- config: expect.stringContaining(expectedFilePrefix),
- output: expect.stringContaining(expectedFilePrefix),
- }),
- );
- });
- it('should create redteam.yaml file in system temp directory when loadedFromCloud is undefined', async () => {
- await doRedteamRun({
- liveRedteamConfig: mockConfig,
- // loadedFromCloud is undefined
- });
- const expectedPath = path.join('/tmp', 'redteam.yaml');
- const expectedFilePrefix = path.join('/tmp', 'redteam-');
- expect(os.tmpdir).toHaveBeenCalledWith();
- expect(fs.mkdirSync).toHaveBeenCalledWith(path.dirname(expectedPath), { recursive: true });
- expect(fs.writeFileSync).toHaveBeenCalledWith(
- expect.stringContaining(expectedFilePrefix),
- 'mocked-yaml-content',
- );
- expect(yaml.dump).toHaveBeenCalledWith(mockConfig);
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- config: expect.stringContaining(expectedFilePrefix),
- output: expect.stringContaining(expectedFilePrefix),
- }),
- );
- });
- it('should generate unique timestamped filenames when loadedFromCloud is true', async () => {
- const firstTimestamp = mockDate.getTime();
- const secondTimestamp = firstTimestamp + 1000;
- // First call
- await doRedteamRun({
- liveRedteamConfig: mockConfig,
- loadedFromCloud: true,
- });
- // Update mock timestamp for second call
- dateNowSpy.mockReturnValue(secondTimestamp);
- // Second call
- await doRedteamRun({
- liveRedteamConfig: mockConfig,
- loadedFromCloud: true,
- });
- const firstExpectedPath = path.join('', `redteam-${firstTimestamp}.yaml`);
- const secondExpectedPath = path.join('', `redteam-${secondTimestamp}.yaml`);
- // Verify different filenames were generated
- expect(fs.writeFileSync).toHaveBeenNthCalledWith(1, firstExpectedPath, 'mocked-yaml-content');
- expect(fs.writeFileSync).toHaveBeenNthCalledWith(
- 2,
- secondExpectedPath,
- 'mocked-yaml-content',
- );
- });
- it('should use liveRedteamConfig.commandLineOptions when provided', async () => {
- const mockConfigWithOptions = {
- ...mockConfig,
- commandLineOptions: {
- verbose: true,
- delay: 500,
- },
- };
- await doRedteamRun({
- liveRedteamConfig: mockConfigWithOptions,
- loadedFromCloud: true,
- });
- expect(doGenerateRedteam).toHaveBeenCalledWith(
- expect.objectContaining({
- liveRedteamConfig: {
- ...mockConfig,
- commandLineOptions: {
- verbose: true,
- delay: 500,
- },
- },
- }),
- );
- });
- it('should log debug information when processing liveRedteamConfig', async () => {
- // Get the mocked logger
- const mockLogger = jest.requireMock('../../src/logger').default;
- await doRedteamRun({
- liveRedteamConfig: mockConfig,
- loadedFromCloud: true,
- });
- const expectedFilename = `redteam-${mockDate.getTime()}.yaml`;
- const expectedPath = path.join('', expectedFilename);
- expect(mockLogger.debug).toHaveBeenCalledWith(`Using live config from ${expectedPath}`);
- expect(mockLogger.debug).toHaveBeenCalledWith(
- `Live config: ${JSON.stringify(mockConfig, null, 2)}`,
- );
- });
- });
- });
|