forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
pytestController.ts
321 lines (295 loc) · 14.5 KB
/
pytestController.ts
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { inject, injectable, named } from 'inversify';
import { flatten } from 'lodash';
import * as path from 'path';
import * as util from 'util';
import { CancellationToken, TestItem, Uri, TestController, WorkspaceFolder } from 'vscode';
import { IWorkspaceService } from '../../../common/application/types';
import { runAdapter } from '../../../common/process/internal/scripts/testing_tools';
import { IConfigurationService } from '../../../common/types';
import { asyncForEach } from '../../../common/utils/arrayUtils';
import { createDeferred, Deferred } from '../../../common/utils/async';
import { traceError } from '../../../logging';
import { sendTelemetryEvent } from '../../../telemetry';
import { EventName } from '../../../telemetry/constants';
import { PYTEST_PROVIDER } from '../../common/constants';
import { TestDiscoveryOptions } from '../../common/types';
import {
createErrorTestItem,
createWorkspaceRootTestItem,
getNodeByUri,
getWorkspaceNode,
removeItemByIdFromChildren,
updateTestItemFromRawData,
} from '../common/testItemUtilities';
import {
ITestFrameworkController,
ITestDiscoveryHelper,
ITestsRunner,
TestData,
RawDiscoveredTests,
ITestRun,
} from '../common/types';
import { preparePytestArgumentsForDiscovery, pytestGetTestFilesAndFolders } from './arguments';
@injectable()
export class PytestController implements ITestFrameworkController {
private readonly testData: Map<string, RawDiscoveredTests[]> = new Map();
private discovering: Map<string, Deferred<void>> = new Map();
private idToRawData: Map<string, TestData> = new Map();
constructor(
@inject(ITestDiscoveryHelper) private readonly discoveryHelper: ITestDiscoveryHelper,
@inject(ITestsRunner) @named(PYTEST_PROVIDER) private readonly runner: ITestsRunner,
@inject(IConfigurationService) private readonly configService: IConfigurationService,
@inject(IWorkspaceService) private readonly workspaceService: IWorkspaceService,
) {}
public async resolveChildren(
testController: TestController,
item: TestItem,
token?: CancellationToken,
): Promise<void> {
const workspace = this.workspaceService.getWorkspaceFolder(item.uri);
if (workspace) {
// if we are still discovering then wait
const discovery = this.discovering.get(workspace.uri.fsPath);
if (discovery) {
await discovery.promise;
}
// see if we have raw test data
const rawTestData = this.testData.get(workspace.uri.fsPath);
if (rawTestData) {
// Refresh each node with new data
if (rawTestData.length === 0) {
const items: TestItem[] = [];
testController.items.forEach((i) => items.push(i));
items.forEach((i) => testController.items.delete(i.id));
return Promise.resolve();
}
const root = rawTestData.length === 1 ? rawTestData[0].root : workspace.uri.fsPath;
if (root === item.id) {
// This is the workspace root node
if (rawTestData.length === 1) {
if (rawTestData[0].tests.length > 0) {
await updateTestItemFromRawData(
item,
testController,
this.idToRawData,
item.id,
rawTestData,
token,
);
} else {
this.idToRawData.delete(item.id);
testController.items.delete(item.id);
return Promise.resolve();
}
} else {
// To figure out which top level nodes have to removed. First we get all the
// existing nodes. Then if they have data we keep those nodes, Nodes without
// data will be removed after we check the raw data.
let subRootWithNoData: string[] = [];
item.children.forEach((c) => subRootWithNoData.push(c.id));
await asyncForEach(rawTestData, async (data) => {
let subRootId = data.root;
let rawId;
if (data.root === root) {
const subRoot = data.parents.filter((p) => p.parentid === '.' || p.parentid === root);
subRootId = path.join(data.root, subRoot.length > 0 ? subRoot[0].id : '');
rawId = subRoot.length > 0 ? subRoot[0].id : undefined;
}
if (data.tests.length > 0) {
let subRootItem = item.children.get(subRootId);
if (!subRootItem) {
subRootItem = createWorkspaceRootTestItem(testController, this.idToRawData, {
id: subRootId,
label: path.basename(subRootId),
uri: Uri.file(subRootId),
runId: subRootId,
parentId: item.id,
rawId,
});
item.children.add(subRootItem);
}
// We found data for a node. Remove its id from the no-data list.
subRootWithNoData = subRootWithNoData.filter((s) => s !== subRootId);
await updateTestItemFromRawData(
subRootItem,
testController,
this.idToRawData,
root, // All the file paths are based on workspace root.
[data],
token,
);
} else {
// This means there are no tests under this node
removeItemByIdFromChildren(this.idToRawData, item, [subRootId]);
}
});
// We did not find any data for these nodes, delete them.
removeItemByIdFromChildren(this.idToRawData, item, subRootWithNoData);
}
} else {
const workspaceNode = getWorkspaceNode(item, this.idToRawData);
if (workspaceNode) {
await updateTestItemFromRawData(
item,
testController,
this.idToRawData,
workspaceNode.id,
rawTestData,
token,
);
}
}
} else {
const workspaceNode = getWorkspaceNode(item, this.idToRawData);
if (workspaceNode) {
testController.items.delete(workspaceNode.id);
}
}
}
return Promise.resolve();
}
public async refreshTestData(testController: TestController, uri: Uri, token?: CancellationToken): Promise<void> {
sendTelemetryEvent(EventName.UNITTEST_DISCOVERING, undefined, { tool: 'pytest' });
const workspace = this.workspaceService.getWorkspaceFolder(uri);
if (workspace) {
// Discovery is expensive. So if it is already running then use the promise
// from the last run
const previous = this.discovering.get(workspace.uri.fsPath);
if (previous) {
return previous.promise;
}
const settings = this.configService.getSettings(workspace.uri);
const options: TestDiscoveryOptions = {
workspaceFolder: workspace.uri,
cwd:
settings.testing.cwd && settings.testing.cwd.length > 0
? settings.testing.cwd
: workspace.uri.fsPath,
args: settings.testing.pytestArgs,
ignoreCache: true,
token,
};
// Get individual test files and directories selected by the user.
const testFilesAndDirectories = pytestGetTestFilesAndFolders(options.args);
// Set arguments to use with pytest discovery script.
const args = runAdapter(['discover', 'pytest', '--', ...preparePytestArgumentsForDiscovery(options)]);
// Build options for each directory selected by the user.
let discoveryRunOptions: TestDiscoveryOptions[];
if (testFilesAndDirectories.length === 0) {
// User did not provide any directory. So we don't need to tweak arguments.
discoveryRunOptions = [
{
...options,
args,
},
];
} else {
discoveryRunOptions = testFilesAndDirectories.map((testDir) => ({
...options,
args: [...args, testDir],
}));
}
const deferred = createDeferred<void>();
this.discovering.set(workspace.uri.fsPath, deferred);
let rawTestData: RawDiscoveredTests[] = [];
try {
// This is where we execute pytest discovery via a common helper.
rawTestData = flatten(
await Promise.all(discoveryRunOptions.map((o) => this.discoveryHelper.runTestDiscovery(o))),
);
this.testData.set(workspace.uri.fsPath, rawTestData);
// Remove error node
testController.items.delete(`DiscoveryError:${workspace.uri.fsPath}`);
deferred.resolve();
} catch (ex) {
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_DONE, undefined, { tool: 'pytest', failed: true });
const cancel = options.token?.isCancellationRequested ? 'Cancelled' : 'Error';
traceError(`${cancel} discovering pytest tests:\r\n`, ex);
const message = getTestDiscoveryExceptions((ex as Error).message);
// Report also on the test view. Getting root node is more complicated due to fact
// that in pytest project can be organized in many ways
testController.items.add(
createErrorTestItem(testController, {
id: `DiscoveryError:${workspace.uri.fsPath}`,
label: `pytest Discovery Error [${path.basename(workspace.uri.fsPath)}]`,
error: util.format(
`${cancel} discovering pytest tests (see Output > Python):\r\n`,
message.length > 0 ? message : ex,
),
}),
);
deferred.reject(ex as Error);
} finally {
// Discovery has finished running we have the raw test data at this point.
this.discovering.delete(workspace.uri.fsPath);
}
const root = rawTestData.length === 1 ? rawTestData[0].root : workspace.uri.fsPath;
const workspaceNode = testController.items.get(root);
if (workspaceNode) {
if (uri.fsPath === workspace.uri.fsPath) {
// this is a workspace level refresh
// This is an existing workspace test node. Just update the children
await this.resolveChildren(testController, workspaceNode, token);
} else {
// This is a child node refresh
const testNode = getNodeByUri(workspaceNode, uri);
if (testNode) {
// We found the node to update
await this.resolveChildren(testController, testNode, token);
} else {
// update the entire workspace tree
await this.resolveChildren(testController, workspaceNode, token);
}
}
} else if (rawTestData.length > 0) {
// This is a new workspace with tests.
const newItem = createWorkspaceRootTestItem(testController, this.idToRawData, {
id: root,
label: path.basename(root),
uri: Uri.file(root),
runId: root,
});
testController.items.add(newItem);
await this.resolveChildren(testController, newItem, token);
}
}
sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_DONE, undefined, { tool: 'pytest', failed: false });
return Promise.resolve();
}
public runTests(testRun: ITestRun, workspace: WorkspaceFolder, token: CancellationToken): Promise<void> {
const settings = this.configService.getSettings(workspace.uri);
try {
return this.runner.runTests(
testRun,
{
workspaceFolder: workspace.uri,
cwd:
settings.testing.cwd && settings.testing.cwd.length > 0
? settings.testing.cwd
: workspace.uri.fsPath,
token,
args: settings.testing.pytestArgs,
},
this.idToRawData,
);
} catch (ex) {
sendTelemetryEvent(EventName.UNITTEST_RUN_ALL_FAILED, undefined);
throw new Error(`Failed to run tests: ${ex}`);
}
}
}
function getTestDiscoveryExceptions(content: string): string {
const lines = content.split(/\r?\n/g);
let start = false;
let exceptions = '';
for (const line of lines) {
if (start) {
exceptions += `${line}\r\n`;
} else if (line.includes(' ERRORS ')) {
start = true;
}
}
return exceptions;
}