forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontroller.ts
More file actions
776 lines (690 loc) · 31.2 KB
/
controller.ts
File metadata and controls
776 lines (690 loc) · 31.2 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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { inject, injectable, named } from 'inversify';
import { uniq } from 'lodash';
import * as minimatch from 'minimatch';
import {
CancellationToken,
TestController,
TestItem,
TestRunRequest,
tests,
WorkspaceFolder,
RelativePattern,
TestRunProfileKind,
CancellationTokenSource,
Uri,
EventEmitter,
TextDocument,
FileCoverageDetail,
TestRun,
MarkdownString,
} from 'vscode';
import { IExtensionSingleActivationService } from '../../activation/types';
import { ICommandManager, IWorkspaceService } from '../../common/application/types';
import * as constants from '../../common/constants';
import { IPythonExecutionFactory } from '../../common/process/types';
import { IConfigurationService, IDisposableRegistry, Resource } from '../../common/types';
import { DelayedTrigger, IDelayedTrigger } from '../../common/utils/delayTrigger';
import { noop } from '../../common/utils/misc';
import { IInterpreterService } from '../../interpreter/contracts';
import { traceError, traceVerbose } from '../../logging';
import { IEventNamePropertyMapping, sendTelemetryEvent } from '../../telemetry';
import { EventName } from '../../telemetry/constants';
import { PYTEST_PROVIDER, UNITTEST_PROVIDER } from '../common/constants';
import { TestProvider } from '../types';
import { createErrorTestItem, DebugTestTag, getNodeByUri, RunTestTag } from './common/testItemUtilities';
import { buildErrorNodeOptions } from './common/utils';
import {
ITestController,
ITestDiscoveryAdapter,
ITestFrameworkController,
TestRefreshOptions,
ITestExecutionAdapter,
} from './common/types';
import { UnittestTestDiscoveryAdapter } from './unittest/testDiscoveryAdapter';
import { UnittestTestExecutionAdapter } from './unittest/testExecutionAdapter';
import { PytestTestDiscoveryAdapter } from './pytest/pytestDiscoveryAdapter';
import { PytestTestExecutionAdapter } from './pytest/pytestExecutionAdapter';
import { WorkspaceTestAdapter } from './workspaceTestAdapter';
import { ITestDebugLauncher } from '../common/types';
import { PythonResultResolver } from './common/resultResolver';
import { onDidSaveTextDocument } from '../../common/vscodeApis/workspaceApis';
import { IEnvironmentVariablesProvider } from '../../common/variables/types';
import { useEnvExtension, getEnvExtApi } from '../../envExt/api.internal';
import { PythonProject } from '../../envExt/types';
// Types gymnastics to make sure that sendTriggerTelemetry only accepts the correct types.
type EventPropertyType = IEventNamePropertyMapping[EventName.UNITTEST_DISCOVERY_TRIGGER];
type TriggerKeyType = keyof EventPropertyType;
type TriggerType = EventPropertyType[TriggerKeyType];
/**
* Represents a project-specific test adapter with its project information
*/
interface ProjectTestAdapter {
adapter: WorkspaceTestAdapter;
project: PythonProject;
}
@injectable()
export class PythonTestController implements ITestController, IExtensionSingleActivationService {
public readonly supportedWorkspaceTypes = { untrustedWorkspace: false, virtualWorkspace: false };
// Map of workspace URI string -> array of project-specific test adapters
private readonly testAdapters: Map<string, ProjectTestAdapter[]> = new Map();
private readonly triggerTypes: TriggerType[] = [];
private readonly testController: TestController;
private readonly refreshData: IDelayedTrigger;
private refreshCancellation: CancellationTokenSource;
private readonly refreshingCompletedEvent: EventEmitter<void> = new EventEmitter<void>();
private readonly refreshingStartedEvent: EventEmitter<void> = new EventEmitter<void>();
private readonly runWithoutConfigurationEvent: EventEmitter<WorkspaceFolder[]> = new EventEmitter<
WorkspaceFolder[]
>();
public readonly onRefreshingCompleted = this.refreshingCompletedEvent.event;
public readonly onRefreshingStarted = this.refreshingStartedEvent.event;
public readonly onRunWithoutConfiguration = this.runWithoutConfigurationEvent.event;
private sendTestDisabledTelemetry = true;
constructor(
@inject(IWorkspaceService) private readonly workspaceService: IWorkspaceService,
@inject(IConfigurationService) private readonly configSettings: IConfigurationService,
@inject(ITestFrameworkController) @named(PYTEST_PROVIDER) private readonly pytest: ITestFrameworkController,
@inject(ITestFrameworkController) @named(UNITTEST_PROVIDER) private readonly unittest: ITestFrameworkController,
@inject(IDisposableRegistry) private readonly disposables: IDisposableRegistry,
@inject(IInterpreterService) private readonly interpreterService: IInterpreterService,
@inject(ICommandManager) private readonly commandManager: ICommandManager,
@inject(IPythonExecutionFactory) private readonly pythonExecFactory: IPythonExecutionFactory,
@inject(ITestDebugLauncher) private readonly debugLauncher: ITestDebugLauncher,
@inject(IEnvironmentVariablesProvider) private readonly envVarsService: IEnvironmentVariablesProvider,
) {
this.refreshCancellation = new CancellationTokenSource();
this.testController = tests.createTestController('python-tests', 'Python Tests');
this.disposables.push(this.testController);
const delayTrigger = new DelayedTrigger(
(uri: Uri, invalidate: boolean) => {
this.refreshTestDataInternal(uri);
if (invalidate) {
this.invalidateTests(uri);
}
},
250, // Delay running the refresh by 250 ms
'Refresh Test Data',
);
this.disposables.push(delayTrigger);
this.refreshData = delayTrigger;
this.disposables.push(
this.testController.createRunProfile(
'Run Tests',
TestRunProfileKind.Run,
this.runTests.bind(this),
true,
RunTestTag,
),
this.testController.createRunProfile(
'Debug Tests',
TestRunProfileKind.Debug,
this.runTests.bind(this),
true,
DebugTestTag,
),
this.testController.createRunProfile(
'Coverage Tests',
TestRunProfileKind.Coverage,
this.runTests.bind(this),
true,
RunTestTag,
),
);
this.testController.resolveHandler = this.resolveChildren.bind(this);
this.testController.refreshHandler = (token: CancellationToken) => {
this.disposables.push(
token.onCancellationRequested(() => {
traceVerbose('Testing: Stop refreshing triggered');
sendTelemetryEvent(EventName.UNITTEST_DISCOVERING_STOP);
this.stopRefreshing();
}),
);
traceVerbose('Testing: Manually triggered test refresh');
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, {
trigger: constants.CommandSource.commandPalette,
});
return this.refreshTestData(undefined, { forceRefresh: true });
};
}
public async activate(): Promise<void> {
const workspaces: readonly WorkspaceFolder[] = this.workspaceService.workspaceFolders || [];
workspaces.forEach((workspace) => {
// Initialize with empty array - projects will be detected during discovery
this.testAdapters.set(workspace.uri.toString(), []);
const settings = this.configSettings.getSettings(workspace.uri);
if (settings.testing.autoTestDiscoverOnSaveEnabled) {
traceVerbose(`Testing: Setting up watcher for ${workspace.uri.fsPath}`);
this.watchForSettingsChanges(workspace);
this.watchForTestContentChangeOnSave();
}
});
}
/**
* Creates a test adapter for a specific project within a workspace.
* @param project The project to create adapter for
* @param testProvider The test provider (pytest or unittest)
* @returns A ProjectTestAdapter instance
*/
private createProjectAdapter(project: PythonProject, testProvider: TestProvider): ProjectTestAdapter {
traceVerbose(`Creating ${testProvider} adapter for project at ${project.uri.fsPath}`);
const resultResolver = new PythonResultResolver(this.testController, testProvider, project.uri);
let discoveryAdapter: ITestDiscoveryAdapter;
let executionAdapter: ITestExecutionAdapter;
if (testProvider === UNITTEST_PROVIDER) {
discoveryAdapter = new UnittestTestDiscoveryAdapter(
this.configSettings,
resultResolver,
this.envVarsService,
);
executionAdapter = new UnittestTestExecutionAdapter(
this.configSettings,
resultResolver,
this.envVarsService,
);
} else {
discoveryAdapter = new PytestTestDiscoveryAdapter(
this.configSettings,
resultResolver,
this.envVarsService,
);
executionAdapter = new PytestTestExecutionAdapter(
this.configSettings,
resultResolver,
this.envVarsService,
);
}
const workspaceTestAdapter = new WorkspaceTestAdapter(
testProvider,
discoveryAdapter,
executionAdapter,
project.uri, // Use project URI instead of workspace URI
resultResolver,
);
return {
adapter: workspaceTestAdapter,
project,
};
}
public refreshTestData(uri?: Resource, options?: TestRefreshOptions): Promise<void> {
if (options?.forceRefresh) {
if (uri === undefined) {
// This is a special case where we want everything to be re-discovered.
traceVerbose('Testing: Clearing all discovered tests');
this.testController.items.forEach((item) => {
const ids: string[] = [];
item.children.forEach((child) => ids.push(child.id));
ids.forEach((id) => item.children.delete(id));
});
traceVerbose('Testing: Forcing test data refresh');
return this.refreshTestDataInternal(undefined);
}
traceVerbose('Testing: Forcing test data refresh');
return this.refreshTestDataInternal(uri);
}
this.refreshData.trigger(uri, false);
return Promise.resolve();
}
public stopRefreshing(): void {
this.refreshCancellation.cancel();
this.refreshCancellation.dispose();
this.refreshCancellation = new CancellationTokenSource();
}
public clearTestController(): void {
const ids: string[] = [];
this.testController.items.forEach((item) => ids.push(item.id));
ids.forEach((id) => this.testController.items.delete(id));
}
private async refreshTestDataInternal(uri?: Resource): Promise<void> {
this.refreshingStartedEvent.fire();
try {
if (uri) {
await this.refreshSingleWorkspace(uri);
} else {
await this.refreshAllWorkspaces();
}
} finally {
this.refreshingCompletedEvent.fire();
}
}
/**
* Discovers tests for a single workspace.
*/
private async refreshSingleWorkspace(uri: Uri): Promise<void> {
const workspace = this.workspaceService.getWorkspaceFolder(uri);
if (!workspace?.uri) {
traceError('Unable to find workspace for given file');
return;
}
const settings = this.configSettings.getSettings(uri);
traceVerbose(`Discover tests for workspace name: ${workspace.name} - uri: ${uri.fsPath}`);
// Ensure we send test telemetry if it gets disabled again
this.sendTestDisabledTelemetry = true;
if (settings.testing.pytestEnabled) {
await this.discoverTestsForProvider(workspace.uri, 'pytest');
} else if (settings.testing.unittestEnabled) {
await this.discoverTestsForProvider(workspace.uri, 'unittest');
} else {
await this.handleNoTestProviderEnabled(workspace);
}
}
/**
* Discovers tests for all workspaces in the workspace folders.
*/
private async refreshAllWorkspaces(): Promise<void> {
traceVerbose('Testing: Refreshing all test data');
const workspaces: readonly WorkspaceFolder[] = this.workspaceService.workspaceFolders || [];
await Promise.all(
workspaces.map(async (workspace) => {
if (!(await this.interpreterService.getActiveInterpreter(workspace.uri))) {
this.commandManager
.executeCommand(constants.Commands.TriggerEnvironmentSelection, workspace.uri)
.then(noop, noop);
return;
}
await this.refreshSingleWorkspace(workspace.uri);
}),
);
}
/**
* Discovers tests for a specific test provider (pytest or unittest).
* Detects all projects within the workspace and runs discovery for each project.
*/
private async discoverTestsForProvider(workspaceUri: Uri, expectedProvider: TestProvider): Promise<void> {
const workspaceKey = workspaceUri.toString();
// Step 1: Get Python projects from the environment extension
let projects: PythonProject[] = [];
if (useEnvExtension()) {
try {
const envExtApi = await getEnvExtApi();
const allProjects = envExtApi.getPythonProjects();
// Filter projects that belong to this workspace
projects = allProjects.filter((project) => {
const projectWorkspace = this.workspaceService.getWorkspaceFolder(project.uri);
return projectWorkspace?.uri.toString() === workspaceKey;
});
traceVerbose(`Found ${projects.length} Python project(s) in workspace ${workspaceUri.fsPath}`);
} catch (error) {
traceError(`Error getting projects from environment extension: ${error}`);
// Fall back to using workspace as single project
projects = [];
}
}
// If no projects found or env extension not available, treat workspace as single project
if (projects.length === 0) {
traceVerbose(`No projects detected, using workspace root as single project: ${workspaceUri.fsPath}`);
projects = [{
name: this.workspaceService.getWorkspaceFolder(workspaceUri)?.name || 'workspace',
uri: workspaceUri,
}];
}
// Step 2: Create or reuse adapters for each project
const existingAdapters = this.testAdapters.get(workspaceKey) || [];
const newAdapters: ProjectTestAdapter[] = [];
for (const project of projects) {
// Check if we already have an adapter for this project
const existingAdapter = existingAdapters.find(
(a) => a.project.uri.toString() === project.uri.toString() &&
a.adapter.getTestProvider() === expectedProvider,
);
if (existingAdapter) {
traceVerbose(`Reusing existing adapter for project at ${project.uri.fsPath}`);
newAdapters.push(existingAdapter);
} else {
// Create new adapter for this project
const projectAdapter = this.createProjectAdapter(project, expectedProvider);
newAdapters.push(projectAdapter);
}
}
// Update the adapters map
this.testAdapters.set(workspaceKey, newAdapters);
// Step 3: Run discovery for each project
const interpreter = await this.interpreterService.getActiveInterpreter(workspaceUri);
await Promise.all(
newAdapters.map(async ({ adapter, project }) => {
traceVerbose(`Running ${expectedProvider} discovery for project at ${project.uri.fsPath}`);
try {
await adapter.discoverTests(
this.testController,
this.pythonExecFactory,
this.refreshCancellation.token,
interpreter,
);
} catch (error) {
traceError(`Error during ${expectedProvider} discovery for project at ${project.uri.fsPath}:`, error);
this.surfaceErrorNode(
project.uri,
`Error discovering tests in project at ${project.uri.fsPath}: ${error}`,
expectedProvider,
);
}
}),
);
}
/**
* Handles the case when no test provider is enabled.
* Sends telemetry and removes test items for the workspace from the tree.
*/
private async handleNoTestProviderEnabled(workspace: WorkspaceFolder): Promise<void> {
if (this.sendTestDisabledTelemetry) {
this.sendTestDisabledTelemetry = false;
sendTelemetryEvent(EventName.UNITTEST_DISABLED);
}
this.removeTestItemsForWorkspace(workspace);
}
/**
* Removes all test items belonging to a specific workspace from the test controller.
* This is used when test discovery is disabled for a workspace.
*/
private removeTestItemsForWorkspace(workspace: WorkspaceFolder): void {
const itemsToDelete: string[] = [];
this.testController.items.forEach((testItem: TestItem) => {
const itemWorkspace = this.workspaceService.getWorkspaceFolder(testItem.uri);
if (itemWorkspace?.uri.fsPath === workspace.uri.fsPath) {
itemsToDelete.push(testItem.id);
}
});
itemsToDelete.forEach((id) => this.testController.items.delete(id));
}
private async resolveChildren(item: TestItem | undefined): Promise<void> {
if (item) {
traceVerbose(`Testing: Resolving item ${item.id}`);
const settings = this.configSettings.getSettings(item.uri);
if (settings.testing.pytestEnabled) {
return this.pytest.resolveChildren(this.testController, item, this.refreshCancellation.token);
}
if (settings.testing.unittestEnabled) {
return this.unittest.resolveChildren(this.testController, item, this.refreshCancellation.token);
}
} else {
traceVerbose('Testing: Refreshing all test data');
this.sendTriggerTelemetry('auto');
const workspaces: readonly WorkspaceFolder[] = this.workspaceService.workspaceFolders || [];
await Promise.all(
workspaces.map(async (workspace) => {
if (!(await this.interpreterService.getActiveInterpreter(workspace.uri))) {
traceError('Cannot trigger test discovery as a valid interpreter is not selected');
return;
}
await this.refreshTestDataInternal(workspace.uri);
}),
);
}
return Promise.resolve();
}
private async runTests(request: TestRunRequest, token: CancellationToken): Promise<void> {
const workspaces = this.getWorkspacesForTestRun(request);
const runInstance = this.testController.createTestRun(
request,
`Running Tests for Workspace(s): ${workspaces.map((w) => w.uri.fsPath).join(';')}`,
true,
);
const dispose = token.onCancellationRequested(() => {
runInstance.appendOutput(`\nRun instance cancelled.\r\n`);
runInstance.end();
});
const unconfiguredWorkspaces: WorkspaceFolder[] = [];
try {
await Promise.all(
workspaces.map((workspace) =>
this.runTestsForWorkspace(workspace, request, runInstance, token, unconfiguredWorkspaces),
),
);
} finally {
traceVerbose('Finished running tests, ending runInstance.');
runInstance.appendOutput(`Finished running tests!\r\n`);
runInstance.end();
dispose.dispose();
if (unconfiguredWorkspaces.length > 0) {
this.runWithoutConfigurationEvent.fire(unconfiguredWorkspaces);
}
}
}
/**
* Gets the list of workspaces to run tests for based on the test run request.
*/
private getWorkspacesForTestRun(request: TestRunRequest): WorkspaceFolder[] {
if (request.include) {
const workspaces: WorkspaceFolder[] = [];
uniq(request.include.map((r) => this.workspaceService.getWorkspaceFolder(r.uri))).forEach((w) => {
if (w) {
workspaces.push(w);
}
});
return workspaces;
}
return Array.from(this.workspaceService.workspaceFolders || []);
}
/**
* Runs tests for a single workspace.
*/
/**
* Runs tests for a single workspace.
* Groups tests by project and executes them using the appropriate project adapter.
*/
private async runTestsForWorkspace(
workspace: WorkspaceFolder,
request: TestRunRequest,
runInstance: TestRun,
token: CancellationToken,
unconfiguredWorkspaces: WorkspaceFolder[],
): Promise<void> {
if (!(await this.interpreterService.getActiveInterpreter(workspace.uri))) {
this.commandManager
.executeCommand(constants.Commands.TriggerEnvironmentSelection, workspace.uri)
.then(noop, noop);
return;
}
const testItems = this.getTestItemsForWorkspace(workspace, request);
const settings = this.configSettings.getSettings(workspace.uri);
if (testItems.length === 0) {
if (!settings.testing.pytestEnabled && !settings.testing.unittestEnabled) {
unconfiguredWorkspaces.push(workspace);
}
return;
}
// Get project adapters for this workspace
const workspaceKey = workspace.uri.toString();
const projectAdapters = this.testAdapters.get(workspaceKey) || [];
if (projectAdapters.length === 0) {
traceError('No test adapters found for workspace. Tests may not have been discovered yet.');
unconfiguredWorkspaces.push(workspace);
return;
}
// Group test items by project
const testItemsByProject = new Map<string, TestItem[]>();
for (const testItem of testItems) {
// Find which project this test belongs to
const projectAdapter = projectAdapters.find(({ project }) => {
const testPath = testItem.uri?.fsPath;
if (!testPath) {
return false;
}
// Check if test path is within project path
return testPath === project.uri.fsPath || testPath.startsWith(project.uri.fsPath + '/');
});
if (projectAdapter) {
const projectKey = projectAdapter.project.uri.toString();
if (!testItemsByProject.has(projectKey)) {
testItemsByProject.set(projectKey, []);
}
testItemsByProject.get(projectKey)!.push(testItem);
} else {
traceError(`Could not find project adapter for test: ${testItem.id}`);
}
}
// Execute tests for each project
const testProvider = settings.testing.pytestEnabled ? 'pytest' : 'unittest';
await Promise.all(
Array.from(testItemsByProject.entries()).map(async ([projectPath, projectTestItems]) => {
const projectAdapter = projectAdapters.find(
({ project }) => project.uri.toString() === projectPath,
);
if (!projectAdapter) {
traceError(`Project adapter not found for project at ${projectPath}`);
return;
}
this.setupCoverageIfNeeded(request, projectAdapter.adapter);
await this.executeTestsForProvider(
workspace,
projectAdapter.adapter,
projectTestItems,
runInstance,
request,
token,
testProvider,
);
}),
);
}
/**
* Gets test items that belong to a specific workspace from the run request.
*/
private getTestItemsForWorkspace(workspace: WorkspaceFolder, request: TestRunRequest): TestItem[] {
const testItems: TestItem[] = [];
// If the run request includes test items then collect only items that belong to
// `workspace`. If there are no items in the run request then just run the `workspace`
// root test node. Include will be `undefined` in the "run all" scenario.
(request.include ?? this.testController.items).forEach((i: TestItem) => {
const w = this.workspaceService.getWorkspaceFolder(i.uri);
if (w?.uri.fsPath === workspace.uri.fsPath) {
testItems.push(i);
}
});
return testItems;
}
/**
* Sets up detailed coverage loading if the run profile is for coverage.
*/
private setupCoverageIfNeeded(request: TestRunRequest, testAdapter: WorkspaceTestAdapter): void {
// no profile will have TestRunProfileKind.Coverage if rewrite isn't enabled
if (request.profile?.kind && request.profile?.kind === TestRunProfileKind.Coverage) {
request.profile.loadDetailedCoverage = (
_testRun: TestRun,
fileCoverage,
_token,
): Thenable<FileCoverageDetail[]> => {
const details = testAdapter.resultResolver.detailedCoverageMap.get(fileCoverage.uri.fsPath);
if (details === undefined) {
// given file has no detailed coverage data
return Promise.resolve([]);
}
return Promise.resolve(details);
};
}
}
/**
* Executes tests using the test adapter for a specific test provider.
*/
private async executeTestsForProvider(
workspace: WorkspaceFolder,
testAdapter: WorkspaceTestAdapter,
testItems: TestItem[],
runInstance: TestRun,
request: TestRunRequest,
token: CancellationToken,
provider: TestProvider,
): Promise<void> {
sendTelemetryEvent(EventName.UNITTEST_RUN, undefined, {
tool: provider,
debugging: request.profile?.kind === TestRunProfileKind.Debug,
});
await testAdapter.executeTests(
this.testController,
runInstance,
testItems,
this.pythonExecFactory,
token,
request.profile?.kind,
this.debugLauncher,
await this.interpreterService.getActiveInterpreter(workspace.uri),
);
}
private invalidateTests(uri: Uri) {
this.testController.items.forEach((root) => {
const item = getNodeByUri(root, uri);
if (item && !!item.invalidateResults) {
// Minimize invalidating to test case nodes for the test file where
// the change occurred
item.invalidateResults();
}
});
}
private watchForSettingsChanges(workspace: WorkspaceFolder): void {
const pattern = new RelativePattern(workspace, '**/{settings.json,pytest.ini,pyproject.toml,setup.cfg}');
const watcher = this.workspaceService.createFileSystemWatcher(pattern);
this.disposables.push(watcher);
this.disposables.push(
onDidSaveTextDocument(async (doc: TextDocument) => {
const file = doc.fileName;
// refresh on any settings file save
if (
file.includes('settings.json') ||
file.includes('pytest.ini') ||
file.includes('setup.cfg') ||
file.includes('pyproject.toml')
) {
traceVerbose(`Testing: Trigger refresh after saving ${doc.uri.fsPath}`);
this.sendTriggerTelemetry('watching');
this.refreshData.trigger(doc.uri, false);
}
}),
);
/* Keep both watchers for create and delete since config files can change test behavior without content
due to their impact on pythonPath. */
this.disposables.push(
watcher.onDidCreate((uri) => {
traceVerbose(`Testing: Trigger refresh after creating ${uri.fsPath}`);
this.sendTriggerTelemetry('watching');
this.refreshData.trigger(uri, false);
}),
);
this.disposables.push(
watcher.onDidDelete((uri) => {
traceVerbose(`Testing: Trigger refresh after deleting in ${uri.fsPath}`);
this.sendTriggerTelemetry('watching');
this.refreshData.trigger(uri, false);
}),
);
}
private watchForTestContentChangeOnSave(): void {
this.disposables.push(
onDidSaveTextDocument(async (doc: TextDocument) => {
const settings = this.configSettings.getSettings(doc.uri);
if (
settings.testing.autoTestDiscoverOnSaveEnabled &&
minimatch.default(doc.uri.fsPath, settings.testing.autoTestDiscoverOnSavePattern)
) {
traceVerbose(`Testing: Trigger refresh after saving ${doc.uri.fsPath}`);
this.sendTriggerTelemetry('watching');
this.refreshData.trigger(doc.uri, false);
}
}),
);
}
/**
* Send UNITTEST_DISCOVERY_TRIGGER telemetry event only once per trigger type.
*
* @param triggerType The trigger type to send telemetry for.
*/
private sendTriggerTelemetry(trigger: TriggerType): void {
if (!this.triggerTypes.includes(trigger)) {
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, {
trigger,
});
this.triggerTypes.push(trigger);
}
}
private surfaceErrorNode(workspaceUri: Uri, message: string, testProvider: TestProvider): void {
let errorNode = this.testController.items.get(`DiscoveryError:${workspaceUri.fsPath}`);
if (errorNode === undefined) {
const options = buildErrorNodeOptions(workspaceUri, message, testProvider);
errorNode = createErrorTestItem(this.testController, options);
this.testController.items.add(errorNode);
}
const errorNodeLabel: MarkdownString = new MarkdownString(message);
errorNodeLabel.isTrusted = true;
errorNode.error = errorNodeLabel;
}
}