forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestFiles.ts
More file actions
321 lines (297 loc) · 11.2 KB
/
testFiles.ts
File metadata and controls
321 lines (297 loc) · 11.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
'use strict';
import {
CancellationToken,
CancellationTokenSource,
CodeLens,
CodeLensProvider,
DocumentSymbolProvider,
Event,
EventEmitter,
Position,
Range,
SymbolInformation,
SymbolKind,
TextDocument,
Uri,
} from 'vscode';
import { IWorkspaceService } from '../../../client/common/application/types';
import { IFileSystem } from '../../../client/common/platform/types';
import { IServiceContainer } from '../../../client/ioc/types';
import * as constants from '../../common/constants';
import {
ITestCollectionStorageService,
TestFile,
TestFunction,
TestStatus,
TestsToRun,
TestSuite,
} from '../common/types';
type FunctionsAndSuites = {
functions: TestFunction[];
suites: TestSuite[];
};
export class TestFileCodeLensProvider implements CodeLensProvider {
private workspaceService: IWorkspaceService;
private fileSystem: IFileSystem;
constructor(
private _onDidChange: EventEmitter<void>,
private symbolProvider: DocumentSymbolProvider,
private testCollectionStorage: ITestCollectionStorageService,
serviceContainer: IServiceContainer,
) {
this.workspaceService = serviceContainer.get<IWorkspaceService>(IWorkspaceService);
this.fileSystem = serviceContainer.get<IFileSystem>(IFileSystem);
}
get onDidChangeCodeLenses(): Event<void> {
return this._onDidChange.event;
}
public async provideCodeLenses(document: TextDocument, token: CancellationToken) {
const wkspace = this.workspaceService.getWorkspaceFolder(document.uri);
if (!wkspace) {
return [];
}
const testItems = this.testCollectionStorage.getTests(wkspace.uri);
if (!testItems || testItems.testFiles.length === 0 || testItems.testFunctions.length === 0) {
return [];
}
const cancelTokenSrc = new CancellationTokenSource();
token.onCancellationRequested(() => {
cancelTokenSrc.cancel();
});
// Strop trying to build the code lenses if unable to get a list of
// symbols in this file afrer x time.
setTimeout(() => {
if (!cancelTokenSrc.token.isCancellationRequested) {
cancelTokenSrc.cancel();
}
}, constants.Delays.MaxUnitTestCodeLensDelay);
return this.getCodeLenses(document, cancelTokenSrc.token, this.symbolProvider);
}
public resolveCodeLens(codeLens: CodeLens, _token: CancellationToken): CodeLens | Thenable<CodeLens> {
codeLens.command = { command: 'python.runtests', title: 'Test' };
return Promise.resolve(codeLens);
}
public getTestFileWhichNeedsCodeLens(document: TextDocument): TestFile | undefined {
const wkspace = this.workspaceService.getWorkspaceFolder(document.uri);
if (!wkspace) {
return;
}
const tests = this.testCollectionStorage.getTests(wkspace.uri);
if (!tests) {
return;
}
return tests.testFiles.find((item) => this.fileSystem.arePathsSame(item.fullPath, document.uri.fsPath));
}
private async getCodeLenses(
document: TextDocument,
token: CancellationToken,
symbolProvider: DocumentSymbolProvider,
) {
const file = this.getTestFileWhichNeedsCodeLens(document);
if (!file) {
return [];
}
const allFuncsAndSuites = getAllTestSuitesAndFunctionsPerFile(file);
try {
const symbols = (await symbolProvider.provideDocumentSymbols(document, token)) as SymbolInformation[];
if (!symbols) {
return [];
}
return symbols
.filter(
(symbol) =>
symbol.kind === SymbolKind.Function ||
symbol.kind === SymbolKind.Method ||
symbol.kind === SymbolKind.Class,
)
.map((symbol) => {
// This is crucial, if the start and end columns are the same then vscode bugs out
// whenever you edit a line (start scrolling magically).
const range = new Range(
symbol.location.range.start,
new Position(symbol.location.range.end.line, symbol.location.range.end.character + 1),
);
return this.getCodeLens(
document.uri,
allFuncsAndSuites,
range,
symbol.name,
symbol.kind,
symbol.containerName,
);
})
.reduce((previous, current) => previous.concat(current), [])
.filter((codeLens) => codeLens !== null);
} catch (reason) {
if (token.isCancellationRequested) {
return [];
}
return Promise.reject(reason);
}
}
private getCodeLens(
file: Uri,
allFuncsAndSuites: FunctionsAndSuites,
range: Range,
symbolName: string,
symbolKind: SymbolKind,
symbolContainer: string,
): CodeLens[] {
switch (symbolKind) {
case SymbolKind.Function:
case SymbolKind.Method: {
return getFunctionCodeLens(file, allFuncsAndSuites, symbolName, range, symbolContainer);
}
case SymbolKind.Class: {
const cls = allFuncsAndSuites.suites.find((item) => item.name === symbolName);
if (!cls) {
return [];
}
return [
new CodeLens(range, {
title: getTestStatusIcon(cls.status) + constants.Text.CodeLensRunUnitTest,
command: constants.Commands.Tests_Run,
arguments: [
undefined,
constants.CommandSource.codelens,
file,
<TestsToRun>{ testSuite: [cls] },
],
}),
new CodeLens(range, {
title: getTestStatusIcon(cls.status) + constants.Text.CodeLensDebugUnitTest,
command: constants.Commands.Tests_Debug,
arguments: [
undefined,
constants.CommandSource.codelens,
file,
<TestsToRun>{ testSuite: [cls] },
],
}),
];
}
default: {
return [];
}
}
}
}
function getTestStatusIcon(status?: TestStatus): string {
switch (status) {
case TestStatus.Pass: {
return `${constants.Octicons.Test_Pass} `;
}
case TestStatus.Error: {
return `${constants.Octicons.Test_Error} `;
}
case TestStatus.Fail: {
return `${constants.Octicons.Test_Fail} `;
}
case TestStatus.Skipped: {
return `${constants.Octicons.Test_Skip} `;
}
default: {
return '';
}
}
}
function getTestStatusIcons(fns: TestFunction[]): string {
const statuses: string[] = [];
let count = fns.filter((fn) => fn.status === TestStatus.Pass).length;
if (count > 0) {
statuses.push(`${constants.Octicons.Test_Pass} ${count}`);
}
count = fns.filter((fn) => fn.status === TestStatus.Skipped).length;
if (count > 0) {
statuses.push(`${constants.Octicons.Test_Skip} ${count}`);
}
count = fns.filter((fn) => fn.status === TestStatus.Fail).length;
if (count > 0) {
statuses.push(`${constants.Octicons.Test_Fail} ${count}`);
}
count = fns.filter((fn) => fn.status === TestStatus.Error).length;
if (count > 0) {
statuses.push(`${constants.Octicons.Test_Error} ${count}`);
}
return statuses.join(' ');
}
function getFunctionCodeLens(
file: Uri,
functionsAndSuites: FunctionsAndSuites,
symbolName: string,
range: Range,
symbolContainer: string,
): CodeLens[] {
let fn: TestFunction | undefined;
if (symbolContainer.length === 0) {
fn = functionsAndSuites.functions.find((func) => func.name === symbolName);
} else {
// Assume single levels for now.
functionsAndSuites.suites
.filter((s) => s.name === symbolContainer)
.forEach((s) => {
const f = s.functions.find((item) => item.name === symbolName);
if (f) {
fn = f;
}
});
}
if (fn) {
return [
new CodeLens(range, {
title: getTestStatusIcon(fn.status) + constants.Text.CodeLensRunUnitTest,
command: constants.Commands.Tests_Run,
arguments: [undefined, constants.CommandSource.codelens, file, <TestsToRun>{ testFunction: [fn] }],
}),
new CodeLens(range, {
title: getTestStatusIcon(fn.status) + constants.Text.CodeLensDebugUnitTest,
command: constants.Commands.Tests_Debug,
arguments: [undefined, constants.CommandSource.codelens, file, <TestsToRun>{ testFunction: [fn] }],
}),
];
}
// Ok, possible we're dealing with parameterized unit tests.
// If we have [ in the name, then this is a parameterized function.
const functions = functionsAndSuites.functions.filter(
(func) => func.name.startsWith(`${symbolName}[`) && func.name.endsWith(']'),
);
if (functions.length === 0) {
return [];
}
// Find all flattened functions.
return [
new CodeLens(range, {
title: `${getTestStatusIcons(functions)} ${constants.Text.CodeLensRunUnitTest} (Multiple)`,
command: constants.Commands.Tests_Picker_UI,
arguments: [undefined, constants.CommandSource.codelens, file, functions],
}),
new CodeLens(range, {
title: `${getTestStatusIcons(functions)} ${constants.Text.CodeLensDebugUnitTest} (Multiple)`,
command: constants.Commands.Tests_Picker_UI_Debug,
arguments: [undefined, constants.CommandSource.codelens, file, functions],
}),
];
}
function getAllTestSuitesAndFunctionsPerFile(testFile: TestFile): FunctionsAndSuites {
const all = { functions: [...testFile.functions], suites: [] as TestSuite[] };
testFile.suites.forEach((suite) => {
all.suites.push(suite);
const allChildItems = getAllTestSuitesAndFunctions(suite);
all.functions.push(...allChildItems.functions);
all.suites.push(...allChildItems.suites);
});
return all;
}
function getAllTestSuitesAndFunctions(testSuite: TestSuite): FunctionsAndSuites {
const all: { functions: TestFunction[]; suites: TestSuite[] } = { functions: [], suites: [] };
testSuite.functions.forEach((fn) => {
all.functions.push(fn);
});
testSuite.suites.forEach((suite) => {
all.suites.push(suite);
const allChildItems = getAllTestSuitesAndFunctions(suite);
all.functions.push(...allChildItems.functions);
all.suites.push(...allChildItems.suites);
});
return all;
}