From 9c145ea25849dba3072f7c46aa75cbd07a6d5608 Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:15:45 +0530 Subject: [PATCH] fix(run): run a Gradle subproject's tests with that subproject's test task (#4846) In a Gradle multi-project build, gutter class/method runs, Run on a test file and JUnit configurations used the build's plain test task, so --tests filtered every subproject and the first one without a match failed the build before the subproject holding the test ran. They now share inGradleModule (the lookup directory runs already used) and run ::test --tests ...; reruns and test-tree selections inherit that task. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- src/features/run/context.ts | 9 ++++-- src/features/run/gradleModuleTests.ts | 40 +++++++++++++++++++++++ src/features/run/junitType.test.ts | 19 +++++++++++ src/features/run/junitType.ts | 8 +++-- src/features/run/producers.test.ts | 44 +++++++++++++++++++++++++- src/features/run/producers.ts | 39 +++-------------------- src/features/run/testing/rerun.test.ts | 11 +++++++ 7 files changed, 130 insertions(+), 40 deletions(-) create mode 100644 src/features/run/gradleModuleTests.ts diff --git a/src/features/run/context.ts b/src/features/run/context.ts index 206658f77..8d9b597ef 100644 --- a/src/features/run/context.ts +++ b/src/features/run/context.ts @@ -4,7 +4,9 @@ * direct interpreter invocation for main files. Best effort, IDEA-style. */ import type { RunConfig } from "@/platform/ipc"; +import { jvmModuleDir } from "@/platform/javaLaunch"; import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes"; +import { inGradleModule } from "./gradleModuleTests"; import { systemPython } from "./pythonTypes"; import { phpunitArgs } from "./testing/phpunit"; import { goTestParts } from "./goArguments"; @@ -277,8 +279,11 @@ export function testConfigFor( const m = /(?:^|\/)tests\/([^/]+)\.rs$/.exec(relPath); return m ? derived(base, relPath, { args: [...base.args, "--test", m[1]!] }) : base; } - case "gradle": - return derived(base, relPath, { args: [...base.args, "--tests", `*${stem(relPath)}`] }); + case "gradle": { + // Class and method runs narrow this file configuration, so they inherit its subproject task. + const module = inGradleModule(base, jvmModuleDir(relPath, configs)); + return derived(module, relPath, { args: [...module.args, "--tests", `*${stem(relPath)}`] }); + } case "maven": return derived(base, relPath, { args: withMavenTests(base.args, stem(relPath)) }); } diff --git a/src/features/run/gradleModuleTests.ts b/src/features/run/gradleModuleTests.ts new file mode 100644 index 000000000..7b0f1ff93 --- /dev/null +++ b/src/features/run/gradleModuleTests.ts @@ -0,0 +1,40 @@ +import type { RunConfig } from "@/platform/ipc"; +import { useBuildModel } from "@/platform/buildModel"; + +/** + * The Gradle build and project path a module directory belongs to. `null` for non-Gradle + * bases and modules the base configuration already runs. Without a loaded model, the Gradle + * path is guessed from the directory's segments below the build: right for the standard + * layout the wrapper itself implies. + */ +function gradleOwnerFor(module: string, base: RunConfig): { dir: string | null; path: string } | null { + if (base.kind !== "gradle" || !module || module === base.cwd) return null; + const dir = module.replace(/\\/g, "/"); + const gradle = useBuildModel + .getState() + .model?.gradle?.find((g) => g.projects.some((p) => p.dir.replace(/\\/g, "/") === dir)); + const project = gradle?.projects.find((p) => p.dir.replace(/\\/g, "/") === dir); + const build = (base.cwd ?? "").replace(/\\/g, "/").replace(/\/+$/, ""); + const inBuild = build && dir.startsWith(`${build}/`) ? dir.slice(build.length + 1) : dir; + return { + dir: gradle ? gradle.dir || null : base.cwd, + path: project?.path ?? `:${inBuild.split("/").join(":")}`, + }; +} + +/** + * `base`, a Gradle test configuration, narrowed to the subproject in `module`: it runs from the + * build root, where `./gradlew` resolves, with its `test` task qualified by the subproject's + * Gradle path (`services/api` → `:services:api:test`). `--tests` on the plain `test` task + * filters every subproject's tests, and one without a match fails the build ("No tests found + * for given includes") before the subproject holding the test runs. + */ +export function inGradleModule(base: RunConfig, module: string): RunConfig { + const owner = gradleOwnerFor(module, base); + if (!owner) return base; + return { + ...base, + cwd: owner.dir, + args: base.args.map((a) => (a === "test" ? `${owner.path}:test` : a)), + }; +} diff --git a/src/features/run/junitType.test.ts b/src/features/run/junitType.test.ts index 9ab30b869..01620cec1 100644 --- a/src/features/run/junitType.test.ts +++ b/src/features/run/junitType.test.ts @@ -63,6 +63,25 @@ describe("JUnit configurations", () => { expect(line({ testKind: "all", vmOptions: "-Xmx1g" }).args).toEqual([":api:test"]); }); + it("run a subproject's tests with its own task when the build's test configuration is the root's", () => { + const root = [cfg({ id: "gradle:test", kind: "gradle", args: ["test"], isTest: true })]; + const line = (p: Record) => junitCommandLine({ module: "services/api", ...p }, root); + expect(line({ testKind: "method", className: "a.OrderTest", methodName: "ships" })).toEqual({ + command: "./gradlew", + args: [":services:api:test", "--tests", "a.OrderTest.ships"], + cwd: null, + }); + expect(line({ testKind: "class", className: "a.OrderTest" }).args).toEqual([ + ":services:api:test", + "--tests", + "a.OrderTest", + ]); + expect(line({ testKind: "package", packageName: "a.b" }).args).toEqual([":services:api:test", "--tests", "a.b.*"]); + expect(line({ testKind: "pattern", pattern: "*IT" }).args).toEqual([":services:api:test", "--tests", "*IT"]); + expect(line({ testKind: "all" }).args).toEqual([":services:api:test"]); + expect(junitCommandLine({ module: ".", testKind: "all" }, root).args).toEqual(["test"]); + }); + it("run nothing without a Maven or Gradle build, and debug and report like build runs", () => { expect(junitCommandLine({ testKind: "all" }, []).command).toBe(""); const line = junitCommandLine({ testKind: "class", className: "a.OrderTest" }, maven); diff --git a/src/features/run/junitType.ts b/src/features/run/junitType.ts index 7d1a0a9af..2960f7c75 100644 --- a/src/features/run/junitType.ts +++ b/src/features/run/junitType.ts @@ -7,6 +7,7 @@ import type { RunConfig } from "@/platform/ipc"; import type { RunConfigTypeContribution } from "@/workbench/contributions"; import { jvmTestConfig } from "./application"; import { testBasesFor, testConfigFor } from "./context"; +import { inGradleModule } from "./gradleModuleTests"; import { ROOT_MODULE, buildModuleOptions, @@ -38,8 +39,9 @@ export function junitCommandLine( p: Readonly>, configs: RunConfig[], ): { command: string; args: string[]; cwd: string | null } { - const base = baseFor(p, configs); - if (!base) return { command: "", args: [], cwd: null }; + const detected = baseFor(p, configs); + if (!detected) return { command: "", args: [], cwd: null }; + const base = inGradleModule(detected, moduleDir(p)); const maven = base.kind === "maven"; let args = [...base.args]; const cls = p.className?.trim() ?? ""; @@ -48,7 +50,7 @@ export function junitCommandLine( case "method": { if (!cls) break; const method = kindOf(p) === "method" ? p.methodName?.trim() || undefined : undefined; - const file = testConfigFor(inModule(p, `src/test/java/${cls.replace(/\./g, "/")}.java`), configs, base); + const file = testConfigFor(inModule(p, `src/test/java/${cls.replace(/\./g, "/")}.java`), configs, detected); const narrowed = file && jvmTestConfig(file, cls, method); if (narrowed) args = narrowed.args; break; diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts index 7da8f3fc4..aac26741e 100644 --- a/src/features/run/producers.test.ts +++ b/src/features/run/producers.test.ts @@ -721,7 +721,7 @@ describe("single-file producers (scratches)", () => { ALL, )!; expect(t.config).toMatchObject({ kind: "gradle", cwd: "backend" }); - expect(t.config!.args).toEqual(["test", "--tests", "demo.AppTest.works"]); + expect(t.config!.args).toEqual([":app:test", "--tests", "demo.AppTest.works"]); }); it("a test-named class with a main runs its main; without one, its tests (IDEA semantics)", () => { @@ -1005,6 +1005,48 @@ describe("project producers", () => { expect(produceDirectory({ path: `${ROOT}/src/main`, root: ROOT, configs })).toBeNull(); expect(produceDirectory({ path: ROOT, root: ROOT, configs })).toBeNull(); }); + + // `--tests` on the root `test` runs every subproject's test task, and one without a match + // fails the build ("No tests found for given includes") before the subproject with the test. + it("Gradle: a subproject's test class, method and file run that subproject's test task", () => { + const gradle = [cfg({ id: "gradle:test", kind: "gradle", command: "./gradlew", args: ["test"], isTest: true })]; + const content = + "package com.acme;\n\nimport org.junit.jupiter.api.Test;\n\nclass OrderTest {\n @Test\n void ships() {\n }\n}\n"; + const input = (path: string, configs = gradle, line?: number): ContextInput => ({ + path: `${ROOT}/${path}`, + root: ROOT, + configs, + content, + line, + }); + const file = "services/api/src/test/java/com/acme/OrderTest.java"; + const method = produceContext(input(file, gradle, 6), ALL)!.config!; + expect(method).toMatchObject({ cwd: null, args: [":services:api:test", "--tests", "com.acme.OrderTest.ships"] }); + expect(produceContext(input(file, gradle, 4), ALL)!.config!.args).toEqual([ + ":services:api:test", + "--tests", + "com.acme.OrderTest", + ]); + expect(produceFile(input(file), ALL)!.config).toMatchObject({ + cwd: null, + args: [":services:api:test", "--tests", "*OrderTest"], + }); + // The root project's own tests keep the plain task. + expect(produceFile(input("src/test/java/com/acme/OrderTest.java"), ALL)!.config!.args).toEqual([ + "test", + "--tests", + "*OrderTest", + ]); + // A build nested in a folder: the subproject path is relative to that build. + const nested = [cfg({ id: "gradle:test:shop", kind: "gradle", args: ["test"], cwd: "shop", isTest: true })]; + expect(produceFile(input("shop/api/src/test/java/com/acme/OrderTest.java", nested), ALL)!.config).toMatchObject({ + cwd: "shop", + args: [":api:test", "--tests", "*OrderTest"], + }); + expect( + produceDirectory({ path: `${ROOT}/shop/api/src/test/java`, root: ROOT, configs: nested })!.config!.args, + ).toEqual([":api:test"]); + }); }); describe("file-level gutter targets", () => { diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index b2358dc66..fad5a5dae 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -14,7 +14,7 @@ import { ipcPath, isSameOrInside } from "@/platform/paths"; import { isTestPath } from "@/platform/languageSettings"; import { currentRoots } from "@/platform/projectRoots"; import { applicationConfig, jvmModuleDir } from "./application"; -import { useBuildModel } from "@/platform/buildModel"; +import { inGradleModule } from "./gradleModuleTests"; import { formatArgs } from "./configs"; import { goGenerateConfig } from "./goGenerate"; import { goTestParts } from "./goArguments"; @@ -1279,27 +1279,6 @@ function rubyDirectory( return make(minitest, label, [...args, relToCwd(minitest)]); } -/** - * The Gradle build and project path a module directory belongs to, so a module - * test run can stay in the build root (where `./gradlew` resolves) and qualify - * its task (`:services:api:test`). `null` for non-Gradle bases and modules the - * base configuration already runs. Without a loaded model, the Gradle path is - * guessed from the directory's segments — right for the standard layout the - * wrapper itself implies. - */ -function gradleOwnerFor(module: string, base: RunConfig): { dir: string | null; path: string } | null { - if (base.kind !== "gradle" || !module || module === base.cwd) return null; - const dir = module.replace(/\\/g, "/"); - const gradle = useBuildModel - .getState() - .model?.gradle?.find((g) => g.projects.some((p) => p.dir.replace(/\\/g, "/") === dir)); - const project = gradle?.projects.find((p) => p.dir.replace(/\\/g, "/") === dir); - return { - dir: gradle?.dir ?? base.cwd, - path: project?.path ?? `:${module.split("/").join(":")}`, - }; -} - export function produceDirectory(input: ContextInput): Produced | null { input = scopedInput(input); const { root } = input; @@ -1335,20 +1314,12 @@ export function produceDirectory(input: ContextInput): Produced | null { const base = closest(["gradle", "maven"]); if (base) { const module = jvmModuleDir(rel + "/x.java", input.configs); - // Gradle in a multi-module project: run from the build root so the - // wrapper (`./gradlew`) resolves, qualifying the task with the module's - // Gradle path (`services/api` → `:services:api:test`). Other builds run - // in the module directory as before. - const owner = gradleOwnerFor(module, base); - const moduleBase = { ...base, cwd: owner ? owner.dir : module || base.cwd }; - const moduleArgs = (base: RunConfig): string[] => { - if (!owner) return [...base.args]; - return base.args.map((a) => (a === "test" ? `${owner.path}:test` : a)); - }; - if (!jvmPackage) return make(moduleBase, "All Tests", moduleArgs(base)); + // Maven runs in the module directory. + const moduleBase = base.kind === "gradle" ? inGradleModule(base, module) : { ...base, cwd: module || base.cwd }; + if (!jvmPackage) return make(moduleBase, "All Tests", [...moduleBase.args]); const pkg = jvmPackage[2]!.replace(/\//g, "."); return base.kind === "gradle" - ? make(moduleBase, `Tests in '${pkg}'`, [...moduleArgs(base), "--tests", `${pkg}.*`]) + ? make(moduleBase, `Tests in '${pkg}'`, [...moduleBase.args, "--tests", `${pkg}.*`]) : make(moduleBase, `Tests in '${pkg}'`, withMavenTests(base.args, `${pkg}.**.*`)); } } diff --git a/src/features/run/testing/rerun.test.ts b/src/features/run/testing/rerun.test.ts index c9e91f150..0d5b4c75e 100644 --- a/src/features/run/testing/rerun.test.ts +++ b/src/features/run/testing/rerun.test.ts @@ -191,6 +191,17 @@ describe("rerunFailedConfig", () => { expect(await rerunFailedConfig(cfg("zig", "zig", ["build", "test"]), [["tally", "subs"]])).toBeNull(); }); + it("gradle: reruns and tree selections of a subproject's run keep its test task", async () => { + const run = cfg("gradle", "./gradlew", [":services:api:test", "--tests", "com.a.FooTest"]); + expect((await rerunFailedConfig(run, [["com.a.FooTest", "bar()"]]))!.args).toEqual([ + ":services:api:test", + "--tests", + "com.a.FooTest.bar", + ]); + const [selected] = await testsConfigs(run, [["com.a.FooTest", "baz"]], "FooTest.baz"); + expect(selected!.args).toEqual([":services:api:test", "--tests", "com.a.FooTest.baz"]); + }); + it("gradle and maven filters", async () => { expect((await rerunFailedConfig(cfg("gradle", "./gradlew", ["test"]), [["com.a.FooTest", "bar()"]]))!.args).toEqual( ["test", "--tests", "com.a.FooTest.bar"],