Skip to content

Discover tests via LSP if available #767

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

Merged
merged 9 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
81 changes: 81 additions & 0 deletions src/TestExplorer/DocumentSymbolTestDiscovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VSCode Swift open source project
//
// Copyright (c) 2021-2024 the VSCode Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VSCode Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import * as vscode from "vscode";
import { TestClass } from "./TestDiscovery";
import { parseTestsFromSwiftTestListOutput } from "./SPMTestDiscovery";

export function parseTestsFromDocumentSymbols(
target: string,
symbols: vscode.DocumentSymbol[],
uri: vscode.Uri
): TestClass[] {
// Converts a document into the output of `swift test list`.
// This _only_ looks for XCTests.
const locationLookup = new Map<string, vscode.Location | undefined>();
const swiftTestListOutput = symbols
.filter(
symbol =>
symbol.kind === vscode.SymbolKind.Class ||
symbol.kind === vscode.SymbolKind.Namespace
)
.flatMap(symbol => {
const functions = symbol.children
.filter(func => func.kind === vscode.SymbolKind.Method)
.filter(func => func.name.match(/^test.*\(\)/))
.map(func => {
const openBrackets = func.name.indexOf("(");
let funcName = func.name;
if (openBrackets) {
funcName = func.name.slice(0, openBrackets);
}
return {
name: funcName,
location: new vscode.Location(uri, func.range),
};
});

const location =
symbol.kind === vscode.SymbolKind.Class
? new vscode.Location(uri, symbol.range)
: undefined;

locationLookup.set(`${target}.${symbol.name}`, location);

return functions.map(func => {
const testName = `${target}.${symbol.name}/${func.name}`;
locationLookup.set(testName, func.location);
return testName;
});
})
.join("\n");

const tests = parseTestsFromSwiftTestListOutput(swiftTestListOutput);

// The locations for each test case/suite were captured when processing the
// symbols. Annotate the processed TestClasses with their locations.
const annotatedTests = annotateTestsWithLocations(tests, locationLookup);
return annotatedTests;
}

function annotateTestsWithLocations(
tests: TestClass[],
locations: Map<string, vscode.Location | undefined>
): TestClass[] {
return tests.map(test => ({
...test,
location: locations.get(test.id),
children: annotateTestsWithLocations(test.children, locations),
}));
}
204 changes: 111 additions & 93 deletions src/TestExplorer/LSPTestDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the VSCode Swift open source project
//
// Copyright (c) 2021 the VSCode Swift project authors
// Copyright (c) 2021-2024 the VSCode Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
Expand All @@ -13,11 +13,15 @@
//===----------------------------------------------------------------------===//

import * as vscode from "vscode";
import * as langclient from "vscode-languageclient/node";
import * as TestDiscovery from "./TestDiscovery";
import { workspaceTestsRequest } from "../sourcekit-lsp/lspExtensions";
import { isPathInsidePath } from "../utilities/utilities";
import {
LSPTestItem,
textDocumentTestsRequest,
workspaceTestsRequest,
} from "../sourcekit-lsp/lspExtensions";
import { LanguageClientManager } from "../sourcekit-lsp/LanguageClientManager";
import { LanguageClient } from "vscode-languageclient/node";
import { SwiftPackage, TargetType } from "../SwiftPackage";

/**
* Used to augment test discovery via `swift test --list-tests`.
Expand All @@ -28,105 +32,119 @@ import { LanguageClientManager } from "../sourcekit-lsp/LanguageClientManager";
* these results.
*/
export class LSPTestDiscovery {
private capCache = new Map<string, boolean>();

constructor(private languageClient: LanguageClientManager) {}

/**
* Used to augment test discovery via `swift test --list-tests`.
*
* Parses result of any document symbol request to add/remove tests from
* the current file.
* Return a list of tests in the supplied document.
* @param document A document to query
*/
getTests(symbols: vscode.DocumentSymbol[], uri: vscode.Uri): TestDiscovery.TestClass[] {
return symbols
.filter(
symbol =>
symbol.kind === vscode.SymbolKind.Class ||
symbol.kind === vscode.SymbolKind.Namespace
)
.map(symbol => {
const functions = symbol.children
.filter(func => func.kind === vscode.SymbolKind.Method)
.filter(func => func.name.match(/^test.*\(\)/))
.map(func => {
const openBrackets = func.name.indexOf("(");
let funcName = func.name;
if (openBrackets) {
funcName = func.name.slice(0, openBrackets);
}
return {
name: funcName,
location: new vscode.Location(uri, func.range),
};
});
const location =
symbol.kind === vscode.SymbolKind.Class
? new vscode.Location(uri, symbol.range)
: undefined;
// As we cannot recognise if a symbol is a new XCTestCase class we have
// to treat everything as an extension of existing classes
return {
name: symbol.name,
location: location,
extension: true, //symbol.kind === vscode.SymbolKind.Namespace
functions: functions,
};
})
.reduce((result, current) => {
const index = result.findIndex(item => item.name === current.name);
if (index !== -1) {
result[index].functions = [...result[index].functions, ...current.functions];
result[index].location = result[index].location ?? current.location;
result[index].extension = result[index].extension || current.extension;
return result;
} else {
return [...result, current];
}
}, new Array<TestDiscovery.TestClass>());
async getDocumentTests(
swiftPackage: SwiftPackage,
document: vscode.Uri
): Promise<TestDiscovery.TestClass[]> {
return await this.languageClient.useLanguageClient(async (client, token) => {
// Only use the lsp for this request if it supports the
// textDocument/tests method, and is at least version 2.
if (this.checkExperimentalCapability(client, textDocumentTestsRequest.method, 2)) {
const testsInDocument = await client.sendRequest(
textDocumentTestsRequest,
{ textDocument: { uri: document.toString() } },
token
);
return this.transformToTestClass(client, swiftPackage, testsInDocument);
} else {
throw new Error(`${textDocumentTestsRequest.method} requests not supported`);
}
});
}

/**
* Return list of workspace tests
* @param workspaceRoot Root of current workspace folder
*/
async getWorkspaceTests(workspaceRoot: vscode.Uri): Promise<TestDiscovery.TestClass[]> {
async getWorkspaceTests(swiftPackage: SwiftPackage): Promise<TestDiscovery.TestClass[]> {
return await this.languageClient.useLanguageClient(async (client, token) => {
const tests = await client.sendRequest(workspaceTestsRequest, {}, token);
const testsInWorkspace = tests.filter(item =>
isPathInsidePath(
client.protocol2CodeConverter.asLocation(item.location).uri.fsPath,
workspaceRoot.fsPath
)
);
const classes = testsInWorkspace
.filter(item => {
return (
item.kind === langclient.SymbolKind.Class &&
isPathInsidePath(
client.protocol2CodeConverter.asLocation(item.location).uri.fsPath,
workspaceRoot.fsPath
)
);
})
.map(item => {
const functions = testsInWorkspace
.filter(func => func.containerName === item.name)
.map(func => {
const openBrackets = func.name.indexOf("(");
let funcName = func.name;
if (openBrackets) {
funcName = func.name.slice(0, openBrackets);
}
return {
name: funcName,
location: client.protocol2CodeConverter.asLocation(func.location),
};
});
return {
name: item.name,
location: client.protocol2CodeConverter.asLocation(item.location),
functions: functions,
};
});
return classes;
// Only use the lsp for this request if it supports the
// workspace/tests method, and is at least version 2.
if (this.checkExperimentalCapability(client, workspaceTestsRequest.method, 2)) {
const tests = await client.sendRequest(workspaceTestsRequest, {}, token);
return this.transformToTestClass(client, swiftPackage, tests);
} else {
throw new Error(`${workspaceTestsRequest.method} requests not supported`);
}
});
}

/**
* Returns `true` if the LSP supports the supplied `method` at or
* above the supplied `minVersion`.
*/
private checkExperimentalCapability(
client: LanguageClient,
method: string,
minVersion: number
) {
const capKey = `${method}:${minVersion}`;
const cachedCap = this.capCache.get(capKey);
if (cachedCap !== undefined) {
return cachedCap;
}

const experimentalCapability = client.initializeResult?.capabilities.experimental;
if (!experimentalCapability) {
throw new Error(`${method} requests not supported`);
}
const targetCapability = experimentalCapability[method];
const canUse = (targetCapability?.version ?? -1) >= minVersion;
this.capCache.set(capKey, canUse);
return canUse;
}

/**
* Convert from `LSPTestItem[]` to `TestDiscovery.TestClass[]`,
* updating the format of the location.
*/
private transformToTestClass(
client: LanguageClient,
swiftPackage: SwiftPackage,
input: LSPTestItem[]
): TestDiscovery.TestClass[] {
return input.map(item => {
const location = client.protocol2CodeConverter.asLocation(item.location);
const id = this.transformId(item, location, swiftPackage);
return {
...item,
id: id,
location: location,
children: this.transformToTestClass(client, swiftPackage, item.children),
};
});
}

/**
* If the test is an XCTest, transform the ID provided by the LSP from a
* swift-testing style ID to one that XCTest can use. This allows the ID to
* be used to tell to the test runner (xctest or swift-testing) which tests to run.
*/
private transformId(
item: LSPTestItem,
location: vscode.Location,
swiftPackage: SwiftPackage
): string {
// XCTest: Target.TestClass/testCase
// swift-testing: TestClass/testCase()
// TestClassOrStruct/NestedTestSuite/testCase()
const target = swiftPackage
.getTargets(TargetType.test)
.find(target => swiftPackage.getTarget(location.uri.fsPath) === target);

const id = target !== undefined ? `${target.name}.${item.id}` : item.id;
if (item.style === "XCTest") {
return id.replace(/\(\)$/, "");
} else {
return id;
}
}
}
Loading