From 18674dc6f48e8ef13da4f73bb6abbdae21bc828c Mon Sep 17 00:00:00 2001 From: fwrq41251 <6220591+fwrq41251@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:17:40 +0900 Subject: [PATCH 1/2] Add Java test gutter debugging --- README.md | 26 ++- debug_adapter_schemas/Java.json | 12 + languages/java/tasks.json | 6 + proxy/src/http.rs | 42 +++- proxy/src/main.rs | 1 + proxy/src/test_runner.rs | 168 ++++++++++++++ src/debug_locator.rs | 64 +++++- src/debugger.rs | 112 ++++++++-- src/java.rs | 39 ++-- src/jdtls_server.rs | 43 +++- src/test_debugger.rs | 380 ++++++++++++++++++++++++++++++++ src/test_support.rs | 123 +++++++++++ 12 files changed, 960 insertions(+), 56 deletions(-) create mode 100644 proxy/src/test_runner.rs create mode 100644 src/test_debugger.rs create mode 100644 src/test_support.rs diff --git a/README.md b/README.md index 049f309..ad6fc29 100644 --- a/README.md +++ b/README.md @@ -155,8 +155,7 @@ mapping. If you disable the built-in Java tasks and provide your own main-method task, add `"ZED_JAVA_RUNNABLE": "main"` to that task's `env` object to opt in. Its environment variables are forwarded to the debug configuration, excluding the -locator's `ZED_JAVA_RUNNABLE` and `ZED_JAVA_MAIN_CLASS` metadata. Test runnables -are not handled by this locator. +locator's `ZED_JAVA_RUNNABLE` and `ZED_JAVA_MAIN_CLASS` metadata. ### Main methods with JDTLS @@ -224,6 +223,29 @@ installation, and its DAP proxy to be enabled. The Scala extension's [debugging documentation](https://github.com/scalameta/metals-zed#debugging) describes its setup and restrictions. +### Test gutter actions + +Test method and class tasks use the `ZED_JAVA_RUNNABLE=test-method` and +`ZED_JAVA_RUNNABLE=test-class` markers. Their existing Run commands are preserved. +The locator creates a `testTarget` containing the source file, class, optional +outer class, and optional method. Discovery and compilation happen only when +you select Debug; creating the gutter action does not contact a language server. +Project-wide test tasks are not converted to debug scenarios. + +With JDTLS, the first test debug launch downloads the pinned Microsoft Java Test +Runner. The extension loads the bundles into the running language server, discovers +tests in the selected file, and resolves the framework's launch arguments. JUnit +methods use their JDT handles, including parameter types. +TestNG uses its bundled runner. A local callback socket receives the test runner's +result protocol; this does not provide a test-results explorer. Build failures, +missing targets, and ambiguous method names stop the launch. + +Test gutter debugging is available with the `Java` adapter. All invocations of a +parameterized method are selected together. + +Custom project tasks that replace the built-in Java tasks must also include the +appropriate marker. Select `Java` in `languages.Java.debuggers` for test debugging. + ### Debugging with JDTLS Debug support is enabled via our [Fork of Java Debug](https://github.com/zed-industries/java-debug), which the extension will automatically download and start for you. Please refer to the [Zed Documentation](https://zed.dev/docs/debugger#getting-started) for general information about how debugging works in Zed. diff --git a/debug_adapter_schemas/Java.json b/debug_adapter_schemas/Java.json index 56d0d8c..195081e 100644 --- a/debug_adapter_schemas/Java.json +++ b/debug_adapter_schemas/Java.json @@ -22,6 +22,18 @@ "type": "string", "description": "The absolute path to a Java source file. Use $ZED_FILE for the currently focused Java source file. Resolves the main class and project from this file and builds before launch. Use mainClass and projectName to disambiguate multiple entries." }, + "testTarget": { + "type": "object", + "description": "Resolve a test class or method from its source file when debugging starts. Requires the bundled Java Test Runner with JDTLS.", + "properties": { + "file": { "type": "string" }, + "className": { "type": "string" }, + "outerClass": { "type": "string" }, + "method": { "type": "string" } + }, + "required": ["file", "className"], + "additionalProperties": false + }, "args": { "oneOf": [ { diff --git a/languages/java/tasks.json b/languages/java/tasks.json index c0e7b8b..128cfc2 100644 --- a/languages/java/tasks.json +++ b/languages/java/tasks.json @@ -29,6 +29,9 @@ "java-test-method", "java-test-method-nested" ], + "env": { + "ZED_JAVA_RUNNABLE": "test-method" + }, "shell": { "with_arguments": { "program": "/bin/sh", @@ -47,6 +50,9 @@ "java-test-class", "java-test-class-nested" ], + "env": { + "ZED_JAVA_RUNNABLE": "test-class" + }, "shell": { "with_arguments": { "program": "/bin/sh", diff --git a/proxy/src/http.rs b/proxy/src/http.rs index 3bed463..b94271a 100644 --- a/proxy/src/http.rs +++ b/proxy/src/http.rs @@ -24,8 +24,19 @@ struct HttpBody { impl HttpBody { fn timeout(&self) -> Duration { if self.method == "workspace/executeCommand" - && self.params.get("command").and_then(Value::as_str) - == Some("vscode.java.buildWorkspace") + && self + .params + .get("command") + .and_then(Value::as_str) + .is_some_and(|command| { + matches!( + command, + "vscode.java.buildWorkspace" + | "java.reloadBundles" + | "vscode.java.test.findTestTypesAndMethods" + | "vscode.java.test.junit.argument" + ) + }) { BUILD_TIMEOUT } else { @@ -91,6 +102,27 @@ pub fn handle_http( } }; + if req.method == "zed/javaTestRunner/start" { + let result = req.params["adapterPort"] + .as_u64() + .and_then(|port| u16::try_from(port).ok()) + .filter(|port| *port > 0) + .ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid DAP port") + }) + .and_then(crate::test_runner::start); + let response = match result { + Ok((dap_port, result_port)) => serde_json::json!({ + "result": { "dapPort": dap_port, "resultPort": result_port } + }), + Err(error) => serde_json::json!({ + "error": { "code": -32603, "message": error.to_string() } + }), + }; + write_response(&mut stream, &response); + return; + } + let seq = counter.fetch_add(1, Ordering::Relaxed); let id = Value::String(format!("{owned_id_prefix}http-{seq}")); let rx = pending.register(id.clone()); @@ -147,7 +179,11 @@ pub fn handle_http( }) }; - let resp_body = serde_json::to_vec(&response).unwrap(); + write_response(&mut stream, &response); +} + +fn write_response(stream: &mut std::net::TcpStream, response: &Value) { + let resp_body = serde_json::to_vec(response).unwrap(); let http_resp = format!( "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", resp_body.len() diff --git a/proxy/src/main.rs b/proxy/src/main.rs index 81af88e..3fb369b 100644 --- a/proxy/src/main.rs +++ b/proxy/src/main.rs @@ -4,6 +4,7 @@ mod http; mod log; mod output; mod pending; +mod test_runner; use completions::{process_completions, sanitize_resolved_completion}; use decompile::{DecompileCoordinator, Priority, RewriteJob, RewriteMode, SharedWriter}; diff --git a/proxy/src/test_runner.rs b/proxy/src/test_runner.rs new file mode 100644 index 0000000..ec8ac1a --- /dev/null +++ b/proxy/src/test_runner.rs @@ -0,0 +1,168 @@ +use std::{ + io::{self, Read}, + net::{Shutdown, TcpListener, TcpStream}, + sync::atomic::{AtomicBool, Ordering}, + thread, + time::{Duration, Instant}, +}; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +const POLL_INTERVAL: Duration = Duration::from_millis(25); + +pub fn start(adapter_port: u16) -> io::Result<(u16, u16)> { + let dap = bind_listener()?; + let results = bind_listener()?; + let ports = (dap.local_addr()?.port(), results.local_addr()?.port()); + thread::Builder::new() + .name("java-test-session".into()) + .spawn(move || { + if let Err(error) = serve(dap, results, adapter_port, CONNECT_TIMEOUT) { + crate::lsp_warn!("Java test session ended: {error}"); + } + })?; + Ok(ports) +} + +fn bind_listener() -> io::Result { + let listener = TcpListener::bind("127.0.0.1:0")?; + listener.set_nonblocking(true)?; + Ok(listener) +} + +fn accept(listener: TcpListener, keep_waiting: impl Fn() -> bool) -> io::Result> { + while keep_waiting() { + match listener.accept() { + Ok((stream, _)) => { + stream.set_nonblocking(false)?; + return Ok(Some(stream)); + } + Err(error) if error.kind() == io::ErrorKind::WouldBlock => { + thread::sleep(POLL_INTERVAL); + } + Err(error) => return Err(error), + } + } + Ok(None) +} + +fn serve( + dap: TcpListener, + results: TcpListener, + adapter_port: u16, + timeout: Duration, +) -> io::Result<()> { + let deadline = Instant::now() + timeout; + let Some(editor) = accept(dap, || Instant::now() < deadline)? else { + return Ok(()); + }; + let adapter = TcpStream::connect_timeout(&([127, 0, 0, 1], adapter_port).into(), timeout)?; + let finished = AtomicBool::new(false); + thread::scope(|scope| { + scope.spawn(|| { + if let Err(error) = drain_results(results, &finished) { + crate::lsp_warn!("Java test result connection ended: {error}"); + } + }); + let result = relay(&editor, &adapter); + finished.store(true, Ordering::Relaxed); + result + }) +} + +fn relay(editor: &TcpStream, adapter: &TcpStream) -> io::Result<()> { + editor.set_nodelay(true)?; + adapter.set_nodelay(true)?; + thread::scope(|scope| { + let request = scope.spawn(|| forward(editor, adapter)); + let response = forward(adapter, editor); + let request = request.join().unwrap(); + response.and(request) + }) +} + +fn forward(mut source: &TcpStream, mut destination: &TcpStream) -> io::Result<()> { + let result = io::copy(&mut source, &mut destination).map(|_| ()); + let _ = source.shutdown(Shutdown::Both); + let _ = destination.shutdown(Shutdown::Both); + result +} + +fn drain_results(listener: TcpListener, finished: &AtomicBool) -> io::Result<()> { + let active = || !finished.load(Ordering::Relaxed); + let Some(mut stream) = accept(listener, active)? else { + return Ok(()); + }; + stream.set_read_timeout(Some(POLL_INTERVAL))?; + let mut buffer = [0; 4096]; + while active() { + match stream.read(&mut buffer) { + Ok(0) => break, + Ok(_) => {} + Err(error) + if matches!( + error.kind(), + io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock + ) => {} + Err(error) => return Err(error), + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn editor_disconnect_releases_results_with_or_without_a_connected_runner() { + for connect_runner in [false, true] { + let adapter = TcpListener::bind("127.0.0.1:0").unwrap(); + let adapter_port = adapter.local_addr().unwrap().port(); + let dap = bind_listener().unwrap(); + let results = bind_listener().unwrap(); + let address = results.local_addr().unwrap(); + let mut editor = TcpStream::connect(dap.local_addr().unwrap()).unwrap(); + let runner = connect_runner.then(|| TcpStream::connect(address).unwrap()); + let handler = thread::spawn(move || serve(dap, results, adapter_port, CONNECT_TIMEOUT)); + let (mut adapter, _) = adapter.accept().unwrap(); + editor + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + adapter + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut message = [0]; + editor.write_all(b"J").unwrap(); + adapter.read_exact(&mut message).unwrap(); + assert_eq!(&message, b"J"); + adapter.write_all(b"D").unwrap(); + editor.read_exact(&mut message).unwrap(); + assert_eq!(&message, b"D"); + drop(editor); + handler.join().unwrap().unwrap(); + assert!(TcpStream::connect(address).is_err()); + if let Some(mut runner) = runner { + runner + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + match runner.read(&mut message) { + Ok(0) => {} + Err(error) if error.kind() == io::ErrorKind::ConnectionReset => {} + result => panic!("Expected the result connection to close, got {result:?}"), + } + } + } + } + + #[test] + fn both_ports_close_when_editor_never_connects() { + let dap = bind_listener().unwrap(); + let results = bind_listener().unwrap(); + let dap_address = dap.local_addr().unwrap(); + let result_address = results.local_addr().unwrap(); + serve(dap, results, 1, POLL_INTERVAL).unwrap(); + assert!(TcpStream::connect(dap_address).is_err()); + assert!(TcpStream::connect(result_address).is_err()); + } +} diff --git a/src/debug_locator.rs b/src/debug_locator.rs index 8e2e50b..9fe3449 100644 --- a/src/debug_locator.rs +++ b/src/debug_locator.rs @@ -3,17 +3,26 @@ use zed_extension_api::{self as zed, serde_json::json}; const RUNNABLE_ENV: &str = "ZED_JAVA_RUNNABLE"; const MAIN_CLASS_ENV: &str = "ZED_JAVA_MAIN_CLASS"; -#[derive(Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] enum JavaRunnable { Main, + TestMethod, + TestClass, } impl JavaRunnable { fn from_task(task: &zed::TaskTemplate) -> Option { - task.env + match task + .env .iter() - .any(|(name, value)| name == RUNNABLE_ENV && value == "main") - .then_some(Self::Main) + .find(|(name, _)| name == RUNNABLE_ENV) + .map(|(_, value)| value.as_str()) + { + Some("main") => Some(Self::Main), + Some("test-method") => Some(Self::TestMethod), + Some("test-class") => Some(Self::TestClass), + _ => None, + } } fn debug_config(self, debug_adapter_name: &str) -> Option { @@ -27,6 +36,20 @@ impl JavaRunnable { "path": "$ZED_FILE", "runType": "runOrTestFile", })), + (Self::TestMethod | Self::TestClass, "Java") => { + let mut target = json!({ + "file": "$ZED_FILE", + "className": "$ZED_CUSTOM_java_class_name", + "outerClass": "${ZED_CUSTOM_java_outer_class_name:}", + }); + if self == Self::TestMethod { + target["method"] = "$ZED_CUSTOM_java_method_name".into(); + } + Some(json!({ + "request": "launch", + "testTarget": target, + })) + } _ => None, } } @@ -39,7 +62,8 @@ pub fn create_scenario( ) -> Option { let runnable = JavaRunnable::from_task(&build_task)?; let mut config = runnable.debug_config(debug_adapter_name)?; - if debug_adapter_name == "Java" + if runnable == JavaRunnable::Main + && debug_adapter_name == "Java" && let Some((_, main_class)) = build_task .env .iter() @@ -182,14 +206,36 @@ mod tests { #[test] fn test_runnables_are_not_converted_to_main_sessions() { - for runnable in ["test-method", "test-class", "test-all"] { + for runnable in ["test-method", "test-class"] { let mut task = main_task(); task.env = vec![(RUNNABLE_ENV.into(), runnable.into())]; - assert_eq!(JavaRunnable::from_task(&task), None); - for adapter in ["Java", "Metals"] { - assert!(create_scenario(task.clone(), "Test Main".into(), adapter).is_none()); + { + let scenario = create_scenario(task.clone(), "Debug test".into(), "Java").unwrap(); + let config: Value = from_str(&scenario.config).unwrap(); + assert_eq!(config["testTarget"]["file"], "$ZED_FILE"); + assert_eq!( + config["testTarget"]["className"], + "$ZED_CUSTOM_java_class_name" + ); + assert!(config.get("mainFile").is_none()); + assert!(config.get("path").is_none()); + assert_eq!( + config["testTarget"].get("method").is_some(), + runnable == "test-method" + ); } + assert!(create_scenario(task, "Debug test".into(), "Metals").is_none()); + } + } + + #[test] + fn whole_project_test_tasks_are_not_converted() { + let mut task = main_task(); + task.env = vec![(RUNNABLE_ENV.into(), "test-all".into())]; + + for adapter in ["Java", "Metals"] { + assert!(create_scenario(task.clone(), "Run tests".into(), adapter).is_none()); } } diff --git a/src/debugger.rs b/src/debugger.rs index 4c221bc..981dba9 100644 --- a/src/debugger.rs +++ b/src/debugger.rs @@ -1,4 +1,8 @@ -use std::{collections::HashMap, fs, path::PathBuf}; +use std::{ + collections::HashMap, + fs, + path::{Path, PathBuf}, +}; use serde::{Deserialize, Serialize}; use zed_extension_api::{ @@ -13,6 +17,7 @@ use crate::{ config::get_java_debug_jar, downloadable::Downloadable, lsp, + test_debugger::TestTarget, util::{ ArgsStringOrList, create_path_if_not_exists, get_curr_dir, path_to_file_uri, path_to_string, record_successful_update_check, should_use_local_or_download, @@ -26,6 +31,8 @@ struct JavaDebugLaunchConfig { request: String, #[serde(skip_serializing)] main_file: Option, + #[serde(skip_serializing)] + test_target: Option, #[serde(skip_serializing_if = "Option::is_none")] project_name: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -336,7 +343,13 @@ impl Debugger { }) } - pub fn inject_config(&self, worktree: &Worktree, config_string: String) -> zed::Result { + pub fn inject_config( + &self, + worktree: &Worktree, + config_string: String, + test_bundle_host: Option<&Path>, + ) -> zed::Result<(String, TcpArgumentsTemplate)> { + let workspace_folder = worktree.root_path(); let config: Value = serde_json::from_str(&config_string) .map_err(|err| format!("Failed to parse debug config: {err}"))?; @@ -345,21 +358,62 @@ impl Debugger { .and_then(Value::as_str) .is_some_and(|req| req != "launch") { - return Ok(config_string); + return Ok((config_string, self.start_session(&workspace_folder)?)); } let mut config = serde_json::from_value::(config) .map_err(|err| format!("Failed to parse Java debug config: {err}"))?; - let workspace_folder = worktree.root_path(); - - let file_launch = config.prepare_main_file(|command, arguments| { - lsp::request( - &workspace_folder, - "workspace/executeCommand", - json!({ "command": command, "arguments": arguments }), - ) - })?; + let mut connection = None; + + let test_launch = if let Some(target) = &config.test_target { + let runner = crate::test_support::prepare(&workspace_folder, test_bundle_host)?; + let launch = target.resolve(Some(&runner), |command, arguments| { + if command == "zed/javaTestRunner/start" { + let mut template = self.start_session(&workspace_folder)?; + let ports = lsp::request::( + &workspace_folder, + command, + json!({ "adapterPort": template.port }), + )?; + template.port = Some(ports.dap_port); + connection = Some(template); + Ok(json!(ports.result_port)) + } else { + lsp::request( + &workspace_folder, + "workspace/executeCommand", + json!({ "command": command, "arguments": arguments }), + ) + } + })?; + config.main_class = Some( + launch + .main_class + .ok_or("Java test runner main class is missing")?, + ); + config.project_name = Some(launch.project_name); + config.class_paths = Some(launch.classpath); + config.module_paths = Some(launch.modulepath); + config.cwd = config.cwd.or(Some(launch.working_directory)); + config.args = Some(test_arguments( + launch.program_arguments, + config.args.take(), + )?); + config.vm_args = Some(test_arguments(launch.vm_arguments, config.vm_args.take())?); + config.console = Some("internalConsole".into()); + true + } else { + false + }; + let file_launch = test_launch + || config.prepare_main_file(|command, arguments| { + lsp::request( + &workspace_folder, + "workspace/executeCommand", + json!({ "command": command, "arguments": arguments }), + ) + })?; let (main_class, project_name) = if file_launch { (config.main_class.take(), config.project_name.take()) @@ -445,7 +499,11 @@ impl Debugger { .map_err(|err| format!("Failed to stringify debug config: {err}"))? .replace("${workspaceFolder}", &workspace_folder); - Ok(config) + let connection = match connection { + Some(connection) => connection, + None => self.start_session(&workspace_folder)?, + }; + Ok((config, connection)) } pub fn plugin_path(&self) -> Option<&PathBuf> { @@ -492,6 +550,34 @@ impl Debugger { } } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct TestSessionPorts { + dap_port: u16, + result_port: u16, +} + +fn test_arguments( + mut generated: Vec, + extra: Option, +) -> zed::Result { + match extra { + Some(ArgsStringOrList::List(extra)) => { + generated.extend(extra); + Ok(ArgsStringOrList::List(generated)) + } + Some(ArgsStringOrList::String(extra)) => { + let generated = serde_json::to_value(ArgsStringOrList::List(generated)) + .map_err(|error| error.to_string())?; + Ok(ArgsStringOrList::String(format!( + "{} {extra}", + generated.as_str().unwrap_or_default() + ))) + } + None => Ok(ArgsStringOrList::List(generated)), + } +} + impl Downloadable for Debugger { const INSTALL_PATH: &'static str = DEBUGGER_INSTALL_PATH; diff --git a/src/java.rs b/src/java.rs index ac34a12..e4b6849 100644 --- a/src/java.rs +++ b/src/java.rs @@ -11,6 +11,8 @@ mod jdtls_server; mod language_server; mod lsp; mod proxy; +mod test_debugger; +mod test_support; mod util; use std::str::FromStr; @@ -142,6 +144,22 @@ impl Extension for Java { } let workspace = worktree.root_path(); + let request = self + .dap_request_kind( + adapter_name, + Value::from_str(config.config.as_str()) + .map_err(|err| format!("Invalid JSON configuration: {err}"))?, + ) + .map_err(|err| format!("Failed to determine debug request kind: {err}"))?; + let (configuration, connection) = self + .jdtls_server + .debugger + .inject_config( + worktree, + config.config, + self.jdtls_server.test_bundle_host(&workspace), + ) + .map_err(|err| format!("Failed to prepare debug session: {err}"))?; Ok(DebugAdapterBinary { command: None, @@ -149,25 +167,10 @@ impl Extension for Java { cwd: Some(workspace.clone()), envs: vec![], request_args: StartDebuggingRequestArguments { - request: self - .dap_request_kind( - adapter_name, - Value::from_str(config.config.as_str()) - .map_err(|err| format!("Invalid JSON configuration: {err}"))?, - ) - .map_err(|err| format!("Failed to determine debug request kind: {err}"))?, - configuration: self - .jdtls_server - .debugger - .inject_config(worktree, config.config) - .map_err(|err| format!("Failed to inject debug configuration: {err}"))?, + request, + configuration, }, - connection: Some(zed::resolve_tcp_template( - self.jdtls_server - .debugger - .start_session(&workspace) - .map_err(|err| format!("Failed to start debug session: {err}"))?, - )?), + connection: Some(zed::resolve_tcp_template(connection)?), }) } diff --git a/src/jdtls_server.rs b/src/jdtls_server.rs index b270580..a7c2507 100644 --- a/src/jdtls_server.rs +++ b/src/jdtls_server.rs @@ -1,4 +1,8 @@ -use std::env; +use std::{ + collections::HashMap, + env, + path::{Path, PathBuf}, +}; use zed_extension_api::{ self as zed, CodeLabel, CodeLabelSpan, LanguageServerId, Worktree, @@ -28,6 +32,7 @@ pub struct JdtlsServer { pub jdk: Jdk, pub debugger: Debugger, pub cached_workspace: Option, + test_bundle_hosts: HashMap, } impl JdtlsServer { @@ -39,8 +44,13 @@ impl JdtlsServer { jdk: Jdk::new(), debugger: Debugger::new(), cached_workspace: None, + test_bundle_hosts: HashMap::new(), } } + + pub fn test_bundle_host(&self, workspace: &str) -> Option<&Path> { + self.test_bundle_hosts.get(workspace).map(PathBuf::as_path) + } } impl LanguageServer for JdtlsServer { @@ -89,7 +99,12 @@ impl LanguageServer for JdtlsServer { let configured_launcher = get_jdtls_launcher(&configuration, worktree) .or_else(|| get_jdtls_launcher_from_path(worktree)); - if let Some(launcher) = configured_launcher { + let test_bundle_host = if let Some(launcher) = configured_launcher { + let host = Path::new(&launcher) + .canonicalize() + .ok() + .and_then(|path| path.parent()?.parent().map(Path::to_path_buf)) + .filter(|path| path.join("plugins").is_dir()); args.push(launcher); if let Some(lombok_jvm_arg) = lombok_jvm_arg { args.push(format!("--jvm-arg={lombok_jvm_arg}")); @@ -97,6 +112,7 @@ impl LanguageServer for JdtlsServer { if let Some(data_path) = configured_data_path.as_deref() { append_jdtls_data_args(&mut args, data_path)?; } + host } else { let data_path = match configured_data_path { Some(data_path) => data_path, @@ -119,7 +135,8 @@ impl LanguageServer for JdtlsServer { ) .map_err(|err| format!("Failed to build JDTLS launch arguments: {err}"))?, ); - } + Some(jdtls_path) + }; if let Err(err) = self.debugger @@ -128,7 +145,13 @@ impl LanguageServer for JdtlsServer { println!("Failed to download debugger: {err}"); }; - self.cached_workspace = Some(worktree.root_path()); + let workspace = worktree.root_path(); + if let Some(host) = test_bundle_host { + self.test_bundle_hosts.insert(workspace.clone(), host); + } else { + self.test_bundle_hosts.remove(&workspace); + } + self.cached_workspace = Some(workspace); Ok(zed::Command { command: proxy_path, @@ -169,13 +192,11 @@ impl LanguageServer for JdtlsServer { .or_insert(json!(true)); if self.debugger.plugin_path().is_some() { - return Ok(Some( - self.debugger - .inject_plugin_into_options(Some(options)) - .map_err(|err| { - format!("Failed to inject debugger plugin into options: {err}") - })?, - )); + return self + .debugger + .inject_plugin_into_options(Some(options)) + .map(Some) + .map_err(|err| format!("Failed to inject debugger plugin into options: {err}")); } Ok(Some(options)) diff --git a/src/test_debugger.rs b/src/test_debugger.rs new file mode 100644 index 0000000..024bf94 --- /dev/null +++ b/src/test_debugger.rs @@ -0,0 +1,380 @@ +use serde::{Deserialize, Serialize}; +use zed_extension_api::{ + self as zed, + serde_json::{self, Value, json}, +}; + +use crate::util::path_to_file_uri; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TestTarget { + pub file: String, + pub class_name: String, + #[serde(default)] + pub outer_class: String, + pub method: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct TestItem { + full_name: String, + project_name: String, + test_level: Value, + test_kind: Value, + jdt_handler: Option, + execution_class_name: Option, + #[serde(default)] + children: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TestLaunch { + pub main_class: Option, + pub project_name: String, + pub working_directory: String, + #[serde(default)] + pub classpath: Vec, + #[serde(default)] + pub modulepath: Vec, + #[serde(default)] + pub vm_arguments: Vec, + #[serde(default)] + pub program_arguments: Vec, +} + +impl TestTarget { + pub fn resolve( + &self, + runner_jar: Option<&str>, + mut request: impl FnMut(&str, Value) -> zed::Result, + ) -> zed::Result { + let response = request( + "vscode.java.test.findTestTypesAndMethods", + json!([path_to_file_uri(&self.file)]), + ) + .map_err(|error| format!("Failed to discover Java tests in {}: {error}", self.file))?; + let items: Vec = serde_json::from_value(response) + .map_err(|error| format!("Invalid Java test discovery response: {error}"))?; + let mut classes = Vec::new(); + collect_classes(&items, &mut classes); + let class_suffix = if self.outer_class.is_empty() { + self.class_name.clone() + } else { + format!("{}.{}", self.outer_class, self.class_name) + }; + let mut matches = classes.into_iter().filter(|item| { + let name = item.full_name.replace('$', "."); + name == class_suffix || name.ends_with(&format!(".{class_suffix}")) + }); + let class = matches + .next() + .ok_or_else(|| format!("No matching test class found in {}", self.file))?; + if matches.next().is_some() { + return Err(format!( + "Multiple matching test classes found in {}", + self.file + )); + } + let item = if let Some(method) = &self.method { + let mut methods = class.children.iter().filter(|item| { + let name = item.full_name.rsplit('#').next().unwrap_or(""); + name.split('(').next() == Some(method.as_str()) && is_level(&item.test_level, 6) + }); + let item = methods + .next() + .ok_or_else(|| format!("No test method {method} found in {}", class.full_name))?; + if methods.next().is_some() { + return Err(format!( + "Multiple test methods named {method} found in {}; use a manual debug configuration", + class.full_name + )); + } + item + } else { + class + }; + if !(0..=3).any(|kind| is_level(&item.test_kind, kind)) { + return Err(format!("Unsupported Java test kind: {}", item.test_kind)); + } + let testng = is_level(&item.test_kind, 2); + let test_name = if self.method.is_some() && !testng { + item.jdt_handler + .as_deref() + .ok_or("Java test discovery did not return a method handle")? + } else { + &item.full_name + }; + let params = json!({ + "projectName": item.project_name, + "testLevel": item.test_level, + "testKind": item.test_kind, + "testNames": [test_name], + "executionClassNames": [item.execution_class_name], + }); + let response = request( + "vscode.java.test.junit.argument", + json!([params.to_string()]), + )?; + if let Some(error) = response.get("errorMessage").and_then(Value::as_str) + && !error.is_empty() + { + return Err(format!( + "Failed to resolve Java test launch arguments: {error}" + )); + } + let mut launch: TestLaunch = serde_json::from_value( + response + .get("body") + .cloned() + .ok_or("Java test launch response has no body")?, + ) + .map_err(|error| format!("Invalid Java test launch arguments: {error}"))?; + let status = request( + "vscode.java.buildWorkspace", + json!([json!({ + "mainClass": class.full_name, + "projectName": class.project_name, + "isFullBuild": false, + }) + .to_string()]), + )?; + if status.as_u64() != Some(1) { + return Err(format!("Java test build did not succeed ({status})")); + } + if testng { + let runner = runner_jar.ok_or("The Java TestNG runner is not installed")?; + launch.main_class = Some("com.microsoft.java.test.runner.Launcher".into()); + launch.classpath.push(runner.to_owned()); + let methods: Vec<_> = if self.method.is_some() { + vec![item.full_name.clone()] + } else { + class + .children + .iter() + .filter(|item| is_level(&item.test_level, 6)) + .map(|item| item.full_name.clone()) + .collect() + }; + if methods.is_empty() { + return Err("No TestNG methods found in the selected class".into()); + } + launch.program_arguments = vec!["testng".into()]; + launch.program_arguments.extend(methods); + } + let port = request("zed/javaTestRunner/start", json!({}))? + .as_u64() + .filter(|port| *port > 0 && *port <= u16::MAX as u64) + .ok_or("Invalid Java test runner socket port")? + .to_string(); + if testng { + launch.program_arguments.insert(0, port); + } else if let Some(index) = launch + .program_arguments + .iter() + .rposition(|arg| arg == "-port") + { + let value = launch + .program_arguments + .get_mut(index + 1) + .ok_or("JUnit launch arguments contain -port without a value")?; + *value = port; + } else { + launch.program_arguments.extend(["-port".into(), port]); + } + Ok(launch) + } +} + +fn is_level(value: &Value, expected: u64) -> bool { + value.as_u64() == Some(expected) + || value + .as_str() + .is_some_and(|value| value == expected.to_string()) +} + +fn collect_classes<'a>(items: &'a [TestItem], classes: &mut Vec<&'a TestItem>) { + for item in items { + if is_level(&item.test_level, 5) { + classes.push(item); + } + collect_classes(&item.children, classes); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn target(method: Option<&str>) -> TestTarget { + TestTarget { + file: "/workspace/module with spaces/src/ExampleTest.java".into(), + class_name: "ExampleTest".into(), + outer_class: String::new(), + method: method.map(str::to_owned), + } + } + + fn discovery(kind: &str) -> Value { + json!([{ + "fullName": "example.ExampleTest", + "projectName": "module-a", + "testLevel": "5", + "testKind": kind, + "children": [{ + "fullName": "example.ExampleTest#selected(java.lang.String)", + "projectName": "module-a", + "testLevel": "6", + "testKind": kind, + "jdtHandler": "=module-a/src Value { + json!({"body": { + "mainClass": "org.eclipse.jdt.internal.junit.runner.RemoteTestRunner", + "projectName": "module-a", + "workingDirectory": "/workspace/module with spaces", + "classpath": ["test-classes", "junit-runtime.jar"], + "programArguments": ["-port", "0", "-test", "selected"] + }}) + } + + #[test] + fn method_uses_jdt_handle_and_replaces_only_the_result_socket_port() { + let mut calls = Vec::new(); + let launch = target(Some("selected")) + .resolve(None, |command, params| { + calls.push((command.to_owned(), params.clone())); + Ok(match command { + "vscode.java.test.findTestTypesAndMethods" => discovery("0"), + "vscode.java.test.junit.argument" => arguments(), + "vscode.java.buildWorkspace" => json!(1), + "zed/javaTestRunner/start" => json!(12345), + _ => panic!("Unexpected command: {command}"), + }) + }) + .unwrap(); + + assert_eq!( + calls[0].1, + json!(["file:///workspace/module%20with%20spaces/src/ExampleTest.java"]) + ); + let params: Value = serde_json::from_str(calls[1].1[0].as_str().unwrap()).unwrap(); + assert_eq!( + params["testNames"][0], + discovery("0")[0]["children"][0]["jdtHandler"] + ); + assert_eq!( + params["executionClassNames"], + json!(["example.ExampleTest"]) + ); + assert_eq!( + launch.program_arguments, + ["-port", "12345", "-test", "selected"] + ); + } + + #[test] + fn missing_and_ambiguous_methods_fail_without_starting_a_test_suite() { + for ambiguous in [false, true] { + let mut items = discovery("0"); + if ambiguous { + let duplicate = items[0]["children"][0].clone(); + items[0]["children"].as_array_mut().unwrap().push(duplicate); + } + let error = target(Some(if ambiguous { "selected" } else { "missing" })) + .resolve(None, |command, _| { + assert_eq!(command, "vscode.java.test.findTestTypesAndMethods"); + Ok(items.clone()) + }) + .unwrap_err(); + + assert!(error.contains(if ambiguous { + "Multiple test methods" + } else { + "No test method" + })); + } + } + + #[test] + fn nested_test_class_resolves_without_a_package_variable() { + let mut target = target(None); + target.outer_class = "ExampleTest".into(); + target.class_name = "NestedTest".into(); + let mut items = discovery("1"); + items[0]["children"].as_array_mut().unwrap().push(json!({ + "fullName": "example.ExampleTest.NestedTest", + "projectName": "module-a", "testLevel": 5, "testKind": 1 + })); + target + .resolve(None, |command, params| { + Ok(match command { + "vscode.java.test.findTestTypesAndMethods" => items.clone(), + "vscode.java.test.junit.argument" => { + let params: Value = + serde_json::from_str(params[0].as_str().unwrap()).unwrap(); + assert_eq!( + params["testNames"], + json!(["example.ExampleTest.NestedTest"]) + ); + arguments() + } + "vscode.java.buildWorkspace" => json!(1), + "zed/javaTestRunner/start" => json!(12345), + _ => panic!("Unexpected command"), + }) + }) + .unwrap(); + } + + #[test] + fn failed_build_never_opens_a_runner_socket() { + let error = target(None) + .resolve(None, |command, _| { + Ok(match command { + "vscode.java.test.findTestTypesAndMethods" => discovery("0"), + "vscode.java.test.junit.argument" => arguments(), + "vscode.java.buildWorkspace" => json!(2), + _ => panic!("Runner must not be started after a failed build"), + }) + }) + .unwrap_err(); + + assert!(error.contains("build did not succeed")); + } + + #[test] + fn testng_uses_its_runner_and_only_the_selected_method() { + let launch = target(Some("selected")) + .resolve(Some("testng-runner.jar"), |command, _| { + Ok(match command { + "vscode.java.test.findTestTypesAndMethods" => discovery("2"), + "vscode.java.test.junit.argument" => arguments(), + "vscode.java.buildWorkspace" => json!(1), + "zed/javaTestRunner/start" => json!(12345), + _ => panic!("Unexpected command"), + }) + }) + .unwrap(); + + assert_eq!( + launch.main_class.as_deref(), + Some("com.microsoft.java.test.runner.Launcher") + ); + assert_eq!(launch.classpath.last().unwrap(), "testng-runner.jar"); + assert_eq!( + launch.program_arguments, + [ + "12345", + "testng", + "example.ExampleTest#selected(java.lang.String)" + ] + ); + } +} diff --git a/src/test_support.rs b/src/test_support.rs new file mode 100644 index 0000000..ad9b310 --- /dev/null +++ b/src/test_support.rs @@ -0,0 +1,123 @@ +use std::{ + fs, + path::{Path, PathBuf}, +}; + +use zed_extension_api::{ + self as zed, DownloadedFileType, + serde_json::{Value, json}, +}; + +const VERSION: &str = "0.47.0"; +const DOWNLOAD_URL: &str = "https://open-vsx.org/api/vscjava/vscode-java-test/0.47.0/file/vscjava.vscode-java-test-0.47.0.vsix"; + +pub fn prepare(workspace: &str, host: Option<&Path>) -> zed::Result { + let (mut bundles, runner) = install()?; + if let Some(host) = host { + let plugins = host.join("plugins"); + bundles.retain(|bundle| { + !Path::new(bundle) + .file_name() + .is_some_and(|name| plugins.join(name).is_file()) + }); + } + let loaded = crate::lsp::request::( + workspace, + "workspace/executeCommand", + json!({"command": "java.reloadBundles", "arguments": [bundles]}), + ) + .map_err(|error| format!("Failed to load Java Test Runner in JDTLS: {error}"))?; + if !loaded { + return Err("JDTLS could not load the Java Test Runner; check the JDTLS log".into()); + } + Ok(runner) +} + +fn install() -> zed::Result<(Vec, String)> { + let directory = std::env::current_dir() + .map_err(|error| error.to_string())? + .join("java-test") + .join(VERSION); + if load_installation(&directory).is_err() { + let staging = directory.with_extension("installing"); + if staging.exists() { + fs::remove_dir_all(&staging).map_err(|error| error.to_string())?; + } + zed::download_file( + DOWNLOAD_URL, + &staging.to_string_lossy(), + DownloadedFileType::Zip, + ) + .map_err(|error| format!("Failed to install Java Test Runner {VERSION}: {error}"))?; + load_installation(&staging)?; + if directory.exists() { + fs::remove_dir_all(&directory).map_err(|error| error.to_string())?; + } + fs::rename(staging, &directory).map_err(|error| error.to_string())?; + } + load_installation(&directory) +} + +fn load_installation(directory: &std::path::Path) -> zed::Result<(Vec, String)> { + let extension = directory.join("extension"); + let manifest: Value = serde_json::from_slice( + &fs::read(extension.join("package.json")).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + let paths = manifest + .pointer("/contributes/javaExtensions") + .and_then(Value::as_array) + .ok_or("Java Test Runner manifest has no Java extensions")?; + if paths.is_empty() { + return Err("Java Test Runner contains no language server bundles".into()); + } + let bundles = paths + .iter() + .map(|path| { + let path = path.as_str().ok_or("Invalid Java test bundle path")?; + let relative = PathBuf::from(path); + if relative.is_absolute() + || relative + .components() + .any(|component| matches!(component, std::path::Component::ParentDir)) + { + return Err("Invalid Java test bundle path".into()); + } + let path = extension.join(relative); + if !path.is_file() { + return Err(format!("Java test bundle is missing: {}", path.display())); + } + Ok(path.to_string_lossy().into_owned()) + }) + .collect::>>()?; + let runner = extension.join("server/com.microsoft.java.test.runner-jar-with-dependencies.jar"); + if !runner.is_file() { + return Err("Java TestNG runner is missing".into()); + } + Ok((bundles, runner.to_string_lossy().into_owned())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn installation_rejects_bundle_paths_outside_the_extension() { + let directory = + std::env::temp_dir().join(format!("java-test-manifest-{}", std::process::id())); + fs::create_dir_all(directory.join("extension")).unwrap(); + fs::write( + directory.join("extension/package.json"), + json!({ + "contributes": {"javaExtensions": ["../../outside.jar"]} + }) + .to_string(), + ) + .unwrap(); + + let error = load_installation(&directory).unwrap_err(); + + assert!(error.contains("Invalid Java test bundle path")); + fs::remove_dir_all(directory).unwrap(); + } +} From ca57fdfd62db01d95fb754d07515c75655f45582 Mon Sep 17 00:00:00 2001 From: fwrq41251 <6220591+fwrq41251@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:53:43 +0900 Subject: [PATCH 2/2] Address Java test debugging review feedback --- README.md | 3 ++ src/debugger.rs | 5 ++- src/java.rs | 1 + src/jdtls_server.rs | 17 +++++---- src/test_debugger.rs | 47 ++++++++++++++++++++++--- src/test_support.rs | 84 ++++++++++++++++++++++++++++++++++++-------- 6 files changed, 131 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index ad6fc29..c5fdf5f 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,9 @@ With JDTLS, the first test debug launch downloads the pinned Microsoft Java Test Runner. The extension loads the bundles into the running language server, discovers tests in the selected file, and resolves the framework's launch arguments. JUnit methods use their JDT handles, including parameter types. +For a custom JDTLS launcher, set `lsp.jdtls.settings.jdtls_home` to the absolute +path of the JDTLS installation that contains `plugins/`. This lets the extension +skip runner bundles already shipped with that installation. TestNG uses its bundled runner. A local callback socket receives the test runner's result protocol; this does not provide a test-results explorer. Build failures, missing targets, and ambiguous method names stop the launch. diff --git a/src/debugger.rs b/src/debugger.rs index 981dba9..c898d04 100644 --- a/src/debugger.rs +++ b/src/debugger.rs @@ -347,6 +347,7 @@ impl Debugger { &self, worktree: &Worktree, config_string: String, + language_server_id: Option<&LanguageServerId>, test_bundle_host: Option<&Path>, ) -> zed::Result<(String, TcpArgumentsTemplate)> { let workspace_folder = worktree.root_path(); @@ -367,7 +368,9 @@ impl Debugger { let mut connection = None; let test_launch = if let Some(target) = &config.test_target { - let runner = crate::test_support::prepare(&workspace_folder, test_bundle_host)?; + let language_server_id = language_server_id.ok_or("JDTLS is not initialized")?; + let runner = + crate::test_support::prepare(language_server_id, worktree, test_bundle_host)?; let launch = target.resolve(Some(&runner), |command, arguments| { if command == "zed/javaTestRunner/start" { let mut template = self.start_session(&workspace_folder)?; diff --git a/src/java.rs b/src/java.rs index e4b6849..f4cd96b 100644 --- a/src/java.rs +++ b/src/java.rs @@ -157,6 +157,7 @@ impl Extension for Java { .inject_config( worktree, config.config, + self.jdtls_server.language_server_id.as_ref(), self.jdtls_server.test_bundle_host(&workspace), ) .map_err(|err| format!("Failed to prepare debug session: {err}"))?; diff --git a/src/jdtls_server.rs b/src/jdtls_server.rs index a7c2507..e6a67a4 100644 --- a/src/jdtls_server.rs +++ b/src/jdtls_server.rs @@ -22,7 +22,7 @@ use crate::{ }, language_server::LanguageServer, proxy::Proxy, - util::{path_to_file_uri, path_to_string}, + util::{expand_home_path, path_to_file_uri, path_to_string}, }; pub struct JdtlsServer { @@ -32,6 +32,7 @@ pub struct JdtlsServer { pub jdk: Jdk, pub debugger: Debugger, pub cached_workspace: Option, + pub language_server_id: Option, test_bundle_hosts: HashMap, } @@ -44,6 +45,7 @@ impl JdtlsServer { jdk: Jdk::new(), debugger: Debugger::new(), cached_workspace: None, + language_server_id: None, test_bundle_hosts: HashMap::new(), } } @@ -100,11 +102,6 @@ impl LanguageServer for JdtlsServer { let configured_launcher = get_jdtls_launcher(&configuration, worktree) .or_else(|| get_jdtls_launcher_from_path(worktree)); let test_bundle_host = if let Some(launcher) = configured_launcher { - let host = Path::new(&launcher) - .canonicalize() - .ok() - .and_then(|path| path.parent()?.parent().map(Path::to_path_buf)) - .filter(|path| path.join("plugins").is_dir()); args.push(launcher); if let Some(lombok_jvm_arg) = lombok_jvm_arg { args.push(format!("--jvm-arg={lombok_jvm_arg}")); @@ -112,7 +109,12 @@ impl LanguageServer for JdtlsServer { if let Some(data_path) = configured_data_path.as_deref() { append_jdtls_data_args(&mut args, data_path)?; } - host + configuration + .as_ref() + .and_then(|settings| settings.get("jdtls_home")) + .and_then(Value::as_str) + .map(|path| expand_home_path(worktree, path.to_owned()).map(PathBuf::from)) + .transpose()? } else { let data_path = match configured_data_path { Some(data_path) => data_path, @@ -152,6 +154,7 @@ impl LanguageServer for JdtlsServer { self.test_bundle_hosts.remove(&workspace); } self.cached_workspace = Some(workspace); + self.language_server_id = Some(language_server_id.clone()); Ok(zed::Command { command: proxy_path, diff --git a/src/test_debugger.rs b/src/test_debugger.rs index 024bf94..b7443b1 100644 --- a/src/test_debugger.rs +++ b/src/test_debugger.rs @@ -1,3 +1,6 @@ +//! Test discovery and launch follow the upstream VS Code Java Test Runner protocol. +//! https://github.com/microsoft/vscode-java-test/blob/0.47.0/src/controller/testController.ts + use serde::{Deserialize, Serialize}; use zed_extension_api::{ self as zed, @@ -29,6 +32,29 @@ struct TestItem { children: Vec, } +// Protocol values from https://github.com/microsoft/vscode-java-test/blob/0.47.0/src/java-test-runner.api.ts +#[derive(Debug, PartialEq, Eq)] +enum TestKind { + JUnit5, + JUnit4, + TestNg, + JUnit6, +} + +impl TestKind { + fn from_protocol(value: &Value) -> zed::Result { + let code = value.as_u64().or_else(|| value.as_str()?.parse().ok()); + + match code { + Some(0) => Ok(Self::JUnit5), + Some(1) => Ok(Self::JUnit4), + Some(2) => Ok(Self::TestNg), + Some(3) => Ok(Self::JUnit6), + _ => Err(format!("Unsupported Java test kind: {value}")), + } + } +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TestLaunch { @@ -58,6 +84,7 @@ impl TestTarget { .map_err(|error| format!("Failed to discover Java tests in {}: {error}", self.file))?; let items: Vec = serde_json::from_value(response) .map_err(|error| format!("Invalid Java test discovery response: {error}"))?; + let mut classes = Vec::new(); collect_classes(&items, &mut classes); let class_suffix = if self.outer_class.is_empty() { @@ -78,6 +105,7 @@ impl TestTarget { self.file )); } + let item = if let Some(method) = &self.method { let mut methods = class.children.iter().filter(|item| { let name = item.full_name.rsplit('#').next().unwrap_or(""); @@ -96,10 +124,8 @@ impl TestTarget { } else { class }; - if !(0..=3).any(|kind| is_level(&item.test_kind, kind)) { - return Err(format!("Unsupported Java test kind: {}", item.test_kind)); - } - let testng = is_level(&item.test_kind, 2); + + let testng = matches!(TestKind::from_protocol(&item.test_kind)?, TestKind::TestNg); let test_name = if self.method.is_some() && !testng { item.jdt_handler .as_deref() @@ -107,6 +133,7 @@ impl TestTarget { } else { &item.full_name }; + let params = json!({ "projectName": item.project_name, "testLevel": item.test_level, @@ -132,6 +159,7 @@ impl TestTarget { .ok_or("Java test launch response has no body")?, ) .map_err(|error| format!("Invalid Java test launch arguments: {error}"))?; + let status = request( "vscode.java.buildWorkspace", json!([json!({ @@ -144,6 +172,7 @@ impl TestTarget { if status.as_u64() != Some(1) { return Err(format!("Java test build did not succeed ({status})")); } + if testng { let runner = runner_jar.ok_or("The Java TestNG runner is not installed")?; launch.main_class = Some("com.microsoft.java.test.runner.Launcher".into()); @@ -164,6 +193,7 @@ impl TestTarget { launch.program_arguments = vec!["testng".into()]; launch.program_arguments.extend(methods); } + let port = request("zed/javaTestRunner/start", json!({}))? .as_u64() .filter(|port| *port > 0 && *port <= u16::MAX as u64) @@ -208,6 +238,15 @@ fn collect_classes<'a>(items: &'a [TestItem], classes: &mut Vec<&'a TestItem>) { mod tests { use super::*; + #[test] + fn accepts_supported_test_kind_codes_and_rejects_unknown_kinds() { + assert_eq!(TestKind::from_protocol(&json!(0)), Ok(TestKind::JUnit5)); + assert_eq!(TestKind::from_protocol(&json!("1")), Ok(TestKind::JUnit4)); + assert_eq!(TestKind::from_protocol(&json!(2)), Ok(TestKind::TestNg)); + assert_eq!(TestKind::from_protocol(&json!("3")), Ok(TestKind::JUnit6)); + assert!(TestKind::from_protocol(&json!(100)).is_err()); + } + fn target(method: Option<&str>) -> TestTarget { TestTarget { file: "/workspace/module with spaces/src/ExampleTest.java".into(), diff --git a/src/test_support.rs b/src/test_support.rs index ad9b310..3d13e5d 100644 --- a/src/test_support.rs +++ b/src/test_support.rs @@ -4,15 +4,27 @@ use std::{ }; use zed_extension_api::{ - self as zed, DownloadedFileType, + self as zed, DownloadedFileType, LanguageServerId, LanguageServerInstallationStatus, Worktree, serde_json::{Value, json}, + set_language_server_installation_status, }; +use crate::downloadable::Downloadable; + const VERSION: &str = "0.47.0"; const DOWNLOAD_URL: &str = "https://open-vsx.org/api/vscjava/vscode-java-test/0.47.0/file/vscjava.vscode-java-test-0.47.0.vsix"; -pub fn prepare(workspace: &str, host: Option<&Path>) -> zed::Result { - let (mut bundles, runner) = install()?; +pub fn prepare( + language_server_id: &LanguageServerId, + worktree: &Worktree, + host: Option<&Path>, +) -> zed::Result { + let mut test_runner = TestRunner; + let directory = match test_runner.find_local() { + Some(path) => path, + None => test_runner.get_or_download(language_server_id, &None, worktree)?, + }; + let (mut bundles, runner) = load_installation(&directory)?; if let Some(host) = host { let plugins = host.join("plugins"); bundles.retain(|bundle| { @@ -22,7 +34,7 @@ pub fn prepare(workspace: &str, host: Option<&Path>) -> zed::Result { }); } let loaded = crate::lsp::request::( - workspace, + &worktree.root_path(), "workspace/executeCommand", json!({"command": "java.reloadBundles", "arguments": [bundles]}), ) @@ -33,29 +45,73 @@ pub fn prepare(workspace: &str, host: Option<&Path>) -> zed::Result { Ok(runner) } -fn install() -> zed::Result<(Vec, String)> { - let directory = std::env::current_dir() - .map_err(|error| error.to_string())? - .join("java-test") - .join(VERSION); - if load_installation(&directory).is_err() { +struct TestRunner; + +impl Downloadable for TestRunner { + const INSTALL_PATH: &'static str = "java-test"; + + fn find_local(&self) -> Option { + let directory = std::env::current_dir() + .ok()? + .join(Self::INSTALL_PATH) + .join(VERSION); + load_installation(&directory).ok().map(|_| directory) + } + + fn loaded(&self) -> bool { + self.find_local().is_some() + } + + fn fetch_latest_version(&self, _worktree: &Worktree) -> zed::Result { + Ok(VERSION.to_owned()) + } + + fn version_for_download( + &self, + _language_server_id: &LanguageServerId, + _configuration: &Option, + worktree: &Worktree, + ) -> zed::Result<(String, bool)> { + self.fetch_latest_version(worktree) + .map(|version| (version, false)) + } + + fn download( + &mut self, + version: &str, + language_server_id: &LanguageServerId, + _worktree: &Worktree, + ) -> zed::Result { + let directory = std::env::current_dir() + .map_err(|error| error.to_string())? + .join(Self::INSTALL_PATH) + .join(version); let staging = directory.with_extension("installing"); if staging.exists() { fs::remove_dir_all(&staging).map_err(|error| error.to_string())?; } - zed::download_file( + set_language_server_installation_status( + language_server_id, + &LanguageServerInstallationStatus::Downloading, + ); + let downloaded = zed::download_file( DOWNLOAD_URL, &staging.to_string_lossy(), DownloadedFileType::Zip, - ) - .map_err(|error| format!("Failed to install Java Test Runner {VERSION}: {error}"))?; + ); + set_language_server_installation_status( + language_server_id, + &LanguageServerInstallationStatus::None, + ); + downloaded + .map_err(|error| format!("Failed to install Java Test Runner {version}: {error}"))?; load_installation(&staging)?; if directory.exists() { fs::remove_dir_all(&directory).map_err(|error| error.to_string())?; } fs::rename(staging, &directory).map_err(|error| error.to_string())?; + Ok(directory) } - load_installation(&directory) } fn load_installation(directory: &std::path::Path) -> zed::Result<(Vec, String)> {