forked from microsoft/vscode-java-test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestController.ts
More file actions
755 lines (686 loc) · 31.7 KB
/
testController.ts
File metadata and controls
755 lines (686 loc) · 31.7 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as _ from 'lodash';
import * as path from 'path';
import { CancellationToken, DebugConfiguration, Disposable, FileCoverage, FileCoverageDetail, FileSystemWatcher, Location, MarkdownString, RelativePattern, TestController, TestItem, TestMessage, TestRun, TestRunProfileKind, TestRunRequest, tests, TestTag, Uri, window, workspace, WorkspaceFolder } from 'vscode';
import { instrumentOperation, sendError, sendInfo } from 'vscode-extension-telemetry-wrapper';
import { refreshExplorer } from '../commands/testExplorerCommands';
import { IProgressReporter } from '../debugger.api';
import { progressProvider } from '../extension';
import { testSourceProvider } from '../provider/testSourceProvider';
import { BaseRunner } from '../runners/baseRunner/BaseRunner';
import { JUnitRunner } from '../runners/junitRunner/JunitRunner';
import { TestNGRunner } from '../runners/testngRunner/TestNGRunner';
import { IJavaTestItem } from '../types';
import { loadRunConfig } from '../utils/configUtils';
import { resolveLaunchConfigurationForRunner } from '../utils/launchUtils';
import { dataCache, ITestItemData } from './testItemDataCache';
import { createTestItem, findDirectTestChildrenForClass, findTestPackagesAndTypes, findTestTypesAndMethods, loadJavaProjects, resolvePath, synchronizeItemsRecursively, updateItemForDocumentWithDebounce } from './utils';
import { JavaTestCoverageProvider } from '../provider/JavaTestCoverageProvider';
import { testRunnerService } from './testRunnerService';
import { IRunTestContext, TestRunner, TestFinishEvent, TestItemStatusChangeEvent, TestKind, TestLevel, TestResultState, TestIdParts } from '../java-test-runner.api';
import { processStackTraceLine } from '../runners/utils';
import { parsePartsFromTestId } from '../utils/testItemUtils';
export let testController: TestController | undefined;
export const watchers: Disposable[] = [];
export const runnableTag: TestTag = new TestTag('runnable');
export function createTestController(): void {
testController?.dispose();
testController = tests.createTestController('java', 'Java Test');
testController.resolveHandler = async (item: TestItem) => {
await loadChildren(item);
};
testController.createRunProfile('Run Tests', TestRunProfileKind.Run, runHandler, true, runnableTag);
testController.createRunProfile('Debug Tests', TestRunProfileKind.Debug, runHandler, true, runnableTag);
testController.createRunProfile('Run Tests with Coverage', TestRunProfileKind.Coverage, runHandler, true, runnableTag);
testController.refreshHandler = () => {
refreshExplorer();
}
startWatchingWorkspace();
}
export function creatTestProfile(name: string, kind: TestRunProfileKind): void {
testController?.createRunProfile(name, kind, runHandler, false, runnableTag);
}
export const loadChildren: (item: TestItem, token?: CancellationToken) => any = instrumentOperation('java.test.explorer.loadChildren', async (_operationId: string, item: TestItem, token?: CancellationToken) => {
if (!item) {
await loadJavaProjects();
return;
}
const data: ITestItemData | undefined = dataCache.get(item);
if (!data) {
return;
}
if (data.testLevel === TestLevel.Project) {
const packageAndTypes: IJavaTestItem[] = await findTestPackagesAndTypes(data.jdtHandler, token);
synchronizeItemsRecursively(item, packageAndTypes);
} else if (data.testLevel === TestLevel.Package) {
// unreachable code
} else if (data.testLevel === TestLevel.Class) {
if (!data.jdtHandler) {
sendError(new Error('The class node does not have jdt handler id.'));
return;
}
const testMethods: IJavaTestItem[] = await findDirectTestChildrenForClass(data.jdtHandler, token);
synchronizeItemsRecursively(item, testMethods);
}
});
async function startWatchingWorkspace(): Promise<void> {
if (!workspace.workspaceFolders) {
return;
}
for (const disposable of watchers) {
disposable.dispose();
}
for (const workspaceFolder of workspace.workspaceFolders) {
const patterns: RelativePattern[] = await testSourceProvider.getTestSourcePattern(workspaceFolder);
for (const pattern of patterns) {
const watcher: FileSystemWatcher = workspace.createFileSystemWatcher(pattern);
watchers.push(
watcher,
watcher.onDidCreate(async (uri: Uri) => {
const testTypes: IJavaTestItem[] = await findTestTypesAndMethods(uri.toString());
if (testTypes.length === 0) {
return;
}
await updateItemForDocumentWithDebounce(uri, testTypes);
}),
watcher.onDidChange(async (uri: Uri) => {
await updateItemForDocumentWithDebounce(uri);
}),
watcher.onDidDelete(async (uri: Uri) => {
const pathsData: IJavaTestItem[] = await resolvePath(uri.toString());
if (_.isEmpty(pathsData) || pathsData.length < 2) {
return;
}
const projectData: IJavaTestItem = pathsData[0];
if (projectData.testLevel !== TestLevel.Project) {
return;
}
const belongingProject: TestItem | undefined = testController?.items.get(projectData.id);
if (!belongingProject) {
return;
}
const packageData: IJavaTestItem = pathsData[1];
if (packageData.testLevel !== TestLevel.Package) {
return;
}
const belongingPackage: TestItem | undefined = belongingProject.children.get(packageData.id);
if (!belongingPackage) {
return;
}
belongingPackage.children.forEach((item: TestItem) => {
if (item.uri?.toString() === uri.toString()) {
belongingPackage.children.delete(item.id);
}
});
if (belongingPackage.children.size === 0) {
belongingProject.children.delete(belongingPackage.id);
}
}),
);
}
}
}
async function runHandler(request: TestRunRequest, token: CancellationToken): Promise<void> {
await runTests(request, { token, isDebug: !!request.profile?.label.includes('Debug') });
}
export const runTests: (request: TestRunRequest, option: IRunOption) => any = instrumentOperation('java.test.runTests', async (operationId: string, request: TestRunRequest, option: IRunOption) => {
sendInfo(operationId, {
isDebug: `${option.isDebug}`,
profile: request.profile?.label ?? 'UNKNOWN',
});
const testItems: TestItem[] = await new Promise<TestItem[]>(async (resolve: (result: TestItem[]) => void): Promise<void> => {
option.progressReporter = option.progressReporter ?? progressProvider?.createProgressReporter(option.isDebug ? 'Debug Tests' : 'Run Tests');
option.token?.onCancellationRequested(() => {
option.progressReporter?.done();
return resolve([]);
});
const progressToken: CancellationToken | undefined = option.progressReporter?.getCancellationToken();
option.onProgressCancelHandler = progressToken?.onCancellationRequested(() => {
option.progressReporter?.done();
return resolve([]);
});
option.progressReporter?.report('Searching tests...');
const result: TestItem[] = await getIncludedItems(request, progressToken);
await expandTests(result, TestLevel.Method, progressToken);
return resolve(result);
});
if (testItems.length === 0) {
option.progressReporter?.done();
return;
}
const run: TestRun = testController!.createTestRun(request);
let coverageProvider: JavaTestCoverageProvider | undefined;
if (request.profile?.kind === TestRunProfileKind.Coverage) {
coverageProvider = new JavaTestCoverageProvider();
request.profile.loadDetailedCoverage = (_testRun: TestRun, fileCoverage: FileCoverage, _token: CancellationToken): Promise<FileCoverageDetail[]> => {
return Promise.resolve(coverageProvider!.getCoverageDetails(fileCoverage.uri));
};
}
try {
await new Promise<void>(async (resolve: () => void): Promise<void> => {
const token: CancellationToken = option.token ?? run.token;
let disposables: Disposable[] = [];
token.onCancellationRequested(() => {
option.progressReporter?.done();
run.end();
disposables.forEach((d: Disposable) => d.dispose());
return resolve();
});
enqueueTestMethods(testItems, run);
// TODO: first group by project, then merge test methods.
const queue: TestItem[][] = mergeTestMethods(testItems);
for (const testsInQueue of queue) {
if (testsInQueue.length === 0) {
continue;
}
const testProjectMapping: Map<string, TestItem[]> = mapTestItemsByProject(testsInQueue);
for (const [projectName, itemsPerProject] of testProjectMapping.entries()) {
const workspaceFolder: WorkspaceFolder | undefined = workspace.getWorkspaceFolder(itemsPerProject[0].uri!);
if (!workspaceFolder) {
window.showErrorMessage(`Failed to get workspace folder from test item: ${itemsPerProject[0].label}.`);
continue;
}
const testContext: IRunTestContext = {
isDebug: option.isDebug,
kind: TestKind.None,
projectName,
testItems: itemsPerProject,
testRun: run,
workspaceFolder,
profile: request.profile,
testConfig: await loadRunConfig(itemsPerProject, workspaceFolder),
};
const testRunner: TestRunner | undefined = testRunnerService.getRunner(request.profile?.label, request.profile?.kind);
if (testRunner) {
await executeWithTestRunner(option, testRunner, testContext, run, disposables);
disposables.forEach((d: Disposable) => d.dispose());
disposables = [];
continue;
}
const testKindMapping: Map<TestKind, TestItem[]> = mapTestItemsByKind(itemsPerProject);
for (const [kind, items] of testKindMapping.entries()) {
testContext.kind = kind;
testContext.testItems = items;
if (option.progressReporter?.isCancelled()) {
option.progressReporter = progressProvider?.createProgressReporter(option.isDebug ? 'Debug Tests' : 'Run Tests');
}
let delegatedToDebugger: boolean = false;
option.onProgressCancelHandler?.dispose();
option.progressReporter?.getCancellationToken().onCancellationRequested(() => {
if (delegatedToDebugger) {
// If the progress reporter has been delegated to debugger, a cancellation event
// might be emitted due to debug session finished, thus we will ignore such event.
return;
}
option.progressReporter?.done();
return resolve();
});
option.progressReporter?.report('Resolving launch configuration...');
if (!testContext.testConfig) {
continue;
}
const runner: BaseRunner | undefined = getRunnerByContext(testContext);
if (!runner) {
window.showErrorMessage(`Failed to get suitable runner for the test kind: ${testContext.kind}.`);
continue;
}
try {
await runner.setup();
const resolvedConfiguration: DebugConfiguration = mergeConfigurations(option.launchConfiguration, testContext.testConfig) ?? await resolveLaunchConfigurationForRunner(runner, testContext, testContext.testConfig);
resolvedConfiguration.__progressId = option.progressReporter?.getId();
delegatedToDebugger = true;
trackTestFrameworkVersion(testContext.kind, resolvedConfiguration.classPaths, resolvedConfiguration.modulePaths);
await runner.run(resolvedConfiguration, token, option.progressReporter);
} catch (error) {
window.showErrorMessage(error.message || 'Failed to run tests.');
option.progressReporter?.done();
} finally {
await runner.tearDown();
}
}
if (request.profile?.kind === TestRunProfileKind.Coverage) {
await coverageProvider!.provideFileCoverage(run, projectName);
}
}
}
return resolve();
});
} finally {
run.end();
}
});
async function executeWithTestRunner(option: IRunOption, testRunner: TestRunner, testContext: IRunTestContext, run: TestRun, disposables: Disposable[]) {
option.progressReporter?.done();
await new Promise<void>(async (resolve: () => void): Promise<void> => {
disposables.push(testRunner.onDidChangeTestItemStatus((event: TestItemStatusChangeEvent) => {
const parts: TestIdParts = parsePartsFromTestId(event.testId);
let parentItem: TestItem;
try {
parentItem = findTestClass(parts);
} catch (e) {
sendError(e);
window.showErrorMessage(e.message);
return resolve();
}
let currentItem: TestItem | undefined;
const invocations: string[] | undefined = parts.invocations;
if (invocations?.length) {
let i: number = 0;
for (; i < invocations.length; i++) {
currentItem = parentItem.children.get(`${parentItem.id}#${invocations[i]}`);
if (!currentItem) {
break;
}
parentItem = currentItem;
}
if (i < invocations.length - 1) {
window.showErrorMessage('Test not found:' + event.testId);
sendError(new Error('Test not found:' + event.testId));
return resolve();
}
if (!currentItem) {
currentItem = createTestItem({
children: [],
uri: parentItem.uri?.toString(),
range: parentItem.range,
jdtHandler: '',
fullName: `${parentItem.id}#${invocations[invocations.length - 1]}`,
label: event.displayName || invocations[invocations.length - 1],
id: `${parentItem.id}#${invocations[invocations.length - 1]}`,
projectName: testContext.projectName,
testKind: TestKind.None,
testLevel: TestLevel.Invocation,
}, parentItem);
}
} else {
currentItem = parentItem;
}
if (event.displayName && getLabelWithoutCodicon(currentItem.label) !== event.displayName) {
currentItem.description = event.displayName;
}
switch (event.state) {
case TestResultState.Running:
run.started(currentItem);
break;
case TestResultState.Passed:
run.passed(currentItem);
break;
case TestResultState.Failed:
case TestResultState.Errored:
const testMessages: TestMessage[] = [];
if (event.message) {
const markdownTrace: MarkdownString = new MarkdownString();
markdownTrace.supportHtml = true;
markdownTrace.isTrusted = true;
const testMessage: TestMessage = new TestMessage(markdownTrace);
testMessages.push(testMessage);
const lines: string[] = event.message.split(/\r?\n/);
for (const line of lines) {
const location: Location | undefined = processStackTraceLine(line, markdownTrace, currentItem, testContext.projectName);
if (location) {
testMessage.location = location;
}
}
}
run.failed(currentItem, testMessages);
break;
case TestResultState.Skipped:
run.skipped(currentItem);
break;
default:
break;
}
}));
disposables.push(testRunner.onDidFinishTestRun((event: TestFinishEvent) => {
if (event.statusCode === 2) { // See: https://build-server-protocol.github.io/docs/specification#statuscode
window.showErrorMessage(event.message ?? 'Failed to run tests.');
}
return resolve();
}));
await testRunner.launch(testContext);
});
function findTestClass(parts: TestIdParts): TestItem {
const projectItem: TestItem | undefined = testController?.items.get(parts.project);
if (!projectItem) {
throw new Error('Failed to get the project test item.');
}
if (parts.package === undefined) { // '' means default package
throw new Error('package is undefined in the id parts.');
}
const packageItem: TestItem | undefined = projectItem.children.get(`${projectItem.id}@${parts.package}`);
if (!packageItem) {
throw new Error('Failed to get the package test item.');
}
if (!parts.class) {
throw new Error('class is undefined in the id parts.');
}
const classes: string[] = parts.class.split('$'); // handle nested classes
let current: TestItem | undefined = packageItem.children.get(`${projectItem.id}@${classes[0]}`);
if (!current) {
throw new Error('Failed to get the class test item.');
}
for (let i: number = 1; i < classes.length; i++) {
current = current.children.get(`${current.id}$${classes[i]}`);
if (!current) {
throw new Error('Failed to get the class test item.');
}
}
return current;
}
}
function mergeConfigurations(launchConfiguration: DebugConfiguration | undefined, config: any): DebugConfiguration | undefined {
if (!launchConfiguration) {
return undefined;
}
const entryKeys: string[] = Object.keys(config);
for (const configKey of entryKeys) {
// for now we merge launcher properties which doesn't have a value.
if (!launchConfiguration[configKey]) {
launchConfiguration[configKey] = config[configKey];
}
}
return launchConfiguration;
}
/**
* Set all the test item to queued state
*/
function enqueueTestMethods(testItems: TestItem[], run: TestRun): void {
const queuedTests: TestItem[] = [...testItems];
while (queuedTests.length) {
const queuedTest: TestItem = queuedTests.shift()!;
run.enqueued(queuedTest);
queuedTest.children.forEach((child: TestItem) => {
queuedTests.push(child);
});
}
}
/**
* Filter out the tests which are in the excluding list
* @param request the test run request
* @returns
*/
async function getIncludedItems(request: TestRunRequest, token?: CancellationToken): Promise<TestItem[]> {
let testItems: TestItem[] = [];
if (request.include) {
testItems.push(...request.include);
} else {
testController?.items.forEach((item: TestItem) => {
testItems.push(item);
});
}
if (testItems.length === 0) {
return [];
}
testItems = handleInvocations(testItems);
testItems = await expandTests(testItems, TestLevel.Class, token);
// @ts-expect-error: ignore
const excludingItems: TestItem[] = await expandTests(request.exclude || [], TestLevel.Class, token);
testItems = _.differenceBy(testItems, excludingItems, 'id');
return testItems;
}
/**
* Check and preparation in case a single invocation of a parameterized test is re-run.
* If a test is run completely, existing invocations are removed.
* @param testItems
* @returns prepared testItems
*/
export function handleInvocations(testItems: TestItem[]): TestItem[] { // export for unit test
if (filterInvocations(testItems)
.some((invocation: TestItem) => !invocation.parent || !dataCache.get(invocation.parent))) { // sanity-checks
const errMsg: string = 'Trying to re-run a single test invocation, but could not find a corresponding method-level parent item with data.';
sendError(new Error(errMsg));
window.showErrorMessage(errMsg);
return [];
}
testItems = mergeInvocations(testItems);
const invocations: TestItem[] = filterInvocations(testItems);
if (invocations.length > _.uniq(invocations.map((item: TestItem) => item.parent)).length) {
window.showErrorMessage('Re-running multiple invocations of a parameterized test is not supported, please select only one invocation at a time.');
return [];
}
// always remove uniqueIds from all non-invocation items, since they would have been set for a past run
testItems.forEach((item: TestItem) => {
const itemData: ITestItemData | undefined = dataCache.get(item);
if (itemData && itemData.testLevel !== TestLevel.Invocation) {
itemData.uniqueId = undefined;
}
});
// if a single invocation is to be re-run,
// we run the parent method instead, but with restriction to the single invocation parameter-set
testItems = testItems.map((item: TestItem) => {
if (isInvocation(item)) {
dataCache.get(item.parent!)!.uniqueId = dataCache.get(item)!.uniqueId;
return item.parent!;
}
return item;
})
removeNonRerunTestInvocations(testItems);
return testItems;
}
function filterInvocations(testItems: TestItem[]): TestItem[] {
return testItems.filter((item: TestItem) => isInvocation(item));
}
function isInvocation(item: TestItem): boolean {
return dataCache.get(item)?.testLevel === TestLevel.Invocation;
}
function mergeInvocations(testItems: TestItem[]): TestItem[] {
// remove invocations if they are already included in selected higher-level tests
testItems = testItems.filter((item: TestItem) => !(isInvocation(item) && isAncestorIncluded(item, testItems)));
// if all invocations of a method are selected, replace by single parent method run
const invocationsPerMethod: Map<TestItem, Set<TestItem>> = filterInvocations(testItems)
/* eslint-disable @typescript-eslint/typedef */
.reduce(
(map, inv) => map.set(inv.parent!,
map.has(inv.parent!) ? new Set([...map.get(inv.parent!)!, inv]) : new Set([inv])),
new Map()
);
const invocationsToMerge: TestItem[] = _.flatten([...invocationsPerMethod.entries()]
.filter(([method, invs]) => method.children.size === invs.size)
.map(([, invs]) => [...invs]));
/* eslint-enable @typescript-eslint/typedef */
return _.uniq(testItems.map((item: TestItem) => invocationsToMerge.includes(item) ? item.parent! : item));
}
function isAncestorIncluded(item: TestItem, potentialAncestors: TestItem[]): boolean {
// walk up the tree and check whether any ancestor is part of the selected test items
let parent: TestItem | undefined = item.parent;
while (parent !== undefined) {
if (potentialAncestors.includes(parent)) {
return true;
}
parent = parent.parent;
}
return false;
}
/**
* Expand the test items to the target level
* @param testItems items to expand
* @param targetLevel target level to expand
*/
async function expandTests(testItems: TestItem[], targetLevel: TestLevel, token?: CancellationToken): Promise<TestItem[]> {
const results: Set<TestItem> = new Set();
const queue: TestItem[] = [...testItems];
while (queue.length) {
const item: TestItem = queue.shift()!;
const testLevel: TestLevel | undefined = dataCache.get(item)?.testLevel;
if (testLevel === undefined) {
continue;
}
if (testLevel >= targetLevel) {
results.add(item);
} else {
await loadChildren(item, token);
item.children.forEach((child: TestItem) => {
queue.push(child);
});
}
}
return Array.from(results);
}
/**
* Remove the test invocations since they might be changed, except for methods where only a single invocation is re-run.
*/
function removeNonRerunTestInvocations(testItems: TestItem[]): void {
const rerunMethods: TestItem[] = testItems.filter((item: TestItem) => dataCache.get(item)?.uniqueId !== undefined);
const queue: TestItem[] = [...testItems];
while (queue.length) {
const item: TestItem = queue.shift()!;
if (rerunMethods.includes(item)) {
continue;
}
if (dataCache.get(item)?.testLevel === TestLevel.Invocation) {
item.parent?.children.delete(item.id);
continue;
}
item.children.forEach((child: TestItem) => {
queue.push(child);
});
}
}
/**
* Eliminate the test methods if they are contained in the test class.
* Because the current test runner cannot run class and methods for the same time,
* in the returned array, all the classes are in one group and each method is a group.
*/
function mergeTestMethods(testItems: TestItem[]): TestItem[][] {
if (testItems.length <= 1) {
return [testItems];
}
// eslint-disable-next-line @typescript-eslint/typedef
const classMapping: Map<string, TestItem> = testItems.reduce((map, i) => {
const testLevel: TestLevel | undefined = dataCache.get(i)?.testLevel;
if (testLevel === undefined) {
return map;
}
if (testLevel === TestLevel.Class) {
map.set(i.id, i);
}
return map;
}, new Map());
// eslint-disable-next-line @typescript-eslint/typedef
const testMapping: Map<TestItem, Set<TestItem>> = testItems.reduce((map, i) => {
const testLevel: TestLevel | undefined = dataCache.get(i)?.testLevel;
if (testLevel === undefined) {
return map;
}
if (testLevel !== TestLevel.Method) {
return map;
}
// skip the method if it's contained in test classes
if (classMapping.has(i.parent?.id || '')) {
return map;
}
const value: Set<TestItem> | undefined = map.get(i.parent);
if (value) {
value.add(i as TestItem);
} else {
map.set(i.parent, new Set([i]));
}
return map;
}, new Map());
const testMethods: TestItem[][] = [];
for (const [clazz, methods] of testMapping) {
// if all methods of a class are selected, prefer running the class instead, to execute them together
if (clazz.children.size === methods.size
// but do not run the whole class when a method is restricted to a single invocation,
// since restricting class items to single invocations is not supported
&& !([...methods].some((m: TestItem) => dataCache.get(m)?.uniqueId))) {
classMapping.set(clazz.id, clazz);
} else {
for (const method of methods.values()) {
testMethods.push([method]);
}
}
}
return [[...classMapping.values()], ...testMethods];
}
function mapTestItemsByProject(items: TestItem[]): Map<string, TestItem[]> {
const map: Map<string, TestItem[]> = new Map<string, TestItem[]>();
for (const item of items) {
const projectName: string | undefined = dataCache.get(item)?.projectName;
if (!projectName) {
sendError(new Error('Item does not have project name.'));
continue;
}
const itemsPerProject: TestItem[] | undefined = map.get(projectName);
if (itemsPerProject) {
itemsPerProject.push(item);
} else {
map.set(projectName, [item]);
}
}
return map;
}
function mapTestItemsByKind(items: TestItem[]): Map<TestKind, TestItem[]> {
const map: Map<TestKind, TestItem[]> = new Map<TestKind, TestItem[]>();
for (const item of items) {
const testKind: TestKind | undefined = dataCache.get(item)?.testKind;
if (testKind === undefined) {
continue;
}
const itemsPerKind: TestItem[] | undefined = map.get(testKind);
if (itemsPerKind) {
itemsPerKind.push(item);
} else {
map.set(testKind, [item]);
}
}
return map;
}
function getRunnerByContext(testContext: IRunTestContext): BaseRunner | undefined {
switch (testContext.kind) {
case TestKind.JUnit:
case TestKind.JUnit5:
return new JUnitRunner(testContext);
case TestKind.TestNG:
return new TestNGRunner(testContext);
default:
return undefined;
}
}
function trackTestFrameworkVersion(testKind: TestKind, classpaths: string[], modulepaths: string[]) {
let artifactPattern: RegExp;
switch (testKind) {
case TestKind.JUnit:
artifactPattern = /junit-(\d+\.\d+\.\d+(-[a-zA-Z\d]+)?).jar/;
break;
case TestKind.JUnit5:
artifactPattern = /junit-jupiter-api-(\d+\.\d+\.\d+(-[a-zA-Z\d]+)?).jar/;
break;
case TestKind.TestNG:
artifactPattern = /testng-(\d+\.\d+\.\d+(-[a-zA-Z\d]+)?).jar/;
break;
default:
return;
}
let version: string = 'unknown';
for (const entry of [...classpaths, ...modulepaths]) {
const fileName: string = path.basename(entry);
const match: RegExpMatchArray | null = artifactPattern.exec(fileName);
if (match) {
version = match[1];
break;
}
}
sendInfo('', {
testFramework: TestKind[testKind],
frameworkVersion: version
});
}
function getLabelWithoutCodicon(name: string): string {
if (name.includes('#')) {
name = name.substring(name.indexOf('#') + 1);
}
const result: RegExpMatchArray | null = name.match(/(?:\$\(.+\) )?(.*)/);
if (result?.length === 2) {
return result[1];
}
return name;
}
interface IRunOption {
isDebug: boolean;
progressReporter?: IProgressReporter;
onProgressCancelHandler?: Disposable;
launchConfiguration?: DebugConfiguration;
token?: CancellationToken;
}