diff --git a/crates/ide-build/src/lib.rs b/crates/ide-build/src/lib.rs index 6d86c4242..94e8d7b5b 100644 --- a/crates/ide-build/src/lib.rs +++ b/crates/ide-build/src/lib.rs @@ -16,6 +16,7 @@ mod process; #[cfg(test)] mod process_numbers; pub mod sbt; +pub mod surefire; mod sync; pub mod web; mod xml; diff --git a/crates/ide-build/src/surefire.rs b/crates/ide-build/src/surefire.rs new file mode 100644 index 000000000..6ff50410f --- /dev/null +++ b/crates/ide-build/src/surefire.rs @@ -0,0 +1,216 @@ +//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of +//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM. +//! +//! Read from the effective POM the last sync cached (Maven merged parents, profiles and +//! `pluginManagement` there), else from the module's own `pom.xml` and its ``. + +use crate::maven::{MavenModel, interpolate}; +use crate::xml::{self, Element}; +use std::collections::{BTreeMap, HashMap}; +use std::path::Path; + +const SUREFIRE: &str = "maven-surefire-plugin"; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SurefireConfig { + /// ``, split into JVM options. + pub arg_line: Vec, + /// `` and the older ``. + pub system_properties: BTreeMap, + /// ``. + pub environment: BTreeMap, + pub working_directory: Option, + /// ``. + pub additional_classpath: Vec, + /// ``: `groupId:artifactId`. + pub classpath_excludes: Vec, +} + +/// The Surefire configuration of the Maven module at `module` (absolute), if it is one. +pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option { + let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok(); + let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?; + let pom = root.join(&project.pom); + let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok(); + // A cache written before the POM last changed would apply an old configuration. + let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| { + let name = path.file_name()?.to_str()?; + if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) { + return None; + } + let root = xml::parse(&xml::read_text(&path)?)?; + let projects: Vec = if root.name == "projects" { + root.children.into_iter().filter(|p| p.name == "project").collect() + } else { + vec![root] + }; + projects.into_iter().find(|p| { + let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned())); + group.as_deref() == Some(project.group_id.as_str()) + && p.text_of("artifactId").as_deref() == Some(&project.artifact_id) + }) + }); + let (element, own) = match effective { + Some(e) => (e, false), + // ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them. + None => (xml::parse(&xml::read_text(&pom)?)?, true), + }; + let mut props: HashMap = element + .child("properties") + .map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect()) + .unwrap_or_default(); + let dir = module.to_string_lossy().into_owned(); + for (key, value) in [ + ("basedir", dir.clone()), + ("project.basedir", dir.clone()), + ("project.build.directory", format!("{dir}/target")), + ("project.groupId", project.group_id.clone()), + ("project.artifactId", project.artifact_id.clone()), + ("project.version", project.version.clone()), + ] { + props.entry(key.into()).or_insert(value); + } + Some(read(&element, &props, own)) +} + +/// `` Surefire's configuration, then its `default-test` execution's. +fn read(project: &Element, props: &HashMap, own: bool) -> SurefireConfig { + let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE); + let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect(); + if own && plugins.is_empty() { + plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect(); + } + let mut configurations: Vec<&Element> = Vec::new(); + for plugin in plugins { + configurations.extend(plugin.child("configuration")); + let default_test = plugin + .list("executions", "execution") + .into_iter() + .find(|e| e.text_of("id").as_deref() == Some("default-test")); + configurations.extend(default_test.and_then(|e| e.child("configuration"))); + } + let value = |text: &str| resolve(text.trim(), props); + let mut config = SurefireConfig::default(); + for c in configurations { + if let Some(arg_line) = c.child("argLine") { + config.arg_line = split_arg_line(&value(&arg_line.text)); + } + for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) { + config.system_properties.insert(p.name.clone(), value(&p.text)); + } + // ``: `` (deprecated, still honoured). + for p in c.list("systemProperties", "property") { + if let Some(name) = p.text_of("name") { + config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default())); + } + } + for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) { + config.environment.insert(e.name.clone(), value(&e.text)); + } + if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) { + config.working_directory = Some(dir); + } + let texts = |list: &str, item: &str| -> Vec { + c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect() + }; + config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement")); + config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude")); + } + config +} + +/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin +/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA). +fn resolve(text: &str, props: &HashMap) -> String { + let mut out = interpolate(text, props); + for open in ["@{", "${"] { + while let Some(start) = out.find(open) { + let Some(len) = out[start..].find('}') else { break }; + let key = &out[start + 2..start + len]; + let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() }; + out.replace_range(start..=start + len, &replacement); + } + } + out.trim().to_owned() +} + +/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes. +fn split_arg_line(line: &str) -> Vec { + let mut out = Vec::new(); + let mut current: Option = None; + let mut quote: Option = None; + for c in line.chars() { + match quote { + Some(q) if c == q => quote = None, + Some(_) => current.get_or_insert_default().push(c), + None if c == '"' || c == '\'' => { + quote = Some(c); + current.get_or_insert_default(); + } + None if c.is_whitespace() => out.extend(current.take()), + None => current.get_or_insert_default().push(c), + } + } + out.extend(current); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const POM: &str = r#" + com.exampleorders1 + true/m2/mockito.jar + + maven-surefire-plugin + + @{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined} + ${openideaFail}${project.build.directory} + oldstyle + UTC + ${basedir}/extra + org.slf4j:slf4j-simple + + default-test${basedir}/work + + "#; + + fn model(dir: &Path) -> MavenModel { + crate::maven::load(dir) + } + + #[test] + fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::write(root.join("pom.xml"), POM).unwrap(); + let cache = root.join("cache"); + std::fs::create_dir_all(&cache).unwrap(); + let config = surefire_config(root, &cache, &model(root), root).unwrap(); + let d = root.to_string_lossy(); + assert_eq!( + config.arg_line, + ["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="] + ); + assert_eq!(config.system_properties["openidea.fail"], "true"); + assert_eq!(config.system_properties["dir"], format!("{d}/target")); + assert_eq!(config.system_properties["old"], "style"); + assert_eq!(config.environment["TZ"], "UTC"); + assert_eq!(config.working_directory, Some(format!("{d}/work"))); + assert_eq!(config.additional_classpath, [format!("{d}/extra")]); + assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]); + + // A sync's effective POM wins: it has what the module inherits. + let effective = POM.replace("", "-Xmx1g ").replace("UTC", "Asia/Tokyo"); + std::fs::write(cache.join("effective-pom-0.xml"), format!("{effective}")).unwrap(); + let config = surefire_config(root, &cache, &model(root), root).unwrap(); + assert_eq!(config.arg_line[0], "-Xmx1g"); + assert_eq!(config.environment["TZ"], "Asia/Tokyo"); + } + + #[test] + fn splits_arg_line_like_surefire() { + assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]); + } +} diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 8b0b579ba..86703c0cf 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -1657,6 +1657,20 @@ pub struct MavenSettings { /// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT /// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`). pub update_snapshots: bool, + /// Who runs the JUnit 5 tests of the gutter's Run / Debug. + pub run_tests_using: MavenRunTestsUsing, +} + +/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build +/// and run actions are delegated to Maven. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum MavenRunTestsUsing { + /// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`). + #[default] + Ide, + /// Surefire (`mvn test -Dtest=…`). + Maven, } impl MavenSettings { @@ -2318,6 +2332,7 @@ mod maven_linkage_tests { let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap(); assert!(old.runner_jre.is_empty()); assert!(!old.delegate_build); + assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide); assert!(MavenSettings::default().runner_jre.is_empty()); let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old }; let encoded = serde_json::to_string(&settings).unwrap(); diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index f18000ad9..c58512ddc 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -646,6 +646,129 @@ pub async fn java_build_workspace( result } +/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath: +/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the +/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and, +/// for a Maven module, what its Surefire configuration gives the forked test JVM. +#[command(trust = trusted)] +pub async fn java_junit_runner( + host: &Host, + window: &str, + module: PathBuf, + class_paths: Vec, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + let module = ide_core::project_roots::resolve(&project.root, &module); + let data_dir = host.local_data_dir.clone(); + tokio::task::spawn_blocking(move || { + let scope = workspace::scope_for(&project, &module)?; + let model = load_launch_model(&scope); + let surefire = model + .maven + .as_ref() + .and_then(|maven| ide_build::surefire::surefire_config(&scope.root, &scope.cache, maven, &module)) + .unwrap_or_default(); + let runner = ide_sdk::java::junit_runner_jar(&data_dir) + .ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?; + let launcher = match ide_sdk::java::junit_launcher(&class_paths) { + ide_sdk::java::JunitLauncher::OnClasspath => None, + ide_sdk::java::JunitLauncher::Found(path) => Some(path), + ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?), + ide_sdk::java::JunitLauncher::NoPlatform => { + return Err(IdeError::unavailable( + "No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \ + Maven, set Settings › Build Tools › Maven › Run tests using to Maven.", + )); + } + }; + Ok(junit_launch(&module, class_paths, surefire, [Some(runner), launcher].into_iter().flatten())) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))? +} + +/// The test JVM of OpenIDEA's JUnit runner. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct JunitLaunch { + pub class_paths: Vec, + /// Surefire's `argLine`, then its system properties as `-Dkey=value`. + pub vm_args: Vec, + pub env: std::collections::BTreeMap, + pub working_directory: Option, + /// The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console. + pub surefire: Vec, +} + +fn junit_launch( + module: &Path, + class_paths: Vec, + surefire: ide_build::surefire::SurefireConfig, + runner: impl Iterator, +) -> JunitLaunch { + let mut applied = Vec::new(); + let mut note = |used: bool, name: &str| { + if used { + applied.push(name.to_owned()); + } + }; + note(!surefire.arg_line.is_empty(), "argLine"); + note(!surefire.system_properties.is_empty(), "systemPropertyVariables"); + note(!surefire.environment.is_empty(), "environmentVariables"); + note(surefire.working_directory.is_some(), "workingDirectory"); + note(!surefire.additional_classpath.is_empty(), "additionalClasspathElements"); + note(!surefire.classpath_excludes.is_empty(), "classpathDependencyExcludes"); + // `group:artifact` in a Maven repository (`g/r/p/artifact/…`) or the Gradle cache (`g.r.p/artifact/…`). + let excluded = |path: &str| { + let path = path.replace('\\', "/"); + surefire.classpath_excludes.iter().any(|e| { + e.split_once(':').is_some_and(|(group, artifact)| { + path.contains(&format!("/{}/{artifact}/", group.replace('.', "/"))) + || path.contains(&format!("/{group}/{artifact}/")) + }) + }) + }; + let mut class_paths: Vec = class_paths.into_iter().filter(|p| !excluded(p)).collect(); + class_paths.extend(surefire.additional_classpath); + class_paths.extend(runner.map(|p| p.to_string_lossy().into_owned())); + let mut vm_args = surefire.arg_line; + vm_args.extend(surefire.system_properties.into_iter().map(|(k, v)| format!("-D{k}={v}"))); + JunitLaunch { + class_paths, + vm_args, + env: surefire.environment, + working_directory: surefire.working_directory.map(|d| module.join(d).to_string_lossy().into_owned()), + surefire: applied, + } +} + +fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult { + if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) { + return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'"))); + } + let name = format!("junit-platform-launcher-{version}.jar"); + let dest = data_dir.join("junit").join(&name); + if dest.is_file() { + return Ok(dest); + } + std::fs::create_dir_all(dest.parent().expect("has a parent"))?; + let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}"); + let partial = dest.with_extension("jar.part"); + // ponytail: unverified like the Lombok download (Central publishes SHA-1 only); HTTPS from Central. + let fetched = ide_tools::Http::new(&ide_core::tool_path::search_path()) + .map(ide_tools::Http::https_only) + .and_then(|http| http.download(&url, &partial, None, &CancellationToken::new(), &|_| {})) + .and_then(|()| Ok(std::fs::rename(&partial, &dest)?)); + fetched.map(|()| dest).map_err(|e| { + IdeError::unavailable(format!( + "Cannot download {name} from Maven Central ({}). Add org.junit.platform:junit-platform-launcher to the \ + test dependencies, or set Settings › Build Tools › Maven › Run tests using to Maven.", + e.message + )) + }) +} + /// An annotation processor's error for writing a file this build already wrote (JDT's /// `IdeFilerImpl`: "Source file already created", javac's Filer: "Attempt to recreate a file"). fn processor_recreated_a_file(message: &str) -> bool { @@ -663,6 +786,35 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) { mod tests { use super::*; + #[test] + fn junit_launch_applies_the_surefire_configuration() { + let surefire = ide_build::surefire::SurefireConfig { + arg_line: vec!["-Xmx1g".into()], + system_properties: [("openidea.fail".to_owned(), "true".to_owned())].into(), + environment: [("TZ".to_owned(), "UTC".to_owned())].into(), + working_directory: Some("work".into()), + additional_classpath: vec!["/extra".into()], + classpath_excludes: vec!["org.slf4j:slf4j-simple".into(), "com.acme:gone".into()], + }; + let classpath = vec![ + "/m/target/test-classes".into(), + "/m2/org/slf4j/slf4j-simple/2.0/slf4j-simple-2.0.jar".into(), + "/gradle/files-2.1/com.acme/gone/1/abc/gone-1.jar".into(), + "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar".into(), + ]; + let launch = junit_launch(Path::new("/m"), classpath, surefire, [PathBuf::from("/runner.jar")].into_iter()); + assert_eq!( + launch.class_paths, + ["/m/target/test-classes", "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar", "/extra", "/runner.jar"] + ); + assert_eq!(launch.vm_args, ["-Xmx1g", "-Dopenidea.fail=true"]); + assert_eq!(launch.env["TZ"], "UTC"); + assert_eq!(launch.working_directory.as_deref(), Path::new("/m").join("work").to_str()); + assert_eq!(launch.surefire.len(), 6); + let plain = junit_launch(Path::new("/m"), vec![], Default::default(), std::iter::empty()); + assert!(plain.surefire.is_empty() && plain.vm_args.is_empty() && plain.working_directory.is_none()); + } + fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf { let bin = dir.join("bin"); std::fs::create_dir_all(&bin).unwrap(); @@ -946,4 +1098,4 @@ mod tests { } } -ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch); +ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_junit_runner, java_resolve_launch); diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index f9df8d5fa..71804aeea 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1644,6 +1644,90 @@ pub fn jdbc_bridge_jar(data_dir: &Path) -> Option { ) } +/// Extracts the JUnit Platform test runner (`java/junit-runner`) into the application's data directory. +pub fn junit_runner_jar(data_dir: &Path) -> Option { + install_bundle( + data_dir, + "junit-runner", + "1.0.0", + include_bytes!("../../../java/junit-runner/openidea-junit-runner.jar"), + ) +} + +/// The JUnit Platform launcher a test classpath needs to start the runner. +#[derive(Debug, PartialEq)] +pub enum JunitLauncher { + /// The classpath has `junit-platform-launcher` already. + OnClasspath, + /// `junit-platform-launcher` of the engine's version, next to the engine jar in its repository. + Found(PathBuf), + /// Not found locally: the engine's version, to download. + Missing(String), + /// No `junit-platform-engine` on the classpath (JUnit 4 alone, TestNG). + NoPlatform, +} + +/// Like IDEA, the launcher must match the engine's version: a project usually depends on +/// `junit-jupiter` only, which brings the engine but no launcher. The Maven local repository +/// (`…/junit-platform-engine//…jar`) and the Gradle cache (`…/junit-platform-engine///…jar`) +/// keep the launcher in a sibling folder. +pub fn junit_launcher(class_paths: &[String]) -> JunitLauncher { + let name = |p: &str| Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or_default().to_owned(); + if class_paths.iter().any(|p| name(p).starts_with("junit-platform-launcher-")) { + return JunitLauncher::OnClasspath; + } + let Some((engine, version)) = class_paths.iter().find_map(|p| { + let version = name(p).strip_prefix("junit-platform-engine-")?.strip_suffix(".jar")?.to_owned(); + Some((PathBuf::from(p), version)) + }) else { + return JunitLauncher::NoPlatform; + }; + let jar = format!("junit-platform-launcher-{version}.jar"); + let artifact = engine.ancestors().find(|a| a.file_name().is_some_and(|n| n == "junit-platform-engine")); + let launcher_dir = artifact.and_then(Path::parent).map(|d| d.join("junit-platform-launcher").join(&version)); + let found = launcher_dir.and_then(|dir| { + let direct = dir.join(&jar); + if direct.is_file() { + return Some(direct); + } + std::fs::read_dir(&dir).ok()?.flatten().map(|e| e.path().join(&jar)).find(|p| p.is_file()) + }); + match found { + Some(path) => JunitLauncher::Found(path), + None => JunitLauncher::Missing(version), + } +} + +#[cfg(test)] +mod junit_launcher_tests { + use super::{JunitLauncher, junit_launcher}; + + #[test] + fn finds_the_launcher_of_the_engine_version_in_maven_and_gradle_repositories() { + let dir = tempfile::tempdir().unwrap(); + let s = |p: &std::path::Path| p.to_string_lossy().into_owned(); + let maven = dir.path().join("m2/org/junit/platform"); + let maven_engine = maven.join("junit-platform-engine/1.11.3/junit-platform-engine-1.11.3.jar"); + let maven_launcher = maven.join("junit-platform-launcher/1.11.3/junit-platform-launcher-1.11.3.jar"); + let gradle = dir.path().join("gradle/files-2.1/org.junit.platform"); + let gradle_engine = gradle.join("junit-platform-engine/1.10.2/aaa/junit-platform-engine-1.10.2.jar"); + let gradle_launcher = gradle.join("junit-platform-launcher/1.10.2/bbb/junit-platform-launcher-1.10.2.jar"); + for jar in [&maven_engine, &maven_launcher, &gradle_engine, &gradle_launcher] { + std::fs::create_dir_all(jar.parent().unwrap()).unwrap(); + std::fs::write(jar, "").unwrap(); + } + assert_eq!(junit_launcher(&["classes".into(), s(&maven_engine)]), JunitLauncher::Found(maven_launcher)); + assert_eq!(junit_launcher(&[s(&gradle_engine)]), JunitLauncher::Found(gradle_launcher)); + let other = dir.path().join("lib/junit-platform-engine-1.9.0.jar"); + assert_eq!(junit_launcher(&[s(&other)]), JunitLauncher::Missing("1.9.0".into())); + assert_eq!( + junit_launcher(&[s(&other), "/x/junit-platform-launcher-1.9.0.jar".into()]), + JunitLauncher::OnClasspath + ); + assert_eq!(junit_launcher(&["/x/junit-4.13.2.jar".into()]), JunitLauncher::NoPlatform); + } +} + /// Installs the app-owned JDT LS bundle that inspects java-debug's JVMs. pub fn jvm_inspect_bundle(data_dir: &Path) -> Option { install_bundle( diff --git a/docs/en/guide/build-tools.mdx b/docs/en/guide/build-tools.mdx index 4ad2cb060..90ca77496 100644 --- a/docs/en/guide/build-tools.mdx +++ b/docs/en/guide/build-tools.mdx @@ -62,17 +62,18 @@ When you edit a POM in the editor, the tool window shows **Build files changed s **Settings › Build, Execution, Deployment › Maven**: -| Setting | What it does | -| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| **Delegate IDE build/run actions to Maven** | Run and Debug build Maven modules with Maven (`javac`) instead of jdtls | -| **JRE** | JDK for Maven sync, builds, goals and tests | -| **Maven home path** | A Maven installation to use instead of the project's `mvnw` | -| **User settings file** | Passed as `-s` | -| **Toolchains file** | Passed as `-t` | -| **Local repository** | Passed as `-Dmaven.repo.local` | -| **Active profiles** | Comma-separated profiles (`-P`); `!id` excludes one | -| **Thread count** | Passed as `-T` (for example `4` or `2C`) | -| **Use Maven Daemon (mvnd)** | Runs builds, sync and run configurations through `mvnd`; falls back to `mvn` if it is missing or the JDK is older than 17 | +| Setting | What it does | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Delegate IDE build/run actions to Maven** | Run and Debug build Maven modules with Maven (`javac`) instead of jdtls | +| **Run tests using** | **OpenIDEA** (default): a JUnit 5 test run from the gutter starts on jdtls' test classpath, without Maven, with the module's Surefire configuration. **Maven**: Surefire | +| **JRE** | JDK for Maven sync, builds, goals and tests | +| **Maven home path** | A Maven installation to use instead of the project's `mvnw` | +| **User settings file** | Passed as `-s` | +| **Toolchains file** | Passed as `-t` | +| **Local repository** | Passed as `-Dmaven.repo.local` | +| **Active profiles** | Comma-separated profiles (`-P`); `!id` excludes one | +| **Thread count** | Passed as `-T` (for example `4` or `2C`) | +| **Use Maven Daemon (mvnd)** | Runs builds, sync and run configurations through `mvnd`; falls back to `mvn` if it is missing or the JDK is older than 17 | ## Gradle diff --git a/docs/en/languages/java.mdx b/docs/en/languages/java.mdx index cc6949f82..9c804c863 100644 --- a/docs/en/languages/java.mdx +++ b/docs/en/languages/java.mdx @@ -100,16 +100,18 @@ In a Maven project with Kotlin sources, OpenIDEA builds the Kotlin code in the b ## Run and test -| What | How it runs | -| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | -| `main` method | **Application** configuration on the module's runtime or test classpath. Java 25 instance `main` methods are recognized. | -| `@SpringBootApplication` class | **Spring Boot** configuration, with active profiles and update actions | -| Executable jar | **JAR Application** configuration | -| WAR | **Tomcat Server** configuration on a local Tomcat installation (the IDE never writes into it) | -| JUnit 4, JUnit 5 and TestNG tests | Maven (Surefire `-Dtest=…`) or Gradle (`--tests …`) test configurations | +| What | How it runs | +| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `main` method | **Application** configuration on the module's runtime or test classpath. Java 25 instance `main` methods are recognized. | +| `@SpringBootApplication` class | **Spring Boot** configuration, with active profiles and update actions | +| Executable jar | **JAR Application** configuration | +| WAR | **Tomcat Server** configuration on a local Tomcat installation (the IDE never writes into it) | +| JUnit 4, JUnit 5 and TestNG tests | Maven (Surefire `-Dtest=…`) or Gradle (`--tests …`) test configurations; JUnit 5 in a Maven module runs on jdtls' test classpath | Gutter icons on main methods, test classes and test methods create these configurations, and Maven and Gradle run configurations are detected from the build files. For Gradle, **Build and run using** decides whether an Application runs as a Gradle `JavaExec` task (the default) or is launched by OpenIDEA on the classpath reported by jdtls. +A JUnit 5 test class or method run from the gutter of a Maven module starts on jdtls' test classpath with OpenIDEA's JUnit Platform runner, without Maven, like IDEA (**Settings › Build, Execution, Deployment › Maven › Run tests using**). The runner adds `junit-platform-launcher` of the engine's version when the project has none (from the local repository, else downloaded once from Maven Central). As in IDEA, the test JVM gets the module's Surefire configuration: `argLine` (with `@{…}` late replacement), `systemPropertyVariables`, `environmentVariables`, `workingDirectory`, `additionalClasspathElements` and `classpathDependencyExcludes`, read from the effective POM of the last Maven sync (before a sync, from the module's own `pom.xml`). Resource filtering and Surefire's other settings (forking, includes, groups) don't apply; choose **Maven** to run through Surefire. + Test results are read from the JUnit XML reports Maven and Gradle write, so passed tests are listed as well. The test tree supports rerunning failed tests. VM options of a Gradle run configuration are applied to the JVMs Gradle forks (`run`, `bootRun`, `test`). When a classpath is too long for the command line (common on Windows), it is moved into an argument file or a manifest-only jar. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing). diff --git a/docs/zh/guide/build-tools.mdx b/docs/zh/guide/build-tools.mdx index c0169ba65..40a39d430 100644 --- a/docs/zh/guide/build-tools.mdx +++ b/docs/zh/guide/build-tools.mdx @@ -62,17 +62,18 @@ Maven 和 Gradle 使用设置里配置的 wrapper 或本地安装(见下文) **设置 › 构建、执行、部署 › Maven**: -| 设置 | 作用 | -| ------------------------------------ | ------------------------------------------------------------------------------- | -| **将 IDE 构建/运行操作委托给 Maven** | 运行和调试时用 Maven(`javac`)构建 Maven 模块,而不是 jdtls | -| **JRE** | Maven 同步、构建、目标和测试使用的 JDK | -| **Maven 主路径** | 使用指定的 Maven 安装,而不是项目里的 `mvnw` | -| **用户设置文件** | 作为 `-s` 传入 | -| **Toolchains 文件** | 作为 `-t` 传入 | -| **本地仓库** | 作为 `-Dmaven.repo.local` 传入 | -| **活动 profiles** | 逗号分隔的 profile(`-P`),`!id` 表示排除 | -| **线程数** | 作为 `-T` 传入(如 `4` 或 `2C`) | -| **使用 Maven Daemon (mvnd)** | 构建、同步和运行配置都通过 `mvnd` 执行;找不到 mvnd 或 JDK 低于 17 时退回 `mvn` | +| 设置 | 作用 | +| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **将 IDE 构建/运行操作委托给 Maven** | 运行和调试时用 Maven(`javac`)构建 Maven 模块,而不是 jdtls | +| **运行测试使用** | **OpenIDEA**(默认):从装订区域运行的 JUnit 5 测试直接在 jdtls 的测试类路径上启动,不经过 Maven,并应用模块的 Surefire 配置;**Maven**:通过 Surefire 运行 | +| **JRE** | Maven 同步、构建、目标和测试使用的 JDK | +| **Maven 主路径** | 使用指定的 Maven 安装,而不是项目里的 `mvnw` | +| **用户设置文件** | 作为 `-s` 传入 | +| **Toolchains 文件** | 作为 `-t` 传入 | +| **本地仓库** | 作为 `-Dmaven.repo.local` 传入 | +| **活动 profiles** | 逗号分隔的 profile(`-P`),`!id` 表示排除 | +| **线程数** | 作为 `-T` 传入(如 `4` 或 `2C`) | +| **使用 Maven Daemon (mvnd)** | 构建、同步和运行配置都通过 `mvnd` 执行;找不到 mvnd 或 JDK 低于 17 时退回 `mvn` | ## Gradle diff --git a/docs/zh/languages/java.mdx b/docs/zh/languages/java.mdx index 7336c015d..d8a6b55c0 100644 --- a/docs/zh/languages/java.mdx +++ b/docs/zh/languages/java.mdx @@ -100,16 +100,18 @@ IDE 会把代理设置传给 jdtls,所以在代理环境下也能解析依赖 ## 运行与测试 -| 对象 | 运行方式 | -| ----------------------------- | -------------------------------------------------------------------------------- | -| `main` 方法 | **应用程序** 配置,使用模块的运行时或测试类路径;支持 Java 25 的实例 `main` 方法 | -| `@SpringBootApplication` 类 | **Spring Boot** 配置,可设置活动 profile 和更新操作 | -| 可执行 jar | **JAR 应用程序** 配置 | -| WAR | **Tomcat 服务器** 配置,运行在本地 Tomcat 安装上(IDE 不会往安装目录里写东西) | -| JUnit 4、JUnit 5、TestNG 测试 | Maven(Surefire `-Dtest=…`)或 Gradle(`--tests …`)测试配置 | +| 对象 | 运行方式 | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `main` 方法 | **应用程序** 配置,使用模块的运行时或测试类路径;支持 Java 25 的实例 `main` 方法 | +| `@SpringBootApplication` 类 | **Spring Boot** 配置,可设置活动 profile 和更新操作 | +| 可执行 jar | **JAR 应用程序** 配置 | +| WAR | **Tomcat 服务器** 配置,运行在本地 Tomcat 安装上(IDE 不会往安装目录里写东西) | +| JUnit 4、JUnit 5、TestNG 测试 | Maven(Surefire `-Dtest=…`)或 Gradle(`--tests …`)测试配置;Maven 模块中的 JUnit 5 直接在 jdtls 的测试类路径上运行 | main 方法、测试类和测试方法旁的边栏图标会创建这些配置;Maven 和 Gradle 的运行配置会从构建文件中自动检测。对 Gradle 项目,**构建和运行使用** 决定“应用程序”是作为 Gradle 的 `JavaExec` 任务运行(默认),还是由 OpenIDEA 用 jdtls 给出的类路径直接启动。 +在 Maven 模块的装订区域运行 JUnit 5 测试类或方法时,OpenIDEA 用自带的 JUnit Platform 运行器在 jdtls 的测试类路径上直接启动,不经过 Maven,与 IDEA 一致(**设置 › 构建、执行、部署 › Maven › 运行测试使用**)。项目没有 `junit-platform-launcher` 时,运行器会补上与 engine 同版本的 launcher(先找本地仓库,找不到再从 Maven Central 下载一次)。与 IDEA 一样,测试 JVM 会应用模块的 Surefire 配置:`argLine`(支持 `@{…}` 晚替换)、`systemPropertyVariables`、`environmentVariables`、`workingDirectory`、`additionalClasspathElements` 和 `classpathDependencyExcludes`,取自最近一次 Maven 同步的有效 POM(同步前取模块自己的 `pom.xml`)。资源过滤和 Surefire 的其他设置(fork、includes、groups)不会生效;需要时请选 **Maven**,通过 Surefire 运行。 + 测试结果从 Maven 和 Gradle 生成的 JUnit XML 报告中读取,通过的测试也会列出;测试树支持只重跑失败的测试。Gradle 运行配置的 VM 选项会作用到 Gradle fork 出来的 JVM(`run`、`bootRun`、`test`)。类路径超出命令行长度限制时(Windows 上常见),会改用参数文件或只含 manifest 的 jar。 另见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。 diff --git a/java/junit-runner/README.md b/java/junit-runner/README.md new file mode 100644 index 000000000..ac96fc802 --- /dev/null +++ b/java/junit-runner/README.md @@ -0,0 +1,20 @@ +# JUnit Platform runner + +`ai.openidea.junit.Runner` runs the JUnit Platform tests named by its arguments +(`com.acme.OrderTest`, `com.acme.OrderTest#method`; a method selects every overload, so +parameterized tests run too) and prints each test as the TeamCity service messages of +`src/features/run/gradleTests.gradle`, which the Run window's JVM parser already reads. It exits +with 1 when a test failed or none ran. + +OpenIDEA starts it for the gutter's JUnit 5 tests of Maven modules (Settings › Maven › Run tests +using: OpenIDEA) as `java -ea -cp :: ai.openidea.junit.Runner …`. +`ide_sdk::java::junit_launcher` picks `junit-platform-launcher` of the engine's version, and +`ide_build::surefire` reads the module's Surefire configuration for the JVM (IDEA's `MavenJUnitPatcher`). + +The jar is committed and embedded by `ide-sdk` (`junit_runner_jar`). Rebuild it after changing +the source, and check it against JUnit with: + +```sh +python3 build.py --test +python3 build.py +``` diff --git a/java/junit-runner/build-dependencies.sha256 b/java/junit-runner/build-dependencies.sha256 new file mode 100644 index 000000000..ce6d9f818 --- /dev/null +++ b/java/junit-runner/build-dependencies.sha256 @@ -0,0 +1,8 @@ +b4727459201b0011beb0742bd807421a1fc8426b116193031ed87825bc2d4f04 org/junit/platform/junit-platform-launcher/1.11.3/junit-platform-launcher-1.11.3.jar +0043f72f611664735da8dc9a308bf12ecd2236b05339351c4741edb4d8fab0da org/junit/platform/junit-platform-engine/1.11.3/junit-platform-engine-1.11.3.jar +be262964b0b6b48de977c61d4f931df8cf61e80e750cc3f3a0a39cdd21c1008c org/junit/platform/junit-platform-commons/1.11.3/junit-platform-commons-1.11.3.jar +b509448ac506d607319f182537f0b35d71007582ec741832a1f111e5b5b70b38 org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar +48e2df636cab6563ced64dcdff8abb2355627cb236ef0bf37598682ddf742f1b org/opentest4j/opentest4j/1.3.0/opentest4j-1.3.0.jar +5d8147a60f49453973e250ed68701b7ff055964fe2462fc2cb1ec1d6d44889ba org/junit/jupiter/junit-jupiter-api/5.11.3/junit-jupiter-api-5.11.3.jar +e62420c99f7c0d59a2159a2ef63e61877e9c80bd722c03ca8bf3bdcea050a589 org/junit/jupiter/junit-jupiter-engine/5.11.3/junit-jupiter-engine-5.11.3.jar +0f798ebec744c4e6605fd4f2072f41a8e989e2d469e21db5aa67cf799c0b51ec org/junit/jupiter/junit-jupiter-params/5.11.3/junit-jupiter-params-5.11.3.jar diff --git a/java/junit-runner/build.py b/java/junit-runner/build.py new file mode 100644 index 000000000..cd879edfc --- /dev/null +++ b/java/junit-runner/build.py @@ -0,0 +1,69 @@ +"""Build the committed JUnit Platform runner (Java 8 bytecode), or test it: python3 build.py [--test]. + +Compiles against the JUnit jars of build-dependencies.sha256, taken from the local Maven +repository (MAVEN_REPO, default ~/.m2/repository; `mvn dependency:get` fetches a missing one). +--test runs tests/SampleTest.java through the runner and checks its service messages.""" +import hashlib +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import zipfile + +root = Path(__file__).resolve().parent +repo = Path(os.environ.get("MAVEN_REPO", Path.home() / ".m2" / "repository")) +java_home = os.environ.get("JAVA_HOME") +test = "--test" in sys.argv[1:] + + +def tool(name): + return str(Path(java_home) / "bin" / name) if java_home else name + + +jars = [] +for line in (root / "build-dependencies.sha256").read_text().splitlines(): + digest, path = line.split() + jar = repo / path + if hashlib.sha256(jar.read_bytes()).hexdigest() != digest: + sys.exit(f"{jar}: SHA-256 mismatch") + jars.append(str(jar)) +# The launcher API only: the runner must not depend on an engine. +api = [j for j in jars if "/junit-platform-" in j or "apiguardian" in j] + +with tempfile.TemporaryDirectory() as scratch: + classes = Path(scratch) / "classes" + sources = sorted((root / "src").rglob("*.java")) + subprocess.run([tool("javac"), "--release", "8", "-encoding", "UTF-8", "-g", "-Xlint:-options", + "-cp", os.pathsep.join(api), "-d", str(classes), *map(str, sources)], check=True) + if test: + sample = Path(scratch) / "sample" + cp = os.pathsep.join(jars) + subprocess.run([tool("javac"), "-encoding", "UTF-8", "-cp", cp, "-d", str(sample), + str(root / "tests" / "SampleTest.java")], check=True) + run = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]), + "ai.openidea.junit.Runner", "sample.SampleTest"], capture_output=True) + out = run.stdout.decode("utf-8") + print(out) + expected = [ + "##teamcity[testStarted name='passes' className='sample.SampleTest']", + "##teamcity[testStdOut name='passes' className='sample.SampleTest' out='hello |[ünï|]|n']", + "##teamcity[testFailed name='fails' className='sample.SampleTest' message='org.opentest4j.AssertionFailedError: it|'s wrong ==> expected: <1> but was: <2>'", + "##teamcity[testIgnored name='disabled' className='sample.SampleTest'", + "##teamcity[testIgnored name='aborted' className='sample.SampleTest']", + "##teamcity[testFailed name='parameterized' className='sample.SampleTest'", + "##teamcity[testFinished name='nested' className='sample.SampleTest$Inner' duration=", + "7 tests completed, 2 failed, 2 skipped", + ] + missing = [e for e in expected if e not in out] + assert not missing, missing + assert run.returncode == 1, run.returncode + method = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]), + "ai.openidea.junit.Runner", "sample.SampleTest#parameterized"], capture_output=True) + assert method.stdout.decode().count("testStarted") == 2, method.stdout + print("ok") + sys.exit(0) + with zipfile.ZipFile(root / "openidea-junit-runner.jar", "w") as jar: + for path in sorted(classes.rglob("*.class")): + entry = zipfile.ZipInfo(path.relative_to(classes).as_posix(), (2026, 1, 1, 0, 0, 0)) + jar.writestr(entry, path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED) diff --git a/java/junit-runner/openidea-junit-runner.jar b/java/junit-runner/openidea-junit-runner.jar new file mode 100644 index 000000000..c9d74763b Binary files /dev/null and b/java/junit-runner/openidea-junit-runner.jar differ diff --git a/java/junit-runner/src/ai/openidea/junit/Runner.java b/java/junit-runner/src/ai/openidea/junit/Runner.java new file mode 100644 index 000000000..bf2352e1b --- /dev/null +++ b/java/junit-runner/src/ai/openidea/junit/Runner.java @@ -0,0 +1,198 @@ +package ai.openidea.junit; + +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.platform.engine.DiscoverySelector; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.TestSource; +import org.junit.platform.engine.discovery.DiscoverySelectors; +import org.junit.platform.engine.reporting.ReportEntry; +import org.junit.platform.engine.support.descriptor.ClassSource; +import org.junit.platform.engine.support.descriptor.MethodSource; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.TestPlan; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the JUnit Platform tests given as arguments ({@code com.acme.OrderTest} or + * {@code com.acme.OrderTest#method}) and reports each test as the TeamCity service messages + * OpenIDEA's Gradle test init script prints ({@code gradleTests.gradle}). Exits with 1 when a + * test failed. + */ +public final class Runner implements TestExecutionListener { + private final PrintStream out; + private final Map started = new HashMap<>(); + private TestPlan plan; + private int tests; + private int failed; + private int skipped; + + private Runner(PrintStream out) { + this.out = out; + } + + public static void main(String[] args) throws UnsupportedEncodingException { + // The original stdout: JUnit replaces System.out while it captures a test's output. + PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out), true, "UTF-8"); + List selectors = new ArrayList<>(); + for (String arg : args) selectors.addAll(selectors(arg)); + Runner runner = new Runner(out); + Launcher launcher = LauncherFactory.create(); + launcher.execute( + LauncherDiscoveryRequestBuilder.request() + .selectors(selectors) + .configurationParameter("junit.platform.output.capture.stdout", "true") + .configurationParameter("junit.platform.output.capture.stderr", "true") + .build(), + runner); + StringBuilder summary = new StringBuilder().append(runner.tests).append(runner.tests == 1 ? " test" : " tests"); + summary.append(" completed"); + if (runner.failed > 0) summary.append(", ").append(runner.failed).append(" failed"); + if (runner.skipped > 0) summary.append(", ").append(runner.skipped).append(" skipped"); + out.println(summary); + out.flush(); + System.exit(runner.failed > 0 || runner.tests == 0 ? 1 : 0); + } + + /** Every method named {@code method} (parameterized ones too); the class when there is none. */ + static List selectors(String arg) { + int hash = arg.indexOf('#'); + List out = new ArrayList<>(); + if (hash < 0) { + out.add(DiscoverySelectors.selectClass(arg)); + return out; + } + String className = arg.substring(0, hash); + String name = arg.substring(hash + 1); + try { + Class type = Class.forName(className, false, Thread.currentThread().getContextClassLoader()); + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + for (Method m : c.getDeclaredMethods()) { + if (m.getName().equals(name) && !m.isSynthetic()) out.add(DiscoverySelectors.selectMethod(type, m)); + } + if (!out.isEmpty()) break; + } + } catch (ClassNotFoundException | LinkageError e) { + // Discovery reports the missing class. + } + if (out.isEmpty()) out.add(DiscoverySelectors.selectClass(className)); + return out; + } + + @Override + public void testPlanExecutionStarted(TestPlan testPlan) { + plan = testPlan; + } + + @Override + public void executionStarted(TestIdentifier id) { + if (!id.isTest()) return; + started.put(id.getUniqueId(), System.currentTimeMillis()); + message("testStarted", id(id)); + } + + @Override + public void executionSkipped(TestIdentifier id, String reason) { + List skippedTests = new ArrayList<>(); + if (id.isTest()) skippedTests.add(id); + else for (TestIdentifier d : plan.getDescendants(id)) if (d.isTest()) skippedTests.add(d); + for (TestIdentifier test : skippedTests) { + tests++; + skipped++; + message("testStarted", id(test)); + message("testIgnored", id(test) + attr("message", reason)); + message("testFinished", id(test) + attr("duration", "0")); + } + } + + @Override + public void executionFinished(TestIdentifier id, TestExecutionResult result) { + TestExecutionResult.Status status = result.getStatus(); + if (!id.isTest()) { + // A class whose set-up failed (`@BeforeAll`): reported as a test, like JUnit 4's initializationError. + Optional className = className(id); + if (status != TestExecutionResult.Status.FAILED || !className.isPresent()) return; + String own = attr("name", "initializationError") + attr("className", className.get()); + message("testStarted", own); + failed(own, result); + message("testFinished", own + attr("duration", "0")); + tests++; + return; + } + tests++; + String own = id(id); + if (status == TestExecutionResult.Status.FAILED) failed(own, result); + else if (status == TestExecutionResult.Status.ABORTED) { + skipped++; + message("testIgnored", own); + } + Long start = started.remove(id.getUniqueId()); + long duration = start == null ? 0 : System.currentTimeMillis() - start; + message("testFinished", own + attr("duration", Long.toString(duration))); + } + + @Override + public void reportingEntryPublished(TestIdentifier id, ReportEntry entry) { + for (Map.Entry e : entry.getKeyValuePairs().entrySet()) { + String kind = e.getKey().equals("stdout") ? "testStdOut" : e.getKey().equals("stderr") ? "testStdErr" : null; + if (kind == null) continue; + // A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name. + String own = id.isTest() ? id(id) : className(id).map(c -> attr("className", c)).orElse(null); + if (own != null) message(kind, own + attr("out", e.getValue())); + } + } + + private void failed(String own, TestExecutionResult result) { + failed++; + Throwable error = result.getThrowable().orElse(null); + StringWriter trace = new StringWriter(); + if (error != null) error.printStackTrace(new PrintWriter(trace)); + message("testFailed", own + attr("message", error == null ? "" : error.toString()) + attr("details", trace.toString())); + } + + /** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */ + private String id(TestIdentifier id) { + for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) { + TestSource source = at.getSource().orElse(null); + if (source instanceof MethodSource) { + MethodSource m = (MethodSource) source; + return attr("name", m.getMethodName()) + attr("className", m.getClassName()); + } + if (source instanceof ClassSource) + return attr("name", id.getLegacyReportingName()) + attr("className", ((ClassSource) source).getClassName()); + } + return attr("name", id.getLegacyReportingName()) + attr("className", id.getDisplayName()); + } + + private Optional className(TestIdentifier id) { + TestSource source = id.getSource().orElse(null); + return source instanceof ClassSource ? Optional.of(((ClassSource) source).getClassName()) : Optional.empty(); + } + + private void message(String kind, String attrs) { + out.println("##teamcity[" + kind + attrs + "]"); + } + + private static String attr(String name, String value) { + return " " + name + "='" + escape(value) + "'"; + } + + static String escape(String s) { + if (s == null) return ""; + return s.replace("|", "||").replace("'", "|'").replace("\n", "|n").replace("\r", "|r") + .replace("[", "|[").replace("]", "|]"); + } +} diff --git a/java/junit-runner/tests/SampleTest.java b/java/junit-runner/tests/SampleTest.java new file mode 100644 index 000000000..7a071316c --- /dev/null +++ b/java/junit-runner/tests/SampleTest.java @@ -0,0 +1,43 @@ +package sample; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class SampleTest { + @Test + void passes() { + System.out.println("hello [ünï]"); + } + + @Test + void fails() { + assertEquals(1, 2, "it's wrong"); + } + + @Test + @Disabled + void disabled() {} + + @Test + void aborted() { + assumeTrue(false); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void parameterized(int n) { + assertEquals(1, n); + } + + @Nested + class Inner { + @Test + void nested() {} + } +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index e4fcacb02..d2301e8a6 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -336,6 +336,7 @@ inspect_code trusted project_host bin java_build_workspace trusted project_host bindings async java_debug_adapter trusted project_host bindings sync java_debug_server trusted project_host bindings async +java_junit_runner trusted project_host bindings async java_resolve_launch trusted project_host bindings async jdk_download always project_host bindings async jdk_download_location always project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index 7a67e7c9f..578e0a928 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -828,6 +828,13 @@ export const commands = { javaDebugAdapter: (module: string) => typedError(__TAURI_INVOKE("java_debug_adapter", { module })), /** Port of java-debug's DAP server inside the jdtls serving `module` (started on demand). */ javaDebugServer: (module: string) => typedError(__TAURI_INVOKE("java_debug_server", { module })), + /** + * The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath: + * the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the + * classpath has one; from the engine's repository, else downloaded once from Maven Central), and, + * for a Maven module, what its Surefire configuration gives the forked test JVM. + */ + javaJunitRunner: (module: string, classPaths: string[]) => typedError(__TAURI_INVOKE("java_junit_runner", { module, classPaths })), /** * Cancellable with `cancel_request(request)`. * Builds according to `policy`, then resolves the runtime (or test) @@ -8715,6 +8722,17 @@ export type JsResponseRule = { body: string, }; +/** The test JVM of OpenIDEA's JUnit runner. */ +export type JunitLaunch = { + classPaths: string[], + /** Surefire's `argLine`, then its system properties as `-Dkey=value`. */ + vmArgs: string[], + env: { [key in string]: string }, + workingDirectory: string | null, + /** The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console. */ + surefire: string[], +}; + /** The backend that reads a debugged JVM's objects (instances, fields, referrers). */ export type JvmBackendState = { kind: "ready" } | /** Turned off for the rest of the session: the debug adapter lacks what it needs. */ @@ -9553,6 +9571,16 @@ export type MavenProject = { env: { [key in string]: string }, }; +/** + * Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build + * and run actions are delegated to Maven. + */ +export type MavenRunTestsUsing = +/** OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`). */ +"ide" | +/** Surefire (`mvn test -Dtest=…`). */ +"maven"; + /** Build Tools › Maven. */ export type MavenSettings = { /** JDK home used to run Maven; empty = Project JDK, else the POM's Java version. */ @@ -9603,6 +9631,8 @@ export type MavenSettings = { * dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`). */ updateSnapshots?: boolean, + /** Who runs the JUnit 5 tests of the gutter's Run / Debug. */ + runTestsUsing?: MavenRunTestsUsing, }; /** What keeps an idle background project loaded. */ diff --git a/src/features/run/application.ts b/src/features/run/application.ts index 488d62daa..3cf095678 100644 --- a/src/features/run/application.ts +++ b/src/features/run/application.ts @@ -1,10 +1,12 @@ /** * IDEA-style "Application" run configurations for Java / Kotlin main classes * (Spring Boot applications get their own kind), the module a source file - * belongs to, and test configurations scoped to one class or method. + * belongs to, and test configurations scoped to one class or method: through Maven / Gradle, + * or for JUnit 5 in a Maven module, OpenIDEA's own runner (Settings › Maven › Run tests using). */ import type { RunConfig } from "@/platform/ipc"; -import { CLASSPATH, TEST_CLASSPATH, jvmModuleDir } from "@/platform/javaLaunch"; +import { CLASSPATH, JUNIT_RUNNER_MAIN, TEST_CLASSPATH, jvmModuleDir, parseJavaArgs } from "@/platform/javaLaunch"; +import { useProject } from "@/platform/project"; import { isTestPath, rootFor } from "@/platform/languageSettings"; import { currentRoots } from "@/platform/projectRoots"; import { simpleClassName } from "./jvmTargets"; @@ -81,3 +83,41 @@ export function jvmTestConfig(fileConfig: RunConfig, className: string, method: } return null; } + +/** A test file of JUnit Jupiter (JUnit 5): OpenIDEA's runner handles JUnit Platform engines only. */ +const JUPITER_IMPORT = /^\s*import\s+(?:static\s+)?org\.junit\.jupiter\./m; + +/** Settings › Build Tools › Maven › Run tests using: OpenIDEA (the default), not Surefire. */ +export function runsJunitInIde(fileConfig: RunConfig, content: string | undefined): boolean { + if (fileConfig.kind !== "maven" || !content || !JUPITER_IMPORT.test(content)) return false; + return useProject.getState().settings?.languages?.java?.maven?.runTestsUsing !== "maven"; +} + +/** + * A test class (`method` unset) or method run by OpenIDEA's JUnit Platform runner on the module's + * test classpath, like IDEA's JUnit configurations: `java -ea -cp ${testClasspath} Class#method`. + * Its working directory is the module's, as Surefire's. + */ +export function junitRunnerConfig( + className: string, + method: string | undefined, + relPath: string, + configs: readonly RunConfig[], +): RunConfig { + const app = applicationConfig({ className }, relPath, configs); + const selector = `${className}${method ? `#${method}` : ""}`; + const simple = simpleClassName(className); + return { + ...app, + id: `junit:${app.module ? `${app.module}:` : ""}${selector}`, + name: method ? `${simple}.${method}` : simple, + args: ["-ea", "-cp", TEST_CLASSPATH, JUNIT_RUNNER_MAIN, selector], + cwd: app.module || null, + isTest: true, + }; +} + +/** A configuration run by OpenIDEA's JUnit runner (its arguments after the main class select the tests). */ +export function isJunitRunner(config: Pick): boolean { + return config.kind === "application" && parseJavaArgs(config.args).mainClass === JUNIT_RUNNER_MAIN; +} diff --git a/src/features/run/gradleRun.ts b/src/features/run/gradleRun.ts index 7192d5d64..d34fcc16a 100644 --- a/src/features/run/gradleRun.ts +++ b/src/features/run/gradleRun.ts @@ -180,7 +180,7 @@ export async function gradleBootLaunch(config: T): Promise< * modules; null to launch it on the language server's classpath. */ export async function gradleDelegation(config: RunConfig): Promise { - if (!isTauri() || !isJvmApplication(config)) return null; + if (!isTauri() || !isJvmApplication(config) || config.isTest) return null; const { project, settings } = useProject.getState(); if (!project?.root || settings?.languages?.java?.gradle?.runUsing === "ide") return null; const { model, gradleOffline } = useBuildModel.getState(); diff --git a/src/features/run/java.test.ts b/src/features/run/java.test.ts index 35eb29ec4..526046d30 100644 --- a/src/features/run/java.test.ts +++ b/src/features/run/java.test.ts @@ -12,6 +12,8 @@ import { import { usePlatform } from "@/platform/platformInfo"; import { useProject } from "@/platform/project"; import { applicationConfig, jvmModuleDir, jvmTestConfig } from "./application"; +import { frameworkFor } from "./testing"; +import { rerunFailedConfig } from "./testing/rerun"; import { buildRows } from "./ConfigChooser"; import { jdwpLaunch } from "./javaDebug"; import { DELEGATED_DEBUG } from "./gradleRun"; @@ -288,6 +290,65 @@ describe("application configurations", () => { }); }); +describe("JUnit 5 through OpenIDEA's runner (Maven › Run tests using)", () => { + const rel = "shop/src/test/java/a/OrderTest.java"; + const jupiter = `package a; +import org.junit.jupiter.api.Test; +class OrderTest { + @Test + void adds() {} +}`; + const junit4 = jupiter.replace("org.junit.jupiter.api.Test", "org.junit.Test"); + const maven = [cfg({ id: "maven:test", kind: "maven", args: ["test"], cwd: "shop", isTest: true })]; + const gradle = [cfg({ id: "gradle:test", kind: "gradle", args: ["test"], cwd: "shop", isTest: true })]; + const target = (src: string, name: string) => + detectRunTargets(src, rel).find((t) => t.path.at(-1) === name || t.name === name)!; + const useTests = (runTestsUsing: "ide" | "maven" | undefined) => + useProject.setState({ + settings: runTestsUsing ? { languages: { java: { maven: { runTestsUsing } } } } : undefined, + } as never); + beforeEach(() => useTests(undefined)); + + it("runs a method or class of a Maven module with the runner on the test classpath, without Maven", () => { + expect(targetConfig(target(jupiter, "adds"), rel, maven, jupiter)).toMatchObject({ + id: "junit:shop:a.OrderTest#adds", + name: "OrderTest.adds", + kind: "application", + command: "java", + args: ["-ea", "-cp", "${testClasspath}", "ai.openidea.junit.Runner", "a.OrderTest#adds"], + module: "shop", + cwd: "shop", + isTest: true, + debugAdapter: "java-debug", + }); + expect(targetConfig(target(jupiter, "OrderTest"), rel, maven, jupiter)!.args.at(-1)).toBe("a.OrderTest"); + }); + + it("keeps Surefire for the Maven setting, JUnit 4 and Gradle", () => { + useTests("maven"); + expect(targetConfig(target(jupiter, "adds"), rel, maven, jupiter)!.kind).toBe("maven"); + useTests("ide"); + expect(targetConfig(target(junit4, "adds"), rel, maven, junit4)!.kind).toBe("maven"); + expect(targetConfig(target(jupiter, "adds"), rel, gradle, jupiter)!.kind).toBe("gradle"); + }); + + it("reports through the JVM parser, debugs with a waiting agent and reruns failed tests by selector", () => { + const config = targetConfig(target(jupiter, "OrderTest"), rel, maven, jupiter)!; + expect(frameworkFor(config)).toBe("jvm"); + expect(jdwpLaunch(config)!.args).toEqual([JDWP_AGENT, ...config.args]); + const failed = rerunFailedConfig(config, [["a.OrderTest", "adds"], ["a.OrderTest$Nested", "b"], ["a.Other"]]); + expect((failed as RunConfig).args).toEqual([ + "-ea", + "-cp", + "${testClasspath}", + "ai.openidea.junit.Runner", + "a.OrderTest#adds", + "a.OrderTest$Nested#b", + "a.Other", + ]); + }); +}); + describe("java compile errors", () => { const base: Omit = { build: "withErrors", diff --git a/src/features/run/javaDebug.ts b/src/features/run/javaDebug.ts index 8c0d1aab8..de0894bbf 100644 --- a/src/features/run/javaDebug.ts +++ b/src/features/run/javaDebug.ts @@ -20,6 +20,7 @@ import { } from "@/platform/javaLaunch"; import { applyBuildPolicyToCommand } from "./buildCommand"; import { startRun, useRun } from "./store"; +import { isJunitRunner } from "./application"; import { DELEGATED_ATTACH_LISTENER, DELEGATED_DEBUG, DELEGATED_MAIN } from "./gradleRun"; import { isWindows } from "./jvmTypes"; @@ -112,6 +113,8 @@ export function jdwpLaunch(config: RunConfig, jdwpPort?: number): RunConfig | nu if (!args.some(isGradleJvmTask)) return null; return args.includes("--debug-jvm") ? config : { ...config, args: [...args, "--debug-jvm"] }; } + // OpenIDEA's JUnit runner keeps its test tree in the Run tab: the agent waits there, the debugger attaches. + if (isJunitRunner(config)) return { ...config, args: [JDWP_AGENT, ...args] }; // Application / Spring Boot configurations are launched by java-debug itself. if (JVM_ADAPTERS.includes(config.debugAdapter ?? "") && !isJvmApplication(config)) return { diff --git a/src/features/run/javaModule.test.ts b/src/features/run/javaModule.test.ts index 90acadff4..24959da37 100644 --- a/src/features/run/javaModule.test.ts +++ b/src/features/run/javaModule.test.ts @@ -29,6 +29,7 @@ const ipc = vi.hoisted(() => { projectRoot: "/p", classPaths: ["/p/app/target/classes"], modulePaths: [], + pathListSeparator: ":", javaHome: null, javaExec: "java", shortenCommandLine: null, @@ -37,6 +38,15 @@ const ipc = vi.hoisted(() => { hints: [], }), ), + javaJunitRunner: vi.fn(() => + ok({ + classPaths: ["/p/app/target/test-classes", "/runner.jar"], + vmArgs: ["-Xmx1g", "-Dopenidea.fail=true"], + env: { TZ: "UTC" }, + workingDirectory: "/p/app/work", + surefire: ["argLine", "systemPropertyVariables"], + }), + ), }; }); vi.mock("@/platform/ipc", async (original) => { @@ -310,3 +320,30 @@ it("does not resolve or launch when saving fails", async () => { expect(ipc.javaResolveLaunch).not.toHaveBeenCalled(); expect(ipc.runStart).not.toHaveBeenCalled(); }); + +it("gives the JUnit runner's JVM the module's Surefire configuration", async () => { + const report = vi.fn(); + const junit: RunConfig = { + ...config, + module: "app", + isTest: true, + args: ["-ea", "-cp", "${testClasspath}", "ai.openidea.junit.Runner", "a.MainTest#adds"], + env: { TZ: "Europe/Paris" }, + }; + const { resolved } = await prepareJavaLaunch(junit, { request: 1, signal: new AbortController().signal, report }); + expect(ipc.javaJunitRunner).toHaveBeenCalledWith("app", ["/p/app/target/classes"]); + expect(resolved).toMatchObject({ + args: [ + "-Xmx1g", + "-Dopenidea.fail=true", + "-ea", + "-cp", + "/p/app/target/test-classes:/runner.jar", + "ai.openidea.junit.Runner", + "a.MainTest#adds", + ], + env: { TZ: "Europe/Paris" }, + cwd: "/p/app/work", + }); + expect(report).toHaveBeenCalledWith("Applying the Surefire configuration: argLine, systemPropertyVariables\n"); +}); diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts index 0b0c3577e..6e1b61b19 100644 --- a/src/features/run/targets.ts +++ b/src/features/run/targets.ts @@ -10,7 +10,7 @@ import { goTargets } from "./goTargets"; import { csharpTargets } from "./csharpTargets"; import { formatArgs } from "./configs"; import type { RunConfig } from "@/platform/ipc"; -import { applicationConfig, jvmTestConfig } from "./application"; +import { applicationConfig, junitRunnerConfig, jvmTestConfig, runsJunitInIde } from "./application"; import { goTestParts, withoutGoSelection } from "./goArguments"; import { contextConfig, relToCwd, testConfigFor } from "./context"; import { djangoLabel, djangoTestsOf } from "./djangoTypes"; @@ -466,12 +466,12 @@ export function targetConfig( } const file = testConfigFor(relPath, configs, base, content); if (!file) return null; - if (target.className && (file.kind === "maven" || file.kind === "gradle")) - return jvmTestConfig( - file, - target.className, - target.kind === "test" ? target.path[target.path.length - 1] : undefined, - ); + if (target.className && (file.kind === "maven" || file.kind === "gradle")) { + const method = target.kind === "test" ? target.path[target.path.length - 1] : undefined; + return runsJunitInIde(file, content) + ? junitRunnerConfig(target.className, method, relPath, configs) + : jvmTestConfig(file, target.className, method); + } const shortName = target.kind === "suite" ? target.path[target.path.length - 1]! : target.name; const named = (args: string[]): RunConfig => ({ ...file, diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 3b5b7cd33..52f5064ac 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -1,5 +1,6 @@ /** Picks the test output parser for a run configuration. */ import type { RunConfig } from "@/platform/ipc"; +import { isJunitRunner } from "../application"; import { cargoParser } from "./cargo"; import { goParser } from "./go"; import { jsParser } from "./js"; @@ -66,6 +67,7 @@ export function frameworkFor(config: FrameworkConfig): Framework { if (config.testRunner === "node-test" || /(^|[\s/\\])(node|tsx)(\.exe)?(\s+-\S*)*\s+--test(\s|$)/.test(cmd)) return "node-test"; if (config.testRunner === "mocha" || /(^|[\s/\\])_?mocha(\.cmd|\.js)?(\s|$)/.test(cmd)) return "mocha"; + if (isJunitRunner(config)) return "jvm"; switch (config.kind) { case "dotnet-test": return "dotnet"; diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index 6bc0e4bbe..4768d9b63 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -6,6 +6,8 @@ import { selectPluginTests } from "@/workbench/contributions"; import { phpunitArgs, phpunitFilter } from "./phpunit"; import type { RunConfig } from "@/platform/ipc"; import { formatArgs, parseArgs } from "../configs"; +import { isJunitRunner } from "../application"; +import { JUNIT_RUNNER_MAIN } from "@/platform/javaLaunch"; import { appendScriptArgs } from "../scriptArgs"; import { djangoTestsOf } from "../djangoTypes"; import { goTestParts, withoutGoSelection } from "../goArguments"; @@ -151,6 +153,10 @@ function jvmArgs(config: RunConfig, paths: string[][]): string[] | null { .map((p) => ({ cls: p[0]!, method: p[p.length - 1]!.replace(/\(\)$/, "") })); const classes = unique(paths.filter((p) => p.length === 1).map((p) => p[0]!)); if (!tests.length && !classes.length) return null; + if (isJunitRunner(config)) { + const runner = config.args.slice(0, config.args.indexOf(JUNIT_RUNNER_MAIN) + 1); + return [...runner, ...unique(tests.map((t) => `${t.cls}#${t.method}`)), ...classes]; + } if (config.kind === "maven" || /\bmvnw?\b/.test(config.command)) { const byClass = new Map(); for (const t of tests) byClass.set(t.cls, [...(byClass.get(t.cls) ?? []), t.method]); diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts index 790ed555a..2a771ebf3 100644 --- a/src/features/settings/__tests__/languages.test.ts +++ b/src/features/settings/__tests__/languages.test.ts @@ -66,6 +66,7 @@ describe("languages settings", () => { delegateBuild: false, downloadSources: false, updateSnapshots: false, + runTestsUsing: "ide", }); expect(validateSettings({}).languages).toEqual(DEFAULT_LANGUAGES); expect(validateLanguages({ java: { maven: { threads: 4 } } }).java.maven.threads).toBe(""); @@ -79,6 +80,8 @@ describe("languages settings", () => { expect(validateLanguages({ java: { maven: { delegateBuild: "yes" } } }).java.maven.delegateBuild).toBe(false); expect(validateLanguages({ java: { maven: { downloadSources: true } } }).java.maven.downloadSources).toBe(true); expect(validateLanguages({ java: { maven: { updateSnapshots: true } } }).java.maven.updateSnapshots).toBe(true); + expect(validateLanguages({ java: { maven: { runTestsUsing: "maven" } } }).java.maven.runTestsUsing).toBe("maven"); + expect(validateLanguages({ java: { maven: { runTestsUsing: "gradle" } } }).java.maven.runTestsUsing).toBe("ide"); const settings = validateSettings({ languages: { java: { maven: { runnerJre: " ./jdks/21 " } } } }); expect(validateSettings(settings).languages.java.maven.runnerJre).toBe("./jdks/21"); }); diff --git a/src/features/settings/languages/LanguagePages.tsx b/src/features/settings/languages/LanguagePages.tsx index 3b1dd890a..c9abbb048 100644 --- a/src/features/settings/languages/LanguagePages.tsx +++ b/src/features/settings/languages/LanguagePages.tsx @@ -579,6 +579,7 @@ export function GradlePage() { export function MavenPage() { const [delegateBuild, setDelegateBuild] = useSetting("languages.java.maven.delegateBuild"); + const [runTestsUsing, setRunTestsUsing] = useSetting("languages.java.maven.runTestsUsing"); const [daemon, setDaemon] = useSetting("languages.java.maven.daemon"); const [downloadSources, setDownloadSources] = useSetting("languages.java.maven.downloadSources"); const [updateSnapshots, setUpdateSnapshots] = useSetting("languages.java.maven.updateSnapshots"); @@ -674,6 +675,20 @@ export function MavenPage() { onChange={setDelegateBuild} hint="Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server." /> + +