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

wrapper.test.ts 7.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
  1. import fs from 'fs';
  2. import { runPython, state, validatePythonPath } from '../../src/python/pythonUtils';
  3. import { runPythonCode } from '../../src/python/wrapper';
  4. jest.mock('../../src/esm');
  5. jest.mock('python-shell');
  6. jest.mock('fs', () => ({
  7. writeFileSync: jest.fn(),
  8. readFileSync: jest.fn(),
  9. unlinkSync: jest.fn(),
  10. }));
  11. jest.mock('../../src/python/pythonUtils', () => {
  12. const originalModule = jest.requireActual('../../src/python/pythonUtils');
  13. return {
  14. ...originalModule,
  15. validatePythonPath: jest.fn(),
  16. runPython: jest.fn(originalModule.runPython),
  17. state: {
  18. cachedPythonPath: '/usr/bin/python3',
  19. },
  20. };
  21. });
  22. interface TestResult {
  23. testId: number;
  24. result: string;
  25. }
  26. interface MixedTestResult {
  27. testId: number;
  28. result: string;
  29. isExplicit: boolean;
  30. }
  31. describe('wrapper', () => {
  32. beforeAll(() => {
  33. delete process.env.PROMPTFOO_PYTHON;
  34. });
  35. beforeEach(() => {
  36. jest.clearAllMocks();
  37. jest
  38. .mocked(validatePythonPath)
  39. .mockImplementation((pythonPath: string, isExplicit: boolean): Promise<string> => {
  40. state.cachedPythonPath = pythonPath;
  41. return Promise.resolve(pythonPath);
  42. });
  43. });
  44. describe('runPythonCode', () => {
  45. it('should clean up the temporary files after execution', async () => {
  46. const mockWriteFileSync = jest.fn();
  47. const mockUnlinkSync = jest.fn();
  48. const mockRunPython = jest.fn().mockResolvedValue('cleanup test');
  49. jest.spyOn(fs, 'writeFileSync').mockImplementation(mockWriteFileSync);
  50. jest.spyOn(fs, 'unlinkSync').mockImplementation(mockUnlinkSync);
  51. jest.mocked(runPython).mockImplementation(mockRunPython);
  52. await runPythonCode('print("cleanup test")', 'main', []);
  53. expect(mockWriteFileSync).toHaveBeenCalledTimes(1);
  54. expect(mockWriteFileSync).toHaveBeenCalledWith(
  55. expect.stringContaining('temp-python-code-'),
  56. 'print("cleanup test")',
  57. );
  58. expect(mockRunPython).toHaveBeenCalledTimes(1);
  59. expect(mockRunPython).toHaveBeenCalledWith(
  60. expect.stringContaining('temp-python-code-'),
  61. 'main',
  62. [],
  63. );
  64. expect(mockUnlinkSync).toHaveBeenCalledTimes(1);
  65. expect(mockUnlinkSync).toHaveBeenCalledWith(expect.stringContaining('temp-python-code-'));
  66. });
  67. it('should execute Python code from a string and read the output file', async () => {
  68. const mockOutput = { type: 'final_result', data: 'execution result' };
  69. jest.spyOn(fs, 'writeFileSync').mockReturnValue();
  70. jest.spyOn(fs, 'unlinkSync').mockReturnValue();
  71. const mockRunPython = jest.mocked(runPython);
  72. mockRunPython.mockResolvedValue(mockOutput.data);
  73. const code = 'print("Hello, world!")';
  74. const result = await runPythonCode(code, 'main', []);
  75. expect(result).toBe('execution result');
  76. expect(mockRunPython).toHaveBeenCalledWith(expect.stringContaining('.py'), 'main', []);
  77. expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.py'), code);
  78. });
  79. });
  80. describe('validatePythonPath race conditions', () => {
  81. // Unmock validatePythonPath for this test suite to test the real implementation
  82. beforeEach(() => {
  83. jest.restoreAllMocks();
  84. // Reset the cached path and validation promise before each test
  85. const actualPythonUtils = jest.requireActual('../../src/python/pythonUtils');
  86. actualPythonUtils.state.cachedPythonPath = null;
  87. actualPythonUtils.state.validationPromise = null;
  88. });
  89. it('should handle concurrent validatePythonPath calls without race conditions', async () => {
  90. const actualPythonUtils = jest.requireActual('../../src/python/pythonUtils');
  91. const { validatePythonPath: realValidatePythonPath, state: realState } = actualPythonUtils;
  92. // Force cache miss
  93. realState.cachedPythonPath = null;
  94. // Launch multiple concurrent validations
  95. const concurrentCalls = 10;
  96. const promises = Array.from({ length: concurrentCalls }, (_, i) =>
  97. realValidatePythonPath('python', false).then(
  98. (result: string): TestResult => ({ testId: i, result }),
  99. ),
  100. );
  101. const results = await Promise.all(promises);
  102. // All calls should succeed
  103. expect(results).toHaveLength(concurrentCalls);
  104. results.forEach((result: TestResult) => {
  105. expect(result.result).toBeTruthy();
  106. expect(typeof result.result).toBe('string');
  107. });
  108. // All results should be consistent (no race condition)
  109. const uniqueResults = new Set(results.map((r: TestResult) => r.result));
  110. expect(uniqueResults.size).toBe(1);
  111. // Cache should be populated
  112. expect(realState.cachedPythonPath).toBeTruthy();
  113. }, 10000); // Increase timeout for this test
  114. it('should handle mixed explicit/implicit validation calls consistently', async () => {
  115. const actualPythonUtils = jest.requireActual('../../src/python/pythonUtils');
  116. const { validatePythonPath: realValidatePythonPath, state: realState } = actualPythonUtils;
  117. // Force cache miss
  118. realState.cachedPythonPath = null;
  119. // Create mixed explicit/implicit calls
  120. const mixedPromises = Array.from({ length: 8 }, (_, i) => {
  121. const isExplicit = i % 2 === 0;
  122. return realValidatePythonPath('python', isExplicit).then(
  123. (result: string): MixedTestResult => ({
  124. testId: i,
  125. result,
  126. isExplicit,
  127. }),
  128. );
  129. });
  130. const results = await Promise.all(mixedPromises);
  131. // All calls should succeed
  132. expect(results).toHaveLength(8);
  133. results.forEach((result: MixedTestResult) => {
  134. expect(result.result).toBeTruthy();
  135. expect(typeof result.result).toBe('string');
  136. });
  137. // Check consistency between explicit and implicit results
  138. const explicitResults = results
  139. .filter((r: MixedTestResult) => r.isExplicit)
  140. .map((r: MixedTestResult) => r.result);
  141. const implicitResults = results
  142. .filter((r: MixedTestResult) => !r.isExplicit)
  143. .map((r: MixedTestResult) => r.result);
  144. const uniqueExplicitResults = new Set(explicitResults);
  145. const uniqueImplicitResults = new Set(implicitResults);
  146. // Both explicit and implicit calls should return consistent results
  147. expect(uniqueExplicitResults.size).toBe(1);
  148. expect(uniqueImplicitResults.size).toBe(1);
  149. // Explicit and implicit results should be the same
  150. expect(explicitResults[0]).toBe(implicitResults[0]);
  151. }, 10000);
  152. it('should handle rapid successive calls without race conditions', async () => {
  153. const actualPythonUtils = jest.requireActual('../../src/python/pythonUtils');
  154. const { validatePythonPath: realValidatePythonPath, state: realState } = actualPythonUtils;
  155. // Force cache miss
  156. realState.cachedPythonPath = null;
  157. // Launch rapid successive calls
  158. const rapidCalls = 20;
  159. const promises = Array.from({ length: rapidCalls }, (_, i) =>
  160. realValidatePythonPath('python', false).then(
  161. (result: string): TestResult => ({ testId: i, result }),
  162. ),
  163. );
  164. const results = await Promise.all(promises);
  165. // All calls should succeed
  166. expect(results).toHaveLength(rapidCalls);
  167. results.forEach((result: TestResult) => {
  168. expect(result.result).toBeTruthy();
  169. expect(typeof result.result).toBe('string');
  170. });
  171. // All results should be consistent
  172. const uniqueResults = new Set(results.map((r: TestResult) => r.result));
  173. expect(uniqueResults.size).toBe(1);
  174. // Cache should be populated with the consistent result
  175. expect(realState.cachedPythonPath).toBe(results[0].result);
  176. }, 10000);
  177. });
  178. });
Tip!

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

Comments

Loading...