diff --git a/lua/neotest-java/build_tool/launcher.lua b/lua/neotest-java/build_tool/launcher.lua index eb058488..308a9a1b 100644 --- a/lua/neotest-java/build_tool/launcher.lua +++ b/lua/neotest-java/build_tool/launcher.lua @@ -1,110 +1,260 @@ local log = require("neotest-java.logger") local nio = require("nio") -local lib = require("neotest.lib") ---- A minimal shape of the job runner this module needs: ---- * `new(opts)` accepts `command`, `cwd`, `args`, `on_stderr`, `on_stdout`, ---- `on_exit` callback fields ---- * the returned job exposes a `start()` method +--- @class neotest-java.SystemProcess +--- @field pid? number +--- @field kill fun(self: table, signal: number) + --- @class neotest-java.JobRunner ---- @field new fun(self: neotest-java.JobRunner, opts: table): { start: fun() } - ---- Default job runner, built directly on `vim.system` (see #317), matching ---- the same `vim.system` usage already established in ---- `command/command_executor.lua`. Unlike that module this doesn't need ---- `nio.wrap`, since `launch_debug_test` below already waits on its own ---- `nio.control.event()` rather than blocking on the process exiting. ---- @type neotest-java.JobRunner +--- @field new fun(self: neotest-java.JobRunner, opts: table): { start: fun(): neotest-java.SystemProcess? } local default_job_runner = { new = function(_, opts) return { start = function() - vim.system(vim.list_extend({ opts.command }, opts.args), { + return vim.system(vim.list_extend({ opts.command }, opts.args), { cwd = opts.cwd, stdout = opts.on_stdout, stderr = opts.on_stderr, }, function(obj) - if opts.on_exit then - opts.on_exit(nil, obj.code) - end + opts.on_exit(nil, obj.code, obj.signal) end) end, } end, } +local active = {} +vim.api.nvim_create_autocmd("VimLeavePre", { + callback = function() + for process in pairs(active) do + process.stop("Neovim exiting", true) + end + end, +}) + +local function close_timer(timer) + if timer and not timer:is_closing() then + timer:stop() + timer:close() + end +end + +local function timer_after(ms, callback) + local timer = assert(vim.uv.new_timer()) + timer:start(ms, 0, callback) + return timer +end + +--- @class neotest-java.DebugProcess +--- @field wait fun(): table Legacy termination-event API, now bounded. +--- @field is_set fun(): boolean +--- @field wait_ready fun(): table +--- @field wait_exit fun(timeout_ms?: number): table +--- @field stop fun(reason?: string, force?: boolean) +--- @field claim fun() Transfer startup ownership to the DAP strategy. +--- @field state table + ---@param deps neotest-java.BuildToolLauncherDeps | nil ----@return neotest-java.BuildToolLauncher local function BuildToolLauncher(deps) deps = deps or {} deps.job_runner = deps.job_runner or default_job_runner - deps.dap_repl = deps.dap_repl if deps.dap_repl == nil then local ok, repl = pcall(require, "dap.repl") - deps.dap_repl = ok and repl or nil + deps.dap_repl = ok and repl or false end return { - ---@param command string - ---@param args string[] - ---@param cwd neotest-java.Path - ---@return nio.control.Event - launch_debug_test = function(command, args, cwd) - lib.notify("Running debug test", vim.log.levels.INFO) - log.trace("run_debug_test function") - + launch_debug_test = function(command, args, cwd, opts) + opts = opts or {} + local startup_ms = opts.startup_timeout_ms or 30000 + local exit_ms = opts.exit_timeout_ms or 5000 + local shutdown_ms = opts.shutdown_timeout_ms or 1000 + local ready, exited = nio.control.event(), nio.control.event() + local state = { ready = false, exited = false, cancelled = false, stderr = "" } + local process, system, startup_timer, orphan_timer, kill_timer + local wait_timers = {} + local output_tail = { stdout = "", stderr = "" } local repl = deps.dap_repl - local test_command_started_listening = nio.control.event() - local terminated_command_event = nio.control.event() + local failure_cleaned = false + local function cleanup_failure() + if failure_cleaned or not opts.on_failure then + return + end + failure_cleaned = true + -- Independent of build_spec's task: a cancelled readiness waiter + -- cannot execute its own finally/cleanup path. + vim.schedule(function() + nio.run(opts.on_failure, function(ok, err) + if not ok then + log.error("Could not clean Java test reports: " .. tostring(err)) + end + end) + end) + end - local stderr = {} - local job = deps.job_runner:new({ - command = command, - cwd = cwd:to_string(), - args = args, - on_stderr = function(_, data) - if data == nil then - return - end - stderr[#stderr + 1] = data - if repl then - vim.schedule(function() - repl.append(data) - end) + local function finish(code, signal) + if state.exited then + return + end + state.exited, state.code, state.signal = true, code, signal + if not state.ready and not state.error then + state.error = "Java exited before JDWP readiness (code " .. tostring(code) .. ")" + end + if state.error then + cleanup_failure() + end + close_timer(startup_timer) + close_timer(orphan_timer) + close_timer(kill_timer) + active[process] = nil + exited.set() + for timer, event in pairs(wait_timers) do + close_timer(timer) + event.set() + end + ready.set() + end + + local function kill(signal) + if system and not state.exited then + local ok, err = pcall(system.kill, system, signal) + if not ok then + log.error("Could not stop test JVM: " .. tostring(err)) end + end + end + + process = { + state = state, + is_set = exited.is_set, + claim = function() + assert(not state.cancelled, state.error) + close_timer(orphan_timer) end, - on_stdout = function(_, data) - if data == nil then - return + stop = function(reason, force) + if force then + kill(9) end - if string.find(data, "Listening") then - test_command_started_listening.set() + if state.exited or state.cancelled then + return end - if repl then - vim.schedule(function() - repl.append(data) + state.cancelled = true + state.error = reason or "Java debug test cancelled" + close_timer(startup_timer) + close_timer(orphan_timer) + ready.set() + kill(force and 9 or 15) + if not state.exited and not force then + kill_timer = timer_after(shutdown_ms, function() + close_timer(kill_timer) + kill(9) end) end end, - on_exit = function(_, code) - terminated_command_event.set() - - log.debug("command exited with code: ", code) - if code ~= 0 then - log.error("command exited with code: ", code) - log.error("stderr: ", table.concat(stderr, "\n")) + wait_ready = function() + ready.wait() + return state + end, + wait_exit = function(timeout_ms) + if state.exited then + return state end + local done = nio.control.event() + -- A per-wait timer bounds even a missing OS exit callback. Polling + -- avoids retaining event waiters after timeout or task cancellation. + local timer = assert(vim.uv.new_timer()) + local reaping = state.cancelled + local deadline = vim.uv.hrtime() + + (reaping and (shutdown_ms + 1000) or (timeout_ms or exit_ms)) * 1e6 + wait_timers[timer] = done + timer:start(0, 10, function() + if state.exited or vim.uv.hrtime() >= deadline then + if not state.exited and not reaping then + reaping = true + deadline = vim.uv.hrtime() + (shutdown_ms + 1000) * 1e6 + process.stop("Timed out waiting for Java test exit/report") + return + end + if not state.exited then + cleanup_failure() + end + wait_timers[timer] = nil + close_timer(timer) + done.set() + end + end) + done.wait() + return state end, - }) - log.debug("starting job with command: ", command, " ", table.concat(args, " ")) - if repl then - repl.clear() + } + process.wait = process.wait_exit + active[process] = true + + local function output(stream, data) + if not data then + return + end + output_tail[stream] = (output_tail[stream] .. data):sub(-8192) + if stream == "stderr" then + state.stderr = output_tail.stderr + end + -- The JVM can split the banner across chunks or write it to stderr. + if + not state.cancelled + and output_tail[stream]:find("Listening for transport dt_socket at address:", 1, true) + then + state.ready = true + close_timer(startup_timer) + ready.set() + end + if repl then + vim.schedule(function() + repl.append(data) + end) + end end - job:start() - test_command_started_listening.wait() - return terminated_command_event + startup_timer = timer_after(startup_ms, function() + process.stop("Timed out waiting for Java JDWP readiness") + end) + -- Also reap a ready JVM if build_spec's caller is cancelled before + -- handing the spec to Neotest. Claiming it does not limit debug time. + orphan_timer = timer_after(opts.attach_timeout_ms or 120000, function() + process.stop("Java debug test was never claimed by DAP") + end) + local ok, err = pcall(function() + if repl then + repl.clear() + end + local job = deps.job_runner:new({ + command = command, + args = args, + cwd = cwd:to_string(), + on_stdout = function(_, data) + output("stdout", data) + end, + on_stderr = function(_, data) + output("stderr", data) + end, + on_exit = function(_, code, signal) + finish(code, signal) + end, + }) + system = job:start() + state.pid = system and system.pid or nil + end) + if not ok then + state.error = "Could not start Java test: " .. tostring(err) + finish(-1, 0) + end + process.wait_ready() + if not state.ready or state.cancelled then + process.stop(state.error) + process.wait_exit(shutdown_ms + 1000) + error((state.error or "Java debug startup failed") .. "\n" .. state.stderr) + end + return process end, } end @@ -114,15 +264,8 @@ end ---@field dap_repl? false | { append: fun(data: string), clear: fun() } ---@class neotest-java.BuildToolLauncher ----@field launch_debug_test fun(command: string, args: string[], cwd: neotest-java.Path): nio.control.Event +---@field launch_debug_test fun(command: string, args: string[], cwd: neotest-java.Path, opts?: table): neotest-java.DebugProcess ---@field new fun(deps: neotest-java.BuildToolLauncherDeps | nil): neotest-java.BuildToolLauncher - --- Module-level singleton, matching the previous `launcher.launch_debug_test` --- call site contract (`require("neotest-java.build_tool.launcher").launch_debug_test(...)`). local launcher = BuildToolLauncher() - --- Exposed for tests / future callers that want to inject a custom job_runner --- (e.g. a stub) without going through the module-level singleton. launcher.new = BuildToolLauncher - return launcher diff --git a/lua/neotest-java/core/result_builder.lua b/lua/neotest-java/core/result_builder.lua index e7123040..df576624 100644 --- a/lua/neotest-java/core/result_builder.lua +++ b/lua/neotest-java/core/result_builder.lua @@ -44,8 +44,11 @@ end -- Public API -- ----------------------------------------------------------------------------- +--- @class neotest-java.StrategyResult : neotest.StrategyResult +--- @field error? string Strategy infrastructure/cancellation failure. + --- @class neotest-java.ResultBuilder ---- @field build_results fun(spec: neotest.RunSpec, result: neotest.StrategyResult, tree: neotest.Tree): table +--- @field build_results fun(spec: neotest.RunSpec, result: neotest-java.StrategyResult, tree: neotest.Tree): table --- @class neotest-java.ResultBuilderDeps --- @field scan_dir fun(dir: neotest-java.Path, opts: { search_patterns: string[] }): neotest-java.Path[] @@ -68,21 +71,64 @@ local ResultBuilder = function(deps) return { --- @param spec neotest.RunSpec - --- @param result neotest.StrategyResult + --- @param result neotest-java.StrategyResult --- @param tree neotest.Tree --- @return table build_results = function(spec, result, tree) - if result.code ~= 0 and result.code ~= 1 then - local node = tree:data() - return { [node.id] = JunitResult.ERROR(node.id, result.output, deps.tempname_fn) } + local function failure(message) + return { + status = "failed", + output = result.output, + short = message, + errors = { { message = message } }, + } + end + local function failed_selection(message) + local failures = {} + for _, position in tree:iter() do + if position.type == "test" then + failures[position.id] = failure(message) + end + end + if next(failures) == nil then + failures[tree:data().id] = failure(message) + end + return failures + end + local function cleanup() + if spec.context.cleanup_reports then + spec.context.cleanup_reports() + end end - if spec.context.strategy == "dap" then - spec.context.terminated_command_event.wait() + local process = spec.context.process + local infrastructure_error = result.error + if process then + if infrastructure_error or (result.code ~= 0 and result.code ~= 1) then + process.stop(infrastructure_error or "Debug strategy failed") + end + local state = process.wait_exit() + infrastructure_error = infrastructure_error or state.error + if state.cancelled or not state.exited then + infrastructure_error = infrastructure_error or "Java debug test cancelled or timed out" + elseif state.code ~= 0 and state.code ~= 1 then + infrastructure_error = infrastructure_error + or ("Java test exited with code " .. tostring(state.code)) + end + end + if infrastructure_error or (result.code ~= 0 and result.code ~= 1) then + cleanup() + return failed_selection( + infrastructure_error or ("Test process exited with code " .. tostring(result.code)) + ) end local report_files = find_report_files(spec.context.reports_dir) - local testcases = deps.junit_result_reader.read_all(report_files) + local read_ok, testcases = pcall(deps.junit_result_reader.read_all, report_files) + if not read_ok then + cleanup() + return failed_selection("Could not read JUnit reports: " .. tostring(testcases)) + end local groups = group_by_method_base(testcases) local results = {} @@ -112,6 +158,18 @@ local ResultBuilder = function(deps) log.debug("Could not remove report file: " .. filepath .. " - " .. tostring(err or "unknown error")) end end + cleanup() + + -- Missing framework evidence is an infrastructure failure, never a + -- pass or an inferred skip (including a partially reported selection). + for _, position in tree:iter() do + if position.type == "test" and not results[position.id] then + results[position.id] = failure("No JUnit result reported for selected test: " .. position.id) + end + end + if next(results) == nil then + return failed_selection("No JUnit results found in " .. tostring(spec.context.reports_dir)) + end return results end, diff --git a/lua/neotest-java/core/spec_builder/compiler/init.lua b/lua/neotest-java/core/spec_builder/compiler/init.lua index 0969dbbe..27655d35 100644 --- a/lua/neotest-java/core/spec_builder/compiler/init.lua +++ b/lua/neotest-java/core/spec_builder/compiler/init.lua @@ -8,7 +8,7 @@ local LspCompiler = require("neotest-java.core.spec_builder.compiler.lsp_compile --- Interface for Java compilers ---@class NeotestJavaCompiler ----@field compile fun(opts: NeotestJavaCompiler.Opts): string classpath_file_arg +---@field compile fun(opts: NeotestJavaCompiler.Opts): boolean? true on success; throws/false on failure. local client_provider = ClientProvider({ get_clients = function(opts) diff --git a/lua/neotest-java/core/spec_builder/compiler/lsp_compiler.lua b/lua/neotest-java/core/spec_builder/compiler/lsp_compiler.lua index adc00b6a..fa87d38a 100644 --- a/lua/neotest-java/core/spec_builder/compiler/lsp_compiler.lua +++ b/lua/neotest-java/core/spec_builder/compiler/lsp_compiler.lua @@ -1,45 +1,62 @@ -local logger = require("neotest-java.logger") +local nio = require("nio") ---- @diagnostic disable-next-line: undefined-doc-name ---- @param deps { client_provider: fun(cwd: neotest-java.Path): vim.lsp.Client } +--- @class neotest-java.BuildClient +--- @field initialized boolean +--- @field request fun(self: table, method: string, params: boolean, callback: fun(err: any, status: any)): boolean, number? +--- @field cancel_request fun(self: table, request_id: number) + +--- @class neotest-java.LspCompilerDeps +--- @field client_provider fun(cwd: neotest-java.Path): neotest-java.BuildClient +--- @field schedule? fun(fn: fun()) +--- @field timeout_ms? number + +--- JDTLS java/buildWorkspace returns CompileWorkspaceStatus: +--- FAILED=0, SUCCEED=1, WITHERROR=2, CANCELLED=3 (not classpath data). +--- @param deps neotest-java.LspCompilerDeps --- @return NeotestJavaCompiler local function LspCompiler(deps) return { compile = function(args) local client = deps.client_provider(args.base_dir) - if not client or not client.initialized then - return + assert(client and client.initialized, "JDTLS is not initialized for " .. tostring(args.base_dir)) + local result = nio.control.future() + local timer = assert(vim.uv.new_timer()) + local request_id + local function finish(err, status) + if result.is_set() then + return + end + timer:stop() + timer:close() + if err then + result.set_error("JDTLS compilation failed: " .. vim.inspect(err)) + elseif status ~= 1 then + result.set_error("JDTLS compilation failed (buildWorkspace status " .. tostring(status) .. ")") + else + result.set(true) + end end - - logger.debug(("compilation in %s mode"):format(args.compile_mode)) - - vim.schedule(function() - --- @diagnostic disable-next-line: undefined-field - client:request( - "java/buildWorkspace", - { forceRebuild = args.compile_mode == "full" }, - function(err, result) - if err then - logger.error("compilation failed: " .. vim.inspect(err)) - end - - -- NOTE: - -- 1) module paths are not duplicated on the classpath, - -- 2) the classpath and modulepath generated by the eclipse jdtls, do - -- not include the target/test-classes directory, for maven projects - -- using the Java Platform Module System. - if next(result.modulepaths) ~= nil then - logger.error( - "Java Platform Module System not supported. Temporarily remove " - .. "module-info.java for the test duration. modulepath=" - .. vim.inspect(result.modulepaths) - ) - end - end - ) + timer:start(deps.timeout_ms or 120000, 0, function() + finish("Timed out waiting for java/buildWorkspace") + if request_id then + vim.schedule(function() + client:cancel_request(request_id) + end) + end end) - - logger.debug("compilation complete!") + local schedule = deps.schedule or vim.schedule + schedule(function() + if result.is_set() then + return + end + local ok, accepted, id = + pcall(client.request, client, "java/buildWorkspace", args.compile_mode == "full", finish) + request_id = id + if not ok or not accepted then + finish(ok and "java/buildWorkspace request rejected" or accepted) + end + end) + return result.wait() end, } end diff --git a/lua/neotest-java/core/spec_builder/init.lua b/lua/neotest-java/core/spec_builder/init.lua index b08f0467..3c55822f 100644 --- a/lua/neotest-java/core/spec_builder/init.lua +++ b/lua/neotest-java/core/spec_builder/init.lua @@ -5,17 +5,19 @@ local logger = require("neotest-java.logger") local random_port = require("neotest-java.util.random_port") local Project = require("neotest-java.model.project") local Path = require("neotest-java.model.path") +local nio = require("nio") --- @class neotest-java.BuildSpecDependencies --- @field mkdir fun(dir: neotest-java.Path) --- @field scan fun(base_dir: neotest-java.Path, opts?: { search_patterns?: string[] }): neotest-java.Path[] ---- @field compile fun(cwd: neotest-java.Path, compile_mode: string) +--- @field compile fun(cwd: neotest-java.Path, compile_mode: string): boolean? nil is accepted for legacy synchronous compilers; false is failure. --- @field classpath_provider neotest-java.ClasspathProvider --- @field report_folder_name_gen fun(module_dir: neotest-java.Path, build_dir: neotest-java.Path): neotest-java.Path --- @field build_tool_getter fun(project_type: string): neotest-java.BuildTool --- @field detect_project_type fun(base_dir: neotest-java.Path): string --- @field binaries neotest-java.LspBinaries ---- @field launch_debug_test fun(command: string, args: string[], cwd: neotest-java.Path): any +--- @field launch_debug_test fun(command: string, args: string[], cwd: neotest-java.Path, opts?: table): neotest-java.DebugProcess +--- @field cleanup_reports? fun(dir: neotest-java.Path) --- @field root_finder? { find_root: fun(dir: string): string | nil } --- @class neotest-java.SpecBuilder @@ -34,8 +36,12 @@ local SpecBuilder = function(deps) ---@return nil | neotest.RunSpec | neotest.RunSpec[] build_spec = function(args, config) if args.strategy == "dap" then - local ok_dap, _ = pcall(require, "dap") + local ok_dap, dap = pcall(require, "dap") assert(ok_dap, "neotest-java requires nvim-dap to run debug tests") + assert( + dap.adapters and dap.adapters.java, + "Java DAP adapter is unavailable; load the Java Debug bundle in JDTLS and call jdtls.setup_dap()" + ) end local tree = args.tree @@ -85,10 +91,6 @@ local SpecBuilder = function(deps) command:basedir(module.base_dir) - -- JUNIT REPORT DIRECTORY - local reports_dir = deps.report_folder_name_gen(module.base_dir, build_dir) - command:reports_dir(reports_dir) - command:spring_property_filepaths(build_tool.get_spring_property_filepaths(project:get_module_dirs())) -- TEST SELECTORS @@ -96,7 +98,11 @@ local SpecBuilder = function(deps) -- COMPILATION STEP local compile_mode = config.incremental_build and "incremental" or "full" - pcall(deps.compile, module.base_dir, compile_mode) + local compiled, compile_result = pcall(deps.compile, module.base_dir, compile_mode) + assert( + compiled and compile_result ~= false, + "Java compilation failed for " .. tostring(module.base_dir) .. ": " .. tostring(compile_result) + ) local classpath_file_arg = deps.classpath_provider.get_classpath( module.base_dir, @@ -104,6 +110,15 @@ local SpecBuilder = function(deps) ) command:classpath_file_arg(classpath_file_arg) + -- Reserve reports only after compilation/classpath succeed. + local reports_dir = deps.report_folder_name_gen(module.base_dir, build_dir) + command:reports_dir(reports_dir) + local function cleanup_reports() + if deps.cleanup_reports then + deps.cleanup_reports(reports_dir) + end + end + -- DAP STRATEGY if args.strategy == "dap" then local port = random_port() @@ -112,7 +127,16 @@ local SpecBuilder = function(deps) command:port(port) local junit = command:build_to_table() logger.debug("junit debug command: ", junit.command, " ", table.concat(junit.args, " ")) - local terminated_command_event = deps.launch_debug_test(junit.command, junit.args, module.base_dir) + local launched, process = pcall(deps.launch_debug_test, junit.command, junit.args, module.base_dir, { + startup_timeout_ms = config.debug_startup_timeout_ms, + exit_timeout_ms = config.debug_exit_timeout_ms, + shutdown_timeout_ms = config.debug_shutdown_timeout_ms, + on_failure = cleanup_reports, + }) + if not launched then + cleanup_reports() + error(process) + end local project_name = module.name return { @@ -123,13 +147,28 @@ local SpecBuilder = function(deps) host = "localhost", port = port, projectName = project_name, + before = function(cfg) + process.claim() + return cfg + end, + after = nio.create(function(reason) + if reason then + process.stop(reason) + end + local state = process.wait_exit() + if state.error or state.cancelled or not state.exited then + error(state.error or "Java test process did not exit") + end + end, 1), }, cwd = module.base_dir:to_string(), symbol = position.type == "test" and position.name or nil, context = { strategy = args.strategy, reports_dir = reports_dir, - terminated_command_event = terminated_command_event, + terminated_command_event = process, + process = process, + cleanup_reports = deps.cleanup_reports and cleanup_reports or nil, }, } end @@ -141,7 +180,10 @@ local SpecBuilder = function(deps) command = command_array, cwd = module.base_dir:to_string(), symbol = position.name, - context = { reports_dir = reports_dir }, + context = { + reports_dir = reports_dir, + cleanup_reports = deps.cleanup_reports and cleanup_reports or nil, + }, } end, } diff --git a/lua/neotest-java/default_config.lua b/lua/neotest-java/default_config.lua index b613049a..64f1d2d3 100644 --- a/lua/neotest-java/default_config.lua +++ b/lua/neotest-java/default_config.lua @@ -38,6 +38,9 @@ end ---@field default_junit_jar_version neotest-java.JunitVersion ---@field test_classname_patterns string[] | nil ---@field disable_update_notifications boolean | nil +---@field debug_startup_timeout_ms? number Maximum JDWP readiness wait (default 30000). +---@field debug_exit_timeout_ms? number Maximum exit/report wait after DAP closes (default 5000). +---@field debug_shutdown_timeout_ms? number Grace period before SIGKILL (default 1000). ---@field get_supported_versions fun(): table[] ---@type neotest-java.ConfigOpts diff --git a/lua/neotest-java/init.lua b/lua/neotest-java/init.lua index 4d7c5d41..b26ab728 100644 --- a/lua/neotest-java/init.lua +++ b/lua/neotest-java/init.lua @@ -49,8 +49,10 @@ local function mkdir(dir) end local function report_folder_name_gen(module_dir, build_dir) - local base = (module_dir and module_dir:append(build_dir:to_string())) or build_dir - return base:append("junit-reports"):append(nio.fn.strftime("%d%m%y%H%M%S")) + local base = build_dir.is_absolute and build_dir or module_dir:append(build_dir:to_string()) + local parent = base:append("junit-reports") + nio.fn.mkdir(tostring(parent), "p") + return Path(assert(vim.uv.fs_mkdtemp(tostring(parent:append("run-XXXXXX"))))) end local function remove_file(filepath) @@ -199,7 +201,7 @@ local function NeotestJavaAdapter(config, deps) mkdir = mkdir, scan = scan, compile = function(base_dir, compile_mode) - resolved.lsp_compiler.compile({ + return resolved.lsp_compiler.compile({ base_dir = base_dir, compile_mode = compile_mode, }) @@ -208,6 +210,9 @@ local function NeotestJavaAdapter(config, deps) build_tool_getter = resolved.build_tool_getter, detect_project_type = detect_project_type, launch_debug_test = launcher.launch_debug_test, + cleanup_reports = function(dir) + nio.fn.delete(tostring(dir), "rf") + end, root_finder = resolved.root_finder, }) diff --git a/tests/integration/test_launcher_spec.lua b/tests/integration/test_launcher_spec.lua index 07a7fda6..c540868b 100644 --- a/tests/integration/test_launcher_spec.lua +++ b/tests/integration/test_launcher_spec.lua @@ -1,53 +1,69 @@ local async = require("tests.async_helpers").async -local assertions = require("tests.assertions") -local eq = assertions.eq +local eq = require("tests.assertions").eq local MiniTest = require("mini.test") - local Path = require("neotest-java.model.path") local BuildToolLauncher = require("neotest-java.build_tool.launcher").new --- dap_repl = false: this environment has no nvim-dap installed. In real --- usage `spec_builder` already asserts `require("dap")` succeeds before --- reaching `launch_debug_test` (see core/spec_builder/init.lua), so the --- real dap.repl module would be present too. Here we only care about the --- job-spawn + JDWP-wait behavior, not the dap.repl integration. local launcher = BuildToolLauncher({ dap_repl = false }) ---- Real-process integration coverage for `launcher.launch_debug_test`. ---- ---- This spawns an actual JVM with a JDWP debug agent (the same mechanism ---- neotest-java uses to run tests under `strategy = "dap"`), without ---- attaching a real debugger. A JVM started with ---- `-agentlib:jdwp=...,suspend=n` prints ---- "Listening for transport dt_socket at address: " to stdout as ---- soon as the debug socket is open, then continues running normally. ---- ---- This exercises the real default `vim.system`-backed job runner's spawn + ---- JDWP "Listening" wait + process-exit logic end-to-end. +local function java(args, opts) + return launcher.launch_debug_test("java", args, Path(vim.uv.cwd()), opts) +end + +local function with_java(fn) + return async(function() + if vim.fn.executable("java") == 0 then + MiniTest.skip("java executable not found on PATH") + return + end + fn() + end) +end + describe("BuildToolLauncher (real JVM integration)", function() it( - "detects the JDWP 'Listening' message from a real JVM and waits for it to exit", - async(function() - if vim.fn.executable("java") == 0 then - MiniTest.skip("java executable not found on PATH; skipping real-JVM integration test") - return - end - - local args = { - "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0", - "-version", - } + "detects JDWP and waits for a real JVM exit", + with_java(function() + local process = java({ "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0", "-version" }) + eq(true, process.state.ready) + eq(0, process.wait().code) + eq(true, process.is_set()) + end) + ) - local terminated_event = launcher.launch_debug_test("java", args, Path(vim.uv.cwd())) + for _, arg in ipairs({ "-version", "-not-a-valid-java-option" }) do + it( + "settles a real JVM exit before readiness: " .. arg, + with_java(function() + local ok, err = pcall(java, { arg }, { startup_timeout_ms = 2000 }) + eq(false, ok) + assert(tostring(err):find("before JDWP readiness", 1, true)) + end) + ) + end - -- `launch_debug_test` only returns once the JVM has printed the - -- "Listening" line, proving the real vim.system-backed stdout wiring - -- correctly detects it. - assert(terminated_event ~= nil, "should return a terminated_command_event") + it( + "reaps a suspended JVM after bounded exit/report wait", + with_java(function() + local process = java({ "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=0", "-version" }, { + exit_timeout_ms = 20, + shutdown_timeout_ms = 20, + }) + local state = process.wait_exit() + eq(true, state.cancelled) + eq(true, state.exited) + assert(state.error:find("exit/report", 1, true)) + local alive = vim.uv.kill(state.pid, 0) + assert(not alive, "the invocation's JVM must be reaped") + end) + ) - -- `java -version` exits almost immediately once started; wait for - -- the process-exit event to prove on_exit fires for a real job. - terminated_event.wait() - eq(true, terminated_event.is_set()) + it( + "settles executable spawn failure", + async(function() + local ok, err = + pcall(launcher.launch_debug_test, "no-such-java-executable-neotest-342", {}, Path(vim.uv.cwd())) + eq(false, ok) + assert(tostring(err):find("Could not start Java test", 1, true)) end) ) end) diff --git a/tests/integration/test_report_lifecycle_spec.lua b/tests/integration/test_report_lifecycle_spec.lua new file mode 100644 index 00000000..ff09f994 --- /dev/null +++ b/tests/integration/test_report_lifecycle_spec.lua @@ -0,0 +1,61 @@ +local eq = require("tests.assertions").eq + +describe("Invocation-owned reports", function() + it("isolates rapid runs, rejects stale XML and removes only owned reports", function() + -- The native mini.test harness intentionally disables nio.scheduler. + -- Use an unpatched child loop for real async file I/O and Vim functions. + local code = [[ +local root_dir = vim.uv.cwd() +for _, path in ipairs({ root_dir, root_dir .. '/.dependencies/nvim-nio', root_dir .. '/.dependencies/neotest', root_dir .. '/.dependencies/plenary.nvim' }) do + vim.opt.rtp:append(path) +end +local nio = require('nio') +local Path = require('neotest-java.model.path') +local Tree = require('neotest.types').Tree +local root = Path(vim.fn.tempname()) +local XML = '' +vim.fn.mkdir(tostring(root:append('src/test/java/example')), 'p') +vim.fn.writefile({ 'fixture' }, tostring(root:append('pom.xml'))) +local stale = root:append('target/junit-reports/stale') +vim.fn.mkdir(tostring(stale), 'p') +vim.fn.writefile({ XML }, tostring(stale:append('TEST-old.xml'))) +local id = 'example.Test#selected()' +local tree = Tree.from_list({ id = id, name = 'selected', type = 'test', path = tostring(root:append('src/test/java/example/Test.java')) }, function(pos) return pos.id end) +tree:data().ref = function() return id end +local adapter = require('neotest-java')({ disable_update_notifications = true }, { + root_finder = { find_root = function() return tostring(root) end }, + check_junit_jar_deps = { file_exists = function() return true end }, + lsp_compiler = { compile = function() return true end }, + binaries = { java = function() return Path('java') end }, + classpath_provider = { get_classpath = function() return 'classes' end }, +}) +local done, ok, err +nio.run(function() + local first = adapter.build_spec({ tree = tree }) + local second = adapter.build_spec({ tree = tree }) + assert(first.context.reports_dir ~= second.context.reports_dir, 'same-second runs must not share reports') + nio.fn.writefile({ XML }, tostring(first.context.reports_dir:append('TEST-current.xml'))) + local result = adapter.results(first, { code = 0, output = 'process.log' }, tree) + assert(result[id].status == 'passed', vim.inspect(result)) + local missing = adapter.results(second, { code = 0, output = 'process.log' }, tree) + assert(missing[id].status == 'failed', vim.inspect(missing)) + assert(missing[id].short:find('No JUnit result', 1, true)) + assert(not vim.uv.fs_stat(tostring(first.context.reports_dir))) + assert(not vim.uv.fs_stat(tostring(second.context.reports_dir))) + assert(vim.uv.fs_stat(tostring(stale:append('TEST-old.xml')))) +end, function(success, message) + ok, err, done = success, message, true +end) +local settled = vim.wait(8000, function() return done end, 10) +vim.fn.delete(tostring(root), 'rf') +if not settled or not ok then + print(tostring(err or 'report lifecycle timed out')) + vim.cmd('cquit 1') +else + vim.cmd('qa!') +end +]] + local result = vim.system({ vim.v.progpath, "--headless", "-u", "NONE", "-c", "lua " .. code }):wait(10000) + eq(0, result.code, result.stderr .. result.stdout) + end) +end) diff --git a/tests/unit/test_binaries_spec.lua b/tests/unit/test_binaries_spec.lua index 0bcea249..7e8b25db 100644 --- a/tests/unit/test_binaries_spec.lua +++ b/tests/unit/test_binaries_spec.lua @@ -19,7 +19,7 @@ describe("Binaries", function() request = function(_, method, params, callback) eq(method, "workspace/executeCommand") eq(params.command, "java.project.getSettings") - eq(params.arguments[1], "file://some") + eq(params.arguments[1], vim.uri_from_fname(expected_cwd:to_string())) eq(params.arguments[2], { "org.eclipse.jdt.ls.core.vm.location" }) if callback then diff --git a/tests/unit/test_launcher_spec.lua b/tests/unit/test_launcher_spec.lua index 0ffd30a5..0492a186 100644 --- a/tests/unit/test_launcher_spec.lua +++ b/tests/unit/test_launcher_spec.lua @@ -1,112 +1,203 @@ local async = require("tests.async_helpers").async -local assertions = require("tests.assertions") -local eq = assertions.eq - +local eq = require("tests.assertions").eq local Path = require("neotest-java.model.path") local BuildToolLauncher = require("neotest-java.build_tool.launcher").new +local BANNER = "Listening for transport dt_socket at address: 12345" + +local function fixture(on_start) + local opts, kills + kills = {} + local launcher = BuildToolLauncher({ + dap_repl = false, + job_runner = { + new = function(_, callbacks) + opts = callbacks + return { + start = function() + on_start(callbacks) + return { + kill = function(_, signal) + kills[#kills + 1] = signal + if signal == 9 then + callbacks.on_exit(nil, 137, 9) + end + end, + } + end, + } + end, + }, + }) + return launcher, function() + return opts, kills + end +end ---- Build a stub job runner mimicking the shape the job runner contract ---- exposes (`Job:new(opts)` returning an object with `start()`). The stub captures ---- the callbacks and lets `start()` drive them synchronously via ---- `on_start`, matching how a real job would invoke them from its own ---- process lifecycle (started -> stdout/stderr chunks -> exit) without ---- needing real process I/O or a scheduler tick. -local function stub_job_runner(on_start) - local started_opts = nil - - return { - new = function(_, opts) - started_opts = opts - return { - start = function() - if on_start then - on_start(opts) - end - end, - } - end, - opts = function() - return started_opts - end, - } +local function launch(launcher, opts) + return launcher.launch_debug_test("java", { "-jar", "test.jar" }, Path("/fake/cwd"), opts) end describe("BuildToolLauncher", function() it( - "starts the job with the given command, args and cwd", + "retains the system handle and the legacy bounded event API", async(function() - local runner = stub_job_runner(function(opts) - opts.on_stdout(nil, "Listening for transport dt_socket at address: 12345") + local launcher, inspect = fixture(function(opts) + opts.on_stdout(nil, BANNER) end) - local launcher = BuildToolLauncher({ job_runner = runner, dap_repl = false }) - - launcher.launch_debug_test("java", { "-jar", "foo.jar" }, Path("/fake/cwd")) - - local opts = runner.opts() - assert(opts ~= nil, "job runner should have been started with opts") + local process = launch(launcher) + local opts = inspect() eq("java", opts.command) - eq({ "-jar", "foo.jar" }, opts.args) - eq(Path("/fake/cwd"):to_string(), opts.cwd) + eq({ "-jar", "test.jar" }, opts.args) + eq(tostring(Path("/fake/cwd")), opts.cwd) + eq(false, process.is_set()) + opts.on_exit(nil, 0, 0) + opts.on_exit(nil, 8, 0) -- duplicate completion cannot overwrite the outcome + eq(true, process.is_set()) + eq(0, process.wait().code) end) ) + for _, stream in ipairs({ "on_stdout", "on_stderr" }) do + it( + "recognizes split JDWP readiness on " .. stream, + async(function() + local launcher, inspect = fixture(function(opts) + opts[stream](nil, nil) + opts[stream](nil, "Listening for transport dt_") + opts[stream](nil, "socket at address: 99") + end) + local process = launch(launcher) + eq(true, process.state.ready) + inspect().on_exit(nil, 0) + end) + ) + end + + for _, code in ipairs({ 0, 1, 7 }) do + it( + "fails promptly on pre-readiness exit " .. code, + async(function() + local launcher = fixture(function(opts) + opts.on_stderr(nil, "broken classpath") + opts.on_exit(nil, code) + end) + local ok, err = pcall(launch, launcher) + eq(false, ok) + assert(tostring(err):find("before JDWP readiness", 1, true)) + assert(tostring(err):find("broken classpath", 1, true)) + end) + ) + end + it( - "resolves the returned event only once stdout reports 'Listening'", + "settles startup exceptions", async(function() - local resolved = false - local runner = stub_job_runner(function(opts) - -- irrelevant stdout should not resolve the wait - opts.on_stdout(nil, "compiling...") - eq(false, resolved) - opts.on_stdout(nil, "Listening for transport dt_socket at address: 54321") + local launcher = fixture(function() + error("spawn exploded") end) - local launcher = BuildToolLauncher({ job_runner = runner, dap_repl = false }) - - launcher.launch_debug_test("java", {}, Path("/fake/cwd")) - resolved = true - - eq(true, resolved) + local ok, err = pcall(launch, launcher) + eq(false, ok) + assert(tostring(err):find("spawn exploded", 1, true)) end) ) it( - "sets the terminated event when the job exits", + "bounds missing readiness and escalates only its owned process", async(function() - local runner = stub_job_runner(function(opts) - opts.on_stdout(nil, "Listening") + local launcher, inspect = fixture(function(opts) + opts.on_stdout(nil, "Listening is not a JDWP banner") end) - local launcher = BuildToolLauncher({ job_runner = runner, dap_repl = false }) - - local terminated_event = launcher.launch_debug_test("java", {}, Path("/fake/cwd")) - - local opts = runner.opts() - assert(opts ~= nil, "job runner should have been started with opts") - local terminated_before = terminated_event.is_set() - opts.on_exit(nil, 0) - local terminated_after = terminated_event.is_set() - - eq(false, terminated_before) - eq(true, terminated_after) + local ok, err = pcall(launch, launcher, { startup_timeout_ms = 10, shutdown_timeout_ms = 10 }) + eq(false, ok) + assert(tostring(err):find("Timed out", 1, true)) + local _, kills = inspect() + eq({ 15, 9 }, kills) end) ) it( - "ignores nil stdout/stderr chunks without erroring", + "bounds exit and makes cancellation idempotent", async(function() - local runner = stub_job_runner(function(opts) - opts.on_stdout(nil, nil) - opts.on_stderr(nil, nil) - opts.on_stdout(nil, "Listening") + local launcher, inspect = fixture(function(opts) + opts.on_stdout(nil, BANNER) end) - local launcher = BuildToolLauncher({ job_runner = runner, dap_repl = false }) + local process = launch(launcher, { exit_timeout_ms = 10, shutdown_timeout_ms = 10 }) + local state = process.wait_exit() + eq(true, state.cancelled) + process.stop("another cancellation") + eq(true, state.exited) + local _, kills = inspect() + eq({ 15, 9 }, kills) + assert(state.error:find("exit/report", 1, true)) + end) + ) - local terminated_event = launcher.launch_debug_test("java", {}, Path("/fake/cwd")) - eq(false, terminated_event.is_set()) + it( + "reaps an unclaimed ready process without limiting a claimed debugger", + async(function() + local launcher, inspect = fixture(function(opts) + opts.on_stdout(nil, BANNER) + end) + local process = launch(launcher, { attach_timeout_ms = 10, shutdown_timeout_ms = 10 }) + eq(true, process.wait_exit(200).exited) + local _, kills = inspect() + eq({ 15, 9 }, kills) + local other, inspect_other = fixture(function(opts) + opts.on_stdout(nil, BANNER) + end) + local claimed = launch(other, { attach_timeout_ms = 10 }) + claimed.claim() + require("nio").wrap(function(callback) + local timer = vim.uv.new_timer() + timer:start(30, 0, function() + timer:close() + callback() + end) + end, 1)() + eq(false, claimed.state.cancelled) + inspect_other().on_exit(nil, 0) end) ) - it("defaults to a vim.system-backed job runner when no job_runner is injected", function() - local launcher = BuildToolLauncher({ dap_repl = false }) - assert(launcher.launch_debug_test ~= nil, "launch_debug_test should exist with default deps") - end) + it( + "does not stop a concurrent invocation", + async(function() + local first, inspect_first = fixture(function(opts) + opts.on_stdout(nil, BANNER) + end) + local second, inspect_second = fixture(function(opts) + opts.on_stdout(nil, BANNER) + end) + local a = launch(first, { shutdown_timeout_ms = 10 }) + local b = launch(second) + a.stop() + eq(true, a.wait_exit(200).exited) + local _, first_kills = inspect_first() + local _, second_kills = inspect_second() + eq({ 15, 9 }, first_kills) + eq({}, second_kills) + eq(false, b.state.cancelled) + inspect_second().on_exit(nil, 0) + end) + ) + it( + "reaps startup even if the readiness task is cancelled", + async(function() + local nio = require("nio") + local launcher, inspect = fixture(function() end) + local task = nio.run(function() + launch(launcher, { startup_timeout_ms = 10, shutdown_timeout_ms = 10 }) + end, function() end) + task.cancel() + nio.wrap(function(callback) + local timer = vim.uv.new_timer() + timer:start(50, 0, function() + timer:close() + callback() + end) + end, 1)() + local _, kills = inspect() + eq({ 15, 9 }, kills) + end) + ) end) diff --git a/tests/unit/test_lsp_compiler_spec.lua b/tests/unit/test_lsp_compiler_spec.lua index 8d7cf124..e3950d51 100644 --- a/tests/unit/test_lsp_compiler_spec.lua +++ b/tests/unit/test_lsp_compiler_spec.lua @@ -1,28 +1,98 @@ local LspCompiler = require("neotest-java.core.spec_builder.compiler.lsp_compiler") local Path = require("neotest-java.model.path") +local eq = require("tests.assertions").eq +local async = require("tests.async_helpers").async +local args = { base_dir = Path("/path/to/project"), compile_mode = "incremental" } -local assertions = require("tests.assertions") -local eq = assertions.eq +local function compiler(client, opts) + return LspCompiler(vim.tbl_extend("force", { + client_provider = function(cwd) + eq(args.base_dir, cwd) + return client + end, + schedule = function(fn) + fn() + end, + timeout_ms = 20, + }, opts or {})) +end describe("LSP compiler", function() - it("works", function() - local compiler = LspCompiler({ - client_provider = function(cwd) - eq(Path("/path/to/project"), cwd) - return { - request = function(_, params, opts) - eq("java/buildWorkspace", params) - eq({ forceRebuild = false }, opts) + for _, mode in ipairs({ "incremental", "full" }) do + it( + "awaits successful " .. mode .. " compilation", + async(function() + local callback, completed = nil, false + local c = compiler({ + initialized = true, + request = function(_, method, params, cb) + eq("java/buildWorkspace", method) + eq(mode == "full", params) + callback = cb + local timer = vim.uv.new_timer() + timer:start(5, 0, function() + eq(false, completed) + timer:close() + cb(nil, 1) + end) + return true, 42 + end, + }) + eq(true, c.compile({ base_dir = args.base_dir, compile_mode = mode })) + completed = true + assert(callback) + callback(nil, 2) -- late callback ignored after exactly-once completion + end) + ) + end + for _, status in ipairs({ 0, 2, 3, false, "unexpected" }) do + it( + "rejects unsuccessful build status " .. tostring(status), + async(function() + local c = compiler({ + initialized = true, + request = function(_, _, _, cb) + cb(nil, status) return true end, - } - end, - }) + }) + local ok, err = pcall(c.compile, args) + eq(false, ok) + assert(tostring(err):find("buildWorkspace status", 1, true)) + end) + ) + end - compiler.compile({ - base_dir = Path("/path/to/project"), - compile_mode = "incremental", - }) + it("rejects an absent or uninitialized JDTLS client", function() + for _, client in ipairs({ false, { initialized = false } }) do + local ok, err = pcall(compiler(client).compile, args) + eq(false, ok) + assert(tostring(err):find("not initialized", 1, true)) + end end) + + for _, kind in ipairs({ "error", "throw", "reject", "timeout" }) do + it( + "settles request " .. kind, + async(function() + local c = compiler({ + initialized = true, + request = function(_, _, _, cb) + if kind == "error" then + cb({ message = "build broken" }) + elseif kind == "throw" then + error("request exploded") + elseif kind == "reject" then + return false + end + return true + end, + }) + local ok, err = pcall(c.compile, args) + eq(false, ok) + assert(tostring(err):find("compilation failed", 1, true)) + end) + ) + end end) diff --git a/tests/unit/test_result_builder_spec.lua b/tests/unit/test_result_builder_spec.lua index a4aa485f..e0b9b599 100644 --- a/tests/unit/test_result_builder_spec.lua +++ b/tests/unit/test_result_builder_spec.lua @@ -95,13 +95,18 @@ local function reader_returning(jrs) } end +local function missing(id) + local message = "No JUnit result reported for selected test: " .. id + return { status = "failed", output = "output", short = message, errors = { { message = message } } } +end + describe("ResultBuilder", function() local remove_file = function() end local fake_tempname = function() return TEMPNAME end - it("returns empty when the reader returns empty", function() + it("fails selected tests when the reader returns empty", function() -- given local file_path = current_dir .. "tests/fixtures/maven-demo/src/test/java/com/example/ExampleTest.java" local tree = TREES.TWO_TESTS_IN_FILE(Path(file_path)) @@ -115,7 +120,10 @@ describe("ResultBuilder", function() }).build_results(DEFAULT_SPEC, SUCCESSFUL_RESULT, tree) -- then - eq({}, result) + eq({ + ["com.example.ExampleTest#firstTestMethod()"] = missing("com.example.ExampleTest#firstTestMethod()"), + ["com.example.ExampleTest#secondTestMethod()"] = missing("com.example.ExampleTest#secondTestMethod()"), + }, result) end) it("should build results from report", function() @@ -172,6 +180,7 @@ describe("ResultBuilder", function() status = "passed", output = TEMPNAME, }, + ["com.example.ExampleTest#secondTestMethod()"] = missing("com.example.ExampleTest#secondTestMethod()"), }, ResultBuilder({ scan_dir = scan_dir_returning(file_path), @@ -274,7 +283,10 @@ describe("ResultBuilder", function() tempname_fn = fake_tempname, }).build_results(DEFAULT_SPEC, SUCCESSFUL_RESULT, tree) - eq({ [id] = { status = "passed", output = TEMPNAME } }, result) + eq({ + [id] = { status = "passed", output = TEMPNAME }, + ["com.example.ExampleTest#firstTestMethod()"] = missing("com.example.ExampleTest#firstTestMethod()"), + }, result) end) it("builds failed results when assertion message contains a greater-than character", function() @@ -308,6 +320,7 @@ describe("ResultBuilder", function() status = "failed", output = TEMPNAME, }, + ["com.example.ExampleTest#secondTestMethod()"] = missing("com.example.ExampleTest#secondTestMethod()"), }, ResultBuilder({ scan_dir = scan_dir_returning(file_path), diff --git a/tests/unit/test_result_lifecycle_spec.lua b/tests/unit/test_result_lifecycle_spec.lua new file mode 100644 index 00000000..4b63d24c --- /dev/null +++ b/tests/unit/test_result_lifecycle_spec.lua @@ -0,0 +1,103 @@ +local ResultBuilder = require("neotest-java.core.result_builder") +local JunitResult = require("neotest-java.model.junit_result") +local Path = require("neotest-java.model.path") +local Tree = require("neotest.types").Tree +local eq = require("tests.assertions").eq + +local id = "example.Test#selected()" +local other = "example.Test#missing()" +local tree = Tree.from_list({ + { id = "file", name = "file", path = "Test.java", type = "file" }, + { id = id, name = "selected", path = "Test.java", type = "test" }, + { id = other, name = "missing", path = "Test.java", type = "test" }, +}, function(pos) + return pos.id +end) + +local function setup(testcases, process) + local cleaned, scans = 0, 0 + local spec = { + context = { + reports_dir = Path("invocation-owned"), + process = process, + cleanup_reports = function() + cleaned = cleaned + 1 + end, + }, + } + local builder = ResultBuilder({ + scan_dir = function() + scans = scans + 1 + return {} + end, + junit_result_reader = { + read_all = function() + return testcases + end, + }, + remove_file = function() + return true + end, + tempname_fn = function() + return vim.fn.tempname() + end, + }) + return function(result) + return builder.build_results(spec, result or { code = 0, output = "process.log" }, tree) + end, function() + return cleaned, scans + end +end + +describe("Result lifecycle", function() + it("fails every selected test when reports are absent or empty", function() + local run, inspect = setup({}) + local results = run() + for _, key in ipairs({ id, other }) do + eq("failed", results[key].status) + assert(results[key].short:find(key, 1, true)) + end + eq(1, inspect()) + end) + + it("preserves a reported pass but fails an unreported selected test", function() + local run = setup({ JunitResult:new({ _attr = { name = "selected()", classname = "example.Test" } }) }) + local results = run() + eq("passed", results[id].status) + eq("failed", results[other].status) + end) + + for _, reason in ipairs({ "cancelled", "attach failed", "exit timeout" }) do + it("never trusts reports after " .. reason, function() + local stopped = 0 + local run, inspect = setup({}, { + stop = function() + stopped = stopped + 1 + end, + wait_exit = function() + return { exited = true, code = 0 } + end, + }) + local results = run({ code = 1, error = reason, output = "process.log" }) + eq(1, stopped) + local cleaned, scans = inspect() + eq(1, cleaned) + eq(0, scans) + for _, key in ipairs({ id, other }) do + eq("failed", results[key].status) + eq(reason, results[key].short) + end + end) + end + + it("uses the owned JVM status even when the debugger says success", function() + local run = setup({}, { + wait_exit = function() + return { exited = true, code = 17, stderr = "JVM failed" } + end, + }) + local results = run() + eq("failed", results[id].status) + assert(results[id].short:find("17", 1, true)) + end) +end) diff --git a/tests/unit/test_spec_builder_spec.lua b/tests/unit/test_spec_builder_spec.lua index 543d4652..632c7b59 100644 --- a/tests/unit/test_spec_builder_spec.lua +++ b/tests/unit/test_spec_builder_spec.lua @@ -520,7 +520,7 @@ describe("SpecBuilder", function() it("builds spec for debug test (dap strategy)", function() -- Mock dap module to avoid error - package.loaded["dap"] = {} + package.loaded["dap"] = { adapters = { java = {} } } local tree = Tree.from_list({ id = "com.example.ExampleTest#shouldNotFail()", @@ -565,7 +565,16 @@ describe("SpecBuilder", function() } -- Mock launch_debug_test - local mock_terminated_event = { mock = "event" } + local claimed, waited = false, false + local mock_terminated_event = { + claim = function() + claimed = true + end, + wait_exit = function() + waited = true + return { exited = true, code = 0 } + end, + } local launch_debug_test_called = false local launch_debug_test_args = {} local captured_port = nil @@ -677,73 +686,109 @@ describe("SpecBuilder", function() eq(Path("report_folder"), actual.context.reports_dir) ---@diagnostic disable-next-line: need-check-nil eq(mock_terminated_event, actual.context.terminated_command_event) + local cfg = {} + assert(actual) + eq(cfg, actual.strategy.before(cfg)) + eq(true, claimed) + -- Legacy Neotest calls this hook outside nio; newer strategies await + -- it inside nio. Both must work without blocking the main loop. + actual.strategy.after() + eq(true, waited) end) - it("builds a spec even if compilation throws an error (resilience)", function() - local path = Path("/user/home/root/src/test/java/com/example/Test.java") - local parent_path = path:parent() - local project_paths = { parent_path, parent_path:append("pom.xml") } + for _, failure in ipairs({ "throw", "false" }) do + it("never builds a stale spec after compilation " .. failure, function() + local path = Path("/user/home/root/src/test/java/com/example/Test.java") + local parent_path = path:parent() + local project_paths = { parent_path, parent_path:append("pom.xml") } - ---@diagnostic disable-next-line: missing-fields - local spec_builder_instance = SpecBuilder({ - mkdir = function() end, - scan = function() - return project_paths - end, - compile = function() - error("jdtls compiler crashed") - end, - classpath_provider = { - get_classpath = function() - return "classpath" + ---@diagnostic disable-next-line: missing-fields + local spec_builder_instance = SpecBuilder({ + mkdir = function() end, + scan = function() + return project_paths end, - }, - report_folder_name_gen = function() - return Path("target/reports") - end, - binaries = { - java = function() - return Path("java") + compile = function() + if failure == "throw" then + error("jdtls compiler crashed") + end + return false end, - javap = function() - return Path("javap") + classpath_provider = { + get_classpath = function() + error("classpath must not be resolved after compile failure") + end, + }, + report_folder_name_gen = function() + error("reports must not be reserved after compile failure") end, - }, - build_tool_getter = function() - return FakeBuildTool - end, - detect_project_type = function() - return "maven" - end, - }) - - local tree = Tree.from_list({ - id = "com.example.Test#myTest()", - path = path:to_string(), - name = "myTest", - type = "test", - }, function(x) - return x - end) - -- Add ref method to the tree node - local position = tree:data() - local mt = getmetatable(position) or {} - local original_index = mt.__index - mt.__index = function(t, k) - if k == "ref" then - return function() - return t.id + binaries = { + java = function() + return Path("java") + end, + javap = function() + return Path("javap") + end, + }, + build_tool_getter = function() + return FakeBuildTool + end, + detect_project_type = function() + return "maven" + end, + launch_debug_test = function() + error("debug JVM must not launch after compile failure") + end, + }) + + local tree = Tree.from_list({ + id = "com.example.Test#myTest()", + path = path:to_string(), + name = "myTest", + type = "test", + }, function(x) + return x + end) + -- Add ref method to the tree node + local position = tree:data() + local mt = getmetatable(position) or {} + local original_index = mt.__index + mt.__index = function(t, k) + if k == "ref" then + return function() + return t.id + end end + return type(original_index) == "function" and original_index(t, k) + or (type(original_index) == "table" and original_index[k]) end - return type(original_index) == "function" and original_index(t, k) - or (type(original_index) == "table" and original_index[k]) - end - setmetatable(position, mt) - - local args = { tree = tree } - local spec = spec_builder_instance.build_spec(args, config) + setmetatable(position, mt) - assert(spec ~= nil, "Spec should be built despite compile error") - assert(spec.command ~= nil, "Command should be built") + local args = { tree = tree } + local ok, err = pcall(spec_builder_instance.build_spec, args, config) + eq(false, ok) + assert(tostring(err):find("Java compilation failed for", 1, true)) + assert(tostring(err):find(tostring(parent_path), 1, true)) + end) + end + it("does not launch a JVM when the Java DAP adapter is unavailable", function() + local previous = package.loaded["dap"] + package.loaded["dap"] = { adapters = {} } + local launched = false + local ok, err = pcall( + ---@diagnostic disable-next-line: missing-fields + SpecBuilder({ + launch_debug_test = function() + launched = true + error("must not launch without Java Debug") + end, + }).build_spec, + { strategy = "dap", tree = TREES.PARAMETERIZED_TEST }, + config + ) + package.loaded["dap"] = previous + eq(false, ok) + eq(false, launched) + assert(tostring(err):find("Java Debug bundle", 1, true)) end) end)