Файли
openidea/src/features/debugger/__tests__/java.test.ts
T
solhovoy e44d7fd396 fix(java): support launch classpaths from Maven POM modules (#6184)
An Application configuration whose classpath module is a dependency-only
Maven module (packaging=pom, such as a distribution or assembly module)
could not launch: launch preparation required the POM to be a Java
project in jdtls, and the Maven fallback rejected aggregators outright.

Such a module now resolves its launch classpath from its dependencies:
reactor modules (including runtime-scoped ones, which are now built as
upstream projects for every launch) and external libraries, without a
Java language server and without its own output directory. NoBuild
reuses the last resolved classpath instead of running the compile
lifecycle, and a launch from such a POM leaves the Java project to
java-debug instead of naming a non-Java project; a JDWP attach at an
aggregator root still names the root project.

Co-authored-by: solhovoy <[email protected]>
2026-11-26 21:39:53 +08:00

344 рядки
14 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
const invoked: Array<[string, unknown[]]> = [];
let shortenCommandLine: string | null = null;
let launchProjectRoot: string | undefined = "/p";
let kotlinFiles = false;
let debugAdapter = "java-debug";
const files: Record<string, string> = {};
let missingTools: string[] = [];
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = null;
},
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok", data });
return {
...real,
commands: {
...real.commands,
findFiles: (name: string) =>
ok(
name === "Main.java"
? [{ path: "/p/api/src/main/java/a/Main.java", relPath: "api/src/main/java/a/Main.java" }]
: [],
),
fsReadText: (path: string) => ok(files[path] ?? "package a;\npublic class Main {}"),
runConfigs: () => ok([]),
toolsList: () =>
ok(
["kotlin-debug-adapter", "kotlin-lsp"].map((name) => ({
name,
status: missingTools.includes(name) ? "missing" : "installed",
})),
),
fsReadDir: (path: string) =>
ok(
kotlinFiles && path.endsWith("/src")
? [{ name: "Main.kt", path: `${path}/Main.kt`, kind: "file", excluded: false }]
: [],
),
javaResolveLaunch: (...a: unknown[]) => {
invoked.push(["javaResolveLaunch", a]);
return ok({
build: "succeeded",
projectRoot: launchProjectRoot,
classPaths: ["/p/target/classes", "/m2/a.jar"],
modulePaths: [],
pathListSeparator: ":",
javaHome: "/jdk21",
javaExec: "/jdk21/bin/java",
shortenCommandLine,
errors: [],
errorCount: 0,
hints: [],
});
},
javaDebugAdapter: (...a: unknown[]) => {
invoked.push(["javaDebugAdapter", a]);
return ok(debugAdapter);
},
javaDebugServer: (...a: unknown[]) => {
invoked.push(["javaDebugServer", a]);
return ok(41234);
},
},
};
});
const { isJavaDebuggable, javaAttachConfig, javaLaunchConfig, javaProjectName, jvmAttachDebuggerReady } =
await import("../java");
const app: RunConfig = {
id: "application:a.Main",
name: "Main",
kind: "application",
command: "java",
args: ["-Xmx1g", "-cp", "${classpath}", "a.Main", "--port", "8081 x"],
cwd: "api",
module: "api",
env: { A: "1" },
detected: true,
isTest: false,
debugAdapter: "java-debug",
};
describe("Java debugging (java-debug through jdtls)", () => {
beforeEach(() => {
invoked.length = 0;
shortenCommandLine = null;
launchProjectRoot = "/p";
kotlinFiles = false;
debugAdapter = "java-debug";
});
it("launches Application configs with the resolved classpath on jdtls' debug server", async () => {
expect(isJavaDebuggable(app)).toBe(true);
expect(isJavaDebuggable({ ...app, kind: "maven" })).toBe(false);
const l = await javaLaunchConfig(app, "/p");
expect(invoked).toEqual([
["javaResolveLaunch", ["api", false, true, "automatic", expect.any(Number), expect.anything()]],
["javaDebugAdapter", ["api"]],
["javaDebugServer", ["api"]],
]);
expect(l).toMatchObject({ adapter: "java-debug", request: "launch", cwd: "/p/api", args: [], env: { A: "1" } });
expect(JSON.parse(l.extraJson!)).toMatchObject({
debugServer: 41234,
mainClass: "a.Main",
classPaths: ["/p/target/classes", "/m2/a.jar"],
javaExec: "/jdk21/bin/java",
vmArgs: "-Xmx1g",
args: '--port "8081 x"',
console: "internalConsole",
shortenCommandLine: "none",
projectName: "p",
});
});
it("echoes the equivalent Java command in the Debug console", async () => {
const report = vi.fn();
await javaLaunchConfig(app, "/p", {
request: 1,
signal: new AbortController().signal,
report,
});
expect(report).toHaveBeenCalledWith(
'/jdk21/bin/java -Xmx1g -cp /p/target/classes:/m2/a.jar a.Main --port "8081 x"\n',
);
});
it("debugs Spring Boot with coloured console output, as Run does", async () => {
const boot = { ...app, kind: "spring-boot" };
expect(JSON.parse((await javaLaunchConfig(boot, "/p")).extraJson!).vmArgs).toBe(
"-Dspring.output.ansi.enabled=always -Xmx1g",
);
const own = { ...boot, args: ["-Dspring.output.ansi.enabled=never", ...app.args] };
expect(JSON.parse((await javaLaunchConfig(own, "/p")).extraJson!).vmArgs).toBe(
"-Dspring.output.ansi.enabled=never -Xmx1g",
);
});
it("passes the configuration's VM options to java-debug's vmArgs, before the main class", async () => {
const args = [
"-Ddemo.flag=on",
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
"-Dname=a b",
"-cp",
"${classpath}",
];
const l = await javaLaunchConfig({ ...app, args: [...args, "a.App", "--spring.profiles.active=dev"] }, "/p");
expect(JSON.parse(l.extraJson!)).toMatchObject({
mainClass: "a.App",
vmArgs: '-Ddemo.flag=on --add-opens java.base/java.lang=ALL-UNNAMED "-Dname=a b"',
args: "--spring.profiles.active=dev",
});
});
it("asks the host for enhanced class redefinition when the configuration turns it on", async () => {
const on = { ...app, params: { enhancedClassRedefinition: "true" } };
expect(JSON.parse((await javaLaunchConfig(on, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
expect(JSON.parse((await javaLaunchConfig(app, "/p")).extraJson!)).not.toHaveProperty("enhancedClassRedefinition");
const kotlin = { ...on, debugAdapter: "kotlin-debug-adapter" };
expect(JSON.parse((await javaLaunchConfig(kotlin, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
});
it("lets java-debug shorten a classpath too long for the OS, as Run does", async () => {
for (const how of ["jarmanifest", "argfile"]) {
shortenCommandLine = how;
// oxlint-disable-next-line no-await-in-loop -- shortenCommandLine is shared module state set per iteration; the assertion must follow the launch that used it
const l = await javaLaunchConfig(app, "/p");
expect(JSON.parse(l.extraJson!).shortenCommandLine).toBe(how);
}
});
it("routes a Kotlin main to the Kotlin adapter and preserves JVM launch arguments", async () => {
const config = { ...app, debugAdapter: "kotlin-debug-adapter" };
expect(isJavaDebuggable(config)).toBe(true);
const l = await javaLaunchConfig(config, "/p");
expect(l).toMatchObject({ adapter: "kotlin-debug-adapter", request: "launch", cwd: "/p/api", env: { A: "1" } });
expect(JSON.parse(l.extraJson!)).toMatchObject({
projectRoot: "/p/api",
mainClass: "a.Main",
classPaths: ["/p/target/classes", "/m2/a.jar"],
javaExec: "/jdk21/bin/java",
vmArguments: ["-Xmx1g"],
programArgs: ["--port", "8081 x"],
});
expect(invoked.some(([command]) => command === "javaDebugServer")).toBe(false);
});
it("routes launch and JDWP attach in a mixed module to Kotlin without starting jdtls' adapter", async () => {
kotlinFiles = true;
expect((await javaLaunchConfig(app, "/p")).adapter).toBe("kotlin-debug-adapter");
const l = await javaAttachConfig({ name: "mvn test", module: "api", hostName: "remote", port: 5005 }, "/p");
expect(l.adapter).toBe("kotlin-debug-adapter");
expect(JSON.parse(l.extraJson!)).toEqual({
projectRoot: "/p/api",
hostName: "remote",
port: 5005,
timeout: 30_000,
});
expect(invoked.some(([command]) => command === "javaDebugServer")).toBe(false);
});
it("debugs a module jdtls doesn't serve with java-analyzer's adapter", async () => {
debugAdapter = "java-analyzer";
const l = await javaLaunchConfig(app, "/p");
expect(l).toMatchObject({ adapter: "java-analyzer", request: "launch", cwd: "/p/api", env: { A: "1" } });
expect(JSON.parse(l.extraJson!)).toEqual({
projectRoot: "/p/api",
mainClass: "a.Main",
classPaths: ["/p/target/classes", "/m2/a.jar"],
modulePaths: [],
javaExec: "/jdk21/bin/java",
vmArgs: ["-Xmx1g"],
args: ["--port", "8081 x"],
});
const a = await javaAttachConfig({ name: "mvn test", module: "api", hostName: "remote", port: 5005 }, "/p");
expect(a).toMatchObject({ adapter: "java-analyzer", request: "attach", cwd: "/p/api" });
expect(JSON.parse(a.extraJson!)).toEqual({
projectRoot: "/p/api",
hostName: "remote",
port: 5005,
timeout: 30_000,
});
expect(invoked.some(([command]) => command === "javaDebugServer")).toBe(false);
});
it("attaches to a JDWP agent", async () => {
const l = await javaAttachConfig({ name: "mvn test", module: "", hostName: "127.0.0.1", port: 5005 }, "/p");
expect(l).toMatchObject({ request: "attach", cwd: "/p" });
expect(JSON.parse(l.extraJson!)).toMatchObject({
debugServer: 41234,
hostName: "127.0.0.1",
port: 5005,
projectName: "p",
});
});
});
it.each(["sibling", "/outside/modules"])("debugs from %s with the main class module", async (cwd) => {
kotlinFiles = false;
for (const module of ["api", undefined]) {
invoked.length = 0;
// oxlint-disable-next-line no-await-in-loop -- invoked is a shared call log reset each iteration; the assertions must follow the matching launch
const launch = await javaLaunchConfig({ ...app, module, cwd }, "/p");
expect(invoked).toContainEqual([
"javaResolveLaunch",
["api", false, true, "automatic", expect.any(Number), expect.anything()],
]);
expect(invoked).toContainEqual(["javaDebugServer", ["api"]]);
expect(launch.cwd).toBe(cwd.startsWith("/") ? cwd : `/p/${cwd}`);
}
});
describe("naming the Java project jdtls imported", () => {
beforeEach(() => {
invoked.length = 0;
for (const key of Object.keys(files)) delete files[key];
});
it("uses the Maven artifactId, not the folder name, and skips the parent's", async () => {
files["/p/pom.xml"] =
"<project><parent><artifactId>orders-parent</artifactId></parent><artifactId>openidea-fixture-orders</artifactId></project>";
expect(await javaProjectName("/p")).toBe("openidea-fixture-orders");
});
it("prefers the Eclipse project descriptor", async () => {
files["/p/.project"] = "<projectDescription><name>taihe</name></projectDescription>";
files["/p/pom.xml"] = "<project><artifactId>orders</artifactId></project>";
expect(await javaProjectName("/p")).toBe("taihe");
});
it("lets java-debug resolve the main class instead of naming a POM-only project", async () => {
launchProjectRoot = undefined;
files["/p/assembly/pom.xml"] = "<project><artifactId>assembly</artifactId><packaging>pom</packaging></project>";
files["/p/assembly/.project"] = "<projectDescription><name>assembly</name></projectDescription>";
kotlinFiles = false;
debugAdapter = "java-debug";
const launch = await javaLaunchConfig({ ...app, module: "assembly" }, "/p");
expect(JSON.parse(launch.extraJson!)).not.toHaveProperty("projectName");
expect(JSON.parse(launch.extraJson!).classPaths).toEqual(["/p/target/classes", "/m2/a.jar"]);
});
it("still names the project of an aggregator root for a JDWP attach", async () => {
files["/p/pom.xml"] = "<project><artifactId>root</artifactId><packaging>pom</packaging></project>";
const attach = await javaAttachConfig({ name: "remote", module: "", hostName: "remote", port: 5005 }, "/p");
expect(JSON.parse(attach.extraJson!).projectName).toBe("root");
});
it("uses the configured Java module when the resolver does not report a project root", async () => {
launchProjectRoot = undefined;
files["/p/pom.xml"] = "<project><artifactId>root</artifactId><packaging>pom</packaging></project>";
files["/p/api/pom.xml"] = "<project><artifactId>api-module</artifactId></project>";
const launch = await javaLaunchConfig({ ...app, module: "api" }, "/p");
expect(JSON.parse(launch.extraJson!).projectName).toBe("api-module");
});
it("falls back to the folder name when the project says nothing, including unresolved properties", async () => {
expect(await javaProjectName("/p/api")).toBe("api");
files["/p/pom.xml"] = "<project><artifactId>${revision}</artifactId></project>";
expect(await javaProjectName("/p")).toBe("p");
});
});
it("reports a save failure before starting Java Debug", async () => {
invoked.length = 0;
const saveAll = vi.fn().mockRejectedValue(new Error("save failed"));
await expect(
javaLaunchConfig(app, "/p", {
request: 1,
signal: new AbortController().signal,
saveAll,
}),
).rejects.toThrow("save failed");
expect(invoked).toEqual([]);
});
describe("the debugger for a build tool's JVMs", () => {
it("is ready for Kotlin sources when kotlin-lsp or kotlin-debug-adapter is installed", async () => {
kotlinFiles = true;
const retry = vi.fn();
try {
for (const missing of [[], ["kotlin-debug-adapter"], ["kotlin-lsp"]]) {
missingTools = missing;
// oxlint-disable-next-line no-await-in-loop -- missingTools is shared state changed per iteration; each assertion must check the matching configuration
expect(await jvmAttachDebuggerReady("app", "/p", retry)).toBe(true);
}
missingTools = ["kotlin-debug-adapter", "kotlin-lsp"];
expect(await jvmAttachDebuggerReady("app", "/p", retry)).toBe(false);
kotlinFiles = false;
expect(await jvmAttachDebuggerReady("app", "/p", retry)).toBe(true);
expect(retry).not.toHaveBeenCalled();
} finally {
kotlinFiles = false;
missingTools = [];
}
});
});