-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsolution-converter.test.ts
More file actions
453 lines (390 loc) · 20.3 KB
/
solution-converter.test.ts
File metadata and controls
453 lines (390 loc) · 20.3 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/**
* Copyright 2025-2026 Arm Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect, it, describe } from '@jest/globals';
import * as path from 'path';
import * as manifest from '../manifest';
import { ExtensionContext } from 'vscode';
import * as vscode from 'vscode';
import { SolutionConverterImpl } from './solution-converter';
import { MockOutputChannelProvider, outputChannelProviderFactory } from '../vscode-api/output-channel-provider.factories';
import { MockConfigurationProvider, configurationProviderFactory } from '../vscode-api/configuration-provider.factories';
import { MockProcessManager, processManagerFactory } from '../vscode-api/runner/process-manager.factories';
import { MockSolutionManager, solutionManagerFactory } from './solution-manager.factories';
import { CmsisToolboxManager, CmsisToolboxManagerImpl } from './cmsis-toolbox';
import { CompileCommandsGenerator } from './intellisense/compile-commands-generator';
import { HandleBuildEnoent } from '../tasks/build/handle-enoent';
import { VcpkgManager } from '../vcpkg/vcpkg-manager';
import { vcpkgManagerFactory } from './../vcpkg/vcpkg-manager.factories';
import { initUtils } from './../util';
import { CSolution } from './csolution';
import { csolutionServiceFactory } from '../json-rpc/csolution-rpc-client.factory';
import { ConvertSolutionParams } from '../json-rpc/csolution-rpc-client';
import { CbuildFile } from './files/cbuild-file';
import * as vscodeUtils from '../utils/vscode-utils';
import { getWorkspaceFolder } from '../utils/vscode-utils';
import * as fsUtils from '../utils/fs-utils';
import { ConvertRequestData, SolutionEventHub } from './solution-event-hub';
import { waitTimeout } from '../__test__/test-waits';
import { SolutionProblemsImpl } from './solution-problems';
jest.mock('which', () => jest.fn((cmd) => Promise.resolve(path.join('path', 'to', cmd))));
const ACTIVE_SOLUTION = path.join(__dirname, 'Active.csolution.yml');
const checkConvertSolution = (
csolutionService: jest.Mocked<ReturnType<typeof csolutionServiceFactory>>,
updateRte: boolean,
activeTarget?: string,
) => {
const expectedArgs: ConvertSolutionParams = {
solution: ACTIVE_SOLUTION,
activeTarget: activeTarget ?? '',
updateRte: updateRte
};
expect(csolutionService.convertSolution).toHaveBeenCalledTimes(1);
expect(csolutionService.convertSolution).toHaveBeenCalledWith(expectedArgs);
};
describe('SolutionConverter', () => {
let solutionManager: MockSolutionManager;
let mockCSolution: jest.Mocked<CSolution>;
let eventHub: SolutionEventHub;
let mockConfigurationProvider: MockConfigurationProvider;
let converter: SolutionConverterImpl;
let outputChannelProvider: MockOutputChannelProvider;
let processManager: MockProcessManager;
let compileCommandsGenerator: CompileCommandsGenerator;
let cmsisToolboxManager: CmsisToolboxManager;
let mockHandleBuildEnoent: jest.MockedFunction<HandleBuildEnoent>;
let mockCsolutionService: jest.Mocked<ReturnType<typeof csolutionServiceFactory>>;
let convertRequestData: ConvertRequestData;
let completedListener: jest.Mock;
let solutionProblems: SolutionProblemsImpl;
/**
* Helper to wait for N completion events from EventHub
*/
const waitForNCompletions = (count: number): Promise<void> => {
let receivedCount = 0;
return new Promise<void>((resolve) => {
const disposable = eventHub.onDidConvertCompleted(() => {
receivedCount++;
if (receivedCount >= count) {
disposable.dispose();
resolve();
}
});
});
};
/**
* Helper to fire convert request and wait for completion
* Follows the extension's event-driven async pattern
*/
const fireAndWaitForConversion = async (): Promise<void> => {
await eventHub.fireConvertRequest(convertRequestData);
await waitForNCompletions(1);
};
beforeEach(async () => {
(VcpkgManager as unknown as { _instance: VcpkgManager | null })._instance = vcpkgManagerFactory();
mockConfigurationProvider = configurationProviderFactory();
// Use real EventHub instance
eventHub = new SolutionEventHub();
completedListener = jest.fn();
eventHub.onDidConvertCompleted(completedListener);
// Initialize convertRequestData with default test values
convertRequestData = {
solutionPath: ACTIVE_SOLUTION,
targetSet: undefined,
updateRte: undefined,
restartRpc: undefined,
lockAbort: undefined
};
solutionManager = solutionManagerFactory();
outputChannelProvider = outputChannelProviderFactory();
processManager = processManagerFactory();
mockHandleBuildEnoent = jest.fn();
mockCsolutionService = csolutionServiceFactory();
cmsisToolboxManager = new CmsisToolboxManagerImpl(
processManager,
mockHandleBuildEnoent,
mockCsolutionService,
);
compileCommandsGenerator = {
runCbuildSetup: jest.fn().mockResolvedValue([true, []]),
} as unknown as jest.Mocked<CompileCommandsGenerator>;
mockCSolution = jest.mocked<CSolution>(new CSolution());
solutionManager.getCsolution.mockReturnValue(mockCSolution);
converter = new SolutionConverterImpl(
solutionManager,
eventHub,
mockConfigurationProvider,
outputChannelProvider,
cmsisToolboxManager,
compileCommandsGenerator,
);
solutionProblems = new SolutionProblemsImpl(solutionManager, eventHub);
initUtils(mockConfigurationProvider, solutionManager);
converter.activate({ subscriptions: [] } as unknown as ExtensionContext);
await solutionProblems.activate({ subscriptions: [] } as unknown as ExtensionContext);
mockCsolutionService.listMissingPacks.mockResolvedValue({ success: true });
mockCsolutionService.convertSolution.mockResolvedValue({ success: true });
mockCsolutionService.discoverLayers.mockResolvedValue({ success: true });
mockCsolutionService.getLogMessages.mockResolvedValue({ success: true });
mockCsolutionService.shutdown.mockResolvedValue({ success: true });
mockCsolutionService.loadPacks.mockResolvedValue({ success: true });
mockCsolutionService.getCsolutionBin.mockReturnValue('path/to/csolution');
});
it('run solution convert without --update-rte if not specified', async () => {
await fireAndWaitForConversion();
checkConvertSolution(mockCsolutionService, false);
expect(completedListener).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledWith(
expect.objectContaining({
severity: 'success',
detection: false
})
);
});
it('run solution convert with --update-rte if specified', async () => {
convertRequestData.updateRte = true;
await fireAndWaitForConversion();
checkConvertSolution(mockCsolutionService, true);
expect(completedListener).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledWith(
expect.objectContaining({
severity: 'success',
detection: false
})
);
});
it('run solution convert with --active when targetSet is specified', async () => {
convertRequestData.targetSet = 'foo';
await fireAndWaitForConversion();
checkConvertSolution(mockCsolutionService, false, 'foo');
expect(completedListener).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledWith(
expect.objectContaining({
severity: 'success',
detection: false
})
);
});
it('should handle restartRpc flag', async () => {
convertRequestData.restartRpc = true;
await fireAndWaitForConversion();
expect(mockCsolutionService.shutdown).toHaveBeenCalledTimes(1);
expect(mockCsolutionService.loadPacks).toHaveBeenCalledTimes(1);
expect(mockCsolutionService.convertSolution).toHaveBeenCalledTimes(1);
});
it('sends output to the output channel', async () => {
await fireAndWaitForConversion();
const outputChannel = outputChannelProvider.mockGetCreatedChannelByName(manifest.CMSIS_SOLUTION_OUTPUT_CHANNEL);
expect(outputChannel!.mockAppendedStrings).toEqual([
expect.stringContaining('⚙️ Converting solution...'),
expect.stringContaining('Check for missing packs...'),
expect.stringContaining('Convert solution...'),
expect.stringContaining('Setup database...'),
expect.stringContaining('Get log messages...'),
expect.stringContaining('✅ Convert solution completed'),
]);
expect(completedListener).toHaveBeenCalledTimes(1);
});
it('prints an error message when ListMissingPacks fails and ConvertSolution is skipped', async () => {
mockCsolutionService.listMissingPacks.mockResolvedValue({ success: false });
mockCsolutionService.convertSolution.mockResolvedValue({ success: false });
await fireAndWaitForConversion();
const outputChannel = outputChannelProvider.mockGetCreatedChannelByName(manifest.CMSIS_SOLUTION_OUTPUT_CHANNEL);
// When listMissingPacks fails, ConvertSolution is skipped
expect(outputChannel!.mockAppendedStrings).toEqual([
expect.stringContaining('⚙️ Converting solution...'),
expect.stringContaining('Check for missing packs...'),
expect.stringContaining('Get log messages...'),
expect.stringContaining('🟥 Convert solution failed'),
]);
expect(completedListener).toHaveBeenCalledTimes(1);
});
it('prints an error when convert solution fails', async () => {
mockCsolutionService.listMissingPacks.mockResolvedValue({ success: true });
mockCsolutionService.convertSolution.mockResolvedValue({ success: false });
await fireAndWaitForConversion();
const outputChannel = outputChannelProvider.mockGetCreatedChannelByName(manifest.CMSIS_SOLUTION_OUTPUT_CHANNEL);
expect(outputChannel!.mockAppendedStrings).toEqual([
expect.stringContaining('⚙️ Converting solution...'),
expect.stringContaining('Check for missing packs...'),
expect.stringContaining('Convert solution...'),
expect.stringContaining('Get log messages...'),
expect.stringContaining('🟥 Convert solution failed'),
]);
expect(completedListener).toHaveBeenCalledTimes(1);
});
it('run solution convert and download missing packs', async () => {
const mockRunCbuildSetup = jest.spyOn(compileCommandsGenerator, 'runCbuildSetup').mockResolvedValue([true, []]);
const mockRunCmsisTool = jest.spyOn(cmsisToolboxManager, 'runCmsisTool').mockResolvedValue([0, undefined]);
mockCsolutionService.listMissingPacks.mockResolvedValue({
success: true, packs: [
'VendorA::PackA@1.0.0', 'VendorB::PackB@2.0.0'
]
});
await fireAndWaitForConversion();
expect(mockRunCmsisTool).toHaveBeenCalledTimes(2);
expect(mockRunCmsisTool).toHaveBeenNthCalledWith(1, 'cpackget',
expect.arrayContaining(['add', 'VendorA::PackA@1.0.0']), expect.any(Function), undefined, undefined, true);
expect(mockRunCmsisTool).toHaveBeenNthCalledWith(2, 'cpackget',
expect.arrayContaining(['add', 'VendorB::PackB@2.0.0']), expect.any(Function), undefined, undefined, true);
expect(mockRunCbuildSetup).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledTimes(1);
});
it('run solution convert and discover layers', async () => {
mockCsolutionService.convertSolution.mockResolvedValue({ success: false, undefinedLayers: ['$Board-Layer'] });
await fireAndWaitForConversion();
expect(mockCsolutionService.discoverLayers).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledWith(
expect.objectContaining({
severity: 'error',
detection: true
})
);
});
it('run solution convert and check whether to update compile commands', async () => {
const mockRunCbuildSetup = jest.spyOn(compileCommandsGenerator, 'runCbuildSetup').mockResolvedValue([true,[]]);
mockCSolution.getContextDescriptors = jest.fn().mockReturnValue([{ displayName: 'context' }]);
mockCSolution.cbuilds = [];
mockCSolution.cbuilds.some = jest.fn().mockReturnValue(false);
mockCSolution.cbuildIdxFile.cbuildFiles.get = jest.fn().mockReturnValue({ outDir: './out' } as CbuildFile);
await fireAndWaitForConversion();
expect(mockRunCbuildSetup).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledTimes(1);
});
it('get log messages and set diagnostics accordingly', async () => {
mockCsolutionService.convertSolution.mockResolvedValue({ success: false });
mockCsolutionService.getLogMessages.mockResolvedValue({
success: true,
errors: ['hello.cproject.yml:41:11 - file path/to/hello.c not found'],
warnings: ['hello.csolution.yml - solution created for unknown tool'],
info: ['hello.cbuild-idx.yml - file generated successfully', 'general info message'],
});
await fireAndWaitForConversion();
expect(completedListener).toHaveBeenCalledTimes(1);
});
it('get cbuild west output and set diagnostics accordingly', async () => {
mockCsolutionService.convertSolution.mockResolvedValue({ success: true });
mockCsolutionService.getLogMessages.mockResolvedValue({ success: true });
let mockRunCbuildSetup = jest.spyOn(compileCommandsGenerator, 'runCbuildSetup').mockResolvedValue([true, [
'warning cbuild: missing ZEPHYR_BASE environment variable',
'error cbuild: exec: "west": executable file not found in $PATH',
]]);
mockCSolution.getContextDescriptors = jest.fn().mockReturnValue([{ displayName: 'context' }]);
mockCSolution.cbuilds = [];
mockCSolution.cbuilds.some = jest.fn().mockReturnValue(false);
mockCSolution.cbuildIdxFile.cbuildFiles.get = jest.fn().mockReturnValue({ outDir: './out' } as CbuildFile);
jest.spyOn(vscodeUtils, 'getWorkspaceFolder').mockReturnValue('workspace/folder');
await fireAndWaitForConversion();
await waitTimeout();
expect(mockRunCbuildSetup).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenLastCalledWith(
expect.objectContaining({
toolsOutputMessages: expect.arrayContaining([
'warning cbuild: missing ZEPHYR_BASE environment variable',
'error cbuild: exec: "west": executable file not found in $PATH',
]),
}),
);
// Remove settings.json
completedListener.mockClear();
const settings = path.join(getWorkspaceFolder(), '.vscode', 'settings.json');
mockRunCbuildSetup.mockClear();
fsUtils.deleteFileIfExists(settings);
await fireAndWaitForConversion();
expect(mockRunCbuildSetup).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledTimes(1);
// No errors/warnings
completedListener.mockClear();
mockRunCbuildSetup = jest.spyOn(compileCommandsGenerator, 'runCbuildSetup').mockResolvedValue([true, []]);
mockRunCbuildSetup.mockClear();
await fireAndWaitForConversion();
expect(mockRunCbuildSetup).toHaveBeenCalledTimes(1);
expect(completedListener).toHaveBeenCalledTimes(1);
});
describe('conversion coalescing', () => {
const mockConvertSolutionDelay = () => {
mockCsolutionService.convertSolution.mockImplementation(async (param) => {
await waitTimeout(50);
// emulate return value to check which request makes through
return { success: true, selectCompiler: param.activeTarget === 'foo' ? [param.activeTarget] : undefined };
});
};
it('should not abort current conversion if locked', async () => {
// Mock convertSolution to take time
mockConvertSolutionDelay();
const waitPromise = waitForNCompletions(1);
convertRequestData.lockAbort = true;
convertRequestData.targetSet = 'foo';
// Fire two requests with small delay
await eventHub.fireConvertRequest(convertRequestData);
await waitTimeout();
convertRequestData.targetSet = 'bar';
await eventHub.fireConvertRequest(convertRequestData);
// Wait for the single completion event
await waitPromise;
// Should only convert once because second request was coalesced
expect(mockCsolutionService.convertSolution).toHaveBeenCalledTimes(1);
expect(mockCsolutionService.convertSolution).toHaveBeenCalledWith(
expect.objectContaining({ activeTarget: 'foo' })
);
expect(completedListener).toHaveBeenCalledTimes(1);
// check if call is from request with 'foo'
expect(completedListener).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'success', detection: true })
);
});
it('should start new conversion if not locked', async () => {
// Mock to take time
mockConvertSolutionDelay();
const waitPromise = waitForNCompletions(1);
// Start first conversion
convertRequestData.targetSet = 'foo';
await eventHub.fireConvertRequest(convertRequestData);
// Fire the second with small delay
await waitTimeout();
convertRequestData.targetSet = 'bar';
await eventHub.fireConvertRequest(convertRequestData);
// Wait for both to complete
await waitPromise;
expect(mockCsolutionService.convertSolution).toHaveBeenCalledTimes(2);
// two conversions requested, only one run to the end => 1
expect(completedListener).toHaveBeenCalledTimes(1);
// check if call is from request with 'bar'
expect(completedListener).toHaveBeenCalledWith(
expect.objectContaining({ severity: 'success', detection: false })
);
});
});
it('creates diagnostic when cpackget fails to download a pack', async () => {
const diagnosticCollection = vscode.languages.createDiagnosticCollection();
const mockDiagnosticsCollectionSet = jest.spyOn(diagnosticCollection, 'set') as unknown as jest.MockedFunction<
(uri: vscode.Uri, diagnostics: readonly vscode.Diagnostic[] | undefined) => void
>;
jest.spyOn(cmsisToolboxManager, 'runCmsisTool').mockImplementation(async (_t, _a, onOutput) => {
onOutput('W: retry failed');
onOutput('E: network timeout');
return [1, undefined];
});
mockCsolutionService.listMissingPacks.mockResolvedValue({ success: true, packs: ['VendorA::PackA@1.0.0'] });
mockCsolutionService.getLogMessages.mockResolvedValue({ success: true });
await fireAndWaitForConversion();
expect(mockDiagnosticsCollectionSet).toHaveBeenCalledTimes(1);
const [[, diagnostics]] = mockDiagnosticsCollectionSet.mock.calls;
expect(diagnostics?.[0]?.message).toContain('network timeout');
expect(diagnostics?.[0]?.message).toContain('retry failed');
});
});