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 11 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
  1. import fs from 'fs';
  2. import { PythonShell } from 'python-shell';
  3. import { getEnvString } from '../../src/envars';
  4. import logger from '../../src/logger';
  5. import { execAsync } from '../../src/python/execAsync';
  6. import * as pythonUtils from '../../src/python/pythonUtils';
  7. jest.mock('fs', () => ({
  8. writeFileSync: jest.fn(),
  9. readFileSync: jest.fn(),
  10. unlinkSync: jest.fn(),
  11. }));
  12. jest.mock('python-shell', () => ({
  13. PythonShell: {
  14. run: jest.fn(),
  15. },
  16. }));
  17. jest.mock('../../src/logger', () => ({
  18. default: {
  19. debug: jest.fn(),
  20. error: jest.fn(),
  21. },
  22. debug: jest.fn(),
  23. error: jest.fn(),
  24. }));
  25. jest.mock('../../src/envars', () => ({
  26. getEnvString: jest.fn(),
  27. }));
  28. jest.mock('../../src/python/execAsync', () => ({
  29. execAsync: jest.fn(),
  30. }));
  31. const mockPythonShellInstance = {
  32. stdout: { on: jest.fn() },
  33. stderr: { on: jest.fn() },
  34. end: jest.fn(),
  35. };
  36. jest.mock('python-shell', () => ({
  37. PythonShell: jest.fn(() => mockPythonShellInstance),
  38. }));
  39. describe('pythonUtils', () => {
  40. beforeEach(() => {
  41. jest.clearAllMocks();
  42. pythonUtils.state.cachedPythonPath = null;
  43. });
  44. describe('tryPath', () => {
  45. it('should return the path for a valid Python 3 executable', async () => {
  46. jest.mocked(execAsync).mockResolvedValue({
  47. stdout: 'Python 3.8.10\n',
  48. stderr: '',
  49. });
  50. const result = await pythonUtils.tryPath('/usr/bin/python3');
  51. expect(result).toBe('/usr/bin/python3');
  52. expect(execAsync).toHaveBeenCalledWith('/usr/bin/python3 --version');
  53. });
  54. it('should return null for a non-existent executable', async () => {
  55. jest.mocked(execAsync).mockRejectedValue(new Error('Command failed'));
  56. const result = await pythonUtils.tryPath('/usr/bin/nonexistent');
  57. expect(result).toBeNull();
  58. expect(execAsync).toHaveBeenCalledWith('/usr/bin/nonexistent --version');
  59. });
  60. it('should return null if the command times out', async () => {
  61. jest.useFakeTimers();
  62. jest.mocked(execAsync).mockImplementation(() => {
  63. const promise = new Promise((resolve) => {
  64. setTimeout(() => resolve({ stdout: 'Python 3.8.10\n', stderr: '' }), 500);
  65. }) as any;
  66. promise.child = { kill: jest.fn() };
  67. return promise;
  68. });
  69. const resultPromise = pythonUtils.tryPath('/usr/bin/python3');
  70. jest.advanceTimersByTime(251);
  71. const result = await resultPromise;
  72. expect(result).toBeNull();
  73. expect(execAsync).toHaveBeenCalledWith('/usr/bin/python3 --version');
  74. jest.useRealTimers();
  75. });
  76. });
  77. describe('validatePythonPath', () => {
  78. it('should validate an existing Python 3 path', async () => {
  79. jest.mocked(execAsync).mockResolvedValue({
  80. stdout: 'Python 3.8.10\n',
  81. stderr: '',
  82. });
  83. const result = await pythonUtils.validatePythonPath('python', false);
  84. expect(result).toBe('python');
  85. expect(pythonUtils.state.cachedPythonPath).toBe('python');
  86. expect(execAsync).toHaveBeenCalledWith('python --version');
  87. });
  88. it('should return the cached path on subsequent calls', async () => {
  89. pythonUtils.state.cachedPythonPath = '/usr/bin/python3';
  90. const result = await pythonUtils.validatePythonPath('python', false);
  91. expect(result).toBe('/usr/bin/python3');
  92. });
  93. it('should fall back to alternative paths for non-existent programs when not explicit', async () => {
  94. jest
  95. .mocked(execAsync)
  96. .mockRejectedValueOnce(new Error('Command failed'))
  97. .mockResolvedValueOnce({ stdout: 'Python 3.9.5\n', stderr: '' });
  98. const result = await pythonUtils.validatePythonPath('non_existent_program', false);
  99. expect(result).toBe(process.platform === 'win32' ? 'py -3' : 'python3');
  100. expect(execAsync).toHaveBeenCalledTimes(2);
  101. });
  102. it('should throw an error for non-existent programs when explicit', async () => {
  103. jest.mocked(execAsync).mockRejectedValue(new Error('Command failed'));
  104. await expect(pythonUtils.validatePythonPath('non_existent_program', true)).rejects.toThrow(
  105. /Python 3 not found\. Tried "non_existent_program"/,
  106. );
  107. expect(execAsync).toHaveBeenCalledWith('non_existent_program --version');
  108. });
  109. it('should throw an error when no valid Python path is found', async () => {
  110. jest.mocked(execAsync).mockRejectedValue(new Error('Command failed'));
  111. await expect(pythonUtils.validatePythonPath('python', false)).rejects.toThrow(
  112. /Python 3 not found\. Tried "python" and ".+"/,
  113. );
  114. expect(execAsync).toHaveBeenCalledTimes(2);
  115. });
  116. it('should use PROMPTFOO_PYTHON environment variable when provided', async () => {
  117. jest.mocked(getEnvString).mockReturnValue('/custom/python/path');
  118. jest.mocked(execAsync).mockResolvedValue({
  119. stdout: 'Python 3.8.10\n',
  120. stderr: '',
  121. });
  122. const result = await pythonUtils.validatePythonPath('/custom/python/path', true);
  123. expect(result).toBe('/custom/python/path');
  124. expect(execAsync).toHaveBeenCalledWith('/custom/python/path --version');
  125. });
  126. });
  127. describe('runPython', () => {
  128. beforeEach(() => {
  129. pythonUtils.state.cachedPythonPath = '/usr/bin/python3';
  130. jest.clearAllMocks();
  131. });
  132. it('should correctly run a Python script with provided arguments and read the output file', async () => {
  133. const mockOutput = JSON.stringify({ type: 'final_result', data: 'test result' });
  134. jest.mocked(fs.writeFileSync).mockImplementation();
  135. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  136. jest.mocked(fs.unlinkSync).mockImplementation();
  137. mockPythonShellInstance.end.mockImplementation((callback) => callback());
  138. const result = await pythonUtils.runPython('testScript.py', 'testMethod', [
  139. 'arg1',
  140. { key: 'value' },
  141. ]);
  142. expect(result).toBe('test result');
  143. expect(PythonShell).toHaveBeenCalledWith(
  144. 'wrapper.py',
  145. expect.objectContaining({
  146. args: expect.arrayContaining([
  147. expect.stringContaining('testScript.py'),
  148. 'testMethod',
  149. expect.stringContaining('promptfoo-python-input-json'),
  150. expect.stringContaining('promptfoo-python-output-json'),
  151. ]),
  152. }),
  153. );
  154. expect(fs.writeFileSync).toHaveBeenCalledWith(
  155. expect.stringContaining('promptfoo-python-input-json'),
  156. expect.any(String),
  157. 'utf-8',
  158. );
  159. expect(fs.readFileSync).toHaveBeenCalledWith(
  160. expect.stringContaining('promptfoo-python-output-json'),
  161. 'utf-8',
  162. );
  163. expect(fs.unlinkSync).toHaveBeenCalledTimes(2);
  164. });
  165. it('should log stdout and stderr', async () => {
  166. const mockOutput = JSON.stringify({ type: 'final_result', data: 'test result' });
  167. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  168. let stdoutCallback: ((chunk: Buffer) => void) | null = null;
  169. let stderrCallback: ((chunk: Buffer) => void) | null = null;
  170. mockPythonShellInstance.stdout.on.mockImplementation((event, callback) => {
  171. if (event === 'data') {
  172. stdoutCallback = callback;
  173. }
  174. });
  175. mockPythonShellInstance.stderr.on.mockImplementation((event, callback) => {
  176. if (event === 'data') {
  177. stderrCallback = callback;
  178. }
  179. });
  180. mockPythonShellInstance.end.mockImplementation((callback) => {
  181. if (stdoutCallback) {
  182. stdoutCallback(Buffer.from('stdout message'));
  183. }
  184. if (stderrCallback) {
  185. stderrCallback(Buffer.from('stderr message'));
  186. }
  187. callback();
  188. });
  189. await pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']);
  190. expect(logger.debug).toHaveBeenCalledWith('stdout message');
  191. expect(logger.error).toHaveBeenCalledWith('stderr message');
  192. });
  193. it('should throw an error if the Python script execution fails', async () => {
  194. const mockError = new Error('Test Error');
  195. mockPythonShellInstance.end.mockImplementation((callback) => callback(mockError));
  196. await expect(pythonUtils.runPython('testScript.py', 'testMethod', ['arg1'])).rejects.toThrow(
  197. 'Error running Python script: Test Error',
  198. );
  199. });
  200. it('should handle Python script returning incorrect result type', async () => {
  201. const mockOutput = JSON.stringify({ type: 'unexpected_result', data: 'test result' });
  202. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  203. mockPythonShellInstance.end.mockImplementation((callback) => callback());
  204. await expect(pythonUtils.runPython('testScript.py', 'testMethod', ['arg1'])).rejects.toThrow(
  205. 'The Python script `call_api` function must return a dict with an `output`',
  206. );
  207. });
  208. it('should handle invalid JSON in the output file', async () => {
  209. jest.mocked(fs.readFileSync).mockReturnValue('Invalid JSON');
  210. mockPythonShellInstance.end.mockImplementation((callback) => callback());
  211. await expect(pythonUtils.runPython('testScript.py', 'testMethod', ['arg1'])).rejects.toThrow(
  212. 'Invalid JSON:',
  213. );
  214. });
  215. it('should log and throw an error with stack trace when Python script execution fails', async () => {
  216. const mockError = new Error('Test Error');
  217. mockError.stack = '--- Python Traceback ---\nError details';
  218. mockPythonShellInstance.end.mockImplementation((callback) => callback(mockError));
  219. await expect(pythonUtils.runPython('testScript.py', 'testMethod', ['arg1'])).rejects.toThrow(
  220. 'Error running Python script: Test Error\nStack Trace: Python Traceback: \nError details',
  221. );
  222. expect(logger.error).toHaveBeenCalledWith(
  223. 'Error running Python script: Test Error\nStack Trace: Python Traceback: \nError details',
  224. );
  225. });
  226. it('should handle error without stack trace', async () => {
  227. const mockError = new Error('Test Error Without Stack');
  228. mockError.stack = undefined;
  229. mockPythonShellInstance.end.mockImplementation((callback) => callback(mockError));
  230. await expect(pythonUtils.runPython('testScript.py', 'testMethod', ['arg1'])).rejects.toThrow(
  231. 'Error running Python script: Test Error Without Stack\nStack Trace: No Python traceback available',
  232. );
  233. expect(logger.error).toHaveBeenCalledWith(
  234. 'Error running Python script: Test Error Without Stack\nStack Trace: No Python traceback available',
  235. );
  236. });
  237. it('should log an error when unable to remove temporary files', async () => {
  238. const mockOutput = JSON.stringify({ type: 'final_result', data: 'test result' });
  239. jest.mocked(fs.readFileSync).mockReturnValue(mockOutput);
  240. mockPythonShellInstance.end.mockImplementation((callback) => callback());
  241. jest.mocked(fs.unlinkSync).mockImplementation(() => {
  242. throw new Error('Unable to delete file');
  243. });
  244. await pythonUtils.runPython('testScript.py', 'testMethod', ['arg1']);
  245. expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('Error removing'));
  246. });
  247. });
  248. });
Tip!

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

Comments

Loading...