-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli-resolver.test.ts
More file actions
373 lines (298 loc) · 12.6 KB
/
cli-resolver.test.ts
File metadata and controls
373 lines (298 loc) · 12.6 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
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
import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest';
import { CliResolver } from '../../src/codeql/cli-resolver';
// Mock child_process
vi.mock('child_process', () => ({
execFile: vi.fn(),
}));
// Mock fs/promises
vi.mock('fs/promises', () => ({
access: vi.fn(),
readdir: vi.fn(),
readFile: vi.fn(),
}));
import { execFile } from 'child_process';
import { access, readdir, readFile } from 'fs/promises';
function createMockLogger() {
return {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
show: vi.fn(),
dispose: vi.fn(),
channel: {},
} as any;
}
describe('CliResolver', () => {
let resolver: CliResolver;
let logger: any;
beforeEach(() => {
vi.resetAllMocks();
logger = createMockLogger();
resolver = new CliResolver(logger);
});
it('should be instantiable', () => {
expect(resolver).toBeDefined();
});
it('should resolve from CODEQL_PATH env var when set', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/usr/local/bin/codeql';
// Mock access to succeed (file exists)
vi.mocked(access).mockResolvedValueOnce(undefined);
// Mock execFile to return a version
vi.mocked(execFile).mockImplementationOnce(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL command-line toolchain release 2.19.0.\n', '');
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBe('/usr/local/bin/codeql');
process.env.CODEQL_PATH = originalEnv;
});
it('should cache resolved path', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/cached/codeql';
vi.mocked(access).mockResolvedValue(undefined);
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL command-line toolchain release 2.19.0.\n', '');
return {} as any;
},
);
const result1 = await resolver.resolve();
const result2 = await resolver.resolve();
expect(result1).toBe('/cached/codeql');
expect(result2).toBe('/cached/codeql');
// access should only be called once due to caching
expect(access).toHaveBeenCalledTimes(1);
process.env.CODEQL_PATH = originalEnv;
});
it('should invalidate cache when instructed', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/cached/codeql';
vi.mocked(access).mockResolvedValue(undefined);
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL command-line toolchain release 2.19.0.\n', '');
return {} as any;
},
);
await resolver.resolve();
resolver.invalidateCache();
await resolver.resolve();
// access should be called twice (once before invalidation, once after)
expect(access).toHaveBeenCalledTimes(2);
process.env.CODEQL_PATH = originalEnv;
});
it('should return undefined when no CLI is found', async () => {
const originalEnv = process.env.CODEQL_PATH;
delete process.env.CODEQL_PATH;
// All access checks fail
vi.mocked(access).mockRejectedValue(new Error('ENOENT'));
// execFile (which/command -v) also fails
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(new Error('not found'), '', '');
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('not found'));
process.env.CODEQL_PATH = originalEnv;
});
it('should fall back to PATH when CODEQL_PATH is invalid', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/nonexistent/codeql';
// CODEQL_PATH access fails
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === '/nonexistent/codeql') return Promise.reject(new Error('ENOENT'));
return Promise.resolve(undefined as any);
});
// which/command -v succeeds
let callCount = 0;
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callCount++;
if (callCount === 1) {
// which codeql
callback(null, '/usr/local/bin/codeql\n', '');
} else {
// codeql --version
callback(null, 'CodeQL CLI 2.19.0\n', '');
}
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBe('/usr/local/bin/codeql');
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('not a valid'));
process.env.CODEQL_PATH = originalEnv;
});
it('should be disposable', () => {
expect(() => resolver.dispose()).not.toThrow();
});
describe('vscode-codeql distribution discovery', () => {
const storagePath = '/mock/globalStorage/github.vscode-codeql';
const binaryName = process.platform === 'win32' ? 'codeql.exe' : 'codeql';
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.CODEQL_PATH;
delete process.env.CODEQL_PATH;
// Make `which codeql` fail
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
if (String(_cmd) === 'which' || String(_cmd) === 'where') {
callback(new Error('not found'), '', '');
} else {
// codeql --version for validateBinary
callback(null, 'CodeQL CLI 2.24.2\n', '');
}
return {} as any;
},
);
// All known filesystem locations fail
vi.mocked(access).mockRejectedValue(new Error('ENOENT'));
});
afterEach(() => {
if (originalEnv === undefined) {
delete process.env.CODEQL_PATH;
} else {
process.env.CODEQL_PATH = originalEnv;
}
});
it('should resolve from distribution.json hint', async () => {
resolver = new CliResolver(logger, storagePath);
// distribution.json exists with folderIndex=3
vi.mocked(readFile).mockResolvedValueOnce(
JSON.stringify({ folderIndex: 3, release: { name: 'v2.24.2' } }),
);
// The binary at distribution3/codeql/codeql is valid
const expectedPath = `${storagePath}/distribution3/codeql/${binaryName}`;
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining('vscode-codeql distribution'),
);
});
it('should fall back to directory scan when distribution.json is missing', async () => {
resolver = new CliResolver(logger, storagePath);
// distribution.json read fails
vi.mocked(readFile).mockRejectedValueOnce(new Error('ENOENT'));
// Directory listing returns distribution directories
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
{ name: 'distribution3', isDirectory: () => true },
{ name: 'distribution2', isDirectory: () => true },
{ name: 'queries', isDirectory: () => true },
{ name: 'distribution.json', isDirectory: () => false },
] as any);
// Only distribution3 has a valid binary
const expectedPath = `${storagePath}/distribution3/codeql/${binaryName}`;
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should scan directories sorted by descending number', async () => {
resolver = new CliResolver(logger, storagePath);
vi.mocked(readFile).mockRejectedValueOnce(new Error('ENOENT'));
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
{ name: 'distribution10', isDirectory: () => true },
{ name: 'distribution2', isDirectory: () => true },
] as any);
// All binaries are valid — should pick distribution10 (highest number)
vi.mocked(access).mockResolvedValue(undefined as any);
const result = await resolver.resolve();
expect(result).toBe(`${storagePath}/distribution10/codeql/${binaryName}`);
});
it('should return undefined when no storage path is provided', async () => {
resolver = new CliResolver(logger); // no storage path
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(new Error('not found'), '', '');
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBeUndefined();
});
it('should skip distribution directories without a valid binary', async () => {
resolver = new CliResolver(logger, storagePath);
vi.mocked(readFile).mockRejectedValueOnce(new Error('ENOENT'));
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution3', isDirectory: () => true },
{ name: 'distribution2', isDirectory: () => true },
{ name: 'distribution1', isDirectory: () => true },
] as any);
const expectedPath = `${storagePath}/distribution1/codeql/${binaryName}`;
vi.mocked(access).mockImplementation((path: any) => {
// Only distribution1 has the binary
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should handle distribution.json with invalid JSON gracefully', async () => {
resolver = new CliResolver(logger, storagePath);
// Return non-JSON content
vi.mocked(readFile).mockResolvedValueOnce('not-valid-json');
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
] as any);
const expectedPath = `${storagePath}/distribution1/codeql/${binaryName}`;
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should discover CLI from alternate casing of storage path', async () => {
// Simulate the caller providing 'GitHub.vscode-codeql' (StoragePaths publisher casing)
// but the actual directory on disk is 'github.vscode-codeql' (lowercased by VS Code).
const lowercaseExtStorage = '/mock/globalStorage/github.vscode-codeql';
const publisherCaseExtStorage = '/mock/globalStorage/GitHub.vscode-codeql';
resolver = new CliResolver(logger, publisherCaseExtStorage);
// distribution.json at the publisher-cased path throws; the lowercase path returns valid JSON
vi.mocked(readFile).mockImplementation((path: any) => {
if (String(path).startsWith(publisherCaseExtStorage)) {
return Promise.reject(new Error('ENOENT'));
}
return Promise.resolve(JSON.stringify({ folderIndex: 1 }) as any);
});
const expectedPath = `${lowercaseExtStorage}/distribution1/codeql/${binaryName}`;
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should handle distribution.json without folderIndex property', async () => {
resolver = new CliResolver(logger, storagePath);
vi.mocked(readFile).mockResolvedValueOnce(
JSON.stringify({ release: { name: 'v2.24.2' } }),
);
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
] as any);
const expectedPath = `${storagePath}/distribution1/codeql/${binaryName}`;
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
});
});