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

server.test.ts 12 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
  1. import opener from 'opener';
  2. import * as cache from '../../src/cache';
  3. import { getDefaultPort, VERSION } from '../../src/constants';
  4. import logger from '../../src/logger';
  5. import * as remoteGeneration from '../../src/redteam/remoteGeneration';
  6. import * as readlineUtils from '../../src/util/readline';
  7. // Import the module under test after mocks are set up
  8. import {
  9. __clearFeatureCache,
  10. BrowserBehavior,
  11. checkServerFeatureSupport,
  12. checkServerRunning,
  13. openBrowser,
  14. } from '../../src/util/server';
  15. // Mock opener
  16. jest.mock('opener', () => jest.fn());
  17. // Mock logger
  18. jest.mock('../../src/logger', () => ({
  19. info: jest.fn(),
  20. debug: jest.fn(),
  21. error: jest.fn(),
  22. }));
  23. // Mock the readline utilities
  24. jest.mock('../../src/util/readline', () => ({
  25. promptYesNo: jest.fn(),
  26. promptUser: jest.fn(),
  27. createReadlineInterface: jest.fn(),
  28. }));
  29. // Mock fetchWithCache
  30. jest.mock('../../src/cache', () => ({
  31. fetchWithCache: jest.fn(),
  32. }));
  33. // Mock remoteGeneration
  34. jest.mock('../../src/redteam/remoteGeneration', () => ({
  35. getRemoteVersionUrl: jest.fn(),
  36. }));
  37. // Properly mock fetch
  38. const originalFetch = global.fetch;
  39. const mockFetch = jest.fn();
  40. describe('Server Utilities', () => {
  41. beforeEach(() => {
  42. jest.clearAllMocks();
  43. // Setup global.fetch as a Jest mock
  44. global.fetch = mockFetch;
  45. mockFetch.mockReset();
  46. });
  47. afterEach(() => {
  48. global.fetch = originalFetch;
  49. });
  50. describe('checkServerRunning', () => {
  51. it('should return true when server is running with matching version', async () => {
  52. mockFetch.mockResolvedValueOnce({
  53. json: async () => ({ status: 'OK', version: VERSION }),
  54. });
  55. const result = await checkServerRunning();
  56. expect(mockFetch).toHaveBeenCalledWith(`http://localhost:${getDefaultPort()}/health`);
  57. expect(result).toBe(true);
  58. });
  59. it('should return false when server status is not OK', async () => {
  60. mockFetch.mockResolvedValueOnce({
  61. json: async () => ({ status: 'ERROR', version: VERSION }),
  62. });
  63. const result = await checkServerRunning();
  64. expect(result).toBe(false);
  65. });
  66. it('should return false when server version does not match', async () => {
  67. mockFetch.mockResolvedValueOnce({
  68. json: async () => ({ status: 'OK', version: 'wrong-version' }),
  69. });
  70. const result = await checkServerRunning();
  71. expect(result).toBe(false);
  72. });
  73. it('should return false when fetch throws an error', async () => {
  74. mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
  75. const result = await checkServerRunning();
  76. expect(result).toBe(false);
  77. expect(logger.debug).toHaveBeenCalledWith(
  78. expect.stringContaining('Failed to check server health'),
  79. );
  80. });
  81. it('should use custom port when provided', async () => {
  82. const customPort = 4000;
  83. mockFetch.mockResolvedValueOnce({
  84. json: async () => ({ status: 'OK', version: VERSION }),
  85. });
  86. await checkServerRunning(customPort);
  87. expect(mockFetch).toHaveBeenCalledWith(`http://localhost:${customPort}/health`);
  88. });
  89. });
  90. describe('openBrowser', () => {
  91. it('should open browser with default URL when BrowserBehavior.OPEN', async () => {
  92. await openBrowser(BrowserBehavior.OPEN);
  93. expect(opener).toHaveBeenCalledWith(`http://localhost:${getDefaultPort()}`);
  94. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Press Ctrl+C'));
  95. });
  96. it('should open browser with report URL when BrowserBehavior.OPEN_TO_REPORT', async () => {
  97. await openBrowser(BrowserBehavior.OPEN_TO_REPORT);
  98. expect(opener).toHaveBeenCalledWith(`http://localhost:${getDefaultPort()}/report`);
  99. });
  100. it('should open browser with redteam setup URL when BrowserBehavior.OPEN_TO_REDTEAM_CREATE', async () => {
  101. await openBrowser(BrowserBehavior.OPEN_TO_REDTEAM_CREATE);
  102. expect(opener).toHaveBeenCalledWith(`http://localhost:${getDefaultPort()}/redteam/setup`);
  103. });
  104. it('should not open browser when BrowserBehavior.SKIP', async () => {
  105. await openBrowser(BrowserBehavior.SKIP);
  106. expect(opener).not.toHaveBeenCalled();
  107. expect(logger.info).not.toHaveBeenCalled();
  108. });
  109. it('should handle opener errors gracefully', async () => {
  110. jest.mocked(opener).mockImplementationOnce(() => {
  111. throw new Error('Failed to open browser');
  112. });
  113. await openBrowser(BrowserBehavior.OPEN);
  114. expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('Failed to open browser'));
  115. });
  116. it('should ask user before opening browser when BrowserBehavior.ASK', async () => {
  117. // Mock promptYesNo to return true
  118. jest.mocked(readlineUtils.promptYesNo).mockResolvedValueOnce(true);
  119. await openBrowser(BrowserBehavior.ASK);
  120. expect(readlineUtils.promptYesNo).toHaveBeenCalledWith('Open URL in browser?', false);
  121. expect(opener).toHaveBeenCalledWith(`http://localhost:${getDefaultPort()}`);
  122. });
  123. it('should not open browser when user answers no to ASK prompt', async () => {
  124. // Mock promptYesNo to return false
  125. jest.mocked(readlineUtils.promptYesNo).mockResolvedValueOnce(false);
  126. await openBrowser(BrowserBehavior.ASK);
  127. expect(readlineUtils.promptYesNo).toHaveBeenCalledWith('Open URL in browser?', false);
  128. expect(opener).not.toHaveBeenCalled();
  129. });
  130. it('should use custom port when provided', async () => {
  131. const customPort = 5000;
  132. await openBrowser(BrowserBehavior.OPEN, customPort);
  133. expect(opener).toHaveBeenCalledWith(`http://localhost:${customPort}`);
  134. });
  135. });
  136. describe('checkServerFeatureSupport', () => {
  137. const featureName = 'test-feature';
  138. beforeEach(() => {
  139. // Clear the feature cache before each test to ensure isolation
  140. __clearFeatureCache();
  141. jest.clearAllMocks();
  142. // Setup default mock for getRemoteVersionUrl to return a valid URL
  143. jest
  144. .mocked(remoteGeneration.getRemoteVersionUrl)
  145. .mockReturnValue('https://api.promptfoo.app/version');
  146. });
  147. it('should return true when server buildDate is after required date', async () => {
  148. const requiredDate = '2024-01-01T00:00:00Z';
  149. const serverBuildDate = '2024-06-15T10:30:00Z';
  150. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  151. data: { buildDate: serverBuildDate, version: '1.0.0' },
  152. cached: false,
  153. status: 200,
  154. statusText: 'OK',
  155. });
  156. const result = await checkServerFeatureSupport(featureName, requiredDate);
  157. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  158. 'https://api.promptfoo.app/version',
  159. {
  160. method: 'GET',
  161. headers: { 'Content-Type': 'application/json' },
  162. },
  163. 5000,
  164. );
  165. expect(result).toBe(true);
  166. expect(logger.debug).toHaveBeenCalledWith(
  167. expect.stringContaining(
  168. `${featureName}: buildDate=${serverBuildDate}, required=${requiredDate}, supported=true`,
  169. ),
  170. );
  171. });
  172. it('should return false when server buildDate is before required date', async () => {
  173. const requiredDate = '2024-06-01T00:00:00Z';
  174. const serverBuildDate = '2024-01-15T10:30:00Z';
  175. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  176. data: { buildDate: serverBuildDate, version: '1.0.0' },
  177. cached: false,
  178. status: 200,
  179. statusText: 'OK',
  180. });
  181. const result = await checkServerFeatureSupport(featureName, requiredDate);
  182. expect(result).toBe(false);
  183. expect(logger.debug).toHaveBeenCalledWith(
  184. expect.stringContaining(
  185. `${featureName}: buildDate=${serverBuildDate}, required=${requiredDate}, supported=false`,
  186. ),
  187. );
  188. });
  189. it('should return false when no version info available', async () => {
  190. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  191. data: {},
  192. cached: false,
  193. status: 200,
  194. statusText: 'OK',
  195. });
  196. const result = await checkServerFeatureSupport(featureName, '2024-01-01T00:00:00Z');
  197. expect(result).toBe(false);
  198. expect(logger.debug).toHaveBeenCalledWith(
  199. expect.stringContaining(`${featureName}: no version info, assuming not supported`),
  200. );
  201. });
  202. it('should return true when no remote URL is available (local server assumption)', async () => {
  203. // Mock getRemoteVersionUrl to return null for this specific test
  204. jest.mocked(remoteGeneration.getRemoteVersionUrl).mockReturnValueOnce(null);
  205. const result = await checkServerFeatureSupport(featureName, '2024-01-01T00:00:00Z');
  206. expect(result).toBe(true);
  207. expect(cache.fetchWithCache).not.toHaveBeenCalled();
  208. expect(logger.debug).toHaveBeenCalledWith(
  209. expect.stringContaining(
  210. `No remote URL available for ${featureName}, assuming local server supports it`,
  211. ),
  212. );
  213. });
  214. it('should return false when fetchWithCache throws an error', async () => {
  215. jest.mocked(cache.fetchWithCache).mockRejectedValueOnce(new Error('Network error'));
  216. const result = await checkServerFeatureSupport(featureName, '2024-01-01T00:00:00Z');
  217. expect(result).toBe(false);
  218. expect(logger.debug).toHaveBeenCalledWith(
  219. expect.stringContaining(
  220. `Version check failed for ${featureName}, assuming not supported: Error: Network error`,
  221. ),
  222. );
  223. });
  224. it('should cache results to avoid repeated API calls', async () => {
  225. const requiredDate = '2024-01-01T00:00:00Z';
  226. const serverBuildDate = '2024-06-15T10:30:00Z';
  227. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  228. data: { buildDate: serverBuildDate, version: '1.0.0' },
  229. cached: false,
  230. status: 200,
  231. statusText: 'OK',
  232. });
  233. // First call
  234. const result1 = await checkServerFeatureSupport(featureName, requiredDate);
  235. // Second call with same parameters
  236. const result2 = await checkServerFeatureSupport(featureName, requiredDate);
  237. expect(result1).toBe(true);
  238. expect(result2).toBe(true);
  239. // fetchWithCache should only be called once due to caching
  240. expect(cache.fetchWithCache).toHaveBeenCalledTimes(1);
  241. });
  242. it('should handle different feature names with separate cache entries', async () => {
  243. const feature1 = 'feature-one';
  244. const feature2 = 'feature-two';
  245. const requiredDate = '2024-01-01T00:00:00Z';
  246. jest
  247. .mocked(cache.fetchWithCache)
  248. .mockResolvedValueOnce({
  249. data: { buildDate: '2024-06-15T10:30:00Z', version: '1.0.0' },
  250. cached: false,
  251. status: 200,
  252. statusText: 'OK',
  253. })
  254. .mockResolvedValueOnce({
  255. data: { buildDate: '2023-12-15T10:30:00Z', version: '1.0.0' },
  256. cached: false,
  257. status: 200,
  258. statusText: 'OK',
  259. });
  260. const result1 = await checkServerFeatureSupport(feature1, requiredDate);
  261. const result2 = await checkServerFeatureSupport(feature2, requiredDate);
  262. expect(result1).toBe(true);
  263. expect(result2).toBe(false);
  264. expect(cache.fetchWithCache).toHaveBeenCalledTimes(2);
  265. });
  266. it('should handle timezone differences correctly', async () => {
  267. const requiredDate = '2024-06-01T00:00:00Z'; // UTC
  268. const serverBuildDate = '2024-06-01T08:00:00+08:00'; // Same moment in different timezone
  269. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  270. data: { buildDate: serverBuildDate, version: '1.0.0' },
  271. cached: false,
  272. status: 200,
  273. statusText: 'OK',
  274. });
  275. const result = await checkServerFeatureSupport(featureName, requiredDate);
  276. expect(result).toBe(true);
  277. });
  278. });
  279. });
Tip!

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

Comments

Loading...