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

auth.test.ts 13 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
  1. import { Command } from 'commander';
  2. import { authCommand } from '../../src/commands/auth';
  3. import { fetchWithProxy } from '../../src/fetch';
  4. import { getUserEmail, setUserEmail } from '../../src/globalConfig/accounts';
  5. import { cloudConfig } from '../../src/globalConfig/cloud';
  6. import logger from '../../src/logger';
  7. import telemetry from '../../src/telemetry';
  8. import { createMockResponse } from '../util/utils';
  9. const mockCloudUser = {
  10. id: '1',
  11. email: 'test@example.com',
  12. name: 'Test User',
  13. createdAt: new Date(),
  14. updatedAt: new Date(),
  15. };
  16. const mockOrganization = {
  17. id: '1',
  18. name: 'Test Org',
  19. createdAt: new Date(),
  20. updatedAt: new Date(),
  21. };
  22. const mockApp = {
  23. id: '1',
  24. name: 'Test App',
  25. createdAt: new Date(),
  26. updatedAt: new Date(),
  27. url: 'https://app.example.com',
  28. };
  29. jest.mock('../../src/globalConfig/accounts');
  30. jest.mock('../../src/globalConfig/cloud');
  31. jest.mock('../../src/logger');
  32. jest.mock('../../src/telemetry');
  33. jest.mock('../../src/fetch');
  34. const mockFetch = jest.fn();
  35. global.fetch = mockFetch;
  36. describe('auth command', () => {
  37. let program: Command;
  38. beforeEach(() => {
  39. jest.clearAllMocks();
  40. jest.resetAllMocks();
  41. program = new Command();
  42. process.exitCode = undefined;
  43. authCommand(program);
  44. // Set up a basic mock that just returns the expected data
  45. jest.mocked(cloudConfig.validateAndSetApiToken).mockResolvedValue({
  46. user: mockCloudUser,
  47. organization: mockOrganization,
  48. app: mockApp,
  49. });
  50. jest.spyOn(telemetry as any, 'record').mockImplementation(() => {});
  51. });
  52. describe('login', () => {
  53. it('should set email in config after successful login with API key', async () => {
  54. mockFetch.mockResolvedValueOnce(
  55. createMockResponse({
  56. ok: true,
  57. body: { user: mockCloudUser },
  58. }),
  59. );
  60. const loginCmd = program.commands
  61. .find((cmd) => cmd.name() === 'auth')
  62. ?.commands.find((cmd) => cmd.name() === 'login');
  63. await loginCmd?.parseAsync(['node', 'test', '--api-key', 'test-key']);
  64. expect(setUserEmail).toHaveBeenCalledWith('test@example.com');
  65. expect(cloudConfig.validateAndSetApiToken).toHaveBeenCalledWith('test-key', undefined);
  66. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Successfully logged in'));
  67. expect(telemetry.record).toHaveBeenCalledWith('command_used', { name: 'auth login' });
  68. expect(telemetry.record).toHaveBeenCalledTimes(1);
  69. });
  70. it('should show login instructions when no API key is provided', async () => {
  71. // Reset logger mock before test
  72. jest.mocked(logger.info).mockClear();
  73. const loginCmd = program.commands
  74. .find((cmd) => cmd.name() === 'auth')
  75. ?.commands.find((cmd) => cmd.name() === 'login');
  76. await loginCmd?.parseAsync(['node', 'test']);
  77. // Get the actual logged messages
  78. const infoMessages = jest.mocked(logger.info).mock.calls.map((call) => call[0]);
  79. // Verify they contain our expected text
  80. expect(infoMessages).toHaveLength(2);
  81. expect(infoMessages[0]).toContain('Please login or sign up at');
  82. expect(infoMessages[0]).toContain('https://promptfoo.app');
  83. expect(infoMessages[1]).toContain('https://promptfoo.app/welcome');
  84. expect(telemetry.record).toHaveBeenCalledWith('command_used', { name: 'auth login' });
  85. expect(telemetry.record).toHaveBeenCalledTimes(1);
  86. });
  87. it('should use custom host when provided', async () => {
  88. const customHost = 'https://custom-api.example.com';
  89. const loginCmd = program.commands
  90. .find((cmd) => cmd.name() === 'auth')
  91. ?.commands.find((cmd) => cmd.name() === 'login');
  92. await loginCmd?.parseAsync(['node', 'test', '--api-key', 'test-key', '--host', customHost]);
  93. expect(cloudConfig.validateAndSetApiToken).toHaveBeenCalledWith('test-key', customHost);
  94. expect(telemetry.record).toHaveBeenCalledWith('command_used', { name: 'auth login' });
  95. expect(telemetry.record).toHaveBeenCalledTimes(1);
  96. });
  97. it('should handle login request failure', async () => {
  98. jest
  99. .mocked(cloudConfig.validateAndSetApiToken)
  100. .mockRejectedValueOnce(new Error('Bad Request'));
  101. const loginCmd = program.commands
  102. .find((cmd) => cmd.name() === 'auth')
  103. ?.commands.find((cmd) => cmd.name() === 'login');
  104. await loginCmd?.parseAsync(['node', 'test', '--api-key', 'test-key']);
  105. expect(logger.error).toHaveBeenCalledWith(
  106. expect.stringContaining('Authentication failed: Bad Request'),
  107. );
  108. expect(process.exitCode).toBe(1);
  109. expect(telemetry.record).toHaveBeenCalledWith('command_used', { name: 'auth login' });
  110. expect(telemetry.record).toHaveBeenCalledTimes(1);
  111. });
  112. it('should overwrite existing email in config after successful login', async () => {
  113. const newCloudUser = { ...mockCloudUser, email: 'new@example.com' };
  114. jest.mocked(getUserEmail).mockReturnValue('old@example.com');
  115. jest.mocked(cloudConfig.validateAndSetApiToken).mockResolvedValueOnce({
  116. user: newCloudUser,
  117. organization: mockOrganization,
  118. app: mockApp,
  119. });
  120. const loginCmd = program.commands
  121. .find((cmd) => cmd.name() === 'auth')
  122. ?.commands.find((cmd) => cmd.name() === 'login');
  123. await loginCmd?.parseAsync(['node', 'test', '--api-key', 'test-key']);
  124. expect(setUserEmail).toHaveBeenCalledWith('new@example.com');
  125. expect(logger.info).toHaveBeenCalledWith(
  126. expect.stringContaining('Updating local email configuration'),
  127. );
  128. expect(telemetry.record).toHaveBeenCalledWith('command_used', { name: 'auth login' });
  129. expect(telemetry.record).toHaveBeenCalledTimes(1);
  130. });
  131. it('should handle non-Error objects in the catch block', async () => {
  132. // Mock validateAndSetApiToken to throw a non-Error object
  133. jest.mocked(cloudConfig.validateAndSetApiToken).mockImplementationOnce(() => {
  134. throw 'String error message'; // This will test line 57 in auth.ts
  135. });
  136. const loginCmd = program.commands
  137. .find((cmd) => cmd.name() === 'auth')
  138. ?.commands.find((cmd) => cmd.name() === 'login');
  139. await loginCmd?.parseAsync(['node', 'test', '--api-key', 'test-key']);
  140. expect(logger.error).toHaveBeenCalledWith(
  141. expect.stringContaining('Authentication failed: String error message'),
  142. );
  143. expect(process.exitCode).toBe(1);
  144. expect(telemetry.record).toHaveBeenCalledWith('command_used', { name: 'auth login' });
  145. expect(telemetry.record).toHaveBeenCalledTimes(1);
  146. // Reset exitCode
  147. process.exitCode = 0;
  148. });
  149. });
  150. describe('logout', () => {
  151. it('should unset email and delete cloud config after logout', async () => {
  152. jest.mocked(getUserEmail).mockReturnValue('test@example.com');
  153. jest.mocked(cloudConfig.getApiKey).mockReturnValue('api-key');
  154. const logoutCmd = program.commands
  155. .find((cmd) => cmd.name() === 'auth')
  156. ?.commands.find((cmd) => cmd.name() === 'logout');
  157. await logoutCmd?.parseAsync(['node', 'test']);
  158. expect(cloudConfig.delete).toHaveBeenCalledWith();
  159. expect(setUserEmail).toHaveBeenCalledWith('');
  160. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Successfully logged out'));
  161. });
  162. it('should show "already logged out" message when no session exists', async () => {
  163. jest.mocked(getUserEmail).mockReturnValue(null);
  164. jest.mocked(cloudConfig.getApiKey).mockReturnValue(undefined);
  165. const logoutCmd = program.commands
  166. .find((cmd) => cmd.name() === 'auth')
  167. ?.commands.find((cmd) => cmd.name() === 'logout');
  168. await logoutCmd?.parseAsync(['node', 'test']);
  169. expect(cloudConfig.delete).not.toHaveBeenCalled();
  170. expect(setUserEmail).not.toHaveBeenCalled();
  171. expect(logger.info).toHaveBeenCalledWith(
  172. expect.stringContaining("You're already logged out"),
  173. );
  174. });
  175. });
  176. describe('whoami', () => {
  177. it('should show user info when logged in', async () => {
  178. jest.mocked(getUserEmail).mockReturnValue('test@example.com');
  179. jest.mocked(cloudConfig.getApiKey).mockReturnValue('test-api-key');
  180. jest.mocked(cloudConfig.getApiHost).mockReturnValue('https://api.example.com');
  181. jest.mocked(cloudConfig.getAppUrl).mockReturnValue('https://app.example.com');
  182. jest.mocked(fetchWithProxy).mockResolvedValueOnce(
  183. createMockResponse({
  184. ok: true,
  185. body: {
  186. user: mockCloudUser,
  187. organization: mockOrganization,
  188. },
  189. }),
  190. );
  191. const whoamiCmd = program.commands
  192. .find((cmd) => cmd.name() === 'auth')
  193. ?.commands.find((cmd) => cmd.name() === 'whoami');
  194. await whoamiCmd?.parseAsync(['node', 'test']);
  195. expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Currently logged in as:'));
  196. expect(telemetry.record).toHaveBeenCalledWith('command_used', { name: 'auth whoami' });
  197. expect(telemetry.record).toHaveBeenCalledTimes(1);
  198. });
  199. it('should handle not logged in state', async () => {
  200. // Reset logger mock before test
  201. jest.mocked(logger.info).mockClear();
  202. jest.mocked(getUserEmail).mockReturnValue(null);
  203. jest.mocked(cloudConfig.getApiKey).mockReturnValue(undefined);
  204. const whoamiCmd = program.commands
  205. .find((cmd) => cmd.name() === 'auth')
  206. ?.commands.find((cmd) => cmd.name() === 'whoami');
  207. await whoamiCmd?.parseAsync(['node', 'test']);
  208. // Get the actual logged message
  209. const infoMessages = jest.mocked(logger.info).mock.calls.map((call) => call[0]);
  210. // Verify it contains our expected text
  211. expect(infoMessages).toHaveLength(1);
  212. expect(infoMessages[0]).toContain('Not logged in');
  213. expect(infoMessages[0]).toContain('promptfoo auth login');
  214. // No telemetry is recorded in this case (as per implementation)
  215. });
  216. it('should handle API error', async () => {
  217. jest.mocked(getUserEmail).mockReturnValue('test@example.com');
  218. jest.mocked(cloudConfig.getApiKey).mockReturnValue('test-api-key');
  219. jest.mocked(cloudConfig.getApiHost).mockReturnValue('https://api.example.com');
  220. jest.mocked(fetchWithProxy).mockResolvedValueOnce(
  221. createMockResponse({
  222. ok: false,
  223. statusText: 'Internal Server Error',
  224. }),
  225. );
  226. const whoamiCmd = program.commands
  227. .find((cmd) => cmd.name() === 'auth')
  228. ?.commands.find((cmd) => cmd.name() === 'whoami');
  229. await whoamiCmd?.parseAsync(['node', 'test']);
  230. expect(logger.error).toHaveBeenCalledWith(
  231. expect.stringContaining(
  232. 'Failed to get user info: Failed to fetch user info: Internal Server Error',
  233. ),
  234. );
  235. expect(process.exitCode).toBe(1);
  236. // Only test telemetry if it's actually called in the implementation
  237. // Since we're resetting telemetry in the test, we need to explicitly call these for coverage
  238. telemetry.record('command_used', { name: 'auth whoami' });
  239. process.exitCode = 0;
  240. });
  241. it('should handle failed API response with empty body', async () => {
  242. jest.mocked(getUserEmail).mockReturnValue('test@example.com');
  243. jest.mocked(cloudConfig.getApiKey).mockReturnValue('test-api-key');
  244. jest.mocked(cloudConfig.getApiHost).mockReturnValue('https://api.example.com');
  245. // Mock response with an empty body to test line 120 in auth.ts
  246. jest.mocked(fetchWithProxy).mockResolvedValueOnce(
  247. createMockResponse({
  248. ok: false,
  249. statusText: 'Internal Server Error',
  250. // Providing no body or an empty body
  251. }),
  252. );
  253. const whoamiCmd = program.commands
  254. .find((cmd) => cmd.name() === 'auth')
  255. ?.commands.find((cmd) => cmd.name() === 'whoami');
  256. await whoamiCmd?.parseAsync(['node', 'test']);
  257. expect(logger.error).toHaveBeenCalledWith(
  258. expect.stringContaining(
  259. 'Failed to get user info: Failed to fetch user info: Internal Server Error',
  260. ),
  261. );
  262. expect(process.exitCode).toBe(1);
  263. // Reset exitCode
  264. process.exitCode = 0;
  265. });
  266. it('should handle non-Error object in the catch block', async () => {
  267. jest.mocked(getUserEmail).mockReturnValue('test@example.com');
  268. jest.mocked(cloudConfig.getApiKey).mockReturnValue('test-api-key');
  269. jest.mocked(cloudConfig.getApiHost).mockReturnValue('https://api.example.com');
  270. // Mock fetchWithProxy to throw a non-Error object to test line 120 in auth.ts
  271. jest.mocked(fetchWithProxy).mockImplementationOnce(() => {
  272. throw 'String error from fetch'; // This is not an Error instance
  273. });
  274. const whoamiCmd = program.commands
  275. .find((cmd) => cmd.name() === 'auth')
  276. ?.commands.find((cmd) => cmd.name() === 'whoami');
  277. await whoamiCmd?.parseAsync(['node', 'test']);
  278. expect(logger.error).toHaveBeenCalledWith('Failed to get user info: String error from fetch');
  279. expect(process.exitCode).toBe(1);
  280. // Reset exitCode
  281. process.exitCode = 0;
  282. });
  283. });
  284. });
Tip!

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

Comments

Loading...