puter-cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,268 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { login, logout, getUserInfo, isAuthenticated, getAuthToken, getCurrentUserName,
3
+ getCurrentDirectory, getUsageInfo } from './commands/auth.js';
4
+ import inquirer from 'inquirer';
5
+ import ora from 'ora';
6
+ import chalk from 'chalk';
7
+ import fetch from 'node-fetch';
8
+ import Conf from 'conf';
9
+ import { BASE_URL } from '../commands/commons.js';
10
+
11
+ // Mock console to prevent actual logging
12
+ vi.spyOn(console, 'log').mockImplementation(() => {});
13
+ vi.spyOn(console, 'error').mockImplementation(() => {});
14
+
15
+ // Mock dependencies
16
+ vi.mock('inquirer');
17
+ vi.mock('chalk', () => ({
18
+ default: {
19
+ green: vi.fn(text => text),
20
+ red: vi.fn(text => text),
21
+ dim: vi.fn(text => text)
22
+ }
23
+ }));
24
+ vi.mock('node-fetch');
25
+
26
+ // Mock Conf
27
+ vi.mock('conf', () => {
28
+ return {
29
+ default: vi.fn().mockImplementation(() => ({
30
+ set: vi.fn(),
31
+ get: vi.fn(),
32
+ }))
33
+ }
34
+ });
35
+
36
+ // Create a mock spinner object
37
+ const mockSpinner = {
38
+ start: vi.fn().mockReturnThis(),
39
+ succeed: vi.fn().mockReturnThis(),
40
+ fail: vi.fn().mockReturnThis()
41
+ };
42
+
43
+ // Mock ora
44
+ vi.mock('ora', () => ({
45
+ default: vi.fn(() => mockSpinner)
46
+ }));
47
+
48
+
49
+ describe('auth.js', () => {
50
+ beforeEach(() => {
51
+ vi.clearAllMocks();
52
+ });
53
+
54
+ describe('login', () => {
55
+ it('should login successfully with valid credentials', async () => {
56
+ // Mock inquirer response
57
+ inquirer.prompt.mockResolvedValue({
58
+ username: 'testuser',
59
+ password: 'testpass'
60
+ });
61
+
62
+ // Mock fetch response
63
+ fetch.mockResolvedValue({
64
+ json: () => Promise.resolve({
65
+ proceed: true,
66
+ token: 'testtoken'
67
+ })
68
+ });
69
+
70
+ await login();
71
+
72
+ // Verify inquirer was called
73
+ expect(inquirer.prompt).toHaveBeenCalled();
74
+
75
+ // Verify fetch was called with correct parameters
76
+ expect(fetch).toHaveBeenCalledWith(`${BASE_URL}/login`, {
77
+ method: 'POST',
78
+ headers: expect.any(Object),
79
+ body: JSON.stringify({
80
+ username: 'testuser',
81
+ password: 'testpass'
82
+ }),
83
+ });
84
+
85
+ // Verify spinner methods were called
86
+ expect(mockSpinner.start).toHaveBeenCalled();
87
+ expect(mockSpinner.succeed).toHaveBeenCalled();
88
+
89
+ });
90
+ /*
91
+ it('should fail login with invalid credentials', async () => {
92
+ inquirer.prompt.mockResolvedValue({ username: 'testuser', password: 'testpass' });
93
+ fetch.mockResolvedValue({
94
+ json: vi.fn().mockResolvedValue({ proceed: false }),
95
+ ok: true,
96
+ });
97
+ const spinner = { start: vi.fn(), fail: vi.fn() };
98
+ ora.mockReturnValue(spinner);
99
+
100
+ await login();
101
+
102
+ expect(spinner.fail).toHaveBeenCalledWith(chalk.red('Login failed. Please check your credentials.'));
103
+ });
104
+
105
+ it('should handle login error', async () => {
106
+ inquirer.prompt.mockResolvedValue({ username: 'testuser', password: 'testpass' });
107
+ fetch.mockRejectedValue(new Error('Network error'));
108
+ const spinner = { start: vi.fn(), fail: vi.fn() };
109
+ ora.mockReturnValue(spinner);
110
+
111
+ await login();
112
+
113
+ expect(spinner.fail).toHaveBeenCalledWith(chalk.red('Failed to login'));
114
+ });*/
115
+ });
116
+ /*
117
+ describe('logout', () => {
118
+ it('should logout successfully', async () => {
119
+ config.get.mockReturnValue('testtoken');
120
+ const spinner = { start: vi.fn(), succeed: vi.fn() };
121
+ ora.mockReturnValue(spinner);
122
+
123
+ await logout();
124
+
125
+ expect(config.clear).toHaveBeenCalled();
126
+ expect(spinner.succeed).toHaveBeenCalledWith(chalk.green('Successfully logged out from Puter!'));
127
+ });
128
+
129
+ it('should handle already logged out', async () => {
130
+ config.get.mockReturnValue(null);
131
+ const spinner = { start: vi.fn(), info: vi.fn() };
132
+ ora.mockReturnValue(spinner);
133
+
134
+ await logout();
135
+
136
+ expect(spinner.info).toHaveBeenCalledWith(chalk.yellow('Already logged out'));
137
+ });
138
+
139
+ it('should handle logout error', async () => {
140
+ config.get.mockReturnValue('testtoken');
141
+ config.clear.mockImplementation(() => { throw new Error('Config error'); });
142
+ const spinner = { start: vi.fn(), fail: vi.fn() };
143
+ ora.mockReturnValue(spinner);
144
+
145
+ await logout();
146
+
147
+ expect(spinner.fail).toHaveBeenCalledWith(chalk.red('Failed to logout'));
148
+ });
149
+ });
150
+
151
+ describe('getUserInfo', () => {
152
+ it('should fetch user info successfully', async () => {
153
+ fetch.mockResolvedValue({
154
+ json: vi.fn().mockResolvedValue({
155
+ username: 'testuser',
156
+ uuid: 'testuuid',
157
+ email: 'test@example.com',
158
+ email_confirmed: true,
159
+ is_temp: false,
160
+ human_readable_age: '1 year',
161
+ feature_flags: { flag1: true, flag2: false },
162
+ }),
163
+ ok: true,
164
+ });
165
+
166
+ await getUserInfo();
167
+
168
+ expect(fetch).toHaveBeenCalledWith(`${API_BASE}/whoami`, {
169
+ method: 'GET',
170
+ headers: expect.any(Object),
171
+ });
172
+ });
173
+
174
+ it('should handle fetch user info error', async () => {
175
+ fetch.mockRejectedValue(new Error('Network error'));
176
+
177
+ await getUserInfo();
178
+
179
+ expect(console.error).toHaveBeenCalledWith(chalk.red('Failed to get user info.\nError: Network error'));
180
+ });
181
+ });
182
+
183
+ describe('isAuthenticated', () => {
184
+ it('should return true if auth token exists', () => {
185
+ config.get.mockReturnValue('testtoken');
186
+
187
+ const result = isAuthenticated();
188
+
189
+ expect(result).toBe(true);
190
+ });
191
+
192
+ it('should return false if auth token does not exist', () => {
193
+ config.get.mockReturnValue(null);
194
+
195
+ const result = isAuthenticated();
196
+
197
+ expect(result).toBe(false);
198
+ });
199
+ });
200
+
201
+ describe('getAuthToken', () => {
202
+ it('should return the auth token', () => {
203
+ config.get.mockReturnValue('testtoken');
204
+
205
+ const result = getAuthToken();
206
+
207
+ expect(result).toBe('testtoken');
208
+ });
209
+ });
210
+
211
+ describe('getCurrentUserName', () => {
212
+ it('should return the current username', () => {
213
+ config.get.mockReturnValue('testuser');
214
+
215
+ const result = getCurrentUserName();
216
+
217
+ expect(result).toBe('testuser');
218
+ });
219
+ });
220
+
221
+ describe('getCurrentDirectory', () => {
222
+ it('should return the current directory', () => {
223
+ config.get.mockReturnValue('/testuser');
224
+
225
+ const result = getCurrentDirectory();
226
+
227
+ expect(result).toBe('/testuser');
228
+ });
229
+ });
230
+
231
+ describe('getUsageInfo', () => {
232
+ it('should fetch usage info successfully', async () => {
233
+ fetch.mockResolvedValue({
234
+ json: vi.fn().mockResolvedValue({
235
+ user: [
236
+ {
237
+ service: { 'driver.interface': 'interface1', 'driver.method': 'method1', 'driver.implementation': 'impl1' },
238
+ month: 1,
239
+ year: 2023,
240
+ monthly_usage: 10,
241
+ monthly_limit: 100,
242
+ policy: { 'rate-limit': { max: 5, period: 30000 } },
243
+ },
244
+ ],
245
+ apps: { app1: { used: 5, available: 50 } },
246
+ usages: [{ name: 'usage1', used: 10, available: 100, refill: 'monthly' }],
247
+ }),
248
+ ok: true,
249
+ });
250
+
251
+ await getUsageInfo();
252
+
253
+ expect(fetch).toHaveBeenCalledWith(`${API_BASE}/drivers/usage`, {
254
+ method: 'GET',
255
+ headers: expect.any(Object),
256
+ });
257
+ });
258
+
259
+ it('should handle fetch usage info error', async () => {
260
+ fetch.mockRejectedValue(new Error('Network error'));
261
+
262
+ await getUsageInfo();
263
+
264
+ expect(console.error).toHaveBeenCalledWith(chalk.red('Failed to fetch usage information.\nError: Network error'));
265
+ });
266
+ });
267
+ */
268
+ });