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 646
/
testUtils.ts
233 lines (203 loc) · 7.27 KB
/
testUtils.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------*/
import cp = require('child_process');
import path = require('path');
import vscode = require('vscode');
import util = require('util');
import { parseEnvFile, getGoRuntimePath, getCurrentGoWorkspaceFromGOPATH } from './goPath';
import { getToolsEnvVars, getGoVersion, LineBuffer, SemVersion, resolvePath, getCurrentGoPath } from './util';
import { GoDocumentSymbolProvider } from './goOutline';
import { getNonVendorPackages } from './goPackages';
let outputChannel = vscode.window.createOutputChannel('Go Tests');
/**
* Input to goTest.
*/
export 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;
/**
* Whether this is a benchmark.
*/
isBenchmark?: boolean;
}
export function getTestEnvVars(config: vscode.WorkspaceConfiguration): any {
const envVars = getToolsEnvVars();
const testEnvConfig = config['testEnvVars'] || {};
let fileEnv = {};
let testEnvFile = config['testEnvFile'];
if (testEnvFile) {
testEnvFile = resolvePath(testEnvFile);
try {
fileEnv = parseEnvFile(testEnvFile);
} catch (e) {
console.log(e);
}
}
Object.keys(testEnvConfig).forEach(key => envVars[key] = resolvePath(testEnvConfig[key]));
Object.keys(fileEnv).forEach(key => envVars[key] = resolvePath(fileEnv[key]));
return envVars;
}
export function getTestFlags(goConfig: vscode.WorkspaceConfiguration, args: any): string[] {
let testFlags: string[] = goConfig['testFlags'] ? goConfig['testFlags'] : goConfig['buildFlags'];
testFlags = [...testFlags]; // Use copy of the flags, dont pass the actual object from config
return (args && args.hasOwnProperty('flags') && Array.isArray(args['flags'])) ? args['flags'] : testFlags;
}
/**
* 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, token: vscode.CancellationToken): Thenable<vscode.SymbolInformation[]> {
let documentSymbolProvider = new GoDocumentSymbolProvider();
return documentSymbolProvider
.provideDocumentSymbols(doc, token)
.then(symbols =>
symbols.filter(sym =>
sym.kind === vscode.SymbolKind.Function
&& (sym.name.startsWith('Test') || sym.name.startsWith('Example')))
);
}
/**
* Returns all Benchmark functions in the given source file.
*
* @param the URI of a Go source file.
* @return benchmark function symbols for the source file.
*/
export function getBenchmarkFunctions(doc: vscode.TextDocument, token: vscode.CancellationToken): Thenable<vscode.SymbolInformation[]> {
let documentSymbolProvider = new GoDocumentSymbolProvider();
return documentSymbolProvider
.provideDocumentSymbols(doc, token)
.then(symbols =>
symbols.filter(sym =>
sym.kind === vscode.SymbolKind.Function
&& sym.name.startsWith('Benchmark'))
);
}
/**
* 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) {
outputChannel.show(true);
}
let buildTags: string = testconfig.goConfig['buildTags'];
let args: Array<string> = ['test', ...testconfig.flags];
let testType: string = testconfig.isBenchmark ? 'Benchmarks' : 'Tests';
if (testconfig.isBenchmark) {
args.push('-benchmem', '-run=^$');
} else {
args.push('-timeout', testconfig.goConfig['testTimeout']);
}
if (buildTags && testconfig.flags.indexOf('-tags') === -1) {
args.push('-tags', buildTags);
}
let testEnvVars = getTestEnvVars(testconfig.goConfig);
let goRuntimePath = getGoRuntimePath();
if (!goRuntimePath) {
vscode.window.showInformationMessage('Cannot find "go" binary. Update PATH or GOROOT appropriately');
return Promise.resolve();
}
// Append the package name to args to enable running tests in symlinked directories
let currentGoWorkspace = getCurrentGoWorkspaceFromGOPATH(getCurrentGoPath(), testconfig.dir);
if (currentGoWorkspace && !testconfig.includeSubDirectories) {
args.push(testconfig.dir.substr(currentGoWorkspace.length + 1));
}
targetArgs(testconfig).then(targets => {
let outTargets = args.slice(0);
if (targets.length > 2) {
outTargets.push('<long arguments omitted>');
} else {
outTargets.push(...targets);
}
outputChannel.appendLine(['Running tool:', goRuntimePath, ...outTargets].join(' '));
outputChannel.appendLine('');
args.push(...targets);
let proc = cp.spawn(goRuntimePath, args, { env: testEnvVars, cwd: testconfig.dir });
const outBuf = new LineBuffer();
const errBuf = new LineBuffer();
outBuf.onLine(line => outputChannel.appendLine(expandFilePathInOutput(line, testconfig.dir)));
outBuf.onDone(last => last && outputChannel.appendLine(expandFilePathInOutput(last, testconfig.dir)));
errBuf.onLine(line => outputChannel.appendLine(line));
errBuf.onDone(last => last && outputChannel.appendLine(last));
proc.stdout.on('data', chunk => outBuf.append(chunk.toString()));
proc.stderr.on('data', chunk => errBuf.append(chunk.toString()));
proc.on('close', code => {
outBuf.done();
errBuf.done();
if (code) {
outputChannel.appendLine(`Error: ${testType} failed.`);
} else {
outputChannel.appendLine(`Success: ${testType} passed.`);
}
resolve(code === 0);
});
}, err => {
outputChannel.appendLine(`Error: ${testType} failed.`);
outputChannel.appendLine(err);
resolve(false);
});
});
}
/**
* Reveals the output channel in the UI.
*/
export function showTestOutput() {
outputChannel.show(true);
}
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(/^\s+(\S+_test.go):(\d+):/);
if (matches) {
lines[i] = lines[i].replace(matches[1], path.join(cwd, matches[1]));
}
}
return lines.join('\n');
}
/**
* Get the test target arguments.
*
* @param testconfig Configuration for the Go extension.
*/
function targetArgs(testconfig: TestConfig): Thenable<Array<string>> {
if (testconfig.functions) {
return Promise.resolve([testconfig.isBenchmark ? '-bench' : '-run', util.format('^%s$', testconfig.functions.join('|'))]);
} else if (testconfig.includeSubDirectories && !testconfig.isBenchmark) {
return getGoVersion().then((ver: SemVersion) => {
if (ver && (ver.major > 1 || (ver.major === 1 && ver.minor >= 9))) {
return ['./...'];
}
return getNonVendorPackages(testconfig.dir);
});
}
return Promise.resolve([]);
}