forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.ts
More file actions
347 lines (312 loc) · 15.3 KB
/
controller.ts
File metadata and controls
347 lines (312 loc) · 15.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { inject, injectable, named } from 'inversify';
import { uniq } from 'lodash';
import {
CancellationToken,
TestController,
TestItem,
TestRunRequest,
tests,
WorkspaceFolder,
RelativePattern,
TestRunProfileKind,
CancellationTokenSource,
Uri,
EventEmitter,
} from 'vscode';
import { IWorkspaceService } from '../../common/application/types';
import { traceVerbose } from '../../common/logger';
import { IConfigurationService, IDisposableRegistry, Resource } from '../../common/types';
import { DelayedTrigger, IDelayedTrigger } from '../../common/utils/delayTrigger';
import { sendTelemetryEvent } from '../../telemetry';
import { EventName } from '../../telemetry/constants';
import { PYTEST_PROVIDER, UNITTEST_PROVIDER } from '../common/constants';
import { getNodeByUri } from './common/testItemUtilities';
import { ITestController, ITestFrameworkController, TestRefreshOptions } from './common/types';
@injectable()
export class PythonTestController implements ITestController {
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;
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,
) {
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),
this.testController.createRunProfile(
'Debug Tests',
TestRunProfileKind.Debug,
this.runTests.bind(this),
true,
),
);
this.testController.resolveHandler = this.resolveChildren.bind(this);
this.watchForTestChanges();
}
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();
if (uri) {
traceVerbose(`Testing: Refreshing test data for ${uri.fsPath}`);
const settings = this.configSettings.getSettings(uri);
if (settings.testing.pytestEnabled) {
await this.pytest.refreshTestData(this.testController, uri, this.refreshCancellation.token);
} else if (settings.testing.unittestEnabled) {
await this.unittest.refreshTestData(this.testController, uri, this.refreshCancellation.token);
} else {
sendTelemetryEvent(EventName.UNITTEST_DISABLED);
// If we are here we may have to remove an existing node from the tree
// This handles the case where user removes test settings. Which should remove the
// tests for that particular case from the tree view
const workspace = this.workspaceService.getWorkspaceFolder(uri);
if (workspace) {
const toDelete: string[] = [];
this.testController.items.forEach((i: TestItem) => {
const w = this.workspaceService.getWorkspaceFolder(i.uri);
if (w?.uri.fsPath === workspace.uri.fsPath) {
toDelete.push(i.id);
}
});
toDelete.forEach((i) => this.testController.items.delete(i));
}
}
} else {
traceVerbose('Testing: Refreshing all test data');
const workspaces: readonly WorkspaceFolder[] = this.workspaceService.workspaceFolders || [];
await Promise.all(workspaces.map((workspace) => this.refreshTestDataInternal(workspace.uri)));
}
this.refreshingCompletedEvent.fire();
return Promise.resolve();
}
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);
}
if (settings.testing.unittestEnabled) {
return this.unittest.resolveChildren(this.testController, item);
}
} else {
traceVerbose('Testing: Refreshing all test data');
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, { trigger: 'auto' });
const workspaces: readonly WorkspaceFolder[] = this.workspaceService.workspaceFolders || [];
await Promise.all(workspaces.map((workspace) => this.refreshTestDataInternal(workspace.uri)));
}
return Promise.resolve();
}
private async runTests(request: TestRunRequest, token: CancellationToken): Promise<void> {
const workspaces: WorkspaceFolder[] = [];
if (request.include) {
uniq(request.include.map((r) => this.workspaceService.getWorkspaceFolder(r.uri))).forEach((w) => {
if (w) {
workspaces.push(w);
}
});
} else {
(this.workspaceService.workspaceFolders || []).forEach((w) => workspaces.push(w));
}
const runInstance = this.testController.createTestRun(
request,
`Running Tests for Workspace(s): ${workspaces.map((w) => w.uri.fsPath).join(';')}`,
true,
);
const dispose = token.onCancellationRequested(() => {
runInstance.end();
});
const unconfiguredWorkspaces: WorkspaceFolder[] = [];
try {
await Promise.all(
workspaces.map((workspace) => {
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);
}
});
const settings = this.configSettings.getSettings(workspace.uri);
if (testItems.length > 0) {
if (settings.testing.pytestEnabled) {
sendTelemetryEvent(EventName.UNITTEST_RUN, undefined, {
tool: 'pytest',
debugging: request.profile?.kind === TestRunProfileKind.Debug,
});
return this.pytest.runTests(
{
includes: testItems,
excludes: request.exclude ?? [],
runKind: request.profile?.kind ?? TestRunProfileKind.Run,
runInstance,
},
workspace,
token,
);
}
if (settings.testing.unittestEnabled) {
sendTelemetryEvent(EventName.UNITTEST_RUN, undefined, {
tool: 'unittest',
debugging: request.profile?.kind === TestRunProfileKind.Debug,
});
return this.unittest.runTests(
{
includes: testItems,
excludes: request.exclude ?? [],
runKind: request.profile?.kind ?? TestRunProfileKind.Run,
runInstance,
},
workspace,
token,
);
}
}
if (!settings.testing.pytestEnabled && !settings.testing.unittestEnabled) {
unconfiguredWorkspaces.push(workspace);
}
return Promise.resolve();
}),
);
} finally {
runInstance.appendOutput(`Finished running tests!\r\n`);
runInstance.end();
dispose.dispose();
if (unconfiguredWorkspaces.length > 0) {
this.runWithoutConfigurationEvent.fire(unconfiguredWorkspaces);
}
}
}
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 watchForTestChanges(): void {
const workspaces: readonly WorkspaceFolder[] = this.workspaceService.workspaceFolders || [];
for (const workspace of workspaces) {
const settings = this.configSettings.getSettings(workspace.uri);
if (settings.testing.autoTestDiscoverOnSaveEnabled) {
traceVerbose(`Testing: Setting up watcher for ${workspace.uri.fsPath}`);
this.watchForSettingsChanges(workspace);
this.watchForTestContentChanges(workspace);
}
}
}
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(
watcher.onDidChange((uri) => {
traceVerbose(`Testing: Trigger refresh after change in ${uri.fsPath}`);
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, { trigger: 'watching' });
this.refreshData.trigger(uri, false);
}),
);
this.disposables.push(
watcher.onDidCreate((uri) => {
traceVerbose(`Testing: Trigger refresh after creating ${uri.fsPath}`);
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, { trigger: 'watching' });
this.refreshData.trigger(uri, false);
}),
);
this.disposables.push(
watcher.onDidDelete((uri) => {
traceVerbose(`Testing: Trigger refresh after deleting in ${uri.fsPath}`);
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, { trigger: 'watching' });
this.refreshData.trigger(uri, false);
}),
);
}
private watchForTestContentChanges(workspace: WorkspaceFolder): void {
const pattern = new RelativePattern(workspace, '**/*.py');
const watcher = this.workspaceService.createFileSystemWatcher(pattern);
this.disposables.push(watcher);
this.disposables.push(
watcher.onDidChange((uri) => {
traceVerbose(`Testing: Trigger refresh after change in ${uri.fsPath}`);
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, { trigger: 'watching' });
// We want to invalidate tests for code change
this.refreshData.trigger(uri, true);
}),
);
this.disposables.push(
watcher.onDidCreate((uri) => {
traceVerbose(`Testing: Trigger refresh after creating ${uri.fsPath}`);
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, { trigger: 'watching' });
this.refreshData.trigger(uri, false);
}),
);
this.disposables.push(
watcher.onDidDelete((uri) => {
traceVerbose(`Testing: Trigger refresh after deleting in ${uri.fsPath}`);
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_TRIGGER, undefined, { trigger: 'watching' });
this.refreshData.trigger(uri, false);
}),
);
}
}