-
Notifications
You must be signed in to change notification settings - Fork 790
/
Copy pathgoTest.ts
418 lines (387 loc) · 13.2 KB
/
goTest.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
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
/* eslint-disable @typescript-eslint/no-explicit-any */
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
'use strict';
import path = require('path');
import vscode = require('vscode');
import { CommandFactory } from './commands';
import { getGoConfig } from './config';
import { GoExtensionContext } from './context';
import { isModSupported } from './goModules';
import {
extractInstanceTestName,
findAllTestSuiteRuns,
getBenchmarkFunctions,
getTestFlags,
getTestFunctionDebugArgs,
getSuiteToTestMap,
getTestFunctions,
getTestTags,
goTest,
TestConfig,
SuiteToTestMap
} from './testUtils';
// lastTestConfig holds a reference to the last executed TestConfig which allows
// the last test to be easily re-executed.
let lastTestConfig: TestConfig | undefined;
// lastDebugConfig holds a reference to the last executed DebugConfiguration which allows
// the last test to be easily re-executed and debugged.
let lastDebugConfig: vscode.DebugConfiguration | undefined;
let lastDebugWorkspaceFolder: vscode.WorkspaceFolder | undefined;
export type TestAtCursorCmd = 'debug' | 'test' | 'benchmark';
class NotFoundError extends Error {}
async function _testAtCursor(
goCtx: GoExtensionContext,
goConfig: vscode.WorkspaceConfiguration,
cmd: TestAtCursorCmd,
args: any
) {
const editor = vscode.window.activeTextEditor;
if (!editor) {
throw new NotFoundError('No editor is active.');
}
if (!editor.document.fileName.endsWith('_test.go')) {
throw new NotFoundError('No tests found. Current file is not a test file.');
}
const getFunctions = cmd === 'benchmark' ? getBenchmarkFunctions : getTestFunctions;
const testFunctions = (await getFunctions(goCtx, editor.document)) ?? [];
const suiteToTest = await getSuiteToTestMap(goCtx, editor.document);
// We use functionName if it was provided as argument
// Otherwise find any test function containing the cursor.
const testFunctionName =
args && args.functionName
? args.functionName
: testFunctions?.filter((func) => func.range.contains(editor.selection.start)).map((el) => el.name)[0];
if (!testFunctionName) {
throw new NotFoundError('No test function found at cursor.');
}
await editor.document.save();
if (cmd === 'debug') {
return debugTestAtCursor(editor, testFunctionName, testFunctions, suiteToTest, goConfig);
} else if (cmd === 'benchmark' || cmd === 'test') {
return runTestAtCursor(editor, testFunctionName, testFunctions, suiteToTest, goConfig, cmd, args);
} else {
throw new Error(`Unsupported command: ${cmd}`);
}
}
/**
* Executes the unit test at the primary cursor using `go test`. Output
* is sent to the 'Go' channel.
* @param goConfig Configuration for the Go extension.
* @param cmd Whether the command is test, benchmark, or debug.
* @param args
*/
export function testAtCursor(cmd: TestAtCursorCmd): CommandFactory {
return (ctx, goCtx) => (args: any) => {
const goConfig = getGoConfig();
_testAtCursor(goCtx, goConfig, cmd, args).catch((err) => {
if (err instanceof NotFoundError) {
vscode.window.showInformationMessage(err.message);
} else {
console.error(err);
}
});
};
}
/**
* Executes the unit test at the primary cursor if found, otherwise re-runs the previous test.
* @param goConfig Configuration for the Go extension.
* @param cmd Whether the command is test, benchmark, or debug.
* @param args
*/
export function testAtCursorOrPrevious(cmd: TestAtCursorCmd): CommandFactory {
return (ctx, goCtx) => async (args: any) => {
const goConfig = getGoConfig();
try {
await _testAtCursor(goCtx, goConfig, cmd, args);
} catch (err) {
if (err instanceof NotFoundError) {
const editor = vscode.window.activeTextEditor;
if (editor) {
await editor.document.save();
}
await testPrevious(ctx, goCtx)();
} else {
console.error(err);
}
}
};
}
/**
* Runs the test at cursor.
*/
async function runTestAtCursor(
editor: vscode.TextEditor,
testFunctionName: string,
testFunctions: vscode.DocumentSymbol[],
suiteToTest: SuiteToTestMap,
goConfig: vscode.WorkspaceConfiguration,
cmd: TestAtCursorCmd,
args: any
) {
const testConfigFns = [testFunctionName];
if (cmd !== 'benchmark' && extractInstanceTestName(testFunctionName)) {
testConfigFns.push(...findAllTestSuiteRuns(editor.document, testFunctions, suiteToTest).map((t) => t.name));
}
const isMod = await isModSupported(editor.document.uri);
const testConfig: TestConfig = {
goConfig,
dir: path.dirname(editor.document.fileName),
flags: getTestFlags(goConfig, args),
functions: testConfigFns,
isBenchmark: cmd === 'benchmark',
isMod,
applyCodeCoverage: goConfig.get<boolean>('coverOnSingleTest')
};
// Remember this config as the last executed test.
lastTestConfig = testConfig;
return goTest(testConfig);
}
/**
* Executes the sub unit test at the primary cursor using `go test`. Output
* is sent to the 'Go' channel.
*/
export const subTestAtCursor: CommandFactory = (ctx, goCtx) => {
return async (args: any) => {
const goConfig = getGoConfig();
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('No editor is active.');
return;
}
if (!editor.document.fileName.endsWith('_test.go')) {
vscode.window.showInformationMessage('No tests found. Current file is not a test file.');
return;
}
await editor.document.save();
try {
const testFunctions = (await getTestFunctions(goCtx, editor.document)) ?? [];
const suiteToTest = await getSuiteToTestMap(goCtx, editor.document);
// We use functionName if it was provided as argument
// Otherwise find any test function containing the cursor.
const currentTestFunctions = testFunctions.filter((func) => func.range.contains(editor.selection.start));
const testFunctionName =
args && args.functionName ? args.functionName : currentTestFunctions.map((el) => el.name)[0];
if (!testFunctionName || currentTestFunctions.length === 0) {
vscode.window.showInformationMessage('No test function found at cursor.');
return;
}
const testFunction = currentTestFunctions[0];
const simpleRunRegex = /t.Run\("([^"]+)",/;
const runRegex = /t.Run\(/;
let lineText: string;
let runMatch: RegExpMatchArray | null | undefined;
let simpleMatch: RegExpMatchArray | null | undefined;
for (let i = editor.selection.start.line; i >= testFunction.range.start.line; i--) {
lineText = editor.document.lineAt(i).text;
simpleMatch = lineText.match(simpleRunRegex);
runMatch = lineText.match(runRegex);
if (simpleMatch || (runMatch && !simpleMatch)) {
break;
}
}
let subtest: string;
if (!simpleMatch) {
const input = await vscode.window.showInputBox({
prompt: 'Enter sub test name'
});
if (input) {
subtest = input;
} else {
vscode.window.showInformationMessage(
'No subtest function with a simple subtest name found at cursor.'
);
return;
}
} else {
subtest = simpleMatch[1];
}
const subTestName = testFunctionName + '/' + subtest;
return await runTestAtCursor(editor, subTestName, testFunctions, suiteToTest, goConfig, 'test', args);
} catch (err) {
vscode.window.showInformationMessage('Unable to run subtest: ' + (err as any).toString());
console.error(err);
}
};
};
/**
* Debugs the test at cursor.
* @param editorOrDocument The text document (or editor) that defines the test.
* @param testFunctionName The name of the test function.
* @param testFunctions All test function symbols defined by the document.
* @param goConfig Go configuration, i.e. flags, tags, environment, etc.
* @param sessionID If specified, `sessionID` is added to the debug
* configuration and can be used to identify the debug session.
* @returns Whether the debug session was successfully started.
*/
export async function debugTestAtCursor(
editorOrDocument: vscode.TextEditor | vscode.TextDocument,
testFunctionName: string,
testFunctions: vscode.DocumentSymbol[],
suiteToFunc: SuiteToTestMap,
goConfig: vscode.WorkspaceConfiguration,
sessionID?: string
) {
const doc = 'document' in editorOrDocument ? editorOrDocument.document : editorOrDocument;
const args = getTestFunctionDebugArgs(doc, testFunctionName, testFunctions, suiteToFunc);
const tags = getTestTags(goConfig);
const buildFlags = tags ? ['-tags', tags] : [];
const flagsFromConfig = getTestFlags(goConfig);
let foundArgsFlag = false;
flagsFromConfig.forEach((x) => {
if (foundArgsFlag) {
args.push(x);
return;
}
if (x === '-args') {
foundArgsFlag = true;
return;
}
buildFlags.push(x);
});
const workspaceFolder = vscode.workspace.getWorkspaceFolder(doc.uri);
const debugConfig: vscode.DebugConfiguration = {
name: 'Debug Test',
type: 'go',
request: 'launch',
mode: 'test',
program: path.dirname(doc.fileName),
env: goConfig.get('testEnvVars', {}),
envFile: goConfig.get('testEnvFile'),
args,
buildFlags: buildFlags.join(' '),
sessionID
};
lastDebugConfig = debugConfig;
lastDebugWorkspaceFolder = workspaceFolder;
vscode.commands.executeCommand('workbench.debug.action.focusRepl');
return await vscode.debug.startDebugging(workspaceFolder, debugConfig);
}
/**
* Runs all tests in the package of the source of the active editor.
*
* @param goConfig Configuration for the Go extension.
*/
export function testCurrentPackage(isBenchmark: boolean): CommandFactory {
return () => async (args: any) => {
const goConfig = getGoConfig();
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('No editor is active.');
return;
}
const isMod = await isModSupported(editor.document.uri);
const testConfig: TestConfig = {
goConfig,
dir: path.dirname(editor.document.fileName),
flags: getTestFlags(goConfig, args),
isBenchmark,
isMod,
applyCodeCoverage: goConfig.get<boolean>('coverOnTestPackage')
};
// Remember this config as the last executed test.
lastTestConfig = testConfig;
return goTest(testConfig);
};
}
/**
* Runs all tests from all directories in the workspace.
*
* @param goConfig Configuration for the Go extension.
*/
export const testWorkspace: CommandFactory = () => (args: any) => {
const goConfig = getGoConfig();
if (!vscode.workspace.workspaceFolders?.length) {
vscode.window.showInformationMessage('No workspace is open to run tests.');
return;
}
let workspaceUri: vscode.Uri | undefined = vscode.workspace.workspaceFolders[0].uri;
if (
vscode.window.activeTextEditor &&
vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri)
) {
workspaceUri = vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri)!.uri;
}
const testConfig: TestConfig = {
goConfig,
dir: workspaceUri.fsPath,
flags: getTestFlags(goConfig, args),
includeSubDirectories: true
};
// Remember this config as the last executed test.
lastTestConfig = testConfig;
isModSupported(workspaceUri, true).then((isMod) => {
testConfig.isMod = isMod;
goTest(testConfig).then(null, (err) => {
console.error(err);
});
});
};
/**
* Runs all tests in the source of the active editor.
*
* @param goConfig Configuration for the Go extension.
* @param isBenchmark Boolean flag indicating if these are benchmark tests or not.
*/
export function testCurrentFile(isBenchmark: boolean, getConfig = getGoConfig): CommandFactory {
return (ctx, goCtx) => async (args: string[]) => {
const goConfig = getConfig();
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('No editor is active.');
return false;
}
if (!editor.document.fileName.endsWith('_test.go')) {
vscode.window.showInformationMessage('No tests found. Current file is not a test file.');
return false;
}
const getFunctions = isBenchmark ? getBenchmarkFunctions : getTestFunctions;
const isMod = await isModSupported(editor.document.uri);
return editor.document
.save()
.then(() => {
return getFunctions(goCtx, editor.document).then((testFunctions) => {
const testConfig: TestConfig = {
goConfig,
dir: path.dirname(editor.document.fileName),
flags: getTestFlags(goConfig, args),
functions: testFunctions?.map((sym) => sym.name),
isBenchmark,
isMod,
applyCodeCoverage: goConfig.get<boolean>('coverOnSingleTestFile')
};
// Remember this config as the last executed test.
lastTestConfig = testConfig;
return goTest(testConfig);
});
})
.then(undefined, (err) => {
console.error(err);
return Promise.resolve(false);
});
};
}
/**
* Runs the previously executed test.
*/
export const testPrevious: CommandFactory = () => () => {
if (!lastTestConfig) {
vscode.window.showInformationMessage('No test has been recently executed.');
return;
}
goTest(lastTestConfig).then(null, (err) => {
console.error(err);
});
};
/**
* Runs the previously executed test.
*/
export const debugPrevious: CommandFactory = () => () => {
if (!lastDebugConfig) {
vscode.window.showInformationMessage('No test has been recently debugged.');
return;
}
return vscode.debug.startDebugging(lastDebugWorkspaceFolder, lastDebugConfig);
};