And add tests!

Fixes #188.
This commit is contained in:
Luke Hoban 2016-02-01 14:03:22 -08:00
Родитель 49e30208c3
Коммит 102e5590a3
5 изменённых файлов: 57 добавлений и 25 удалений

Просмотреть файл

@ -19,7 +19,7 @@ export interface ICheckResult {
severity: string;
}
function runTool(cmd: string, args: string[], cwd: string, severity: string, notFoundError: string) {
function runTool(cmd: string, args: string[], cwd: string, severity: string, useStdErr: boolean, notFoundError: string) {
return new Promise((resolve, reject) => {
cp.execFile(cmd, args, { cwd: cwd }, (err, stdout, stderr) => {
try {
@ -27,16 +27,16 @@ function runTool(cmd: string, args: string[], cwd: string, severity: string, not
vscode.window.showInformationMessage(notFoundError);
return resolve([]);
}
var lines = stderr.toString().split('\n');
var lines = (useStdErr ? stderr : stdout).toString().split('\n');
var ret: ICheckResult[] = [];
for (var i = 0; i < lines.length; i++) {
if (lines[i][0] == '\t' && ret.length > 0) {
ret[ret.length - 1].msg += "\n" + lines[i];
continue;
}
var match = /^([^:]*: )?([^:]*):(\d+)(:\d+)?: (.*)$/.exec(lines[i]);
var match = /^([^:]*: )?((.:)?[^:]*):(\d+)(:(\d+))?: (.*)$/.exec(lines[i]);
if (!match) continue;
var [_, _, file, lineStr, charStr, msg] = match;
var [_, _, file, _, lineStr, _, charStr, msg] = match;
var line = +lineStr;
ret.push({ file: path.resolve(cwd, file), line, msg, severity });
}
@ -64,6 +64,7 @@ export function check(filename: string, goConfig: vscode.WorkspaceConfiguration)
args,
cwd,
'error',
true,
"No 'go' binary could be found in GOROOT: '" + process.env["GOROOT"] + "'"
));
}
@ -75,6 +76,7 @@ export function check(filename: string, goConfig: vscode.WorkspaceConfiguration)
[...lintFlags, filename],
cwd,
'warning',
false,
"The 'golint' command is not available. Use 'go get -u github.com/golang/lint/golint' to install."
));
}
@ -86,6 +88,7 @@ export function check(filename: string, goConfig: vscode.WorkspaceConfiguration)
["tool", "vet", ...vetFlags, filename],
cwd,
'warning',
true,
"No 'go' binary could be found in GOROOT: '" + process.env["GOROOT"] + "'"
));
}

Просмотреть файл

@ -69,10 +69,10 @@ function correctBinname(binname: string) {
export function getGoRuntimePath(): string {
if (runtimePathCache) return runtimePathCache;
if (process.env["GOROOT"]) {
runtimePathCache = path.join(process.env["GOROOT"], "bin", "go");
} else if (process.env.PATH) {
runtimePathCache = path.join(process.env["GOROOT"], "bin", correctBinname("go"));
} else if (process.env["PATH"]) {
var pathparts = (<string>process.env.PATH).split((<any>path).delimiter);
runtimePathCache = pathparts.map(dir => path.join(dir, 'go' + (os.platform() == "win32" ? ".exe" : ""))).filter(candidate => fs.existsSync(candidate))[0];
runtimePathCache = pathparts.map(dir => path.join(dir, correctBinname("go"))).filter(candidate => fs.existsSync(candidate))[0];
}
return runtimePathCache;
}

11
test/fixtures/errors.go поставляемый Normal file
Просмотреть файл

@ -0,0 +1,11 @@
package main
import (
"fmt"
)
func Print2(txt string) {
fmt.Printf("", txt)
}
func main2() {
prin("Hello")
}

11
test/fixtures/test.go поставляемый Normal file
Просмотреть файл

@ -0,0 +1,11 @@
package main
import (
"fmt"
)
func print(txt string) {
fmt.Println(txt)
}
func main() {
print("Hello")
}

Просмотреть файл

@ -10,31 +10,20 @@ import * as vscode from 'vscode';
import { GoHoverProvider } from '../src/goExtraInfo';
import { GoCompletionItemProvider } from '../src/goSuggest';
import { GoSignatureHelpProvider } from '../src/goSignature';
var fixtureSrc =
`package main
import (
"fmt"
)
func print(txt string) {
fmt.Println(txt)
}
func main() {
print("Hello")
}`;
import { check } from '../src/goCheck'
suite("Go Extension Tests", () => {
let gopath = process.env['GOPATH'];
let repoPath = path.join(gopath, 'src', '___testrepo');
let fixturePath = path.join(repoPath, 'test', 'testfixture');
let fixture = path.join(fixturePath, "test.go");
let fixtureSourcePath = path.join(__dirname, "..", "..", "test", "fixtures");
suiteSetup(() => {
assert.ok(gopath !== null, "GOPATH is not defined");
fs.removeSync(repoPath);
fs.mkdirsSync(fixturePath);
fs.writeFileSync(fixture, fixtureSrc);
fs.copySync(path.join(fixtureSourcePath, "test.go"), path.join(fixturePath, "test.go"))
fs.copySync(path.join(fixtureSourcePath, "errors.go"), path.join(fixturePath, "errors.go"))
});
suiteTeardown(() => {
@ -50,7 +39,7 @@ suite("Go Extension Tests", () => {
[new vscode.Position(6, 6), 'Println func(a ...interface{}) (n int, err error)'],
[new vscode.Position(9, 3), 'print func(txt string)']
];
let uri = vscode.Uri.file(fixture);
let uri = vscode.Uri.file(path.join(fixturePath, "test.go"));
vscode.workspace.openTextDocument(uri).then((textDocument) => {
let promises = testCases.map(([position, expected]) =>
provider.provideHover(textDocument, position, null).then(res => {
@ -72,7 +61,7 @@ suite("Go Extension Tests", () => {
[new vscode.Position(6, 4), ['fmt']],
[new vscode.Position(7, 0), ['main', 'print', 'fmt', 'txt']]
];
let uri = vscode.Uri.file(fixture);
let uri = vscode.Uri.file(path.join(fixturePath, "test.go"));
vscode.workspace.openTextDocument(uri).then((textDocument) => {
let promises = testCases.map(([position, expected]) =>
provider.provideCompletionItems(textDocument, position, null).then(items => {
@ -96,7 +85,7 @@ suite("Go Extension Tests", () => {
[new vscode.Position(6, 13), "Println(a ...interface{}) (n int, err error)"],
[new vscode.Position(9, 7), "print(txt string)"]
];
let uri = vscode.Uri.file(fixture);
let uri = vscode.Uri.file(path.join(fixturePath, "test.go"));
vscode.workspace.openTextDocument(uri).then((textDocument) => {
let promises = testCases.map(([position, expected]) =>
provider.provideSignatureHelp(textDocument, position, null).then(sigHelp => {
@ -109,4 +98,22 @@ suite("Go Extension Tests", () => {
assert.ok(false, `error in OpenTextDocument ${err}`);
}).then(() => done(), done);
});
test("Error checking", (done) => {
var config = vscode.workspace.getConfiguration('go');
var expected = [
{ line: 6, severity: "warning", msg: "exported function Print2 should have comment or be unexported" },
{ line: 7, severity: "warning", msg: "no formatting directive in Printf call" },
{ line: 10, severity: "error", msg: "undefined: prin" },
]
check(path.join(fixturePath, "errors.go"), config).then(diagnostics => {
let sortedDiagnostics = diagnostics.sort((a, b) => a.line - b.line);
assert.equal(sortedDiagnostics.length, expected.length, `wrong number of diagnostics`);
for (let i in expected) {
assert.equal(sortedDiagnostics[i].line, expected[i].line)
assert.equal(sortedDiagnostics[i].severity, expected[i].severity)
assert.equal(sortedDiagnostics[i].msg, expected[i].msg)
}
}).then(() => done(), done);
})
});