Skip to content
This repository was archived by the owner on Jul 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,11 @@
"type": "string",
"default": "",
"description": "The Go build tags to use for all commands that support a `-tags '...'` argument"
},
"go.testEnvVars": {
"type": "object",
"default": {},
"description": "Environment variables that will passed to the process that runs the Go tests"
}
}
}
Expand Down
22 changes: 13 additions & 9 deletions src/goTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ interface TestConfig {
/**
* Executes the unit test at the primary cursor using `go test`. Output
* is sent to the 'Go' channel.
*
*
* @param timeout a ParseDuration formatted timeout string for the tests.
*
* TODO: go test returns filenames with no path information for failures,
Expand Down Expand Up @@ -94,19 +94,19 @@ export function testCurrentPackage(timeout: string) {
*
* @param timeout a ParseDuration formatted timeout string for the tests.
*/
export function testCurrentFile(timeout: string) {
export function testCurrentFile(timeout: string, goConfig?: vscode.WorkspaceConfiguration): Thenable<boolean> {
let editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showInformationMessage('No editor is active.');
return;
}
getTestFunctions(editor.document).then(testFunctions => {
return getTestFunctions(editor.document).then(testFunctions => {
return goTest({
timeout: timeout,
dir: path.dirname(editor.document.fileName),
functions: testFunctions.map(func => { return func.name; })
});
}).then(null, err => {
}, goConfig);
}, err => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly minor - but this change will mean that any exceptions thrown during execution of goTest are not handled and reported to console.error. A weirdness of .then on promises. Possibly just leave the additional .then call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put the console.error(err) to back where it was and returned promise from there

console.error(err);
});
}
Expand All @@ -116,19 +116,23 @@ export function testCurrentFile(timeout: string) {
*
* @param config the test execution configuration.
*/
function goTest(config: TestConfig): Thenable<boolean> {
function goTest(config: TestConfig, goConfig?: vscode.WorkspaceConfiguration): Thenable<boolean> {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason not to make this required and fix up callers?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

None at all. Made the update to pass goConfig from goMain.ts

return new Promise<boolean>((resolve, reject) => {
outputChannel.clear();
outputChannel.show(2);
let buildFlags: string[] = vscode.workspace.getConfiguration('go')['buildFlags'];
let buildTags: string = vscode.workspace.getConfiguration('go')['buildTags'];
if (!goConfig) {
goConfig = vscode.workspace.getConfiguration('go');
}
let buildFlags: string[] = goConfig['buildFlags'];
let buildTags: string = goConfig['buildTags'];
let args = ['test', '-v', '-timeout', config.timeout, '-tags', buildTags, ...buildFlags];
let testEnvVars = Object.assign({}, goConfig['testEnvVars'], process.env);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't the order need to be changed to ensure that the testEnvVars overrride the process environment settings?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, nice catch. Corrected


if (config.functions) {
args.push('-run');
args.push(util.format('^%s$', config.functions.join('|')));
}
let proc = cp.spawn(getGoRuntimePath(), args, { env: process.env, cwd: config.dir });
let proc = cp.spawn(getGoRuntimePath(), args, { env: testEnvVars, cwd: config.dir });
proc.stdout.on('data', chunk => outputChannel.append(chunk.toString()));
proc.stderr.on('data', chunk => outputChannel.append(chunk.toString()));
proc.on('close', code => {
Expand Down
18 changes: 18 additions & 0 deletions test/fixtures/sample_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

import (
"fmt"
"os"
"testing"
)

func hello() {
fmt.Println("Hello")
}

// TestMe
func TestMe(t *testing.T) {
if os.Getenv("dummyEnvVar") != "dummyEnvValue" {
t.Errorf("Oops! Value for the variable is %q", os.Getenv("dummyEnvVar"))
}
}
25 changes: 22 additions & 3 deletions test/go.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { GoHoverProvider } from '../src/goExtraInfo';
import { GoCompletionItemProvider } from '../src/goSuggest';
import { GoSignatureHelpProvider } from '../src/goSignature';
import { check } from '../src/goCheck';
import { testCurrentFile } from '../src/goTest';

suite('Go Extension Tests', () => {
let gopath = process.env['GOPATH'];
Expand All @@ -23,7 +24,8 @@ suite('Go Extension Tests', () => {
fs.removeSync(repoPath);
fs.mkdirsSync(fixturePath);
fs.copySync(path.join(fixtureSourcePath, 'test.go'), path.join(fixturePath, 'test.go'));
fs.copySync(path.join(fixtureSourcePath, 'errors.go'), path.join(fixturePath, 'errors.go'));
fs.copySync(path.join(fixtureSourcePath, 'errorsTest', 'errors.go'), path.join(fixturePath, 'errorsTest', 'errors.go'));
fs.copySync(path.join(fixtureSourcePath, 'sample_test.go'), path.join(fixturePath, 'sample_test.go'));
});

suiteTeardown(() => {
Expand Down Expand Up @@ -117,7 +119,7 @@ encountered.
// { line: 7, severity: 'warning', msg: 'no formatting directive in Printf call' },
{ line: 11, severity: 'error', msg: 'undefined: prin' },
];
check(path.join(fixturePath, 'errors.go'), config).then(diagnostics => {
check(path.join(fixturePath, 'errorsTest', 'errors.go'), config).then(diagnostics => {
let sortedDiagnostics = diagnostics.sort((a, b) => a.line - b.line);
for (let i in expected) {
assert.equal(sortedDiagnostics[i].line, expected[i].line);
Expand Down Expand Up @@ -145,7 +147,7 @@ encountered.
{ line: 11, severity: 'warning', msg: 'unused global variable undeclared name: prin (varcheck)' },
{ line: 11, severity: 'warning', msg: 'unused struct field undeclared name: prin (structcheck)' },
];
check(path.join(fixturePath, 'errors.go'), config).then(diagnostics => {
check(path.join(fixturePath, 'errorsTest', 'errors.go'), config).then(diagnostics => {
let sortedDiagnostics = diagnostics.sort((a, b) => {
if ( a.msg < b.msg )
return -1;
Expand All @@ -161,4 +163,21 @@ encountered.
assert.equal(sortedDiagnostics.length, expected.length, `too many errors ${JSON.stringify(sortedDiagnostics)}`);
}).then(() => done(), done);
});

test('Test Env Variables are passed to Tests', (done) => {
let config = Object.create(vscode.workspace.getConfiguration('go'), {
'testEnvVars': { value: { 'dummyEnvVar': 'dummyEnvValue'} }
});

let uri = vscode.Uri.file(path.join(fixturePath, 'sample_test.go'));
vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return testCurrentFile('30s', config).then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
});
}).then(() => done(), done);
});

});