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

telemetry.test.ts 16 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
505
506
507
508
  1. import { fetchWithTimeout } from '../src/fetch';
  2. import { Telemetry } from '../src/telemetry';
  3. jest.mock('../src/fetch', () => ({
  4. fetchWithTimeout: jest.fn().mockResolvedValue({ ok: true }),
  5. }));
  6. jest.mock('crypto', () => ({
  7. randomUUID: jest.fn().mockReturnValue('test-uuid'),
  8. }));
  9. jest.mock('../src/globalConfig/globalConfig', () => ({
  10. readGlobalConfig: jest
  11. .fn()
  12. .mockReturnValue({ id: 'test-user-id', account: { email: 'test@example.com' } }),
  13. writeGlobalConfig: jest.fn(),
  14. }));
  15. jest.mock('../src/constants', () => ({
  16. VERSION: '1.0.0',
  17. }));
  18. jest.mock('../src/cliState', () => ({
  19. __esModule: true,
  20. default: {
  21. config: undefined,
  22. },
  23. }));
  24. jest.mock('../src/envars', () => ({
  25. ...jest.requireActual('../src/envars'),
  26. getEnvBool: jest.fn().mockImplementation((key) => {
  27. if (key === 'PROMPTFOO_DISABLE_TELEMETRY') {
  28. return process.env.PROMPTFOO_DISABLE_TELEMETRY === '1';
  29. }
  30. if (key === 'IS_TESTING') {
  31. return process.env.IS_TESTING === 'true' || process.env.IS_TESTING === '1';
  32. }
  33. return false;
  34. }),
  35. getEnvString: jest.fn().mockImplementation((key) => {
  36. if (key === 'PROMPTFOO_POSTHOG_KEY') {
  37. return process.env.PROMPTFOO_POSTHOG_KEY || 'test-key';
  38. }
  39. if (key === 'PROMPTFOO_POSTHOG_HOST') {
  40. return process.env.PROMPTFOO_POSTHOG_HOST || undefined;
  41. }
  42. if (key === 'NODE_ENV') {
  43. return process.env.NODE_ENV || undefined;
  44. }
  45. return undefined;
  46. }),
  47. isCI: jest.fn().mockReturnValue(false),
  48. }));
  49. jest.mock('../src/logger', () => ({
  50. __esModule: true,
  51. default: {
  52. debug: jest.fn(),
  53. },
  54. }));
  55. jest.mock('../src/globalConfig/accounts', () => ({
  56. isLoggedIntoCloud: jest.fn().mockReturnValue(false),
  57. getUserEmail: jest.fn().mockReturnValue('test@example.com'),
  58. getUserId: jest.fn().mockReturnValue('test-user-id'),
  59. }));
  60. jest.mock('../src/constants/build', () => ({
  61. POSTHOG_KEY: 'test-posthog-key',
  62. }));
  63. describe('Telemetry', () => {
  64. let originalEnv: NodeJS.ProcessEnv;
  65. let fetchSpy: jest.SpyInstance;
  66. let sendEventSpy: jest.SpyInstance;
  67. beforeEach(() => {
  68. originalEnv = process.env;
  69. process.env = { ...originalEnv };
  70. process.env.PROMPTFOO_POSTHOG_KEY = 'test-key';
  71. fetchSpy = jest
  72. .spyOn(global, 'fetch')
  73. .mockImplementation(() => Promise.resolve({ ok: true } as Response));
  74. sendEventSpy = jest.spyOn(Telemetry.prototype, 'sendEvent' as any);
  75. jest.useFakeTimers();
  76. });
  77. afterEach(() => {
  78. process.env = originalEnv;
  79. jest.clearAllMocks();
  80. jest.restoreAllMocks();
  81. jest.useRealTimers();
  82. });
  83. it('should not track events with PostHog when telemetry is disabled', () => {
  84. process.env.PROMPTFOO_DISABLE_TELEMETRY = '1';
  85. const _telemetry = new Telemetry();
  86. _telemetry.record('eval_ran', { foo: 'bar' });
  87. expect(sendEventSpy).not.toHaveBeenCalledWith('eval_ran', expect.anything());
  88. });
  89. it('should include version in telemetry events', () => {
  90. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  91. const _telemetry = new Telemetry();
  92. _telemetry.record('eval_ran', { foo: 'bar' });
  93. expect(sendEventSpy).toHaveBeenCalledWith('eval_ran', { foo: 'bar' });
  94. expect(fetchSpy).toHaveBeenCalledWith(
  95. expect.any(String),
  96. expect.objectContaining({
  97. method: 'POST',
  98. }),
  99. );
  100. const fetchCalls = fetchSpy.mock.calls;
  101. let foundVersion = false;
  102. for (const call of fetchCalls) {
  103. if (
  104. call[1] &&
  105. call[1].body &&
  106. typeof call[1].body === 'string' &&
  107. call[1].body.includes('packageVersion')
  108. ) {
  109. foundVersion = true;
  110. break;
  111. }
  112. }
  113. expect(foundVersion).toBe(true);
  114. });
  115. it('should include version and CI status in telemetry events', async () => {
  116. jest.useRealTimers(); // Temporarily use real timers for this test
  117. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  118. process.env.IS_TESTING = ''; // Clear IS_TESTING to allow fetch calls
  119. const isCI = jest.requireMock('../src/envars').isCI;
  120. isCI.mockReturnValue(true);
  121. fetchSpy.mockClear();
  122. const _telemetry = new Telemetry();
  123. _telemetry.record('feature_used', { test: 'value' });
  124. await new Promise((resolve) => setTimeout(resolve, 10));
  125. const fetchCalls = fetchSpy.mock.calls;
  126. expect(fetchCalls.length).toBeGreaterThan(0);
  127. let foundExpectedProperties = false;
  128. for (const call of fetchCalls) {
  129. if (call[1] && call[1].body && typeof call[1].body === 'string') {
  130. try {
  131. const data = JSON.parse(call[1].body);
  132. if (data.events && data.events.length > 0) {
  133. const properties = data.events[0].properties;
  134. if (
  135. properties &&
  136. properties.test === 'value' &&
  137. properties.packageVersion === '1.0.0' &&
  138. properties.isRunningInCi === true
  139. ) {
  140. foundExpectedProperties = true;
  141. break;
  142. }
  143. }
  144. } catch {
  145. // Skip JSON parse errors
  146. }
  147. }
  148. }
  149. expect(foundExpectedProperties).toBe(true);
  150. isCI.mockReset();
  151. process.env.IS_TESTING = 'true'; // Reset IS_TESTING
  152. jest.useFakeTimers(); // Restore fake timers
  153. });
  154. it('should save consent successfully', async () => {
  155. jest.mocked(fetchWithTimeout).mockResolvedValue({ ok: true } as any);
  156. const _telemetry = new Telemetry();
  157. await _telemetry.saveConsent('test@example.com', { source: 'test' });
  158. expect(fetchWithTimeout).toHaveBeenCalledWith(
  159. 'https://api.promptfoo.dev/consent',
  160. {
  161. method: 'POST',
  162. headers: {
  163. 'Content-Type': 'application/json',
  164. },
  165. body: JSON.stringify({ email: 'test@example.com', metadata: { source: 'test' } }),
  166. },
  167. 1000,
  168. );
  169. });
  170. it('should handle failed consent save', async () => {
  171. jest.mocked(fetchWithTimeout).mockResolvedValue({ ok: false, statusText: 'Not Found' } as any);
  172. const _telemetry = new Telemetry();
  173. await _telemetry.saveConsent('test@example.com', { source: 'test' });
  174. expect(fetchWithTimeout).toHaveBeenCalledWith(
  175. 'https://api.promptfoo.dev/consent',
  176. expect.objectContaining({
  177. method: 'POST',
  178. body: JSON.stringify({
  179. email: 'test@example.com',
  180. metadata: { source: 'test' },
  181. }),
  182. }),
  183. 1000,
  184. );
  185. });
  186. it('should not initialize PostHog client when telemetry is disabled', async () => {
  187. process.env.PROMPTFOO_DISABLE_TELEMETRY = '1';
  188. jest.resetModules();
  189. const telemetryModule = await import('../src/telemetry');
  190. const telemetryInstance = telemetryModule.default;
  191. telemetryInstance.record('eval_ran', { foo: 'bar' });
  192. expect(sendEventSpy).toHaveBeenCalledTimes(0);
  193. });
  194. describe('PostHog client initialization', () => {
  195. it('should initialize PostHog client when telemetry is enabled and POSTHOG_KEY is present', async () => {
  196. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  197. process.env.IS_TESTING = '';
  198. process.env.PROMPTFOO_POSTHOG_KEY = 'test-posthog-key';
  199. const mockPostHog = jest.fn().mockImplementation(() => ({
  200. identify: jest.fn(),
  201. capture: jest.fn(),
  202. flush: jest.fn().mockResolvedValue(undefined),
  203. }));
  204. jest.resetModules();
  205. jest.doMock('posthog-node', () => ({
  206. PostHog: mockPostHog,
  207. }));
  208. const telemetryModule = await import('../src/telemetry');
  209. const _telemetry = new telemetryModule.Telemetry();
  210. _telemetry.identify();
  211. expect(mockPostHog).toHaveBeenCalledWith('test-posthog-key', {
  212. host: 'https://a.promptfoo.app',
  213. });
  214. });
  215. it('should handle PostHog initialization errors gracefully', async () => {
  216. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  217. process.env.IS_TESTING = '';
  218. process.env.PROMPTFOO_POSTHOG_KEY = 'test-posthog-key';
  219. const mockPostHog = jest.fn().mockImplementation(() => {
  220. throw new Error('PostHog initialization failed');
  221. });
  222. jest.resetModules();
  223. jest.doMock('posthog-node', () => ({
  224. PostHog: mockPostHog,
  225. }));
  226. const telemetryModule = await import('../src/telemetry');
  227. const _telemetry = new telemetryModule.Telemetry();
  228. expect(() => _telemetry.identify()).not.toThrow();
  229. });
  230. });
  231. describe('PostHog operations', () => {
  232. let mockPostHogInstance: any;
  233. let mockPostHog: jest.Mock;
  234. beforeEach(() => {
  235. mockPostHogInstance = {
  236. identify: jest.fn(),
  237. capture: jest.fn(),
  238. flush: jest.fn().mockResolvedValue(undefined),
  239. };
  240. mockPostHog = jest.fn().mockImplementation(() => mockPostHogInstance);
  241. jest.resetModules();
  242. jest.doMock('posthog-node', () => ({
  243. PostHog: mockPostHog,
  244. }));
  245. });
  246. it('should call PostHog identify when telemetry is enabled', async () => {
  247. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  248. process.env.IS_TESTING = '';
  249. process.env.PROMPTFOO_POSTHOG_KEY = 'test-posthog-key';
  250. const telemetryModule = await import('../src/telemetry');
  251. const _telemetry = new telemetryModule.Telemetry();
  252. _telemetry.identify();
  253. expect(mockPostHogInstance.identify).toHaveBeenCalledWith({
  254. distinctId: 'test-user-id',
  255. properties: { email: 'test@example.com', isLoggedIntoCloud: false },
  256. });
  257. expect(mockPostHogInstance.flush).toHaveBeenCalledWith();
  258. });
  259. it('should handle PostHog identify errors gracefully', async () => {
  260. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  261. process.env.IS_TESTING = '';
  262. process.env.PROMPTFOO_POSTHOG_KEY = 'test-posthog-key';
  263. mockPostHogInstance.identify.mockImplementation(() => {
  264. throw new Error('Identify failed');
  265. });
  266. const { default: logger } = await import('../src/logger');
  267. const loggerSpy = jest.spyOn(logger, 'debug');
  268. const telemetryModule = await import('../src/telemetry');
  269. const _telemetry = new telemetryModule.Telemetry();
  270. expect(() => _telemetry.identify()).not.toThrow();
  271. expect(loggerSpy).toHaveBeenCalledWith('PostHog identify error: Error: Identify failed');
  272. });
  273. it('should call PostHog capture when sending events', async () => {
  274. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  275. process.env.IS_TESTING = '';
  276. process.env.PROMPTFOO_POSTHOG_KEY = 'test-posthog-key';
  277. const telemetryModule = await import('../src/telemetry');
  278. const _telemetry = new telemetryModule.Telemetry();
  279. _telemetry.record('eval_ran', { test: 'value' });
  280. expect(mockPostHogInstance.capture).toHaveBeenCalledWith({
  281. distinctId: 'test-user-id',
  282. event: 'eval_ran',
  283. properties: {
  284. test: 'value',
  285. packageVersion: '1.0.0',
  286. isRunningInCi: false,
  287. },
  288. });
  289. expect(mockPostHogInstance.flush).toHaveBeenCalledWith();
  290. });
  291. it('should handle PostHog capture errors gracefully', async () => {
  292. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  293. process.env.IS_TESTING = '';
  294. process.env.PROMPTFOO_POSTHOG_KEY = 'test-posthog-key';
  295. mockPostHogInstance.capture.mockImplementation(() => {
  296. throw new Error('Capture failed');
  297. });
  298. const { default: logger } = await import('../src/logger');
  299. const loggerSpy = jest.spyOn(logger, 'debug');
  300. const telemetryModule = await import('../src/telemetry');
  301. const _telemetry = new telemetryModule.Telemetry();
  302. expect(() => _telemetry.record('eval_ran', { test: 'value' })).not.toThrow();
  303. expect(loggerSpy).toHaveBeenCalledWith('PostHog capture error: Error: Capture failed');
  304. });
  305. it('should handle PostHog flush errors silently', async () => {
  306. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  307. process.env.IS_TESTING = '';
  308. process.env.PROMPTFOO_POSTHOG_KEY = 'test-posthog-key';
  309. mockPostHogInstance.flush.mockRejectedValue(new Error('Flush failed'));
  310. const telemetryModule = await import('../src/telemetry');
  311. const _telemetry = new telemetryModule.Telemetry();
  312. expect(() => _telemetry.identify()).not.toThrow();
  313. });
  314. });
  315. describe('telemetry disabled recording', () => {
  316. it('should record telemetry disabled event only once', () => {
  317. process.env.PROMPTFOO_DISABLE_TELEMETRY = '1';
  318. const _telemetry = new Telemetry();
  319. _telemetry.record('eval_ran', { foo: 'bar' });
  320. expect(sendEventSpy).toHaveBeenCalledWith('feature_used', { feature: 'telemetry disabled' });
  321. expect(sendEventSpy).toHaveBeenCalledTimes(1);
  322. sendEventSpy.mockClear();
  323. _telemetry.record('command_used', { name: 'test' });
  324. expect(sendEventSpy).not.toHaveBeenCalled();
  325. });
  326. });
  327. describe('consent save error handling', () => {
  328. it('should handle network errors when saving consent', async () => {
  329. const mockError = new Error('Network error');
  330. // Reset modules to ensure clean state
  331. jest.resetModules();
  332. // Re-mock fetchWithTimeout
  333. jest.doMock('../src/fetch', () => ({
  334. fetchWithTimeout: jest.fn().mockRejectedValue(mockError),
  335. }));
  336. // Re-mock logger to capture debug calls
  337. jest.doMock('../src/logger', () => ({
  338. __esModule: true,
  339. default: {
  340. debug: jest.fn(),
  341. },
  342. }));
  343. const { default: logger } = await import('../src/logger');
  344. const { Telemetry: TelemetryClass } = await import('../src/telemetry');
  345. const _telemetry = new TelemetryClass();
  346. await _telemetry.saveConsent('test@example.com');
  347. expect(logger.debug).toHaveBeenCalledWith('Failed to save consent: Network error');
  348. });
  349. it('should save consent without metadata', async () => {
  350. jest.mocked(fetchWithTimeout).mockResolvedValue({ ok: true } as any);
  351. const _telemetry = new Telemetry();
  352. await _telemetry.saveConsent('test@example.com');
  353. expect(fetchWithTimeout).toHaveBeenCalledWith(
  354. 'https://api.promptfoo.dev/consent',
  355. {
  356. method: 'POST',
  357. headers: {
  358. 'Content-Type': 'application/json',
  359. },
  360. body: JSON.stringify({ email: 'test@example.com', metadata: undefined }),
  361. },
  362. 1000,
  363. );
  364. });
  365. });
  366. describe('KA endpoint calls', () => {
  367. beforeEach(() => {
  368. jest.useRealTimers(); // Use real timers for these tests
  369. });
  370. afterEach(() => {
  371. jest.useFakeTimers(); // Restore fake timers
  372. });
  373. it('should send identify data to KA endpoint', async () => {
  374. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  375. process.env.IS_TESTING = ''; // Clear IS_TESTING to allow telemetry
  376. // Need to reset modules to pick up the env change
  377. jest.resetModules();
  378. // Re-mock fetchWithTimeout
  379. jest.doMock('../src/fetch', () => ({
  380. fetchWithTimeout: jest.fn().mockResolvedValue({ ok: true }),
  381. }));
  382. const { fetchWithTimeout } = await import('../src/fetch');
  383. const telemetryModule = await import('../src/telemetry');
  384. const _telemetry = new telemetryModule.Telemetry();
  385. // Wait for constructor identify to complete
  386. await new Promise((resolve) => setTimeout(resolve, 20));
  387. expect(fetchWithTimeout).toHaveBeenCalledWith(
  388. 'https://ka.promptfoo.app/',
  389. expect.objectContaining({
  390. method: 'POST',
  391. headers: {
  392. 'Content-Type': 'application/json',
  393. },
  394. body: JSON.stringify({ profile_id: 'test-user-id', email: 'test@example.com' }),
  395. }),
  396. 1000,
  397. );
  398. });
  399. it('should handle KA endpoint errors silently', async () => {
  400. process.env.PROMPTFOO_DISABLE_TELEMETRY = '0';
  401. fetchSpy.mockRejectedValue(new Error('KA endpoint error'));
  402. const _telemetry = new Telemetry();
  403. // Should not throw error
  404. expect(() => _telemetry.identify()).not.toThrow();
  405. });
  406. });
  407. });
Tip!

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

Comments

Loading...