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 pathgoGenerateTests.ts
182 lines (166 loc) · 5.18 KB
/
goGenerateTests.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
/*---------------------------------------------------------
* 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 { getBinPath, getToolsEnvVars } from './util';
import { promptForMissingTool } from './goInstallTools';
import { GoDocumentSymbolProvider } from './goOutline';
const generatedWord = 'Generated ';
/**
* If current active editor has a Go file, returns the editor.
*/
function checkActiveEditor(): vscode.TextEditor {
let editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('Cannot generate unit tests. No editor selected.');
return;
}
if (!editor.document.fileName.endsWith('.go')) {
vscode.window.showInformationMessage('Cannot generate unit tests. File in the editor is not a Go file.');
return;
}
if (editor.document.isDirty) {
vscode.window.showInformationMessage('File has unsaved changes. Save and try again.');
return;
}
return editor;
}
/**
* Toggles between file in current active editor and the corresponding test file.
*/
export function toggleTestFile(): void {
let editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('Cannot toggle test file. No editor selected.');
return;
}
let currentFilePath = editor.document.fileName;
if (!currentFilePath.endsWith('.go')) {
vscode.window.showInformationMessage('Cannot toggle test file. File in the editor is not a Go file.');
return;
}
let targetFilePath = '';
if (currentFilePath.endsWith('_test.go')) {
targetFilePath = currentFilePath.substr(0, currentFilePath.lastIndexOf('_test.go')) + '.go';
} else {
targetFilePath = currentFilePath.substr(0, currentFilePath.lastIndexOf('.go')) + '_test.go';
}
for (let doc of vscode.window.visibleTextEditors) {
if (doc.document.fileName === targetFilePath) {
vscode.commands.executeCommand('vscode.open', vscode.Uri.file(targetFilePath), doc.viewColumn);
return;
}
}
vscode.commands.executeCommand('vscode.open', vscode.Uri.file(targetFilePath));
}
export function generateTestCurrentPackage(): Thenable<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
}
let dir = path.dirname(editor.document.uri.fsPath);
return generateTests({ dir: dir });
}
export function generateTestCurrentFile(): Thenable<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
}
let file = editor.document.uri.fsPath;
return generateTests({ dir: file });
}
export function generateTestCurrentFunction(): Thenable<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
}
let file = editor.document.uri.fsPath;
return getFunctions(editor.document).then(functions => {
let currentFunction: vscode.SymbolInformation;
for (let func of functions) {
let selection = editor.selection;
if (selection && func.location.range.contains(selection.start)) {
currentFunction = func;
break;
}
};
if (!currentFunction) {
vscode.window.showInformationMessage('No function found at cursor.');
return Promise.resolve(false);
}
let funcName = currentFunction.name;
if (funcName.includes('.')) {
funcName = funcName.split('.')[1];
}
return generateTests({ dir: file, func: funcName });
});
}
/**
* Input to goTests.
*/
interface Config {
/**
* The working directory for `gotests`.
*/
dir: string;
/**
* Specific function names to generate tests squeleton.
*/
func?: string;
}
function generateTests(conf: Config): Thenable<boolean> {
return new Promise<boolean>((resolve, reject) => {
let cmd = getBinPath('gotests');
let args;
if (conf.func) {
args = ['-w', '-only', `^${conf.func}$`, conf.dir];
} else {
args = ['-w', '-all', conf.dir];
}
cp.execFile(cmd, args, {env: getToolsEnvVars()}, (err, stdout, stderr) => {
try {
if (err && (<any>err).code === 'ENOENT') {
promptForMissingTool('gotests');
return resolve(false);
}
if (err) {
console.log(err);
return reject('Cannot generate test due to errors');
}
let message = stdout;
let testsGenerated = false;
// Expected stdout is of the format "Generated TestMain\nGenerated Testhello\n"
if (stdout.startsWith(generatedWord)) {
let lines = stdout.split('\n').filter(element => {
return element.startsWith(generatedWord);
}).map((element) => {
return element.substr(generatedWord.length);
});
message = `Generated ${lines.join(', ')}`;
testsGenerated = true;
}
vscode.window.showInformationMessage(message);
if (testsGenerated) {
toggleTestFile();
}
return resolve(true);
} catch (e) {
vscode.window.showInformationMessage(e.msg);
reject(e);
}
});
});
}
function getFunctions(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)
);
}