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

accounts.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
  1. import input from '@inquirer/input';
  2. import chalk from 'chalk';
  3. import { getEnvString, isCI } from '../../src/envars';
  4. import { fetchWithTimeout } from '../../src/fetch';
  5. import {
  6. checkEmailStatus,
  7. checkEmailStatusOrExit,
  8. getAuthor,
  9. getUserEmail,
  10. getUserId,
  11. isLoggedIntoCloud,
  12. promptForEmailUnverified,
  13. setUserEmail,
  14. } from '../../src/globalConfig/accounts';
  15. import {
  16. readGlobalConfig,
  17. writeGlobalConfig,
  18. writeGlobalConfigPartial,
  19. } from '../../src/globalConfig/globalConfig';
  20. import logger from '../../src/logger';
  21. import telemetry from '../../src/telemetry';
  22. // Mock fetchWithTimeout before any imports that might use telemetry
  23. jest.mock('../../src/fetch', () => ({
  24. fetchWithTimeout: jest.fn().mockResolvedValue({ ok: true }),
  25. }));
  26. jest.mock('@inquirer/input');
  27. jest.mock('../../src/envars');
  28. jest.mock('../../src/telemetry', () => {
  29. const mockTelemetry = {
  30. record: jest.fn().mockResolvedValue(undefined),
  31. identify: jest.fn(),
  32. saveConsent: jest.fn().mockResolvedValue(undefined),
  33. disabled: false,
  34. };
  35. return {
  36. __esModule: true,
  37. default: mockTelemetry,
  38. Telemetry: jest.fn().mockImplementation(() => mockTelemetry),
  39. };
  40. });
  41. jest.mock('../../src/util');
  42. describe('accounts', () => {
  43. beforeEach(() => {
  44. jest.clearAllMocks();
  45. });
  46. describe('getUserId', () => {
  47. it('should return existing ID from global config', () => {
  48. const existingId = 'existing-test-id';
  49. jest.mocked(readGlobalConfig).mockReturnValue({
  50. id: existingId,
  51. account: { email: 'test@example.com' },
  52. });
  53. const result = getUserId();
  54. expect(result).toBe(existingId);
  55. expect(writeGlobalConfig).not.toHaveBeenCalled();
  56. });
  57. it('should generate new ID and save to config when no ID exists', () => {
  58. jest.mocked(readGlobalConfig).mockReturnValue({
  59. account: { email: 'test@example.com' },
  60. });
  61. const result = getUserId();
  62. // Should return a UUID-like string
  63. expect(typeof result).toBe('string');
  64. expect(result).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
  65. // Should have saved the config with the new ID
  66. expect(writeGlobalConfig).toHaveBeenCalledWith({
  67. account: { email: 'test@example.com' },
  68. id: result,
  69. });
  70. });
  71. it('should generate new ID when global config is null', () => {
  72. jest.mocked(readGlobalConfig).mockReturnValue(null as any);
  73. const result = getUserId();
  74. // Should return a UUID-like string
  75. expect(typeof result).toBe('string');
  76. expect(result).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
  77. // Should have saved the config with the new ID
  78. expect(writeGlobalConfig).toHaveBeenCalledWith({
  79. id: result,
  80. });
  81. });
  82. it('should generate new ID when global config is undefined', () => {
  83. jest.mocked(readGlobalConfig).mockReturnValue(undefined as any);
  84. const result = getUserId();
  85. // Should return a UUID-like string
  86. expect(typeof result).toBe('string');
  87. expect(result).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
  88. // Should have saved the config with the new ID
  89. expect(writeGlobalConfig).toHaveBeenCalledWith({
  90. id: result,
  91. });
  92. });
  93. it('should generate new ID when config exists but has no id property', () => {
  94. jest.mocked(readGlobalConfig).mockReturnValue({
  95. account: { email: 'test@example.com' },
  96. });
  97. const result = getUserId();
  98. // Should return a UUID-like string
  99. expect(typeof result).toBe('string');
  100. expect(result).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
  101. // Should have saved the config with the new ID
  102. expect(writeGlobalConfig).toHaveBeenCalledWith({
  103. account: { email: 'test@example.com' },
  104. id: result,
  105. });
  106. });
  107. });
  108. describe('getUserEmail', () => {
  109. it('should return email from global config', () => {
  110. jest.mocked(readGlobalConfig).mockReturnValue({
  111. id: 'test-id',
  112. account: { email: 'test@example.com' },
  113. });
  114. expect(getUserEmail()).toBe('test@example.com');
  115. });
  116. it('should return null if no email in config', () => {
  117. jest.mocked(readGlobalConfig).mockReturnValue({
  118. id: 'test-id',
  119. });
  120. expect(getUserEmail()).toBeNull();
  121. });
  122. });
  123. describe('setUserEmail', () => {
  124. it('should write email to global config', () => {
  125. const email = 'test@example.com';
  126. setUserEmail(email);
  127. expect(writeGlobalConfigPartial).toHaveBeenCalledWith({
  128. account: { email },
  129. });
  130. });
  131. });
  132. describe('getAuthor', () => {
  133. it('should return env var if set', () => {
  134. jest.mocked(getEnvString).mockReturnValue('author@env.com');
  135. expect(getAuthor()).toBe('author@env.com');
  136. });
  137. it('should fall back to user email if no env var', () => {
  138. jest.mocked(getEnvString).mockReturnValue('');
  139. jest.mocked(readGlobalConfig).mockReturnValue({
  140. id: 'test-id',
  141. account: { email: 'test@example.com' },
  142. });
  143. expect(getAuthor()).toBe('test@example.com');
  144. });
  145. it('should return null if no author found', () => {
  146. jest.mocked(getEnvString).mockReturnValue('');
  147. jest.mocked(readGlobalConfig).mockReturnValue({
  148. id: 'test-id',
  149. });
  150. expect(getAuthor()).toBeNull();
  151. });
  152. });
  153. describe('promptForEmailUnverified', () => {
  154. beforeEach(() => {
  155. jest.mocked(isCI).mockReturnValue(false);
  156. jest.mocked(readGlobalConfig).mockReturnValue({
  157. id: 'test-id',
  158. });
  159. });
  160. it('should use CI email if in CI environment', async () => {
  161. jest.mocked(isCI).mockReturnValue(true);
  162. await promptForEmailUnverified();
  163. expect(telemetry.saveConsent).toHaveBeenCalledWith('ci-placeholder@promptfoo.dev', {
  164. source: 'promptForEmailUnverified',
  165. });
  166. });
  167. it('should not prompt for email if already set', async () => {
  168. jest.mocked(readGlobalConfig).mockReturnValue({
  169. id: 'test-id',
  170. account: { email: 'existing@example.com' },
  171. });
  172. await promptForEmailUnverified();
  173. expect(input).not.toHaveBeenCalled();
  174. expect(telemetry.saveConsent).toHaveBeenCalledWith('existing@example.com', {
  175. source: 'promptForEmailUnverified',
  176. });
  177. });
  178. it('should prompt for email and save valid input', async () => {
  179. jest.mocked(input).mockResolvedValue('new@example.com');
  180. await promptForEmailUnverified();
  181. expect(writeGlobalConfigPartial).toHaveBeenCalledWith({
  182. account: { email: 'new@example.com' },
  183. });
  184. expect(telemetry.saveConsent).toHaveBeenCalledWith('new@example.com', {
  185. source: 'promptForEmailUnverified',
  186. });
  187. });
  188. describe('email validation', () => {
  189. let validateFn: (input: string) => Promise<string | boolean>;
  190. beforeEach(async () => {
  191. await promptForEmailUnverified();
  192. validateFn = jest.mocked(input).mock.calls[0][0].validate as (
  193. input: string,
  194. ) => Promise<string | boolean>;
  195. });
  196. it('should reject invalid email formats with error message', async () => {
  197. const invalidEmails = [
  198. '',
  199. 'invalid',
  200. '@example.com',
  201. 'user@',
  202. 'user@.',
  203. 'user.com',
  204. 'user@.com',
  205. '@.',
  206. 'user@example.',
  207. 'user.@example.com',
  208. 'us..er@example.com',
  209. ];
  210. for (const email of invalidEmails) {
  211. const result = await validateFn(email);
  212. expect(typeof result).toBe('string');
  213. expect(result).toBe('Please enter a valid email address');
  214. }
  215. });
  216. it('should accept valid email formats with true', async () => {
  217. const validEmails = [
  218. 'valid@example.com',
  219. 'user.name@example.com',
  220. 'user+tag@example.com',
  221. 'user@subdomain.example.com',
  222. 'user@example.co.uk',
  223. '123@example.com',
  224. 'user-name@example.com',
  225. 'user_name@example.com',
  226. ];
  227. for (const email of validEmails) {
  228. await expect(validateFn(email)).toBe(true);
  229. }
  230. });
  231. });
  232. it('should save consent after successful email input', async () => {
  233. jest.mocked(input).mockResolvedValue('test@example.com');
  234. await promptForEmailUnverified();
  235. expect(telemetry.saveConsent).toHaveBeenCalledWith('test@example.com', {
  236. source: 'promptForEmailUnverified',
  237. });
  238. });
  239. });
  240. describe('checkEmailStatusOrExit', () => {
  241. const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => undefined as never);
  242. beforeEach(() => {
  243. jest.clearAllMocks();
  244. });
  245. it('should use CI email when in CI environment', async () => {
  246. jest.mocked(isCI).mockReturnValue(true);
  247. const mockResponse = new Response(JSON.stringify({ status: 'ok' }), {
  248. status: 200,
  249. statusText: 'OK',
  250. });
  251. jest.mocked(fetchWithTimeout).mockResolvedValue(mockResponse);
  252. await checkEmailStatusOrExit();
  253. expect(fetchWithTimeout).toHaveBeenCalledWith(
  254. 'https://api.promptfoo.app/api/users/status?email=ci-placeholder%40promptfoo.dev',
  255. undefined,
  256. 500,
  257. );
  258. });
  259. it('should use user email when not in CI environment', async () => {
  260. jest.mocked(isCI).mockReturnValue(false);
  261. jest.mocked(readGlobalConfig).mockReturnValue({
  262. id: 'test-id',
  263. account: { email: 'test@example.com' },
  264. });
  265. const mockResponse = new Response(JSON.stringify({ status: 'ok' }), {
  266. status: 200,
  267. statusText: 'OK',
  268. });
  269. jest.mocked(fetchWithTimeout).mockResolvedValue(mockResponse);
  270. await checkEmailStatusOrExit();
  271. expect(fetchWithTimeout).toHaveBeenCalledWith(
  272. 'https://api.promptfoo.app/api/users/status?email=test%40example.com',
  273. undefined,
  274. 500,
  275. );
  276. });
  277. it('should exit if limit exceeded', async () => {
  278. jest.mocked(isCI).mockReturnValue(false);
  279. jest.mocked(readGlobalConfig).mockReturnValue({
  280. id: 'test-id',
  281. account: { email: 'test@example.com' },
  282. });
  283. const mockResponse = new Response(JSON.stringify({ status: 'exceeded_limit' }), {
  284. status: 200,
  285. statusText: 'OK',
  286. });
  287. jest.mocked(fetchWithTimeout).mockResolvedValue(mockResponse);
  288. await checkEmailStatusOrExit();
  289. expect(mockExit).toHaveBeenCalledWith(1);
  290. expect(logger.error).toHaveBeenCalledWith(
  291. 'You have exceeded the maximum cloud inference limit. Please contact inquiries@promptfoo.dev to upgrade your account.',
  292. );
  293. });
  294. it('should display warning message when status is show_usage_warning', async () => {
  295. jest.mocked(isCI).mockReturnValue(false);
  296. jest.mocked(readGlobalConfig).mockReturnValue({
  297. id: 'test-id',
  298. account: { email: 'test@example.com' },
  299. });
  300. const warningMessage = 'You are approaching your usage limit';
  301. const mockResponse = new Response(
  302. JSON.stringify({ status: 'show_usage_warning', message: warningMessage }),
  303. {
  304. status: 200,
  305. statusText: 'OK',
  306. },
  307. );
  308. jest.mocked(fetchWithTimeout).mockResolvedValue(mockResponse);
  309. await checkEmailStatusOrExit();
  310. expect(logger.info).toHaveBeenCalledTimes(2);
  311. expect(logger.warn).toHaveBeenCalledWith(chalk.yellow(warningMessage));
  312. expect(mockExit).not.toHaveBeenCalled();
  313. });
  314. it('should handle fetch errors', async () => {
  315. jest.mocked(isCI).mockReturnValue(false);
  316. jest.mocked(readGlobalConfig).mockReturnValue({
  317. id: 'test-id',
  318. account: { email: 'test@example.com' },
  319. });
  320. jest.mocked(fetchWithTimeout).mockRejectedValue(new Error('Network error'));
  321. await checkEmailStatusOrExit();
  322. expect(logger.debug).toHaveBeenCalledWith(
  323. 'Failed to check user status: Error: Network error',
  324. );
  325. expect(mockExit).not.toHaveBeenCalled();
  326. });
  327. });
  328. describe('checkEmailStatus', () => {
  329. beforeEach(() => {
  330. jest.clearAllMocks();
  331. });
  332. it('should return no_email status when no email is provided', async () => {
  333. jest.mocked(isCI).mockReturnValue(false);
  334. jest.mocked(readGlobalConfig).mockReturnValue({});
  335. const result = await checkEmailStatus();
  336. expect(result).toEqual({
  337. status: 'no_email',
  338. hasEmail: false,
  339. message: 'Redteam evals require email verification. Please enter your work email:',
  340. });
  341. });
  342. it('should use CI email when in CI environment', async () => {
  343. jest.mocked(isCI).mockReturnValue(true);
  344. const mockResponse = new Response(JSON.stringify({ status: 'ok' }), {
  345. status: 200,
  346. statusText: 'OK',
  347. });
  348. jest.mocked(fetchWithTimeout).mockResolvedValue(mockResponse);
  349. const result = await checkEmailStatus();
  350. expect(fetchWithTimeout).toHaveBeenCalledWith(
  351. 'https://api.promptfoo.app/api/users/status?email=ci-placeholder%40promptfoo.dev',
  352. undefined,
  353. 500,
  354. );
  355. expect(result).toEqual({
  356. status: 'ok',
  357. hasEmail: true,
  358. email: 'ci-placeholder@promptfoo.dev',
  359. message: undefined,
  360. });
  361. });
  362. it('should return exceeded_limit status', async () => {
  363. jest.mocked(isCI).mockReturnValue(false);
  364. jest.mocked(readGlobalConfig).mockReturnValue({
  365. account: { email: 'test@example.com' },
  366. });
  367. const mockResponse = new Response(JSON.stringify({ status: 'exceeded_limit' }), {
  368. status: 200,
  369. statusText: 'OK',
  370. });
  371. jest.mocked(fetchWithTimeout).mockResolvedValue(mockResponse);
  372. const result = await checkEmailStatus();
  373. expect(result).toEqual({
  374. status: 'exceeded_limit',
  375. hasEmail: true,
  376. email: 'test@example.com',
  377. message: undefined,
  378. });
  379. });
  380. it('should return show_usage_warning status with message', async () => {
  381. jest.mocked(isCI).mockReturnValue(false);
  382. jest.mocked(readGlobalConfig).mockReturnValue({
  383. account: { email: 'test@example.com' },
  384. });
  385. const warningMessage = 'You are approaching your usage limit';
  386. const mockResponse = new Response(
  387. JSON.stringify({ status: 'show_usage_warning', message: warningMessage }),
  388. {
  389. status: 200,
  390. statusText: 'OK',
  391. },
  392. );
  393. jest.mocked(fetchWithTimeout).mockResolvedValue(mockResponse);
  394. const result = await checkEmailStatus();
  395. expect(result).toEqual({
  396. status: 'show_usage_warning',
  397. hasEmail: true,
  398. email: 'test@example.com',
  399. message: warningMessage,
  400. });
  401. });
  402. it('should handle fetch errors gracefully', async () => {
  403. jest.mocked(isCI).mockReturnValue(false);
  404. jest.mocked(readGlobalConfig).mockReturnValue({
  405. account: { email: 'test@example.com' },
  406. });
  407. jest.mocked(fetchWithTimeout).mockRejectedValue(new Error('Network error'));
  408. const result = await checkEmailStatus();
  409. expect(logger.debug).toHaveBeenCalledWith(
  410. 'Failed to check user status: Error: Network error',
  411. );
  412. expect(result).toEqual({
  413. status: 'ok',
  414. hasEmail: true,
  415. email: 'test@example.com',
  416. message: 'Unable to verify email status, but proceeding',
  417. });
  418. });
  419. });
  420. describe('isLoggedIntoCloud', () => {
  421. beforeEach(() => {
  422. jest.clearAllMocks();
  423. });
  424. it('should return true when user has email and not in CI', () => {
  425. jest.mocked(readGlobalConfig).mockReturnValue({
  426. account: { email: 'test@example.com' },
  427. });
  428. jest.mocked(isCI).mockReturnValue(false);
  429. expect(isLoggedIntoCloud()).toBe(true);
  430. });
  431. it('should return false when user has no email', () => {
  432. jest.mocked(readGlobalConfig).mockReturnValue({});
  433. jest.mocked(isCI).mockReturnValue(false);
  434. expect(isLoggedIntoCloud()).toBe(false);
  435. });
  436. it('should return false when in CI environment', () => {
  437. jest.mocked(readGlobalConfig).mockReturnValue({});
  438. jest.mocked(isCI).mockReturnValue(true);
  439. expect(isLoggedIntoCloud()).toBe(false);
  440. });
  441. it('should return false when user has email but in CI environment', () => {
  442. jest.mocked(readGlobalConfig).mockReturnValue({
  443. account: { email: 'test@example.com' },
  444. });
  445. jest.mocked(isCI).mockReturnValue(true);
  446. expect(isLoggedIntoCloud()).toBe(false);
  447. });
  448. });
  449. });
Tip!

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

Comments

Loading...