This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 645
/
Copy pathgoTest.ts
304 lines (276 loc) · 8.64 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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------*/
'use strict';
import cp = require('child_process');
import path = require('path');
import vscode = require('vscode');
import util = require('util');
import os = require('os');
import { parseEnvFile, getGoRuntimePath, resolvePath } from './goPath';
import { getToolsEnvVars } from './util';
import { GoDocumentSymbolProvider } from './goOutline';
let outputChannel = vscode.window.createOutputChannel('Go Tests');
/**
* Input to goTest.
*/
interface TestConfig {
/**
* The working directory for `go test`.
*/
dir: string;
/**
* Configuration for the Go extension
*/
goConfig: vscode.WorkspaceConfiguration;
/**
* Test flags to override the testFlags and buildFlags from goConfig.
*/
flags: string[];
/**
* Specific function names to test.
*/
functions?: string[];
/**
* Test was not requested explicitly. The output should not appear in the UI.
*/
background?: boolean;
/**
* Run all tests from all sub directories under `dir`
*/
includeSubDirectories?: boolean;
}
// lastTestConfig holds a reference to the last executed TestConfig which allows
// the last test to be easily re-executed.
let lastTestConfig: TestConfig;
/**
* 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.
*/
export function testAtCursor(goConfig: vscode.WorkspaceConfiguration, args: any) {
let 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;
}
if (editor.document.isDirty) {
vscode.window.showInformationMessage('File has unsaved changes. Save and try again.');
return;
}
getTestFunctions(editor.document).then(testFunctions => {
let testFunctionName: string;
// We use functionName if it was provided as argument
// Otherwise find any test function containing the cursor.
if (args && args.functionName) {
testFunctionName = args.functionName;
} else {
for (let func of testFunctions) {
let selection = editor.selection;
if (selection && func.location.range.contains(selection.start)) {
testFunctionName = func.name;
break;
}
};
}
if (!testFunctionName) {
vscode.window.showInformationMessage('No test function found at cursor.');
return;
}
return goTest({
goConfig: goConfig,
dir: path.dirname(editor.document.fileName),
flags: getTestFlags(goConfig, args),
functions: [ testFunctionName ]
});
}).then(null, err => {
console.error(err);
});
}
/**
* Runs all tests in the package of the source of the active editor.
*
* @param goConfig Configuration for the Go extension.
*/
export function testCurrentPackage(goConfig: vscode.WorkspaceConfiguration, args: any) {
let editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('No editor is active.');
return;
}
goTest({
goConfig: goConfig,
dir: path.dirname(editor.document.fileName),
flags: getTestFlags(goConfig, args)
}).then(null, err => {
console.error(err);
});
}
/**
* Runs all tests from all directories in the workspace.
*
* @param goConfig Configuration for the Go extension.
*/
export function testWorkspace(goConfig: vscode.WorkspaceConfiguration, args: any) {
goTest({
goConfig: goConfig,
dir: vscode.workspace.rootPath,
flags: getTestFlags(goConfig, args),
includeSubDirectories: true
}).then(null, err => {
console.error(err);
});
}
export function getTestEnvVars(): any {
const config = vscode.workspace.getConfiguration('go');
const toolsEnv = getToolsEnvVars();
const testEnv = config['testEnvVars'] || {};
let fileEnv = {};
let testEnvFile = config['testEnvFile'];
if (testEnvFile) {
testEnvFile = resolvePath(testEnvFile, vscode.workspace.rootPath);
try {
fileEnv = parseEnvFile(testEnvFile);
} catch (e) {
console.log(e);
}
}
return Object.assign({}, toolsEnv, fileEnv, testEnv);
}
/**
* Runs all tests in the source of the active editor.
*
* @param goConfig Configuration for the Go extension.
*/
export function testCurrentFile(goConfig: vscode.WorkspaceConfiguration, args: string[]): Thenable<boolean> {
let 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;
}
return getTestFunctions(editor.document).then(testFunctions => {
return goTest({
goConfig: goConfig,
dir: path.dirname(editor.document.fileName),
flags: getTestFlags(goConfig, args),
functions: testFunctions.map(func => { return func.name; })
});
}).then(null, err => {
console.error(err);
return Promise.resolve(false);
});
}
/**
* Runs the previously executed test.
*/
export function testPrevious() {
let editor = vscode.window.activeTextEditor;
if (!lastTestConfig) {
vscode.window.showInformationMessage('No test has been recently executed.');
return;
}
goTest(lastTestConfig).then(null, err => {
console.error(err);
});
}
/**
* Reveals the output channel in the UI.
*/
export function showTestOutput() {
outputChannel.show(true);
}
/**
* Runs go test and presents the output in the 'Go' channel.
*
* @param goConfig Configuration for the Go extension.
*/
export function goTest(testconfig: TestConfig): Thenable<boolean> {
return new Promise<boolean>((resolve, reject) => {
outputChannel.clear();
if (!testconfig.background) {
// Remember this config as the last executed test.
lastTestConfig = testconfig;
outputChannel.show(true);
}
let buildTags: string = testconfig.goConfig['buildTags'];
let args = ['test', ...testconfig.flags, '-timeout', testconfig.goConfig['testTimeout'], '-tags', buildTags];
let testEnvVars = getTestEnvVars();
let goRuntimePath = getGoRuntimePath();
if (!goRuntimePath) {
vscode.window.showInformationMessage('Cannot find "go" binary. Update PATH or GOROOT appropriately');
return Promise.resolve();
}
if (testconfig.functions) {
args.push('-run');
args.push(util.format('^%s$', testconfig.functions.join('|')));
} else if (testconfig.includeSubDirectories) {
args.push('./...');
}
outputChannel.appendLine(['Running tool:', goRuntimePath, ...args].join(' '));
outputChannel.appendLine('');
let proc = cp.spawn(goRuntimePath, args, { env: testEnvVars, cwd: testconfig.dir });
proc.stdout.on('data', chunk => {
let testOutput = expandFilePathInOutput(chunk.toString(), testconfig.dir);
outputChannel.append(testOutput);
});
proc.stderr.on('data', chunk => outputChannel.append(chunk.toString()));
proc.on('close', code => {
if (code) {
outputChannel.append('Error: Tests failed.');
} else {
outputChannel.append('Success: Tests passed.');
}
resolve(code === 0);
});
});
}
/**
* Returns all Go unit test functions in the given source file.
*
* @param the URI of a Go source file.
* @return test function symbols for the source file.
*/
export function getTestFunctions(doc: vscode.TextDocument): Thenable<vscode.SymbolInformation[]> {
let documentSymbolProvider = new GoDocumentSymbolProvider();
return documentSymbolProvider
.provideDocumentSymbols(doc, null)
.then(symbols =>
symbols.filter(sym =>
sym.kind === vscode.SymbolKind.Function
&& hasTestFunctionPrefix(sym.name))
);
}
/**
* Returns whether a given function name has a test prefix.
* Test functions have "Test" or "Example" as a prefix.
*
* @param the function name.
* @return whether the name has a test function prefix.
*/
function hasTestFunctionPrefix(name: string): boolean {
return name.startsWith('Test') || name.startsWith('Example');
}
function getTestFlags(goConfig: vscode.WorkspaceConfiguration, args: any): string[] {
let testFlags = goConfig['testFlags'] ? goConfig['testFlags'] : goConfig['buildFlags'];
return (args && args.hasOwnProperty('flags') && Array.isArray(args['flags'])) ? args['flags'] : testFlags;
}
function expandFilePathInOutput(output: string, cwd: string): string {
let lines = output.split('\n');
for (let i = 0; i < lines.length; i++) {
let matches = lines[i].match(/^\t(\S+_test.go):(\d+):/);
if (matches) {
lines[i] = lines[i].replace(matches[1], path.join(cwd, matches[1]));
}
}
return lines.join('\n');
}