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

pythonUtils.test.ts 18 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
  1. import fs from 'fs';
  2. import path from 'path';
  3. import { Readable, Writable } from 'stream';
  4. import type { ChildProcess } from 'child_process';
  5. import { PythonShell } from 'python-shell';
  6. import { getEnvBool, getEnvString } from '../../src/envars';
  7. import logger from '../../src/logger';
  8. import { execAsync } from '../../src/python/execAsync';
  9. import * as pythonUtils from '../../src/python/pythonUtils';
  10. // Mock setup
  11. jest.mock('fs', () => ({
  12. writeFileSync: jest.fn(),
  13. readFileSync: jest.fn(),
  14. unlinkSync: jest.fn(),
  15. }));
  16. jest.mock('../../src/envars', () => ({
  17. getEnvString: jest.fn(),
  18. getEnvBool: jest.fn(),
  19. }));
  20. jest.mock('../../src/python/execAsync', () => ({
  21. execAsync: jest.fn(),
  22. }));
  23. const mockPythonShellInstance = {
  24. stdout: { on: jest.fn() },
  25. stderr: { on: jest.fn() },
  26. end: jest.fn(),
  27. };
  28. jest.mock('python-shell', () => ({
  29. PythonShell: jest.fn(() => mockPythonShellInstance),
  30. }));
  31. // Test utilities
  32. function createMockChildProcess(): Partial<ChildProcess> {
  33. const dummyWritable = new Writable();
  34. const dummyReadable = new Readable({ read() {} });
  35. return {
  36. stdin: dummyWritable,
  37. stdout: dummyReadable,
  38. stderr: dummyReadable,
  39. stdio: [dummyWritable, dummyReadable, dummyReadable, null, null],
  40. pid: 1234,
  41. connected: false,
  42. kill: jest.fn(),
  43. send: jest.fn(),
  44. disconnect: jest.fn(),
  45. unref: jest.fn(),
  46. ref: jest.fn(),
  47. addListener: jest.fn(),
  48. emit: jest.fn(),
  49. on: jest.fn(),
  50. once: jest.fn(),
  51. prependListener: jest.fn(),
  52. prependOnceListener: jest.fn(),
  53. removeAllListeners: jest.fn(),
  54. removeListener: jest.fn(),
  55. eventNames: jest.fn(),
  56. getMaxListeners: jest.fn(),
  57. listenerCount: jest.fn(),
  58. listeners: jest.fn(),
  59. off: jest.fn(),
  60. rawListeners: jest.fn(),
  61. setMaxListeners: jest.fn(),
  62. };
  63. }
  64. describe('Python Utils', () => {
  65. beforeEach(() => {
  66. jest.clearAllMocks();
  67. jest.mocked(execAsync).mockReset();
  68. pythonUtils.state.cachedPythonPath = null;
  69. pythonUtils.state.validationPromise = null;
  70. // Set default mock return values
  71. jest.mocked(getEnvString).mockReturnValue('');
  72. jest.mocked(getEnvBool).mockReturnValue(false);
  73. });
  74. describe('tryPath', () => {
  75. describe('successful path validation', () => {
  76. it('should return the path for a valid Python 3 executable', async () => {
  77. jest.mocked(execAsync).mockResolvedValue({
  78. stdout: 'Python 3.8.10\n',
  79. stderr: '',
  80. child: createMockChildProcess() as ChildProcess,
  81. });
  82. const result = await pythonUtils.tryPath('/usr/bin/python3');
  83. expect(result).toBe('/usr/bin/python3');
  84. expect(execAsync).toHaveBeenCalledWith('/usr/bin/python3 --version');
  85. });
  86. });
  87. describe('failed path validation', () => {
  88. it('should return null for a non-existent executable', async () => {
  89. jest.mocked(execAsync).mockRejectedValue(new Error('Command failed'));
  90. const result = await pythonUtils.tryPath('/usr/bin/nonexistent');
  91. expect(result).toBeNull();
  92. expect(execAsync).toHaveBeenCalledWith('/usr/bin/nonexistent --version');
  93. });
  94. it('should return null if the command times out', async () => {
  95. jest.useFakeTimers();
  96. const mockChildProcess = createMockChildProcess() as ChildProcess;
  97. const execPromise = new Promise<{ stdout: string; stderr: string; child: ChildProcess }>(
  98. (resolve) => {
  99. setTimeout(() => {
  100. resolve({
  101. stdout: 'Python 3.8.10\n',
  102. stderr: '',
  103. child: mockChildProcess,
  104. });
  105. }, 3000);
  106. },
  107. );
  108. jest.mocked(execAsync).mockReturnValue(execPromise as any);
  109. const resultPromise = pythonUtils.tryPath('/usr/bin/python3');
  110. jest.advanceTimersByTime(2501);
  111. const result = await resultPromise;
  112. expect(result).toBeNull();
  113. expect(execAsync).toHaveBeenCalledWith('/usr/bin/python3 --version');
  114. jest.useRealTimers();
  115. });
  116. });
  117. });
  118. describe('validatePythonPath', () => {
  119. describe('caching behavior', () => {
  120. it('should validate and cache an existing Python 3 path', async () => {
  121. jest.mocked(execAsync).mockResolvedValue({
  122. stdout: 'Python 3.8.10\n',
  123. stderr: '',
  124. child: createMockChildProcess() as ChildProcess,
  125. });
  126. const result = await pythonUtils.validatePythonPath('python', false);
  127. expect(result).toBe('python');
  128. expect(pythonUtils.state.cachedPythonPath).toBe('python');
  129. expect(execAsync).toHaveBeenCalledWith('python --version');
  130. });
  131. it('should return the cached path on subsequent calls', async () => {
  132. pythonUtils.state.cachedPythonPath = '/usr/bin/python3';
  133. const result = await pythonUtils.validatePythonPath('python', false);
  134. expect(result).toBe('/usr/bin/python3');
  135. expect(execAsync).not.toHaveBeenCalled();
  136. });
  137. });
  138. describe('fallback behavior', () => {
  139. it('should fall back to alternative paths for non-existent programs when not explicit', async () => {
  140. jest.mocked(execAsync).mockReset();
  141. jest
  142. .mocked(execAsync)
  143. .mockRejectedValueOnce(new Error('Command failed'))
  144. .mockResolvedValueOnce({
  145. stdout: 'Python 3.9.5\n',
  146. stderr: '',
  147. child: createMockChildProcess() as ChildProcess,
  148. });
  149. const result = await pythonUtils.validatePythonPath('non_existent_program', false);
  150. expect(result).toBe(process.platform === 'win32' ? 'py -3' : 'python3');
  151. expect(execAsync).toHaveBeenCalledTimes(2);
  152. });
  153. it('should throw an error for non-existent programs when explicit', async () => {
  154. jest.mocked(execAsync).mockRejectedValue(new Error('Command failed'));
  155. await expect(pythonUtils.validatePythonPath('non_existent_program', true)).rejects.toThrow(
  156. 'Python 3 not found. Tried "non_existent_program"',
  157. );
  158. expect(execAsync).toHaveBeenCalledWith('non_existent_program --version');
  159. });
  160. it('should throw an error when no valid Python path is found', async () => {
  161. jest.mocked(execAsync).mockReset();
  162. jest.mocked(execAsync).mockRejectedValue(new Error('Command failed'));
  163. await expect(pythonUtils.validatePythonPath('python', false)).rejects.toThrow(
  164. 'Python 3 not found. Tried "python" and',
  165. );
  166. expect(execAsync).toHaveBeenCalledTimes(2);
  167. });
  168. });
  169. describe('environment variable handling', () => {
  170. it('should use PROMPTFOO_PYTHON environment variable when provided', async () => {
  171. jest.mocked(getEnvString).mockReturnValue('/custom/python/path');
  172. jest.mocked(execAsync).mockResolvedValue({
  173. stdout: 'Python 3.8.10\n',
  174. stderr: '',
  175. child: createMockChildProcess() as ChildProcess,
  176. });
  177. const result = await pythonUtils.validatePythonPath('/custom/python/path', true);
  178. expect(result).toBe('/custom/python/path');
  179. expect(execAsync).toHaveBeenCalledWith('/custom/python/path --version');
  180. });
  181. });
  182. describe('concurrent validation', () => {
  183. it('should share validation promise between concurrent calls', async () => {
  184. jest.mocked(execAsync).mockResolvedValue({
  185. stdout: 'Python 3.8.10\n',
  186. stderr: '',
  187. child: createMockChildProcess() as ChildProcess,
  188. });
  189. const promise1 = pythonUtils.validatePythonPath('python', false);
  190. const promise2 = pythonUtils.validatePythonPath('python', false);
  191. // Both should resolve to the same value
  192. const [result1, result2] = await Promise.all([promise1, promise2]);
  193. expect(result1).toBe('python');
  194. expect(result2).toBe('python');
  195. // Only one exec call should be made
  196. expect(execAsync).toHaveBeenCalledTimes(1);
  197. // After resolution, validation promise should be cleared
  198. expect(pythonUtils.state.validationPromise).toBeNull();
  199. });
  200. it('should handle race conditions between concurrent validation attempts', async () => {
  201. const mockChildProcess = createMockChildProcess() as ChildProcess;
  202. let firstResolve:
  203. | ((value: { stdout: string; stderr: string; child: ChildProcess }) => void)
  204. | undefined;
  205. const firstPromise = new Promise<{ stdout: string; stderr: string; child: ChildProcess }>(
  206. (resolve) => {
  207. firstResolve = resolve;
  208. },
  209. );
  210. jest.mocked(execAsync).mockReturnValueOnce(firstPromise as any);
  211. const promise1 = pythonUtils.validatePythonPath('python', false);
  212. const promise2 = pythonUtils.validatePythonPath('python', false);
  213. // Resolve the first promise
  214. if (firstResolve) {
  215. firstResolve({
  216. stdout: 'Python 3.8.0\n',
  217. stderr: '',
  218. child: mockChildProcess,
  219. });
  220. }
  221. const [result1, result2] = await Promise.all([promise1, promise2]);
  222. // Both should get the same result
  223. expect(result1).toBe('python');
  224. expect(result2).toBe('python');
  225. // Only one exec call should be made
  226. expect(execAsync).toHaveBeenCalledTimes(1);
  227. // After resolution, validation promise should be cleared
  228. expect(pythonUtils.state.validationPromise).toBeNull();
  229. });
  230. });
  231. describe('promise cleanup', () => {
  232. it('should clear validation promise after successful validation', async () => {
  233. jest.mocked(execAsync).mockResolvedValue({
  234. stdout: 'Python 3.8.10\n',
  235. stderr: '',
  236. child: createMockChildProcess() as ChildProcess,
  237. });
  238. await pythonUtils.validatePythonPath('python', false);
  239. expect(pythonUtils.state.validationPromise).toBeNull();
  240. });
  241. it('should clear validation promise after failed validation', async () => {
  242. jest.mocked(execAsync).mockRejectedValue(new Error('Command failed'));
  243. await expect(pythonUtils.validatePythonPath('python', true)).rejects.toThrow(
  244. 'Python 3 not found. Tried "python"',
  245. );
  246. expect(pythonUtils.state.validationPromise).toBeNull();
  247. });
  248. });
  249. });
  250. describe('runPython', () => {
  251. beforeEach(() => {
  252. pythonUtils.state.cachedPythonPath = '/usr/bin/python3';
  253. jest.clearAllMocks();
  254. });
  255. describe('successful execution', () => {
  256. it('should correctly run a Python script with provided arguments and read the output file', async () => {
  257. const mockOutput = JSON.stringify({ type: 'final_result', data: 'test result' });
  258. jest.mocked(fs.writeFileSync).mockImplementation();
  259. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  260. jest.mocked(fs.unlinkSync).mockImplementation();
  261. mockPythonShellInstance.end.mockImplementation((callback: any) => callback());
  262. const result = await pythonUtils.runPython('testScript.py', 'testMethod', [
  263. 'arg1',
  264. { key: 'value' },
  265. ]);
  266. expect(result).toBe('test result');
  267. expect(PythonShell).toHaveBeenCalledWith(
  268. 'wrapper.py',
  269. expect.objectContaining({
  270. args: expect.arrayContaining([
  271. expect.stringContaining('testScript.py'),
  272. 'testMethod',
  273. expect.stringContaining('promptfoo-python-input-json'),
  274. expect.stringContaining('promptfoo-python-output-json'),
  275. ]),
  276. }),
  277. );
  278. expect(fs.writeFileSync).toHaveBeenCalledWith(
  279. expect.stringContaining('promptfoo-python-input-json'),
  280. expect.any(String),
  281. 'utf-8',
  282. );
  283. expect(fs.readFileSync).toHaveBeenCalledWith(
  284. expect.stringContaining('promptfoo-python-output-json'),
  285. 'utf-8',
  286. );
  287. expect(fs.unlinkSync).toHaveBeenCalledTimes(2);
  288. });
  289. it('should handle undefined result data gracefully', async () => {
  290. const mockOutput = JSON.stringify({
  291. type: 'final_result',
  292. data: undefined,
  293. });
  294. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  295. mockPythonShellInstance.end.mockImplementation((callback: any) => callback());
  296. const result = await pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']);
  297. expect(result).toBeUndefined();
  298. expect(logger.debug).toHaveBeenCalledWith(
  299. expect.stringContaining(
  300. `Python script ${path.resolve('testScript.py')} parsed output type: object, structure: ["type"]`,
  301. ),
  302. );
  303. });
  304. });
  305. describe('logging and output handling', () => {
  306. it('should log stdout and stderr', async () => {
  307. const mockOutput = JSON.stringify({ type: 'final_result', data: 'test result' });
  308. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  309. let stdoutCallback: ((chunk: Buffer) => void) | null = null;
  310. let stderrCallback: ((chunk: Buffer) => void) | null = null;
  311. mockPythonShellInstance.stdout.on.mockImplementation((event: string, callback: any) => {
  312. if (event === 'data') {
  313. stdoutCallback = callback;
  314. }
  315. });
  316. mockPythonShellInstance.stderr.on.mockImplementation((event: string, callback: any) => {
  317. if (event === 'data') {
  318. stderrCallback = callback;
  319. }
  320. });
  321. mockPythonShellInstance.end.mockImplementation((callback: any) => {
  322. if (stdoutCallback) {
  323. stdoutCallback(Buffer.from('stdout message'));
  324. }
  325. if (stderrCallback) {
  326. stderrCallback(Buffer.from('stderr message'));
  327. }
  328. callback();
  329. });
  330. await pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']);
  331. expect(logger.debug).toHaveBeenCalledWith('stdout message');
  332. expect(logger.error).toHaveBeenCalledWith('stderr message');
  333. });
  334. it('should log debug messages about parsed output type and structure', async () => {
  335. const mockOutput = JSON.stringify({
  336. type: 'final_result',
  337. data: { key1: 'value1', key2: 'value2' },
  338. });
  339. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  340. mockPythonShellInstance.end.mockImplementation((callback: any) => callback());
  341. await pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']);
  342. expect(logger.debug).toHaveBeenCalledWith(
  343. expect.stringContaining(
  344. `Python script ${path.resolve('testScript.py')} parsed output type: object`,
  345. ),
  346. );
  347. });
  348. });
  349. describe('error handling', () => {
  350. it('should throw an error if the Python script execution fails', async () => {
  351. const mockError = new Error('Test Error');
  352. mockPythonShellInstance.end.mockImplementation((callback: any) => callback(mockError));
  353. await expect(
  354. pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']),
  355. ).rejects.toThrow('Error running Python script: Test Error');
  356. });
  357. it('should handle Python script returning incorrect result type', async () => {
  358. const mockOutput = JSON.stringify({ type: 'unexpected_result', data: 'test result' });
  359. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  360. mockPythonShellInstance.end.mockImplementation((callback: any) => callback());
  361. await expect(
  362. pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']),
  363. ).rejects.toThrow(
  364. 'The Python script `call_api` function must return a dict with an `output`',
  365. );
  366. });
  367. it('should handle invalid JSON in the output file', async () => {
  368. jest.mocked(fs.readFileSync).mockReturnValue('Invalid JSON');
  369. mockPythonShellInstance.end.mockImplementation((callback: any) => callback());
  370. await expect(
  371. pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']),
  372. ).rejects.toThrow('Invalid JSON:');
  373. });
  374. it('should log and throw an error with stack trace when Python script execution fails', async () => {
  375. const mockError = new Error('Test Error');
  376. mockError.stack = '--- Python Traceback ---\nError details';
  377. mockPythonShellInstance.end.mockImplementation((callback: any) => callback(mockError));
  378. await expect(
  379. pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']),
  380. ).rejects.toThrow(
  381. 'Error running Python script: Test Error\nStack Trace: Python Traceback: \nError details',
  382. );
  383. expect(logger.error).toHaveBeenCalledWith(
  384. 'Error running Python script: Test Error\nStack Trace: Python Traceback: \nError details',
  385. );
  386. });
  387. it('should handle error without stack trace', async () => {
  388. const mockError = new Error('Test Error Without Stack');
  389. mockError.stack = undefined;
  390. mockPythonShellInstance.end.mockImplementation((callback: any) => callback(mockError));
  391. await expect(
  392. pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']),
  393. ).rejects.toThrow(
  394. 'Error running Python script: Test Error Without Stack\nStack Trace: No Python traceback available',
  395. );
  396. expect(logger.error).toHaveBeenCalledWith(
  397. 'Error running Python script: Test Error Without Stack\nStack Trace: No Python traceback available',
  398. );
  399. });
  400. });
  401. describe('file handling', () => {
  402. it('should log an error when unable to remove temporary files', async () => {
  403. const mockOutput = JSON.stringify({ type: 'final_result', data: 'test result' });
  404. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  405. mockPythonShellInstance.end.mockImplementation((callback: any) => callback());
  406. jest.mocked(fs.unlinkSync).mockImplementation(() => {
  407. throw new Error('Unable to delete file');
  408. });
  409. await pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']);
  410. expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('Error removing'));
  411. });
  412. });
  413. });
  414. });
Tip!

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

Comments

Loading...