Skip to content

Commit f234bc2

Browse files
committed
feat: merge profile feature and fix tests
1 parent c922db9 commit f234bc2

File tree

2 files changed

+38
-132
lines changed

2 files changed

+38
-132
lines changed

src/commands/auth.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ export function getAuthToken() {
8686
}
8787

8888
export function getCurrentUserName() {
89-
return config.get('username');
89+
const context = get_context();
90+
const profileAPI = context[ProfileAPI];
91+
return profileAPI.getCurrentProfile()?.username;
9092
}
9193

9294
export function getCurrentDirectory() {

tests/login.test.js

Lines changed: 35 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import chalk from 'chalk';
77
import fetch from 'node-fetch';
88
import Conf from 'conf';
99
import { BASE_URL, PROJECT_NAME, API_BASE } from '../src/commons.js';
10+
import { ProfileAPI } from '../src/modules/ProfileModule.js';
11+
import * as contextHelpers from '../src/temporary/context_helpers.js';
1012

1113
// Mock console to prevent actual logging
1214
vi.spyOn(console, 'log').mockImplementation(() => {});
@@ -49,68 +51,38 @@ vi.mock('conf', () => {
4951
};
5052
});
5153

52-
describe('auth.js', () => {
53-
// let config;
54+
const mockProfileModule = {
55+
switchProfileWizard: vi.fn(),
56+
getAuthToken: vi.fn(),
57+
getCurrentProfile: vi.fn(),
58+
};
59+
60+
const mockContext = {
61+
[ProfileAPI]: mockProfileModule,
62+
};
5463

64+
vi.spyOn(contextHelpers, 'get_context').mockReturnValue(mockContext);
65+
66+
67+
describe('auth.js', () => {
5568
beforeEach(() => {
5669
vi.clearAllMocks();
57-
// config = new Conf({ projectName: PROJECT_NAME });
5870
});
5971

6072
describe('login', () => {
6173
it('should login successfully with valid credentials', async () => {
62-
// Mock inquirer response
63-
inquirer.prompt.mockResolvedValue({
64-
username: 'testuser',
65-
password: 'testpass'
66-
});
67-
68-
// Mock fetch response
69-
fetch.mockResolvedValue({
70-
json: () => Promise.resolve({
71-
proceed: true,
72-
token: 'testtoken'
73-
})
74-
});
75-
76-
await login();
77-
78-
// Verify inquirer was called
79-
expect(inquirer.prompt).toHaveBeenCalled();
80-
81-
// Verify fetch was called with correct parameters
82-
expect(fetch).toHaveBeenCalledWith(`${BASE_URL}/login`, {
83-
method: 'POST',
84-
headers: expect.any(Object),
85-
body: JSON.stringify({
86-
username: 'testuser',
87-
password: 'testpass'
88-
}),
89-
});
90-
91-
// Verify spinner methods were called
92-
expect(mockSpinner.start).toHaveBeenCalled();
93-
expect(mockSpinner.succeed).toHaveBeenCalled();
74+
await login({}, mockContext);
75+
expect(mockProfileModule.switchProfileWizard).toHaveBeenCalled();
9476
});
9577

9678
it('should fail login with invalid credentials', async () => {
97-
inquirer.prompt.mockResolvedValue({ username: 'testuser', password: 'testpass' });
98-
fetch.mockResolvedValue({
99-
json: vi.fn().mockResolvedValue({ proceed: false }),
100-
ok: true,
101-
});
102-
103-
await login();
104-
expect(mockSpinner.fail).toHaveBeenCalledWith(chalk.red('Login failed. Please check your credentials.'));
79+
mockProfileModule.switchProfileWizard.mockRejectedValue(new Error('Invalid credentials'));
80+
await expect(login({}, mockContext)).rejects.toThrow('Invalid credentials');
81+
expect(mockProfileModule.switchProfileWizard).toHaveBeenCalled();
10582
});
10683

10784
it.skip('should handle login error', async () => {
108-
inquirer.prompt.mockResolvedValue({ username: 'testuser', password: 'testpass' });
109-
fetch.mockRejectedValue(new Error('Network error'));
110-
111-
// await expect(login()).rejects.toThrow('Network error');
112-
expect(mockSpinner.fail).toHaveBeenCalledWith(chalk.red('Failed to login'));
113-
// expect(console.error).toHaveBeenCalledWith(chalk.red('Error: Network error'));
85+
// This test needs to be updated to reflect the new login flow
11486
});
11587
});
11688

@@ -121,145 +93,78 @@ describe('auth.js', () => {
12193
beforeEach(() => {
12294
vi.clearAllMocks();
12395
config = new Conf({ projectName: PROJECT_NAME });
124-
// config.clear = vi.fn();
12596
});
12697

12798
it.skip('should logout successfully', async () => {
128-
// Mock config.get to return a token
129-
config.get = vi.fn().mockReturnValue('testtoken');
130-
await logout();
131-
// Verify config.clear was called
132-
expect(config.clear).toHaveBeenCalled();
133-
expect(mockSpinner.succeed).toHaveBeenCalledWith(chalk.green('Successfully logged out from Puter!'));
99+
// This test needs to be updated to reflect the new login flow
134100
});
135101

136102
it('should handle already logged out', async () => {
137103
config.get = vi.fn().mockReturnValue(null);
138-
139104
await logout();
140-
141105
expect(mockSpinner.info).toHaveBeenCalledWith(chalk.yellow('Already logged out'));
142106
});
143107

144108
it.skip('should handle logout error', async () => {
145-
config.get = vi.fn().mockReturnValue('testtoken');
146-
config.clear = vi.fn().mockImplementation(() => { throw new Error('Config error'); });
147-
148-
await logout();
149-
150-
expect(mockSpinner.fail).toHaveBeenCalled();
151-
expect(mockSpinner.fail).toHaveBeenCalledWith(chalk.red('Failed to logout'));
109+
// This test needs to be updated to reflect the new login flow
152110
});
153111

154112
});
155113

156114

157115
describe('getUserInfo', () => {
158116
it('should fetch user info successfully', async () => {
159-
// Mock fetch response
117+
mockProfileModule.getAuthToken.mockReturnValue('testtoken');
160118
fetch.mockResolvedValue({
161119
json: () => Promise.resolve({
162120
username: 'testuser',
163-
uuid: 'testuuid',
164-
165-
email_confirmed: true,
166-
is_temp: false,
167-
human_readable_age: '1 year',
168-
feature_flags: { flag1: true, flag2: false },
169121
}),
170122
ok: true,
171123
});
172124

173125
await getUserInfo();
174126

175-
// Verify fetch was called with correct parameters
176127
expect(fetch).toHaveBeenCalledWith(`${API_BASE}/whoami`, {
177128
method: 'GET',
178129
headers: expect.any(Object),
179130
});
180131
});
181132

182133
it('should handle fetch user info error', async () => {
183-
// Mock fetch to throw an error
134+
mockProfileModule.getAuthToken.mockReturnValue('testtoken');
184135
fetch.mockRejectedValue(new Error('Network error'));
185-
186136
await getUserInfo();
187-
188-
// Verify console.error was called
189-
expect(console.error).toHaveBeenCalledWith(chalk.red('Failed to get user info.\nError: Network error'));
137+
expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Failed to get user info.'));
190138
});
191139
});
192140

193141

194142
describe('Authentication', () => {
195-
let config;
196-
197-
beforeEach(() => {
198-
vi.clearAllMocks();
199-
config = new Conf({ projectName: PROJECT_NAME });
200-
});
201-
202143
it('should return false if auth token does not exist', () => {
203-
config.get.mockReturnValue(null);
204-
144+
mockProfileModule.getAuthToken.mockReturnValue(null);
205145
const result = isAuthenticated();
206-
207146
expect(result).toBe(false);
208147
});
209148

210149
it('should return null if the auth_token is not defined', () => {
211-
config.get.mockReturnValue(null);
212-
150+
mockProfileModule.getAuthToken.mockReturnValue(null);
213151
const result = getAuthToken();
214-
215-
expect(result).toBeUndefined();
152+
expect(result).toBe(null);
216153
});
217154

218155
it('should return the current username if it is defined', () => {
219-
config.get.mockReturnValue(null);
220-
156+
mockProfileModule.getCurrentProfile.mockReturnValue({ username: 'testuser' });
221157
const result = getCurrentUserName();
222-
223-
expect(result).toBeUndefined();
158+
expect(result).toBe('testuser');
224159
});
225160

226161
});
227162

228-
// describe('getCurrentDirectory', () => {
229-
// let config;
230-
231-
// beforeEach(() => {
232-
// vi.clearAllMocks();
233-
// config = new Conf({ projectName: PROJECT_NAME });
234-
// // config.get = vi.fn().mockReturnValue('testtoken')
235-
// });
236-
237-
// it('should return the current directory', () => {
238-
// config.get.mockReturnValue('/testuser');
239-
240-
// const result = getCurrentDirectory();
241-
242-
// expect(result).toBe('/testuser');
243-
// });
244-
// });
245-
246163
describe('getUsageInfo', () => {
247164
it('should fetch usage info successfully', async () => {
165+
mockProfileModule.getAuthToken.mockReturnValue('testtoken');
248166
fetch.mockResolvedValue({
249-
json: vi.fn().mockResolvedValue({
250-
user: [
251-
{
252-
service: { 'driver.interface': 'interface1', 'driver.method': 'method1', 'driver.implementation': 'impl1' },
253-
month: 1,
254-
year: 2023,
255-
monthly_usage: 10,
256-
monthly_limit: 100,
257-
policy: { 'rate-limit': { max: 5, period: 30000 } },
258-
},
259-
],
260-
apps: { app1: { used: 5, available: 50 } },
261-
usages: [{ name: 'usage1', used: 10, available: 100, refill: 'monthly' }],
262-
}),
167+
json: vi.fn().mockResolvedValue({}),
263168
ok: true,
264169
});
265170

@@ -272,11 +177,10 @@ describe('auth.js', () => {
272177
});
273178

274179
it('should handle fetch usage info error', async () => {
180+
mockProfileModule.getAuthToken.mockReturnValue('testtoken');
275181
fetch.mockRejectedValue(new Error('Network error'));
276-
277182
await getUsageInfo();
278-
279-
expect(console.error).toHaveBeenCalledWith(chalk.red('Failed to fetch usage information.\nError: Network error'));
183+
expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Failed to fetch usage information.'));
280184
});
281185
});
282186

0 commit comments

Comments
 (0)