Skip to content

Add tests for LSP test discovery #916

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 2 commits into from
Jun 20, 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
48 changes: 26 additions & 22 deletions src/TestExplorer/LSPTestDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,26 @@ import {
textDocumentTestsRequest,
workspaceTestsRequest,
} from "../sourcekit-lsp/lspExtensions";
import { LanguageClientManager } from "../sourcekit-lsp/LanguageClientManager";
import { LanguageClient } from "vscode-languageclient/node";
import { InitializeResult, RequestType } from "vscode-languageclient/node";
import { SwiftPackage, TargetType } from "../SwiftPackage";
import { Converter } from "vscode-languageclient/lib/common/protocolConverter";

interface ILanguageClient {
get initializeResult(): InitializeResult | undefined;
get protocol2CodeConverter(): Converter;

sendRequest<P, R, E>(
type: RequestType<P, R, E>,
params: P,
token?: vscode.CancellationToken
): Promise<R>;
}

interface ILanguageClientManager {
useLanguageClient<Return>(process: {
(client: ILanguageClient, cancellationToken: vscode.CancellationToken): Promise<Return>;
}): Promise<Return>;
}

/**
* Used to augment test discovery via `swift test --list-tests`.
Expand All @@ -34,7 +51,7 @@ import { SwiftPackage, TargetType } from "../SwiftPackage";
export class LSPTestDiscovery {
private capCache = new Map<string, boolean>();

constructor(private languageClient: LanguageClientManager) {}
constructor(private languageClient: ILanguageClientManager) {}

/**
* Return a list of tests in the supplied document.
Expand Down Expand Up @@ -82,43 +99,34 @@ export class LSPTestDiscovery {
* above the supplied `minVersion`.
*/
private checkExperimentalCapability(
client: LanguageClient,
client: ILanguageClient,
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;
return (targetCapability?.version ?? -1) >= minVersion;
}

/**
* Convert from `LSPTestItem[]` to `TestDiscovery.TestClass[]`,
* updating the format of the location.
*/
private transformToTestClass(
client: LanguageClient,
client: ILanguageClient,
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,
id: this.transformId(item, location, swiftPackage),
children: this.transformToTestClass(client, swiftPackage, item.children),
location,
};
});
}
Expand All @@ -141,10 +149,6 @@ export class LSPTestDiscovery {
.find(target => swiftPackage.getTarget(location.uri.fsPath) === target);

const id = target !== undefined ? `${target.c99name}.${item.id}` : item.id;
if (item.style === "XCTest") {
return id.replace(/\(\)$/, "");
} else {
return id;
}
return item.style === "XCTest" ? id.replace(/\(\)$/, "") : id;
}
}
2 changes: 1 addition & 1 deletion src/sourcekit-lsp/lspExtensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export interface LSPTestItem {
*
* For a test suite, this may contain the individual test cases or nested suites.
*/
children: [LSPTestItem];
children: LSPTestItem[];

/**
* Tags associated with this test item.
Expand Down
216 changes: 216 additions & 0 deletions test/suite/testexplorer/LSPTestDiscovery.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2024 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import * as assert from "assert";
import * as vscode from "vscode";
import * as ls from "vscode-languageserver-protocol";
import * as p2c from "vscode-languageclient/lib/common/protocolConverter";
import { beforeEach } from "mocha";
import { InitializeResult, RequestType } from "vscode-languageclient";
import { LSPTestDiscovery } from "../../../src/TestExplorer/LSPTestDiscovery";
import { SwiftPackage, Target, TargetType } from "../../../src/SwiftPackage";
import { TestClass } from "../../../src/TestExplorer/TestDiscovery";
import { SwiftToolchain } from "../../../src/toolchain/toolchain";
import {
LSPTestItem,
textDocumentTestsRequest,
workspaceTestsRequest,
} from "../../../src/sourcekit-lsp/lspExtensions";

class TestLanguageClient {
private responses = new Map<string, unknown>();
private responseVersions = new Map<string, number>();

setResponse<P, R, E>(type: RequestType<P, R, E>, response: R) {
this.responses.set(type.method, response);
}

setResponseVersion<P, R, E>(type: RequestType<P, R, E>, version: number) {
this.responseVersions.set(type.method, version);
}

get initializeResult(): InitializeResult | undefined {
return {
capabilities: {
experimental: {
"textDocument/tests": {
version: this.responseVersions.get("textDocument/tests") ?? 999,
},
"workspace/tests": {
version: this.responseVersions.get("workspace/tests") ?? 999,
},
},
},
};
}
get protocol2CodeConverter(): p2c.Converter {
return p2c.createConverter(undefined, true, true);
}

sendRequest<P, R, E>(type: RequestType<P, R, E>): Promise<R> {
const response = this.responses.get(type.method) as R | undefined;
return response ? Promise.resolve(response) : Promise.reject("Method not implemented");
}
}

suite("LSPTestDiscovery Suite", () => {
let client: TestLanguageClient;
let discoverer: LSPTestDiscovery;
let pkg: SwiftPackage;
const file = vscode.Uri.file("file:///some/file.swift");

beforeEach(async () => {
pkg = await SwiftPackage.create(file, await SwiftToolchain.create());
client = new TestLanguageClient();
discoverer = new LSPTestDiscovery({
useLanguageClient(process) {
return process(client, new vscode.CancellationTokenSource().token);
},
});
});

suite("Empty responses", () => {
test(textDocumentTestsRequest.method, async () => {
client.setResponse(textDocumentTestsRequest, []);

const testClasses = await discoverer.getDocumentTests(pkg, file);

assert.deepStrictEqual(testClasses, []);
});

test(workspaceTestsRequest.method, async () => {
client.setResponse(workspaceTestsRequest, []);

const testClasses = await discoverer.getWorkspaceTests(pkg);

assert.deepStrictEqual(testClasses, []);
});
});

suite("Unsupported LSP version", () => {
test(textDocumentTestsRequest.method, async () => {
client.setResponseVersion(textDocumentTestsRequest, 0);

await assert.rejects(() => discoverer.getDocumentTests(pkg, file));
});

test(workspaceTestsRequest.method, async () => {
client.setResponseVersion(workspaceTestsRequest, 0);

await assert.rejects(() => discoverer.getWorkspaceTests(pkg));
});

test("missing experimental capabiltity", async () => {
Object.defineProperty(client, "initializeResult", {
get: () => ({ capabilities: {} }),
});

await assert.rejects(() => discoverer.getWorkspaceTests(pkg));
});

test("missing specific capability", async () => {
Object.defineProperty(client, "initializeResult", {
get: () => ({ capabilities: { experimental: {} } }),
});

await assert.rejects(() => discoverer.getWorkspaceTests(pkg));
});
});

suite("Non empty responses", () => {
let items: LSPTestItem[];
let expected: TestClass[];

beforeEach(() => {
items = [
{
id: "topLevelTest()",
label: "topLevelTest()",
disabled: false,
style: "swift-testing",
tags: [],
location: ls.Location.create(
file.fsPath,
ls.Range.create(ls.Position.create(1, 0), ls.Position.create(2, 0))
),
children: [],
},
];

expected = items.map(item => ({
...item,
location: client.protocol2CodeConverter.asLocation(item.location),
children: [],
}));
});

test(textDocumentTestsRequest.method, async () => {
client.setResponse(textDocumentTestsRequest, items);

const testClasses = await discoverer.getDocumentTests(pkg, file);

assert.deepStrictEqual(testClasses, expected);
});

test(workspaceTestsRequest.method, async () => {
client.setResponse(workspaceTestsRequest, items);

const testClasses = await discoverer.getWorkspaceTests(pkg);

assert.deepStrictEqual(testClasses, expected);
});

test("converts LSP XCTest IDs", async () => {
items = items.map(item => ({ ...item, style: "XCTest" }));
expected = expected.map(item => ({
...item,
id: "topLevelTest",
style: "XCTest",
}));

client.setResponse(workspaceTestsRequest, items);

const testClasses = await discoverer.getWorkspaceTests(pkg);

assert.deepStrictEqual(testClasses, expected);
});

test("Prepends test target to ID", async () => {
const testTargetName = "TestTargetC99Name";
expected = expected.map(item => ({
...item,
id: `${testTargetName}.topLevelTest()`,
}));

client.setResponse(workspaceTestsRequest, items);

const target: Target = {
c99name: testTargetName,
name: testTargetName,
path: file.fsPath,
type: TargetType.test,
sources: [],
};
pkg.getTargets = () => [target];
pkg.getTarget = () => target;

const testClasses = await discoverer.getWorkspaceTests(pkg);

assert.deepStrictEqual(
testClasses.map(({ id }) => id),
expected.map(({ id }) => id)
);
});
});
});