Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display test results in CodeLens #24

Merged
merged 13 commits into from
Nov 26, 2017
23 changes: 22 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,26 @@
"type": "boolean",
"default": true,
"description": "If true, dotnet restore will run when refreshing the test explorer."
},
"dotnet-test-explorer.showCodeLens": {
"type": "boolean",
"default": true,
"description": "Determines whether to show the CodeLens test status or not."
},
"dotnet-test-explorer.codeLensFailed": {
"type": "string",
"default": "",
"description": "The text to display in the code lens when a test has failed."
},
"dotnet-test-explorer.codeLensPassed": {
"type": "string",
"default": "",
"description": "The text to display in the code lens when a test has passed."
},
"dotnet-test-explorer.codeLensSkipped": {
"type": "string",
"default": "",
"description": "The text to display in the code lens when a test has been skipped."
}
}
}
Expand All @@ -131,6 +151,7 @@
"vscode": "^1.0.0"
},
"dependencies": {
"applicationinsights": "^0.21.0"
"applicationinsights": "^0.21.0",
"xmldom": "^0.1.27"
}
}
31 changes: 26 additions & 5 deletions src/dotnetTestExplorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { TreeDataProvider, TreeItem, TreeItemCollapsibleState } from "vscode";
import { AppInsightsClient } from "./appInsightsClient";
import { Executor } from "./executor";
import { TestNode } from "./testNode";
import { TestResultsFile } from "./testResultsFile";
import { Utility } from "./utility";

export class DotnetTestExplorer implements TreeDataProvider<TestNode> {
Expand All @@ -16,7 +17,7 @@ export class DotnetTestExplorer implements TreeDataProvider<TestNode> {
*/
private testDirectoryPath: string;

constructor(private context: vscode.ExtensionContext) {}
constructor(private context: vscode.ExtensionContext, private resultsFile: TestResultsFile) { }

/**
* @description
Expand All @@ -41,7 +42,7 @@ export class DotnetTestExplorer implements TreeDataProvider<TestNode> {
*/
public runAllTests(): void {
this.evaluateTestDirectory();
Executor.runInTerminal(`dotnet test${this.checkBuildOption()}${this.checkRestoreOption()}`, this.testDirectoryPath);
Executor.runInTerminal(`dotnet test${this.getDotNetTestOptions()}${this.outputTestResults()}`, this.testDirectoryPath);
AppInsightsClient.sendEvent("runAllTests");
}

Expand All @@ -53,7 +54,7 @@ export class DotnetTestExplorer implements TreeDataProvider<TestNode> {
* to do a restore, so it can be very slow.
*/
public runTest(test: TestNode): void {
Executor.runInTerminal(`dotnet test${this.checkBuildOption()}${this.checkRestoreOption()} --filter FullyQualifiedName~${test.fullName}`, this.testDirectoryPath);
Executor.runInTerminal(`dotnet test${this.getDotNetTestOptions()}${this.outputTestResults()} --filter FullyQualifiedName~${test.fullName}`, this.testDirectoryPath);
AppInsightsClient.sendEvent("runTest");
}

Expand Down Expand Up @@ -175,6 +176,26 @@ export class DotnetTestExplorer implements TreeDataProvider<TestNode> {
return option ? "" : " --no-restore";
}

/**
* @description
* Gets the options for build/restore before running tests.
*/
private getDotNetTestOptions(): string {
return this.checkBuildOption() + this.checkRestoreOption();
}

/**
* @description
* Gets the dotnet test argument to speicfy the output for the test results.
*/
private outputTestResults(): string {
if (Utility.codeLensEnabled) {
return " --logger \"trx;LogFileName=" + this.resultsFile.fileName + "\"";
} else {
return "";
}
}

/**
* @description
* Checks to see if the options specify a directory to run the
Expand All @@ -198,7 +219,7 @@ export class DotnetTestExplorer implements TreeDataProvider<TestNode> {
return new Promise((c, e) => {
try {
const results = Executor
.execSync(`dotnet test -t -v=q${this.checkBuildOption()}${this.checkRestoreOption()}`, this.testDirectoryPath)
.execSync(`dotnet test -t -v=q${this.getDotNetTestOptions()}`, this.testDirectoryPath)
Copy link
Owner

Choose a reason for hiding this comment

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

You did not add ${this.outputTestResults()}, so the test result will not be shown when VS Code starts. Is it by design?

Copy link
Owner

Choose a reason for hiding this comment

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

Oh, please ignore. It only lists the tests.

.split(/[\r\n]+/g)
/*
* The dotnet-cli prefixes all discovered unit tests
Expand All @@ -207,7 +228,7 @@ export class DotnetTestExplorer implements TreeDataProvider<TestNode> {
* structures.
**/
.filter((item) => item && item.startsWith(" "))
.sort((a, b) => a > b ? 1 : b > a ? - 1 : 0 )
.sort((a, b) => a > b ? 1 : b > a ? - 1 : 0)
.map((item) => item.trim());

c(results);
Expand Down
19 changes: 18 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,29 @@ import { AppInsightsClient } from "./appInsightsClient";
import { DotnetTestExplorer } from "./dotnetTestExplorer";
import { Executor } from "./executor";
import { TestNode } from "./testNode";
import { TestResultsFile } from "./testResultsFile";
import { TestStatusCodeLensProvider } from "./testStatusCodeLensProvider";
import { Utility } from "./utility";

export function activate(context: vscode.ExtensionContext) {
const dotnetTestExplorer = new DotnetTestExplorer(context);
const testResults = new TestResultsFile();
context.subscriptions.push(testResults);

Utility.updateCache();
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(() => {
Utility.updateCache();
}));

const dotnetTestExplorer = new DotnetTestExplorer(context, testResults);
vscode.window.registerTreeDataProvider("dotnetTestExplorer", dotnetTestExplorer);
AppInsightsClient.sendEvent("loadExtension");

const codeLensProvider = new TestStatusCodeLensProvider(testResults);
context.subscriptions.push(codeLensProvider);
context.subscriptions.push(vscode.languages.registerCodeLensProvider(
{ language: "csharp", scheme: "file" },
codeLensProvider));

context.subscriptions.push(vscode.commands.registerCommand("dotnet-test-explorer.refreshTestExplorer", () => {
dotnetTestExplorer.refreshTestExplorer();
}));
Expand Down
37 changes: 37 additions & 0 deletions src/testResult.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
export class TestResult {
private className: string;
private method: string;

public constructor(private _testId: string, private _outcome: string) {
}

public get fullName(): string {
return this.className + "." + this.method;
}

public get id(): string {
return this._testId;
}

public get outcome(): string {
return this._outcome;
}

public matches(className: string, method: string): boolean {
// The passed in class name won't have the namespace, hence the
// check with endsWith
return (this.method === method) && this.className.endsWith(className);
}

public updateName(className: string, method: string): void {
this.className = className;

// xUnit includes the class name in the name of the unit test
// i.e. classname.method
if (method.startsWith(className)) {
this.method = method.substring(className.length + 1); // +1 to include the .
} else {
this.method = method;
}
}
}
134 changes: 134 additions & 0 deletions src/testResultsFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"use strict";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { setTimeout } from "timers";
import { Disposable, Event, EventEmitter } from "vscode";
import { DOMParser, Element, Node } from "xmldom";
import { TestResult } from "./testResult";

function findChildElement(node: Node, name: string): Node {
let child = node.firstChild;
while (child) {
if (child.nodeName === name) {
return child;
}

child = child.nextSibling;
}

return null;
}

function getAttributeValue(node: Node, name: string): string {
const attribute = node.attributes.getNamedItem(name);
return (attribute === null) ? null : attribute.nodeValue;
}

function parseUnitTestResults(xml: Element): TestResult[] {
const results: TestResult[] = [];
const nodes = xml.getElementsByTagName("UnitTestResult");

// TSLint wants to use for-of here, but nodes doesn't support it
for (let i = 0; i < nodes.length; i++) { // tslint:disable-line
results.push(new TestResult(
getAttributeValue(nodes[i], "testId"),
getAttributeValue(nodes[i], "outcome"),
));
}

return results;
}

function updateUnitTestDefinitions(xml: Element, results: TestResult[]): void {
const nodes = xml.getElementsByTagName("UnitTest");
const names = new Map<string, any>();

for (let i = 0; i < nodes.length; i++) { // tslint:disable-line
const id = getAttributeValue(nodes[i], "id");
const testMethod = findChildElement(nodes[i], "TestMethod");
if (testMethod) {
names.set(id, {
className: getAttributeValue(testMethod, "className"),
method: getAttributeValue(testMethod, "name"),
});
}
}

for (const result of results) {
const name = names.get(result.id);
if (name) {
result.updateName(name.className, name.method);
}
}
}

export class TestResultsFile implements Disposable {
private static readonly ResultsFileName = "Results.trx";
private onNewResultsEmitter = new EventEmitter<TestResult[]>();
private resultsFile: string;
private watcher: fs.FSWatcher;

public dispose(): void {
try {
if (this.watcher) {
this.watcher.close();
}

if (this.resultsFile) {
// When we ask for a random directory it creates one for us,
// however, we can't delete it if there's a file inside of it
if (fs.existsSync(this.resultsFile)) {
fs.unlinkSync(this.resultsFile);
}

fs.rmdir(path.dirname(this.resultsFile));
}
} catch (error) {
}
}

public get fileName(): string {
this.ensureTemproaryPathExists();
return this.resultsFile;
}

public get onNewResults(): Event<TestResult[]> {
return this.onNewResultsEmitter.event;
}

private ensureTemproaryPathExists(): void {
if (!this.resultsFile) {
const tempFolder = fs.mkdtempSync(path.join(os.tmpdir(), "test-explorer-"));
this.resultsFile = path.join(tempFolder, TestResultsFile.ResultsFileName);
this.watchFolder(tempFolder);
}
}

private parseResults(): void {
const emitter = this.onNewResultsEmitter;
fs.readFile(this.resultsFile, (err, data) => {
if (!err) {
const xdoc = new DOMParser().parseFromString(data.toString(), "application/xml");
const results = parseUnitTestResults(xdoc.documentElement);
updateUnitTestDefinitions(xdoc.documentElement, results);
emitter.fire(results);
}
});
}

private watchFolder(folder: string): void {
// The change event gets called multiple times, so use a one-second
// delay before we read anything to avoid doing too much work
const me = this;
let changeDelay: NodeJS.Timer;
this.watcher = fs.watch(folder, (eventType, fileName) => {
if (fileName === TestResultsFile.ResultsFileName) {
clearTimeout(changeDelay);
changeDelay = setTimeout(() => {
me.parseResults();
}, 1000);
}
});
}
}
26 changes: 26 additions & 0 deletions src/testStatusCodeLens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"use strict";
import { CodeLens, Range } from "vscode";
import { Utility } from "./utility";

export class TestStatusCodeLens extends CodeLens {
public static parseOutcome(outcome: string): string {
if (outcome === "Passed") {
return Utility.codeLensPassed;
} else if (outcome === "Failed") {
return Utility.codeLensFailed;
} else if (outcome === "NotExecuted") {
return Utility.codeLensSkipped;
} else {
return null;
}
}

public constructor(range: Range, status: string) {
super(range);

this.command = {
title: status,
command: null,
};
}
}
Loading