-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-command.test.ts
More file actions
223 lines (172 loc) · 7.63 KB
/
auth-command.test.ts
File metadata and controls
223 lines (172 loc) · 7.63 KB
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
/**
* Tests for Auth Command
* Following TDD approach
*/
import { Command } from 'commander';
import { AuthCommand } from '../../src/cli/commands/auth';
import { ConfigService } from '../../src/storage/config';
import { DeepLClient } from '../../src/api/deepl-client';
import { createMockConfigService } from '../helpers/mock-factories';
// Mock chalk (ESM-only)
jest.mock('chalk', () => {
const passthrough = (s: string) => s;
const obj: Record<string, unknown> & { level: number } = {
level: 3, red: passthrough, green: passthrough, blue: passthrough,
yellow: passthrough, gray: passthrough, bold: passthrough,
};
return { __esModule: true, default: obj };
});
// Mock Logger for registerAuth deprecation tests
jest.mock('../../src/utils/logger', () => ({
Logger: {
info: jest.fn(),
success: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
output: jest.fn(),
debug: jest.fn(),
},
}));
// Mock dependencies
jest.mock('../../src/storage/config');
jest.mock('../../src/api/deepl-client');
describe('AuthCommand', () => {
let mockConfigService: jest.Mocked<ConfigService>;
let authCommand: AuthCommand;
beforeEach(() => {
jest.clearAllMocks();
mockConfigService = createMockConfigService();
authCommand = new AuthCommand(mockConfigService);
});
describe('setKey()', () => {
it('should store API key in config', async () => {
// Mock DeepL client validation
const mockGetUsage = jest.fn().mockResolvedValue({ character: { count: 0, limit: 500000 } });
(DeepLClient as jest.MockedClass<typeof DeepLClient>).mockImplementation(() => ({
getUsage: mockGetUsage,
} as any));
await authCommand.setKey('a1b2c3d4-e5f6-7890-abcd-ef1234567890:fx');
expect(mockConfigService.set).toHaveBeenCalledWith('auth.apiKey', 'a1b2c3d4-e5f6-7890-abcd-ef1234567890:fx');
expect(mockGetUsage).toHaveBeenCalled();
});
it('should create client without config baseUrl to allow auto-detection', async () => {
const mockGetUsage = jest.fn().mockResolvedValue({ character: { count: 0, limit: 500000 } });
(DeepLClient as jest.MockedClass<typeof DeepLClient>).mockImplementation(() => ({
getUsage: mockGetUsage,
} as any));
await authCommand.setKey('test-key:fx');
// Client should be created with just the key, no baseUrl from config
expect(DeepLClient).toHaveBeenCalledWith('test-key:fx');
});
it('should throw error for empty API key', async () => {
await expect(authCommand.setKey('')).rejects.toThrow('API key cannot be empty');
});
it('should validate API key with DeepL API', async () => {
// Mock DeepL client validation
const mockGetUsage = jest.fn().mockResolvedValue({ character: { count: 0, limit: 500000 } });
(DeepLClient as jest.MockedClass<typeof DeepLClient>).mockImplementation(() => ({
getUsage: mockGetUsage,
} as any));
await authCommand.setKey('a1b2c3d4-e5f6-7890-abcd-ef1234567890:fx');
// Should validate by making a test request
expect(mockGetUsage).toHaveBeenCalled();
expect(mockConfigService.set).toHaveBeenCalled();
});
it('should handle config save errors', async () => {
// Mock DeepL client validation to succeed
const mockGetUsage = jest.fn().mockResolvedValue({ character: { count: 0, limit: 500000 } });
(DeepLClient as jest.MockedClass<typeof DeepLClient>).mockImplementation(() => ({
getUsage: mockGetUsage,
} as any));
(mockConfigService.set as jest.Mock).mockImplementationOnce(() => { throw new Error('Failed to save config'); });
await expect(authCommand.setKey('a1b2c3d4-e5f6-7890-abcd-ef1234567890:fx')).rejects.toThrow('Failed to save config');
});
it('should handle non-Error exceptions during validation', async () => {
// Mock DeepL client to throw non-Error exception
const mockGetUsage = jest.fn().mockRejectedValue('String error');
(DeepLClient as jest.MockedClass<typeof DeepLClient>).mockImplementation(() => ({
getUsage: mockGetUsage,
} as any));
await expect(authCommand.setKey('test-key')).rejects.toThrow('Failed to validate API key');
});
it('should handle non-authentication API errors', async () => {
// Mock DeepL client to throw error without "Authentication failed" message
const mockGetUsage = jest.fn().mockRejectedValue(new Error('Network timeout'));
(DeepLClient as jest.MockedClass<typeof DeepLClient>).mockImplementation(() => ({
getUsage: mockGetUsage,
} as any));
await expect(authCommand.setKey('test-key')).rejects.toThrow('Network timeout');
});
});
describe('getKey()', () => {
it('should retrieve API key from config', async () => {
(mockConfigService.getValue as jest.Mock).mockReturnValueOnce('test-api-key-123');
const key = await authCommand.getKey();
expect(key).toBe('test-api-key-123');
expect(mockConfigService.getValue).toHaveBeenCalledWith('auth.apiKey');
});
it('should return undefined when no key is set', async () => {
const originalEnv = process.env['DEEPL_API_KEY'];
delete process.env['DEEPL_API_KEY'];
try {
const key = await authCommand.getKey();
expect(key).toBeUndefined();
} finally {
if (originalEnv !== undefined) {
process.env['DEEPL_API_KEY'] = originalEnv;
}
}
});
it('should check environment variable DEEPL_API_KEY', async () => {
process.env['DEEPL_API_KEY'] = 'env-api-key';
const key = await authCommand.getKey();
expect(key).toBe('env-api-key');
delete process.env['DEEPL_API_KEY'];
});
it('should prefer config over environment variable', async () => {
process.env['DEEPL_API_KEY'] = 'env-api-key';
(mockConfigService.getValue as jest.Mock).mockReturnValueOnce('config-api-key');
const key = await authCommand.getKey();
expect(key).toBe('config-api-key');
delete process.env['DEEPL_API_KEY'];
});
});
describe('clearKey()', () => {
it('should remove API key from config', async () => {
await authCommand.clearKey();
expect(mockConfigService.delete).toHaveBeenCalledWith('auth.apiKey');
});
it('should handle config delete errors', async () => {
(mockConfigService.delete as jest.Mock).mockImplementationOnce(() => { throw new Error('Failed to delete'); });
await expect(authCommand.clearKey()).rejects.toThrow('Failed to delete');
});
});
});
describe('registerAuth - deprecation warning', () => {
// Dynamic import to avoid hoisting issues with chalk mock
let registerAuth: typeof import('../../src/cli/commands/register-auth').registerAuth;
beforeAll(async () => {
registerAuth = (await import('../../src/cli/commands/register-auth')).registerAuth;
});
beforeEach(() => {
jest.clearAllMocks();
});
it('should warn when positional API key is passed without --from-stdin', async () => {
const mockConfigService = createMockConfigService();
const mockGetUsage = jest.fn().mockResolvedValue({ character: { count: 0, limit: 500000 } });
(DeepLClient as jest.MockedClass<typeof DeepLClient>).mockImplementation(() => ({
getUsage: mockGetUsage,
} as any));
const program = new Command();
program.exitOverride();
registerAuth(program, {
getConfigService: () => mockConfigService,
handleError: (error: unknown) => { throw error; },
});
await program.parseAsync(['node', 'deepl', 'auth', 'set-key', 'test-key-123']);
const { Logger } = await import('../../src/utils/logger');
expect(Logger.warn).toHaveBeenCalledWith(
expect.stringContaining('deprecated'),
);
});
});