From 7911a74c058666993308ed4d4475bf3911e5dfd7 Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:59:35 +0530 Subject: [PATCH] fix(run): run a Gradle test with the Test task of its source set (#8207) Run and Debug from the gutter on a test in a JVM test suite (src/integrationTest/java) or in a source set with its own Test task (functionalTest) ran `:app:test --tests ...`, and Gradle answered "No tests found for given includes": the run configurations only knew a test task and every Gradle test run was narrowed to :test. The Gradle sync now reports, for each source set, the Test tasks whose testClassesDirs hold its classes (GradleProject.testTasks), and a test file, class, method or folder runs with the task of its source set (`:app:integrationTest --tests demo.GreeterIT`); those folders also get the All Tests and package runs src/test/java has, and debugging a configuration that runs such a task gets the JDWP agent. Before a sync reports the tasks, runs keep using test; older Gradle caches are marked stale so the next reload reads them. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- crates/ide-build/src/gradle-model.gradle | 14 ++++ crates/ide-build/src/gradle.rs | 77 +++++++++++++++++++ crates/ide-build/src/sync.rs | 13 +++- src/bindings.ts | 10 +++ src/features/run/context.ts | 2 +- src/features/run/gradleModuleTests.ts | 54 ++++++++++++-- src/features/run/java.test.ts | 38 ++++++++++ src/features/run/javaDebug.ts | 5 +- src/features/run/jvmTypes.test.ts | 18 +++++ src/features/run/jvmTypes.ts | 4 +- src/features/run/producers.test.ts | 95 ++++++++++++++++++++++++ src/features/run/producers.ts | 19 +++-- 12 files changed, 330 insertions(+), 19 deletions(-) diff --git a/crates/ide-build/src/gradle-model.gradle b/crates/ide-build/src/gradle-model.gradle index a5e5e7a7fc..b165c3fff4 100644 --- a/crates/ide-build/src/gradle-model.gradle +++ b/crates/ide-build/src/gradle-model.gradle @@ -40,6 +40,15 @@ def describe = { Project p -> try { p.extensions.findByName('testing')?.suites?.each { suites << it.sources.name } } catch (ignored) {} def ideaTests = [] as Set try { p.extensions.findByName('idea')?.module?.testSources?.files?.each { ideaTests << canon(it) } } catch (ignored) {} + // The `Test` tasks running each classes folder, as IDEA maps tests to tasks: a JVM test + // suite's tests run with its own task (`integrationTest`), not with `test`. + def testTasks = [:] + try { + p.tasks.withType(Test).each { t -> + def dirs = t.hasProperty('testClassesDirs') ? t.testClassesDirs.files : [t.testClassesDir] + dirs.findAll { it != null }.each { testTasks.get(canon(it), []) << t.name } + } + } catch (ignored) {} m.sourceSets = sets.collect { s -> def res = s.resources.srcDirs.collect(canon) def src = s.allSource.srcDirs.collect(canon) - res @@ -49,6 +58,11 @@ def describe = { Project p -> def set = [name: s.name, test: test, src: src, res: res] def processed = processedResources(p, s) if (processed != null) set.processed = processed + try { + def classes = s.output.hasProperty('classesDirs') ? s.output.classesDirs.files : [s.output.classesDir] + def tasks = classes.findAll { it != null }.collectMany { testTasks[canon(it)] ?: [] }.unique() + if (!tasks.isEmpty()) set.testTasks = tasks + } catch (ignored) {} set } } diff --git a/crates/ide-build/src/gradle.rs b/crates/ide-build/src/gradle.rs index 052f614060..5eb1753785 100644 --- a/crates/ide-build/src/gradle.rs +++ b/crates/ide-build/src/gradle.rs @@ -51,6 +51,20 @@ pub struct GradleProject { /// `:buildSrc`); null for the opened build. #[serde(default)] pub build: Option, + /// The project's `Test` tasks, or null before Gradle reports the project. + #[serde(default)] + #[specta(optional)] + pub test_tasks: Option>, +} + +/// A `Test` task and the source folders of the source sets whose test classes it runs. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct GradleTestTask { + /// Name in its project (`test`, `integrationTest`). + pub name: String, + /// Project-relative. + pub source_folders: Vec, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -341,6 +355,7 @@ fn project_at(root: &Path, path: String, name: String, pdir: &Path) -> GradlePro tasks, resolvable_configurations: None, build: None, + test_tasks: None, } } @@ -380,6 +395,9 @@ pub struct ReportedSourceSet { /// includes / excludes, extra sources), which the Java language server's copy does not. #[serde(default, skip_serializing_if = "Option::is_none")] pub processed: Option, + /// The `Test` tasks whose `testClassesDirs` hold the set's classes. + #[serde(default, rename = "testTasks", skip_serializing_if = "Vec::is_empty")] + pub test_tasks: Vec, } /// The task that copies a source set's resources, and where it writes them. @@ -455,6 +473,7 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: & } project.resolvable_configurations = p.resolvable_configurations.clone(); project.build = p.build.clone(); + project.test_tasks = Some(test_tasks(root, p)); project }) .collect(); @@ -466,6 +485,20 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: & } } +fn test_tasks(root: &Path, p: &ReportedProject) -> Vec { + let mut out: Vec = Vec::new(); + for set in &p.source_sets { + for name in &set.test_tasks { + let folders = set.src.iter().map(|dir| rel(root, Path::new(dir))); + match out.iter_mut().find(|t| t.name == *name) { + Some(task) => task.source_folders.extend(folders), + None => out.push(GradleTestTask { name: name.clone(), source_folders: folders.collect() }), + } + } + } + out +} + /// Project directories outside `root`, outermost only (`../svc`, not also `../svc/sources/app`): /// the folders IDEA shows as extra top-level module roots. pub fn external_roots<'a>(root: &Path, dirs: impl IntoIterator) -> Vec { @@ -1748,4 +1781,48 @@ Pattern: clean: Cleans the output files of a task. assert!(!model.projects[4].tasks.is_empty()); assert!(build_files(&root, &model).contains(&ws.join("lib/settings.gradle"))); } + + #[test] + fn reported_test_tasks_carry_the_source_folders_they_run() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let src = |dir: &str| root.join(dir).to_string_lossy().into_owned(); + let set = |name: &str, dirs: &[&str], tasks: &[&str]| ReportedSourceSet { + name: name.into(), + test: !tasks.is_empty(), + src: dirs.iter().map(|d| src(d)).collect(), + test_tasks: tasks.iter().map(|t| (*t).into()).collect(), + ..ReportedSourceSet::default() + }; + // As `gradle-model.gradle` prints a project with a JVM test suite. + let reported = ReportedProject { + path: ":app".into(), + dir: src("app"), + source_sets: vec![ + set("main", &["app/src/main/java"], &[]), + set("test", &["app/src/test/java"], &["test"]), + set( + "integrationTest", + &["app/src/integrationTest/java", "app/src/integrationTest/kotlin"], + &["integrationTest"], + ), + ], + ..ReportedProject::default() + }; + let line = format!("{MODEL_LINE}{}\n", serde_json::to_string(&reported).unwrap()); + assert!(line.contains(r#""testTasks":["integrationTest"]"#), "{line}"); + let mut model = GradleModel::default(); + merge_reported_projects(&root, &mut model, &parse_reported_projects(&line)); + let task = |name: &str, folders: &[&str]| GradleTestTask { + name: name.into(), + source_folders: folders.iter().map(|f| (*f).into()).collect(), + }; + assert_eq!( + model.projects[0].test_tasks, + Some(vec![ + task("test", &["app/src/test/java"]), + task("integrationTest", &["app/src/integrationTest/java", "app/src/integrationTest/kotlin"]), + ]) + ); + } } diff --git a/crates/ide-build/src/sync.rs b/crates/ide-build/src/sync.rs index 5c231f6f60..f450a96f72 100644 --- a/crates/ide-build/src/sync.rs +++ b/crates/ide-build/src/sync.rs @@ -81,6 +81,9 @@ struct GradleCache { /// The projects report how their resources are processed; older caches are stale. #[serde(default)] resources: bool, + /// The source sets report the `Test` tasks running them; older caches are stale. + #[serde(default)] + test_tasks: bool, } /// Init script printing every project, its source sets and Java version once configured. @@ -300,8 +303,9 @@ pub fn apply_gradle_cache(root: &Path, cache_dir: &Path, model: &mut GradleModel } } // A successful sync from before projects were cached has not seen computed includes, - // nor, before resources were read, which launches need Gradle to process them. - let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources); + // nor, before resources were read, which launches need Gradle to process them, nor, before + // test tasks were read, which task runs the tests of a test suite. + let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources || !cache.test_tasks); model.synced_at = Some(cache.at_ms); model.sync_error = cache.error; model.stale = outdated || cache.hash != hash_gradle_files(&gradle::build_files(root, model)); @@ -532,6 +536,7 @@ pub fn sync_gradle_model( tasks: if out.success { gradle::parse_tasks(&out.text) } else { Vec::new() }, projects, resources: true, + test_tasks: true, }; write_cache(&cache_dir, GRADLE_CACHE, &cache) } @@ -789,7 +794,7 @@ mod tests { test, src: src.iter().map(|p| core_src(p)).collect(), res: res.iter().map(|p| core_src(p)).collect(), - processed: None, + ..Default::default() }; // A settings script's own println comes first; task listing lines follow. let out = format!( @@ -890,6 +895,7 @@ mod tests { }) .collect(), resources: true, + test_tasks: true, }; write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap(); apply_gradle_cache(&root, &cache_dir, &mut model); @@ -935,6 +941,7 @@ mod tests { ..Default::default() }], resources: true, + test_tasks: true, ..Default::default() }; write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap(); diff --git a/src/bindings.ts b/src/bindings.ts index 0a9133cada..95014a7b6b 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -10615,6 +10615,8 @@ export type GradleProject = { * `:buildSrc`); null for the opened build. */ build?: string | null, + /** The project's `Test` tasks, or null before Gradle reports the project. */ + testTasks?: GradleTestTask[] | null, }; /** IDEA's "Build and run using" for Gradle builds; IDEA defaults to Gradle. */ @@ -10646,6 +10648,14 @@ export type GradleTask = { description: string | null, }; +/** A `Test` task and the source folders of the source sets whose test classes it runs. */ +export type GradleTestTask = { + /** Name in its project (`test`, `integrationTest`). */ + name: string, + /** Project-relative. */ + sourceFolders: string[], +}; + export type GtkFilter = { name: string, extensions: string[], diff --git a/src/features/run/context.ts b/src/features/run/context.ts index dacefedb85..533b246c53 100644 --- a/src/features/run/context.ts +++ b/src/features/run/context.ts @@ -367,7 +367,7 @@ export function testConfigFor( } case "gradle": { // Class and method runs narrow this file configuration, so they inherit its subproject task. - const module = inGradleModule(base, jvmModuleDir(relPath, configs)); + const module = inGradleModule(base, jvmModuleDir(relPath, configs), relPath); return derived(module, relPath, { args: [...module.args, "--tests", `*${stem(relPath)}`] }); } case "maven": diff --git a/src/features/run/gradleModuleTests.ts b/src/features/run/gradleModuleTests.ts index 7b0f1ff930..7b711c8821 100644 --- a/src/features/run/gradleModuleTests.ts +++ b/src/features/run/gradleModuleTests.ts @@ -1,6 +1,44 @@ -import type { RunConfig } from "@/platform/ipc"; +import type { GradleProject, RunConfig } from "@/platform/ipc"; import { useBuildModel } from "@/platform/buildModel"; +const slashes = (path: string) => path.replace(/\\/g, "/"); + +const gradleProjects = (): GradleProject[] => (useBuildModel.getState().model?.gradle ?? []).flatMap((g) => g.projects); + +/** + * The `Test` task running the tests under `path` (project-relative) in the Gradle project in + * `module`: the one whose source folders hold it, as Gradle reported them; `test` before a sync + * or when none does. `test` wins when it runs the same folder as another task. + */ +function testTaskFor(module: string, path: string | undefined): string { + if (path === undefined) return "test"; + const target = slashes(path); + const holds = (folder: string) => target === slashes(folder) || target.startsWith(`${slashes(folder)}/`); + const project = gradleProjects().find((p) => slashes(p.dir) === slashes(module)); + const tasks = (project?.testTasks ?? []).filter((t) => t.sourceFolders.some(holds)); + return tasks.find((t) => t.name === "test")?.name ?? tasks[0]?.name ?? "test"; +} + +/** + * The Gradle test source folder holding `path` (project-relative), as Gradle reported it, and the + * package folders below it (`""` for the source folder itself). + */ +export function gradleTestFolder(path: string): { folder: string; packagePath: string } | null { + const target = slashes(path); + for (const folder of gradleProjects().flatMap((p) => (p.testTasks ?? []).flatMap((t) => t.sourceFolders))) { + const f = slashes(folder); + if (target === f) return { folder: f, packagePath: "" }; + if (target.startsWith(`${f}/`)) return { folder: f, packagePath: target.slice(f.length + 1) }; + } + return null; +} + +/** Whether `task` (`integrationTest`, `:app:integrationTest`) is `test` or another `Test` task Gradle reported. */ +export function isGradleTestTask(task: string): boolean { + const name = task.slice(task.lastIndexOf(":") + 1); + return name === "test" || gradleProjects().some((p) => p.testTasks?.some((t) => t.name === name)); +} + /** * 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 @@ -27,14 +65,18 @@ function gradleOwnerFor(module: string, base: RunConfig): { dir: string | null; * 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. + * for given includes") before the subproject holding the test runs. With `path`, the file or + * folder to test, the task is the one running its source set (`integrationTest` for a JVM test + * suite): `test` finds no test outside its own source set either. */ -export function inGradleModule(base: RunConfig, module: string): RunConfig { +export function inGradleModule(base: RunConfig, module: string, path?: string): RunConfig { + if (base.kind !== "gradle") return base; + const task = testTaskFor(module, path); const owner = gradleOwnerFor(module, base); - if (!owner) return base; + if (!owner && task === "test") return base; return { ...base, - cwd: owner.dir, - args: base.args.map((a) => (a === "test" ? `${owner.path}:test` : a)), + cwd: owner ? owner.dir : base.cwd, + args: base.args.map((a) => (a === "test" ? (owner ? `${owner.path}:${task}` : task) : a)), }; } diff --git a/src/features/run/java.test.ts b/src/features/run/java.test.ts index b1181438d0..df8c644b43 100644 --- a/src/features/run/java.test.ts +++ b/src/features/run/java.test.ts @@ -9,6 +9,7 @@ import { parseJavaArgs, resolveJavaCommand, } from "@/platform/javaLaunch"; +import { useBuildModel } from "@/platform/buildModel"; import { usePlatform } from "@/platform/platformInfo"; import { useProject } from "@/platform/project"; import { applicationConfig, jvmModuleDir, jvmTestConfig } from "./application"; @@ -492,6 +493,43 @@ describe("debugging build tool configurations", () => { expect(jdwpLaunch(cfg({ id: "n", kind: "npm", args: ["test"] }))).toBeNull(); }); + it("debugs the Test tasks Gradle reported, whatever their name", () => { + const functional = cfg({ id: "ft", kind: "gradle", args: [":app:functionalTest"] }); + expect(jdwpLaunch(functional)).toBeNull(); + useBuildModel.setState({ + model: { + maven: null, + sbt: [], + gradle: [ + { + dir: "", + projects: [ + { + path: ":app", + name: "app", + dir: "app", + buildFile: null, + tasks: [], + testTasks: [{ name: "functionalTest", sourceFolders: ["app/src/functionalTest/java"] }], + }, + ], + javaVersion: null, + command: "gradle", + env: {}, + syncedAt: 1, + stale: false, + syncError: null, + }, + ], + }, + } as never); + try { + expect(jdwpLaunch(functional)!.args).toEqual([":app:functionalTest", DELEGATED_DEBUG]); + } finally { + useBuildModel.setState({ model: null }); + } + }); + const AGENT = /-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127\.0\.0\.1:0$/; it.each([ diff --git a/src/features/run/javaDebug.ts b/src/features/run/javaDebug.ts index 9699a3ad66..d5f0021792 100644 --- a/src/features/run/javaDebug.ts +++ b/src/features/run/javaDebug.ts @@ -23,11 +23,12 @@ import { parsePluginJavaDebug } from "@/workbench/contributions"; import { startRun, useRun, type RunSession } from "./store"; import { isJunitRunner } from "./application"; import { DELEGATED_ATTACH_LISTENER, DELEGATED_DEBUG, DELEGATED_MAIN } from "./gradleRun"; +import { isGradleTestTask } from "./gradleModuleTests"; import { isWindows } from "./jvmTypes"; const isMavenTestGoal = (a: string) => /^(test|verify|integration-test|surefire:test|failsafe:integration-test)$/.test(a); -const isGradleJvmTask = (a: string) => /(^|:)(test|bootRun|run|integrationTest|check)$/.test(a); +const isGradleJvmTask = (a: string) => isGradleTestTask(a) || /(^|:)(bootRun|run|integrationTest|check)$/.test(a); /** A plugin goal that runs the application in Maven's own JVM (`tomcat7:run`, `jetty:run-war`, `exec:java`). */ const isMavenInProcessGoal = (a: string) => /^[\w.-]+(:[\w.-]+)*:(run|run-war|run-exploded|java)$/.test(a); const JVM_ADAPTERS = ["java-debug", "kotlin-debug-adapter"]; @@ -106,7 +107,7 @@ export function jdwpLaunch(config: RunConfig, jdwpPort?: number): RunConfig | nu return missing.length ? { ...config, args: [...args, ...missing] } : config; } // Gradle Test forks test workers: the init script gives them a dynamic JDWP port. - if (config.isTest || args.some((a) => /(^|:)(test|integrationTest)$/.test(a))) + if (config.isTest || args.some((a) => isGradleTestTask(a) || /(^|:)integrationTest$/.test(a))) return args.includes(DELEGATED_DEBUG) ? config : { ...config, args: [...args, DELEGATED_DEBUG] }; // BootRun's init script gives the forked application JVM a dynamic port. if (args.some((a) => /(^|:)bootRun$/.test(a))) diff --git a/src/features/run/jvmTypes.test.ts b/src/features/run/jvmTypes.test.ts index 193183c034..ba6512ebfd 100644 --- a/src/features/run/jvmTypes.test.ts +++ b/src/features/run/jvmTypes.test.ts @@ -28,6 +28,7 @@ vi.mock("@/platform/ipc", async (orig) => { }; }); +const { useBuildModel } = await import("@/platform/buildModel"); const { usePlatform } = await import("@/platform/platformInfo"); const { parseJavaArgs, joinJavaArgs, isJvmApplication, JDWP_AGENT } = await import("@/platform/javaLaunch"); const { parseArgs } = await import("./configs"); @@ -306,6 +307,23 @@ describe("Maven / Gradle: VM options of the forked JVM", () => { "-Dspring.profiles.active=dev", ]); expect(gradleJvmArgs({ tasks: "build", vmOptions: "-Xmx1g" })).toEqual([]); + // A Test task of another name counts once Gradle reported it. + expect(gradleJvmArgs({ tasks: "functionalTest", vmOptions: "-Xmx1g" })).toEqual([]); + const gradleProject = { path: ":", name: "demo", dir: "", buildFile: null, tasks: [] }; + const testTasks = [{ name: "functionalTest", sourceFolders: ["src/functionalTest/java"] }]; + const gradleModel = { + dir: "", + projects: [{ ...gradleProject, testTasks }], + javaVersion: null, + command: "gradle", + env: {}, + }; + useBuildModel.setState({ model: { maven: null, sbt: [], gradle: [gradleModel] } } as never); + try { + expect(gradleJvmArgs({ tasks: "functionalTest", vmOptions: "-Xmx1g" })).toEqual(["-Xmx1g"]); + } finally { + useBuildModel.setState({ model: null }); + } const c = withParams(cfg({ kind: "gradle" }), params); // Gradle's own command line is unchanged. expect(c.args).toEqual(["bootRun"]); diff --git a/src/features/run/jvmTypes.ts b/src/features/run/jvmTypes.ts index e61237aa96..74f00af8ae 100644 --- a/src/features/run/jvmTypes.ts +++ b/src/features/run/jvmTypes.ts @@ -12,6 +12,7 @@ import { useBuildPresentation } from "@/platform/projectPresentation"; import type { RunConfigTypeContribution, RunConfigTypeField } from "@/workbench/contributions"; import { formatArgs, parseArgs } from "./configs"; import { commandName } from "./commandName"; +import { isGradleTestTask } from "./gradleModuleTests"; import { updatePolicyDefaults, updatePolicyFields } from "./updatePolicies"; /** Whether this window's commands run on Windows: the remote server's OS in a remote window, else the desktop's. */ @@ -241,7 +242,8 @@ const isSpringBootRun = (goal: string) => const isMavenTestGoal = (goal: string) => /^(test|verify|integration-test|surefire:test|failsafe:integration-test)$/.test(goal); const isBootRun = (task: string) => /(^|:)bootRun$/.test(task); -const isGradleJvmTask = (task: string) => /(^|:)(test|bootRun|run|integrationTest|check)$/.test(task); +const isGradleJvmTask = (task: string) => + isGradleTestTask(task) || /(^|:)(bootRun|run|integrationTest|check)$/.test(task); /** What a build tool configuration does with VM options and Spring Boot profiles. */ export interface ForkedJvm { diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts index 207a59d718..8be576ca07 100644 --- a/src/features/run/producers.test.ts +++ b/src/features/run/producers.test.ts @@ -2,6 +2,7 @@ import swiftXCTests from "../../../fixtures/swiftpm-app/Tests/TallyTests/TallyXC import swiftTesting from "../../../fixtures/swiftpm-app/Tests/TallyTests/TallySwiftTests.swift?raw"; import { afterEach, describe, expect, it, vi } from "vitest"; import * as projectRoots from "@/platform/projectRoots"; +import { useBuildModel } from "@/platform/buildModel"; import type { HierarchyItem, RunConfig } from "@/platform/ipc"; import { innermostTarget, @@ -1210,6 +1211,100 @@ describe("project producers", () => { produceDirectory({ path: `${ROOT}/shop/api/src/test/java`, root: ROOT, configs: nested })!.config!.args, ).toEqual([":api:test"]); }); + + // The `test` task finds no test of another source set ("No tests found for given includes"). + it("Gradle: a test suite's class, method, file and folder run the Test task of its source set", () => { + const gradle = [cfg({ id: "gradle:test", kind: "gradle", command: "./gradlew", args: ["test"], isTest: true })]; + const task = (name: string, ...folders: string[]) => ({ name, sourceFolders: folders }); + const project = (path: string, dir: string, testTasks?: ReturnType[]) => ({ + path, + name: path, + dir, + buildFile: null, + tasks: [], + build: null, + testTasks, + }); + // As Gradle reports them after a sync: a JVM test suite and a plain source set with its own Test task. + const reported = [ + project(":", "", [task("test", "src/test/java"), task("integrationTest", "src/integrationTest/java")]), + project(":app", "app", [ + task("test", "app/src/test/java"), + task("integrationTest", "app/src/integrationTest/java", "app/src/integrationTest/kotlin"), + task("functionalTest", "app/src/functionalTest/java"), + ]), + ]; + const sync = (projects: ReturnType[]) => + useBuildModel.setState({ + model: { + maven: null, + sbt: [], + gradle: [ + { + dir: "", + projects, + javaVersion: null, + command: "gradle", + env: {}, + syncedAt: 1, + stale: false, + syncError: null, + }, + ], + }, + } as never); + const content = + "package demo;\n\nimport org.junit.jupiter.api.Test;\n\nclass GreeterIT {\n @Test\n void greets() {\n }\n}\n"; + const input = (path: string, line?: number): ContextInput => ({ + path: `${ROOT}/${path}`, + root: ROOT, + configs: gradle, + content, + line, + }); + const folder = (path: string) => + produceDirectory({ path: `${ROOT}/${path}`, root: ROOT, configs: gradle })!.config!; + try { + sync(reported); + const file = "app/src/integrationTest/java/demo/GreeterIT.java"; + expect(produceContext(input(file, 6), ALL)!.config!.args).toEqual([ + ":app:integrationTest", + "--tests", + "demo.GreeterIT.greets", + ]); + expect(produceContext(input(file, 4), ALL)!.config!.args).toEqual([ + ":app:integrationTest", + "--tests", + "demo.GreeterIT", + ]); + expect(produceFile(input(file), ALL)!.config).toMatchObject({ + cwd: null, + args: [":app:integrationTest", "--tests", "*GreeterIT"], + }); + expect(produceFile(input("app/src/functionalTest/java/demo/GreeterIT.java"), ALL)!.config!.args).toEqual([ + ":app:functionalTest", + "--tests", + "*GreeterIT", + ]); + expect(folder("app/src/integrationTest/kotlin")).toMatchObject({ + name: "All Tests", + args: [":app:integrationTest"], + }); + expect(folder("app/src/integrationTest/java/demo").args).toEqual([":app:integrationTest", "--tests", "demo.*"]); + // The root project's own suite keeps the task unqualified, like `test`. + expect(produceFile(input("src/integrationTest/java/demo/GreeterIT.java"), ALL)!.config!.args).toEqual([ + "integrationTest", + "--tests", + "*GreeterIT", + ]); + expect(produceFile(input("app/src/test/java/demo/GreeterIT.java"), ALL)!.config!.args[0]).toBe(":app:test"); + // Before Gradle reports its tasks, `test` stays the guess. + sync(reported.map((p) => ({ ...p, testTasks: undefined }))); + expect(produceFile(input(file), ALL)!.config!.args[0]).toBe(":app:test"); + } finally { + useBuildModel.setState({ model: null } as never); + } + }); }); describe("file-level gutter targets", () => { diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index 4d1ff0339b..1aeb8a81eb 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 { inGradleModule } from "./gradleModuleTests"; +import { gradleTestFolder, inGradleModule } from "./gradleModuleTests"; import { formatArgs } from "./configs"; import { goGenerateConfig } from "./goGenerate"; import { goTestParts } from "./goArguments"; @@ -1428,6 +1428,8 @@ export function produceDirectory(input: ContextInput): Produced | null { const name = baseName(rel); const jvmRoot = /^(?:(.*)\/)?src\/test(?:\/(java|kotlin|scala|groovy))?$/.exec(rel); const jvmPackage = /^(?:(.*)\/)?src\/test\/(?:java|kotlin|scala|groovy)\/(.+)$/.exec(rel); + // Other Gradle test source folders, as Gradle reported them (`src/integrationTest/java`). + const gradleTests = gradleTestFolder(rel); const marked = isTestPath(currentRoots(), rel); const tests = input.configs.filter((c) => c.isTest); const closest = (kinds: string[]) => @@ -1463,20 +1465,25 @@ export function produceDirectory(input: ContextInput): Produced | null { ); return { ...p, name: config.name, config }; }; - if (!rel || (!TEST_DIR.test(rel) && !jvmRoot && !jvmPackage && !marked && !/(^|\/)src\/test(\/|$)/.test(rel))) { + if ( + !rel || + (!TEST_DIR.test(rel) && !jvmRoot && !jvmPackage && !gradleTests && !marked && !/(^|\/)src\/test(\/|$)/.test(rel)) + ) { // Like GoLand, any folder of a Go module runs the packages under it, unless it belongs as closely to other tests. const owners = allClosest(tests, rel); return owners.every((c) => c.kind === "go") ? goTests(owners[0]) : null; } - if (jvmRoot || jvmPackage || /(^|\/)src\/test(\/|$)/.test(rel)) { + if (jvmRoot || jvmPackage || gradleTests || /(^|\/)src\/test(\/|$)/.test(rel)) { const base = closest(["gradle", "maven"]); if (base) { const module = jvmModuleDir(rel + "/x.java", input.configs); // 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, "."); + const moduleBase = + base.kind === "gradle" ? inGradleModule(base, module, rel) : { ...base, cwd: module || base.cwd }; + const packagePath = jvmPackage?.[2] ?? gradleTests?.packagePath; + if (!packagePath) return make(moduleBase, "All Tests", [...moduleBase.args]); + const pkg = packagePath.replace(/\//g, "."); return base.kind === "gradle" ? make(moduleBase, `Tests in '${pkg}'`, [...moduleBase.args, "--tests", `${pkg}.*`]) : make(moduleBase, `Tests in '${pkg}'`, withMavenTests(base.args, `${pkg}.**.*`));