Skip to content
This repository has been archived by the owner on Jul 15, 2023. It is now read-only.

Commit

Permalink
Adding new 'gotests' flags option.
Browse files Browse the repository at this point in the history
gotests has many options not used for vscode by default. This allows
similar flags to other tools like lint and build where they are just
free formed flags.

The one difference here is some arguments have values needed but we are
not validating on any specific flags and go with flexibility.

The main use case here is the new 'template_dir' flag added to allow
users to define custom templates.
  • Loading branch information
jeffbean committed Aug 12, 2018
1 parent 9cc625e commit 189323a
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 24 deletions.
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,15 @@
"description": "Flags to pass to `go test`. If null, then buildFlags will be used.",
"scope": "resource"
},
"go.genTestsFlags": {
"type": "array",
"items": {
"type": "string"
},
"default": [],
"description": "Additional command line flags to pass to `gotests`.",
"scope": "resource"
},
"go.toolsEnvVars": {
"type": "object",
"default": {},
Expand Down
77 changes: 60 additions & 17 deletions src/goGenerateTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ import vscode = require('vscode');
import { getBinPath, getToolsEnvVars } from './util';
import { promptForMissingTool } from './goInstallTools';
import { GoDocumentSymbolProvider } from './goOutline';
import { outputChannel } from './goStatus';

const generatedWord = 'Generated ';
export const FUNCTION_TYPE = "function";
export const FILE_TYPE = "file";
export const PACKAGE_TYPE = "package";

/**
* If current active editor has a Go file, returns the editor.
Expand Down Expand Up @@ -64,30 +68,54 @@ export function toggleTestFile(): void {
vscode.commands.executeCommand('vscode.open', vscode.Uri.file(targetFilePath));
}

export function generateTestCurrentPackage(): Thenable<boolean> {
function getGoConfigObject(editor: vscode.TextEditor): vscode.WorkspaceConfiguration {
let documentUri = editor ? editor.document.uri : null;
return vscode.workspace.getConfiguration('go', documentUri);
}

/**
*
* @param type The type of tests to generate. In this case a simple string to indicate what
* type of tests we need to create, function, file, or package
*/
export function GenerateTests(type: string): Thenable<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
}

let goConfig = getGoConfigObject(editor);

switch (type) {
case PACKAGE_TYPE:
return generateTestCurrentPackage(editor, goConfig);
case FILE_TYPE:
return generateTestCurrentFile(editor, goConfig);
case FUNCTION_TYPE:
return generateTestCurrentFunction(editor, goConfig);
default:
vscode.window.showErrorMessage('unknown type passed to generate tests: ' + type);
return Promise.resolve(false);
}
}

function generateTestCurrentPackage(editor: vscode.TextEditor, goConfig: vscode.WorkspaceConfiguration): Thenable<boolean> {
let dir = path.dirname(editor.document.uri.fsPath);
return generateTests({ dir: dir });
const goGenerateTestsFlags: string[] = goConfig['genTestsFlags'] || [];
return generateTests({ dir: dir, genFlags: goGenerateTestsFlags });
}

export function generateTestCurrentFile(): Thenable<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
}
function generateTestCurrentFile(editor: vscode.TextEditor, goConfig: vscode.WorkspaceConfiguration): Thenable<boolean> {
let file = editor.document.uri.fsPath;
return generateTests({ dir: file });
const goGenerateTestsFlags: string[] = goConfig['genTestsFlags'] || [];
return generateTests({ dir: file, genFlags: goGenerateTestsFlags });
}

export function generateTestCurrentFunction(): Thenable<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
}
function generateTestCurrentFunction(editor: vscode.TextEditor,goConfig: vscode.WorkspaceConfiguration): Thenable<boolean> {
let file = editor.document.uri.fsPath;

const goGenerateTestsFlags: string[] = goConfig['genTestsFlags'] || [];

return getFunctions(editor.document).then(functions => {
let currentFunction: vscode.SymbolInformation;
for (let func of functions) {
Expand All @@ -105,7 +133,7 @@ export function generateTestCurrentFunction(): Thenable<boolean> {
if (funcName.includes('.')) {
funcName = funcName.split('.')[1];
}
return generateTests({ dir: file, func: funcName });
return generateTests({ dir: file, func: funcName , genFlags: goGenerateTestsFlags });
});
}

Expand All @@ -117,6 +145,10 @@ interface Config {
* The working directory for `gotests`.
*/
dir: string;
/**
* Optional Template dir for any custom templates for `gotests`.
*/
genFlags: string[];
/**
* Specific function names to generate tests squeleton.
*/
Expand All @@ -126,20 +158,29 @@ interface Config {
function generateTests(conf: Config): Thenable<boolean> {
return new Promise<boolean>((resolve, reject) => {
let cmd = getBinPath('gotests');
let args;
let args = ['-w'];

conf.genFlags.forEach(flag => {
args.push(flag);
});

if (conf.func) {
args = ['-w', '-only', `^${conf.func}$`, conf.dir];
args = args.concat(['-only', `^${conf.func}$`, conf.dir]);
} else {
args = ['-w', '-all', conf.dir];
args = args.concat(['-all', conf.dir]);
}
console.log()
cp.execFile(cmd, args, {env: getToolsEnvVars()}, (err, stdout, stderr) => {
outputChannel.appendLine("Generating Tests: " + cmd + ' ' + args.join(' '));

try {
if (err && (<any>err).code === 'ENOENT') {
promptForMissingTool('gotests');
return resolve(false);
}
if (err) {
console.log(err);
outputChannel.appendLine(err.message);
return reject('Cannot generate test due to errors');
}

Expand All @@ -158,13 +199,15 @@ function generateTests(conf: Config): Thenable<boolean> {
}

vscode.window.showInformationMessage(message);
outputChannel.append(message);
if (testsGenerated) {
toggleTestFile();
}

return resolve(true);
} catch (e) {
vscode.window.showInformationMessage(e.msg);
outputChannel.append(e.msg);
reject(e);
}
});
Expand Down
8 changes: 5 additions & 3 deletions src/goMain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,15 +329,15 @@ export function activate(ctx: vscode.ExtensionContext): void {
}));

ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.package', () => {
goGenerateTests.generateTestCurrentPackage();
goGenerateTests.GenerateTests(goGenerateTests.PACKAGE_TYPE);
}));

ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.file', () => {
goGenerateTests.generateTestCurrentFile();
goGenerateTests.GenerateTests(goGenerateTests.FILE_TYPE);
}));

ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.function', () => {
goGenerateTests.generateTestCurrentFunction();
goGenerateTests.GenerateTests(goGenerateTests.FUNCTION_TYPE);
}));

ctx.subscriptions.push(vscode.commands.registerCommand('go.toggle.test.file', () => {
Expand Down Expand Up @@ -424,6 +424,7 @@ function sendTelemetryEventForConfig(goConfig: vscode.WorkspaceConfiguration) {
"buildTags": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"formatTool": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"formatFlags": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"genTestsFlags": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"lintOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"lintFlags": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"lintTool": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
Expand Down Expand Up @@ -465,6 +466,7 @@ function sendTelemetryEventForConfig(goConfig: vscode.WorkspaceConfiguration) {
lintOnSave: goConfig['lintOnSave'] + '',
lintFlags: goConfig['lintFlags'],
lintTool: goConfig['lintTool'],
genTestsFlags: goConfig['genTestsFlags'],
vetOnSave: goConfig['vetOnSave'] + '',
vetFlags: goConfig['vetFlags'],
testOnSave: goConfig['testOnSave'] + '',
Expand Down
8 changes: 4 additions & 4 deletions test/go.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { testCurrentFile } from '../src/goTest';
import { getBinPath, getGoVersion, isVendorSupported } from '../src/util';
import { documentSymbols } from '../src/goOutline';
import { listPackages, getTextEditForAddImport } from '../src/goImport';
import { generateTestCurrentFile, generateTestCurrentPackage, generateTestCurrentFunction } from '../src/goGenerateTests';
import { GenerateTests, FUNCTION_TYPE, PACKAGE_TYPE, FILE_TYPE } from '../src/goGenerateTests';
import { getAllPackages } from '../src/goPackages';
import { getImportPath } from '../src/util';
import { goPlay } from '../src/goPlayground';
Expand Down Expand Up @@ -302,7 +302,7 @@ It returns the number of bytes written and any write error encountered.
let uri = vscode.Uri.file(path.join(generateTestsSourcePath, 'generatetests.go'));
return vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return generateTestCurrentFile().then((result: boolean) => {
return GenerateTests(FILE_TYPE).then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
Expand Down Expand Up @@ -331,7 +331,7 @@ It returns the number of bytes written and any write error encountered.
assert(vscode.window.activeTextEditor, 'No active editor');
let selection = new vscode.Selection(5, 0, 6, 0);
editor.selection = selection;
return generateTestCurrentFunction().then((result: boolean) => {
return GenerateTests(FUNCTION_TYPE).then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
Expand All @@ -357,7 +357,7 @@ It returns the number of bytes written and any write error encountered.
let uri = vscode.Uri.file(path.join(generatePackageTestSourcePath, 'generatetests.go'));
return vscode.workspace.openTextDocument(uri).then(document => {
return vscode.window.showTextDocument(document).then(editor => {
return generateTestCurrentPackage().then((result: boolean) => {
return GenerateTests(PACKAGE_TYPE).then((result: boolean) => {
assert.equal(result, true);
return Promise.resolve();
});
Expand Down

0 comments on commit 189323a

Please sign in to comment.