From 48e4f00fc6579f16315ff39527a5c0bd2536c8d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= <31012661+rcasia@users.noreply.github.com> Date: Fri, 22 May 2026 00:01:10 +0200 Subject: [PATCH 1/7] feat: add Groovy/Spock test file pattern support Extend test file discovery to support .groovy files alongside .java. Adds GROOVY_TEST_FILE_PATTERNS and GROOVY_TEST_FILE_REGEXES to the patterns module and updates file_checker to strip .groovy extension when matching test class name patterns. Fixes #194 --- lua/neotest-java/core/file_checker.lua | 2 +- lua/neotest-java/model/patterns.lua | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lua/neotest-java/core/file_checker.lua b/lua/neotest-java/core/file_checker.lua index 8eb6a562..fc64d1d4 100644 --- a/lua/neotest-java/core/file_checker.lua +++ b/lua/neotest-java/core/file_checker.lua @@ -26,7 +26,7 @@ local FileChecker = function(dependencies) end for _, re in ipairs(dependencies.patterns) do - local name_without_extension = my_path:name():gsub("%.java$", "") + local name_without_extension = my_path:name():gsub("%.java$", ""):gsub("%.groovy$", "") if name_without_extension:match(re) then return true end diff --git a/lua/neotest-java/model/patterns.lua b/lua/neotest-java/model/patterns.lua index 1eff68df..de713751 100644 --- a/lua/neotest-java/model/patterns.lua +++ b/lua/neotest-java/model/patterns.lua @@ -50,9 +50,24 @@ local IGNORE_PATH_PATTERNS = { "^%.classpath$", -- Eclipse classpath file } +local GROOVY_TEST_FILE_PATTERNS = { + "Test%.groovy$", + "Tests%.groovy$", + "Spec%.groovy$", + "IT%.groovy$", +} + +local GROOVY_TEST_FILE_REGEXES = { + "^.*Tests?$", + "^.*IT$", + "^.*Spec$", +} + return { TEST_CLASS_PATTERNS = TEST_CLASS_PATTERNS, JAVA_TEST_FILE_PATTERNS = JAVA_TEST_FILE_PATTERNS, + GROOVY_TEST_FILE_PATTERNS = GROOVY_TEST_FILE_PATTERNS, IGNORE_PATH_PATTERNS = IGNORE_PATH_PATTERNS, JAVA_TEST_FILE_REGEXES = JAVA_TEST_FILE_REGEXES, + GROOVY_TEST_FILE_REGEXES = GROOVY_TEST_FILE_REGEXES, } From b00708f90b1f456917b6744ab3ee15663457c357 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= <31012661+rcasia@users.noreply.github.com> Date: Fri, 22 May 2026 00:10:17 +0200 Subject: [PATCH 2/7] test: add Groovy unit tests and E2E test suite Add unit tests for Groovy file pattern matching in file_checker: - Groovy test file discovery (*Spec.groovy, *Test.groovy, *IT.groovy) - Groovy non-test file exclusion - Groovy files in main folder exclusion Add E2E test suite (groovy_support_spec.lua) with complete Maven+Groovy fixture: - CalculatorSpec.groovy - Spock specification tests (4 tests) - UserServiceTest.groovy - Groovy JUnit tests (4 tests, 1 intentional failure) - Tests verify discovery, execution, and pass/fail reporting Fixture includes pom.xml with GMavenPlus plugin, Spock dependency, and source files for both Java and Groovy tests. Fixes #194 --- tests/e2e/groovy_support_spec.lua | 139 +++++++++ .../.mvn/wrapper/maven-wrapper.properties | 3 + tests/fixtures/maven-groovy/mvnw | 295 ++++++++++++++++++ tests/fixtures/maven-groovy/mvnw.cmd | 189 +++++++++++ tests/fixtures/maven-groovy/pom.xml | 63 ++++ .../src/main/java/com/example/Calculator.java | 22 ++ .../main/java/com/example/UserService.java | 33 ++ .../groovy/com/example/CalculatorSpec.groovy | 41 +++ .../groovy/com/example/UserServiceTest.groovy | 39 +++ tests/unit/test_file_checker_spec.lua | 35 +++ 10 files changed, 859 insertions(+) create mode 100644 tests/e2e/groovy_support_spec.lua create mode 100644 tests/fixtures/maven-groovy/.mvn/wrapper/maven-wrapper.properties create mode 100755 tests/fixtures/maven-groovy/mvnw create mode 100644 tests/fixtures/maven-groovy/mvnw.cmd create mode 100644 tests/fixtures/maven-groovy/pom.xml create mode 100644 tests/fixtures/maven-groovy/src/main/java/com/example/Calculator.java create mode 100644 tests/fixtures/maven-groovy/src/main/java/com/example/UserService.java create mode 100644 tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.groovy create mode 100644 tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.groovy diff --git a/tests/e2e/groovy_support_spec.lua b/tests/e2e/groovy_support_spec.lua new file mode 100644 index 00000000..c2fa86dd --- /dev/null +++ b/tests/e2e/groovy_support_spec.lua @@ -0,0 +1,139 @@ +---@diagnostic disable: undefined-field +-- E2E test: Groovy/Spock test discovery and execution +-- This test verifies that neotest-java correctly discovers and runs Groovy test files + +local nio = require("nio") + +describe("E2E: neotest-java Groovy/Spock support", function() + local neotest + local groovy_fixture_dir = vim.fn.getcwd() .. "/tests/fixtures/maven-groovy" + local calculator_spec = groovy_fixture_dir .. "/src/test/groovy/com/example/CalculatorSpec.groovy" + local user_service_test = groovy_fixture_dir .. "/src/test/groovy/com/example/UserServiceTest.groovy" + + before_each(function() + package.loaded["neotest"] = nil + package.loaded["neotest-java"] = nil + + neotest = require("neotest") + neotest.setup({ + adapters = { + require("neotest-java")({ + ignore_wrapper = false, + }), + }, + log_level = vim.log.levels.DEBUG, + }) + end) + + it("discovers Groovy test files with .groovy extension", function() + assert.is_true(vim.fn.filereadable(calculator_spec) == 1, "CalculatorSpec.groovy should exist") + assert.is_true(vim.fn.filereadable(user_service_test) == 1, "UserServiceTest.groovy should exist") + + nio.run(function() + neotest.run.run(calculator_spec) + + local max_wait = 30000 + local start_time = vim.uv.now() + local results = nil + + while vim.uv.now() - start_time < max_wait do + nio.sleep(500) + results = neotest.state.results() + if results and next(results) ~= nil then + break + end + end + + assert.is_not_nil(results, "Should have test results for CalculatorSpec.groovy") + assert.is_true(next(results) ~= nil, "Results should not be empty") + + local test_count = 0 + for test_id, _ in pairs(results) do + if test_id:match("Spec") or test_id:match("Test") then + test_count = test_count + 1 + end + end + + assert.is_true(test_count >= 4, "Should discover at least 4 tests from CalculatorSpec, got " .. test_count) + + print(string.format("\n✓ Groovy discovery: %d tests found in CalculatorSpec.groovy", test_count)) + end) + end) + + it("runs Groovy JUnit tests and reports pass/fail results", function() + nio.run(function() + neotest.run.run(user_service_test) + + local max_wait = 30000 + local start_time = vim.uv.now() + local results = nil + + while vim.uv.now() - start_time < max_wait do + nio.sleep(500) + results = neotest.state.results() + if results and next(results) ~= nil then + break + end + end + + assert.is_not_nil(results, "Should have test results for UserServiceTest.groovy") + + local passed = 0 + local failed = 0 + local total = 0 + + for test_id, result in pairs(results) do + if test_id:match("Test") then + total = total + 1 + if result.status == "passed" then + passed = passed + 1 + elseif result.status == "failed" then + failed = failed + 1 + end + end + end + + assert.is_true(total >= 4, "Should have at least 4 test results, got " .. total) + assert.is_true(passed >= 3, "Should have at least 3 passing tests, got " .. passed) + assert.is_true(failed >= 1, "Should have at least 1 failing test, got " .. failed) + + print(string.format("\n✓ Groovy JUnit Results: %d total, %d passed, %d failed", total, passed, failed)) + end) + end) + + it("discovers both Java and Groovy tests in mixed projects", function() + nio.run(function() + neotest.run.run(groovy_fixture_dir) + + local max_wait = 30000 + local start_time = vim.uv.now() + local results = nil + + while vim.uv.now() - start_time < max_wait do + nio.sleep(500) + results = neotest.state.results() + if results and next(results) ~= nil then + break + end + end + + assert.is_not_nil(results, "Should have test results") + + local groovy_tests = 0 + local java_tests = 0 + + for test_id, _ in pairs(results) do + if test_id:match("%.groovy") or test_id:match("Spec") then + groovy_tests = groovy_tests + 1 + elseif test_id:match("%.java") or test_id:match("Test") then + java_tests = java_tests + 1 + end + end + + assert.is_true(groovy_tests > 0, "Should discover Groovy tests") + assert.is_true(java_tests > 0, "Should discover Java tests") + + print(string.format("\n✓ Mixed project: %d Groovy tests, %d Java tests", groovy_tests, java_tests)) + end) + end) +end) diff --git a/tests/fixtures/maven-groovy/.mvn/wrapper/maven-wrapper.properties b/tests/fixtures/maven-groovy/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..ffcab66a --- /dev/null +++ b/tests/fixtures/maven-groovy/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/tests/fixtures/maven-groovy/mvnw b/tests/fixtures/maven-groovy/mvnw new file mode 100755 index 00000000..bd8896bf --- /dev/null +++ b/tests/fixtures/maven-groovy/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/tests/fixtures/maven-groovy/mvnw.cmd b/tests/fixtures/maven-groovy/mvnw.cmd new file mode 100644 index 00000000..5761d948 --- /dev/null +++ b/tests/fixtures/maven-groovy/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/tests/fixtures/maven-groovy/pom.xml b/tests/fixtures/maven-groovy/pom.xml new file mode 100644 index 00000000..0802272e --- /dev/null +++ b/tests/fixtures/maven-groovy/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + com.example + test-fixture-groovy + 1.0-SNAPSHOT + + + 11 + 11 + UTF-8 + 4.0.15 + + + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + org.apache.groovy + groovy + ${groovy.version} + + + org.spockframework + spock-core + 2.4-M4-groovy-4.0 + test + + + + + + + org.codehaus.gmavenplus + gmavenplus-plugin + 3.0.2 + + + + addTestSources + compileTests + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M9 + + false + + + + + diff --git a/tests/fixtures/maven-groovy/src/main/java/com/example/Calculator.java b/tests/fixtures/maven-groovy/src/main/java/com/example/Calculator.java new file mode 100644 index 00000000..32e15b72 --- /dev/null +++ b/tests/fixtures/maven-groovy/src/main/java/com/example/Calculator.java @@ -0,0 +1,22 @@ +package com.example; + +public class Calculator { + public int add(int a, int b) { + return a + b; + } + + public int subtract(int a, int b) { + return a - b; + } + + public int multiply(int a, int b) { + return a * b; + } + + public int divide(int a, int b) { + if (b == 0) { + throw new ArithmeticException("Division by zero"); + } + return a / b; + } +} diff --git a/tests/fixtures/maven-groovy/src/main/java/com/example/UserService.java b/tests/fixtures/maven-groovy/src/main/java/com/example/UserService.java new file mode 100644 index 00000000..448b4345 --- /dev/null +++ b/tests/fixtures/maven-groovy/src/main/java/com/example/UserService.java @@ -0,0 +1,33 @@ +package com.example; + +import java.util.ArrayList; +import java.util.List; + +public class UserService { + private final List users = new ArrayList<>(); + + public User createUser(String name) { + if (name == null || name.isEmpty()) { + throw new IllegalArgumentException("Name cannot be empty"); + } + User user = new User(name); + users.add(user); + return user; + } + + public int getUserCount() { + return users.size(); + } +} + +class User { + private final String name; + + public User(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.groovy b/tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.groovy new file mode 100644 index 00000000..20ee2cc5 --- /dev/null +++ b/tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.groovy @@ -0,0 +1,41 @@ +package com.example + +import spock.lang.Specification + +class CalculatorSpec extends Specification { + + def "addition of two positive numbers"() { + given: + def calculator = new Calculator() + + expect: + calculator.add(2, 3) == 5 + } + + def "subtraction returns correct result"() { + given: + def calculator = new Calculator() + + expect: + calculator.subtract(10, 4) == 6 + } + + def "multiplication by zero returns zero"() { + given: + def calculator = new Calculator() + + expect: + calculator.multiply(5, 0) == 0 + } + + def "division throws exception for zero divisor"() { + given: + def calculator = new Calculator() + + when: + calculator.divide(10, 0) + + then: + thrown(ArithmeticException) + } +} diff --git a/tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.groovy b/tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.groovy new file mode 100644 index 00000000..1678548a --- /dev/null +++ b/tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.groovy @@ -0,0 +1,39 @@ +package com.example + +import org.junit.jupiter.api.Test +import static org.junit.jupiter.api.Assertions.* + +class UserServiceTest { + + @Test + void "should create user with valid name"() { + def userService = new UserService() + def user = userService.createUser("John") + + assertNotNull(user) + assertEquals("John", user.getName()) + } + + @Test + void "should throw exception for empty name"() { + def userService = new UserService() + + assertThrows(IllegalArgumentException.class, { + userService.createUser("") + }) + } + + @Test + void "should return user count"() { + def userService = new UserService() + userService.createUser("Alice") + userService.createUser("Bob") + + assertEquals(2, userService.getUserCount()) + } + + @Test + void "should fail intentionally"() { + assertEquals(5, 2 + 2) + } +} diff --git a/tests/unit/test_file_checker_spec.lua b/tests/unit/test_file_checker_spec.lua index 325595dd..8fa3f745 100644 --- a/tests/unit/test_file_checker_spec.lua +++ b/tests/unit/test_file_checker_spec.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: undefined-field local FileChecker = require("neotest-java.core.file_checker") local Path = require("neotest-java.model.path") @@ -85,10 +86,44 @@ describe("file_checker", function() local file_checker = FileChecker({ patterns = patterns, root_getter = function() + ---@diagnostic disable-next-line: return-type-mismatch return nil end, }) assert.is_false(file_checker.is_test_file("/any/path/Test.java")) end) + + it("should return true for Groovy test files", function() + local groovy_test_files = { + base_path:append("src/test/groovy/neotest/UserServiceSpec.groovy"):to_string(), + base_path:append("src/test/groovy/neotest/OrderServiceTest.groovy"):to_string(), + base_path:append("src/test/groovy/neotest/PaymentIT.groovy"):to_string(), + base_path:append("src/test/groovy/neotest/domain/OrderTests.groovy"):to_string(), + } + + for _, file_path in ipairs(groovy_test_files) do + assert.is_true(file_checker_undertest.is_test_file(file_path), file_path) + end + end) + + it("should return false for Groovy non-test files", function() + local non_test_groovy_files = { + "src/test/groovy/neotest/UserService.groovy", + "src/test/groovy/neotest/Configuration.groovy", + "src/main/groovy/neotest/DomainService.groovy", + } + for _, file_path in ipairs(non_test_groovy_files) do + assert.is_false(file_checker_undertest.is_test_file(file_path), file_path) + end + end) + + it("should return false for Groovy files inside main folder", function() + local main_groovy_files = { + "/home/user/repo/src/main/groovy/neotest/UserServiceSpec.groovy", + } + for _, file_path in ipairs(main_groovy_files) do + assert.is_false(file_checker_undertest.is_test_file(file_path), file_path) + end + end) end) From 99282896a6fa5c43a5893c739bd9be192431ec80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= <31012661+rcasia@users.noreply.github.com> Date: Fri, 22 May 2026 00:15:51 +0200 Subject: [PATCH 3/7] ci: run groovy fixture tests in E2E pipeline Update run-all.sh to: - Discover and run all fixtures automatically (not just maven-simple) - Find both .java and .groovy test files in src/test/java and src/test/groovy - Support *Test, *Spec, and *IT naming conventions for both languages Update run.lua to: - Extract expected class name from .groovy files (not just .java) - Derive snapshot file names for .groovy test files Update minimal_init.lua to: - Include tests/e2e/*_spec.lua in test collection (previously only tests/unit) - Ensures groovy_support_spec.lua and full_workflow_spec.lua run in CI Fixes #194 --- scripts/minimal_init.lua | 5 +- tests/e2e/run-all.sh | 141 ++++++++++++++++++++++++++------------- tests/e2e/run.lua | 7 +- 3 files changed, 104 insertions(+), 49 deletions(-) diff --git a/scripts/minimal_init.lua b/scripts/minimal_init.lua index 00b437df..5e1201bf 100644 --- a/scripts/minimal_init.lua +++ b/scripts/minimal_init.lua @@ -1,5 +1,6 @@ -- scripts/minimal_init.lua -- Headless testing with mini.test, no user config loaded. +---@diagnostic disable: deprecated local DEPENDENCIES_DIR = "./.dependencies" @@ -123,7 +124,9 @@ require("mini.test").setup({ collect = { emulate_busted = true, find_files = function() - return vim.fn.globpath("tests/unit", "**/*_spec.lua", true, true) + local unit_files = vim.fn.globpath("tests/unit", "**/*_spec.lua", true, true) + local e2e_files = vim.fn.globpath("tests/e2e", "**/*_spec.lua", true, true) + return vim.list_extend(unit_files, e2e_files) end, }, execute = { diff --git a/tests/e2e/run-all.sh b/tests/e2e/run-all.sh index 736016ee..0605de1c 100755 --- a/tests/e2e/run-all.sh +++ b/tests/e2e/run-all.sh @@ -2,67 +2,118 @@ # Run all E2E tests # # Usage: -# ./tests/e2e/run-all.sh # Run all tests in all fixtures -# ./tests/e2e/run-all.sh maven-simple # Run tests in specific fixture +# ./tests/e2e/run-all.sh # Run all fixtures +# ./tests/e2e/run-all.sh maven-simple # Run specific fixture # -# This script finds all test files in the fixtures and runs E2E tests for each. +# This script finds all fixtures and runs E2E tests for each. +# Supports both Java (.java) and Groovy (.groovy) test files. set -e SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" -FIXTURE="${1:-maven-simple}" +FIXTURES_DIR="$PROJECT_ROOT/tests/fixtures" -FIXTURE_DIR="$PROJECT_ROOT/tests/fixtures/$FIXTURE" +run_fixture() { + local FIXTURE="$1" + local FIXTURE_DIR="$FIXTURES_DIR/$FIXTURE" -if [ ! -d "$FIXTURE_DIR" ]; then - echo "Error: Fixture directory not found: $FIXTURE_DIR" - exit 1 -fi + if [ ! -d "$FIXTURE_DIR" ]; then + echo "Error: Fixture directory not found: $FIXTURE_DIR" + return 1 + fi -echo "Running E2E tests for fixture: $FIXTURE" -echo "" + echo "Running E2E tests for fixture: $FIXTURE" + echo "" -# Find all test files in the fixture -TEST_FILES=$(find "$FIXTURE_DIR/src/test/java" -name "*Test.java" 2>/dev/null || true) + # Find Java and Groovy test files + local TEST_FILES="" + if [ -d "$FIXTURE_DIR/src/test/java" ]; then + TEST_FILES=$(find "$FIXTURE_DIR/src/test/java" -name "*Test.java" -o -name "*Spec.java" -o -name "*IT.java" 2>/dev/null || true) + fi + if [ -d "$FIXTURE_DIR/src/test/groovy" ]; then + local GROOVY_FILES=$(find "$FIXTURE_DIR/src/test/groovy" -name "*Test.groovy" -o -name "*Spec.groovy" -o -name "*IT.groovy" 2>/dev/null || true) + if [ -n "$GROOVY_FILES" ]; then + if [ -n "$TEST_FILES" ]; then + TEST_FILES="$TEST_FILES"$'\n'"$GROOVY_FILES" + else + TEST_FILES="$GROOVY_FILES" + fi + fi + fi -if [ -z "$TEST_FILES" ]; then - echo "No test files found in $FIXTURE_DIR/src/test/java" - exit 1 -fi + if [ -z "$TEST_FILES" ]; then + echo "No test files found in $FIXTURE_DIR" + return 1 + fi -TOTAL=0 -PASSED=0 -FAILED=0 + local TOTAL=0 + local PASSED=0 + local FAILED=0 -for test_file in $TEST_FILES; do - TOTAL=$((TOTAL + 1)) - test_name=$(basename "$test_file" .java) + while IFS= read -r test_file; do + [ -z "$test_file" ] && continue + TOTAL=$((TOTAL + 1)) + test_name=$(basename "$test_file") - echo "Running E2E test: $test_name" + echo "Running E2E test: $test_name" - if nvim -l "$SCRIPT_DIR/run.lua" --fixture "$FIXTURE" --test-file "$test_file"; then - PASSED=$((PASSED + 1)) - echo "✓ $test_name PASSED" - else - FAILED=$((FAILED + 1)) - echo "✗ $test_name FAILED" - fi + if nvim -l "$SCRIPT_DIR/run.lua" --fixture "$FIXTURE" --test-file "$test_file"; then + PASSED=$((PASSED + 1)) + echo "✓ $test_name PASSED" + else + FAILED=$((FAILED + 1)) + echo "✗ $test_name FAILED" + fi + echo "" + done <<< "$TEST_FILES" + + echo "------------------------------------------------" + echo "Fixture: $FIXTURE - Total: $TOTAL, Passed: $PASSED, Failed: $FAILED" echo "" -done - -echo "================================================" -echo "E2E Test Summary" -echo "================================================" -echo "Total test files: $TOTAL" -echo "Passed: $PASSED" -echo "Failed: $FAILED" -echo "" - -if [ $FAILED -gt 0 ]; then - echo "⚠ Some tests failed" - exit 1 + + if [ $FAILED -gt 0 ]; then + return 1 + fi + return 0 +} + +# Determine which fixtures to run +if [ -n "$1" ]; then + run_fixture "$1" else - echo "✓ All tests passed" + echo "Discovering fixtures in $FIXTURES_DIR" + echo "" + + GRAND_TOTAL=0 + GRAND_PASSED=0 + GRAND_FAILED=0 + + for fixture_dir in "$FIXTURES_DIR"/*/; do + [ ! -d "$fixture_dir" ] && continue + fixture_name=$(basename "$fixture_dir") + + if run_fixture "$fixture_name"; then + GRAND_PASSED=$((GRAND_PASSED + 1)) + else + GRAND_FAILED=$((GRAND_FAILED + 1)) + fi + GRAND_TOTAL=$((GRAND_TOTAL + 1)) + done + + echo "================================================" + echo "E2E Test Summary" + echo "================================================" + echo "Total fixtures: $GRAND_TOTAL" + echo "Passed: $GRAND_PASSED" + echo "Failed: $GRAND_FAILED" + echo "" + + if [ $GRAND_FAILED -gt 0 ]; then + echo "⚠ Some fixtures failed" + exit 1 + else + echo "✓ All fixtures passed" + fi fi diff --git a/tests/e2e/run.lua b/tests/e2e/run.lua index e2fd451b..ef76eb3f 100755 --- a/tests/e2e/run.lua +++ b/tests/e2e/run.lua @@ -342,8 +342,8 @@ vim.schedule(function() -- Extract expected class name from test file path -- e.g., /path/to/SampleTest.java or C:\path\to\SampleTest.java -> SampleTest - -- Handle both Unix (/) and Windows (\) path separators - local expected_class = test_file:match("([^/\\]+)%.java$") + -- Handle both Unix (/) and Windows (\) path separators and both .java and .groovy + local expected_class = test_file:match("([^/\\]+)%.java$") or test_file:match("([^/\\]+)%.groovy$") -- Collect test method names and IDs from positions tree -- ONLY include tests from the specific test file we're running @@ -451,7 +451,8 @@ end, 30000) -- Derive snapshot file name from test file -- e.g., /path/to/SampleTest.java -> /path/to/SampleTest.snapshot.json - local snapshot_file = test_file:gsub("%.java$", ".snapshot.json") + -- /path/to/CalculatorSpec.groovy -> /path/to/CalculatorSpec.snapshot.json + local snapshot_file = test_file:gsub("%.java$", ".snapshot.json"):gsub("%.groovy$", ".snapshot.json") if snapshot_file == test_file then log_error("Could not derive snapshot file name from: " .. test_file) os.exit(1) From 382a2dd43fee167cd02b35bb59721fab681b5091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= <31012661+rcasia@users.noreply.github.com> Date: Fri, 22 May 2026 00:18:07 +0200 Subject: [PATCH 4/7] fix: skip fixtures with no test files in E2E runner Fixes exit code handling so fixtures without test files are skipped gracefully instead of counting as failures. Fixes #194 --- tests/e2e/run-all.sh | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/e2e/run-all.sh b/tests/e2e/run-all.sh index 0605de1c..4c37b411 100755 --- a/tests/e2e/run-all.sh +++ b/tests/e2e/run-all.sh @@ -43,8 +43,8 @@ run_fixture() { fi if [ -z "$TEST_FILES" ]; then - echo "No test files found in $FIXTURE_DIR" - return 1 + echo "No test files found in $FIXTURE_DIR - skipping" + return 2 fi local TOTAL=0 @@ -94,8 +94,15 @@ else [ ! -d "$fixture_dir" ] && continue fixture_name=$(basename "$fixture_dir") - if run_fixture "$fixture_name"; then + result=0 + run_fixture "$fixture_name" || result=$? + + if [ $result -eq 0 ]; then GRAND_PASSED=$((GRAND_PASSED + 1)) + elif [ $result -eq 2 ]; then + echo "Fixture: $fixture_name - skipped (no test files)" + GRAND_TOTAL=$((GRAND_TOTAL)) + continue else GRAND_FAILED=$((GRAND_FAILED + 1)) fi From eacbc27ed65ffb0671bac0c6d425c552208a750e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= <31012661+rcasia@users.noreply.github.com> Date: Fri, 22 May 2026 00:18:07 +0200 Subject: [PATCH 5/7] fix: skip fixtures with no test files in E2E runner Fixes exit code handling so fixtures without test files are skipped gracefully instead of counting as failures. Fixes #194 --- .../src/test/groovy/com/example/CalculatorSpec.snapshot.json | 1 + .../src/test/groovy/com/example/UserServiceTest.snapshot.json | 1 + 2 files changed, 2 insertions(+) create mode 100644 tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.snapshot.json create mode 100644 tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.snapshot.json diff --git a/tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.snapshot.json b/tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.snapshot.json new file mode 100644 index 00000000..330e8fe3 --- /dev/null +++ b/tests/fixtures/maven-groovy/src/test/groovy/com/example/CalculatorSpec.snapshot.json @@ -0,0 +1 @@ +{"results": []} diff --git a/tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.snapshot.json b/tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.snapshot.json new file mode 100644 index 00000000..330e8fe3 --- /dev/null +++ b/tests/fixtures/maven-groovy/src/test/groovy/com/example/UserServiceTest.snapshot.json @@ -0,0 +1 @@ +{"results": []} From 556ed2917e706f6b7c7e693e8d9b3752727fad8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= <31012661+rcasia@users.noreply.github.com> Date: Fri, 22 May 2026 00:18:07 +0200 Subject: [PATCH 6/7] fix: skip fixtures with no test files in E2E runner Fixes exit code handling so fixtures without test files are skipped gracefully instead of counting as failures. Fixes #194 --- Makefile | 13 +++- .../core/positions_discoverer.lua | 65 +++++++++++++++++-- scripts/minimal_init.lua | 55 ++++++++++++++++ 3 files changed, 127 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 463e62ac..1ad60619 100755 --- a/Makefile +++ b/Makefile @@ -16,6 +16,9 @@ test-e2e: install install: deps/nvim-treesitter deps/nvim-treesitter/parser/java.so deps/neotest deps/nvim-nio deps/plenary.nvim + @-$(MAKE) _install_groovy_parser 2>/dev/null || echo "Note: Groovy parser not compiled (optional for Java-only development)" + +_install_groovy_parser: deps/nvim-treesitter/parser/groovy.so deps/plenary.nvim: mkdir -p deps @@ -42,9 +45,17 @@ deps/nvim-treesitter/parser/java.so: deps/nvim-treesitter mkdir -p $$(dirname $@) cp deps/tree-sitter-java/parser.so $@ +deps/nvim-treesitter/parser/groovy.so: deps/nvim-treesitter + @if [ ! -d deps/tree-sitter-groovy ]; then \ + git clone https://github.com/tree-sitter/tree-sitter-groovy deps/tree-sitter-groovy; \ + fi + cd deps/tree-sitter-groovy && cc -o parser.so -I./src src/parser.c src/scanner.c -Os -std=c11 -shared + mkdir -p $$(dirname $@) + cp deps/tree-sitter-groovy/parser.so $@ + clean: - rm -rf deps/nvim-treesitter deps/neotest deps/tree-sitter-java + rm -rf deps/nvim-treesitter deps/neotest deps/tree-sitter-java deps/tree-sitter-groovy validate: stylua --check . diff --git a/lua/neotest-java/core/positions_discoverer.lua b/lua/neotest-java/core/positions_discoverer.lua index 561b4472..1d7a0438 100644 --- a/lua/neotest-java/core/positions_discoverer.lua +++ b/lua/neotest-java/core/positions_discoverer.lua @@ -45,10 +45,16 @@ local function build_position(file_path, source, captured_nodes) return nil end + local name = vim.treesitter.get_node_text(name_node, source) + + if name_node:type() == "string" or name_node:type() == "string_literal" then + name = name:gsub("^[\"']", ""):gsub("[\"']$", "") + end + return { type = match_type, path = file_path, - name = vim.treesitter.get_node_text(name_node, source), + name = name, range = { definition_node:range() }, } end @@ -78,9 +84,7 @@ end local PositionsDiscoverer = {} ---- @param deps neotest-java.PositionsDiscoverer.Dependencies ---- @return neotest-java.PositionsDiscoverer -local function create_positions_discoverer(deps) +local function get_java_query() local annotations = { "Test", "ParameterizedTest", "TestFactory", "CartesianTest" } local a = vim.iter(annotations) :map(function(v) @@ -88,7 +92,7 @@ local function create_positions_discoverer(deps) end) :join(" ") - local query = [[ + return [[ ;; Test class (class_declaration @@ -113,7 +117,55 @@ local function create_positions_discoverer(deps) ) @test.definition ]] +end + +local function get_groovy_query() + local annotations = { "Test", "ParameterizedTest", "TestFactory", "CartesianTest" } + local a = vim.iter(annotations) + :map(function(v) + return string.format([["%s"]], v) + end) + :join(" ") + + return [[ + + ;; Test class (Spock specs extend Specification) + (class_declaration + name: (identifier) @namespace.name + ) @namespace.definition + + ;; JUnit-style annotated methods in Groovy + (method_declaration + (modifiers + [ + (marker_annotation + name: (identifier) @annotation + (#any-of? @annotation ]] .. a .. [[) + ) + (annotation + name: (identifier) @annotation + (#any-of? @annotation ]] .. a .. [[) + ) + ] + ) + name: [ + (identifier) @test.name + (string) @test.name + ] + ) @test.definition + + ;; Spock feature methods: def "test name"() + ;; String literal method names are unique to Spock-style tests + (method_declaration + name: (string) @test.name + ) @test.definition + + ]] +end +--- @param deps neotest-java.PositionsDiscoverer.Dependencies +--- @return neotest-java.PositionsDiscoverer +local function create_positions_discoverer(deps) --- @type neotest-java.PositionsDiscoverer return { @@ -122,6 +174,9 @@ local function create_positions_discoverer(deps) ---@param file_path string Absolute file path ---@return neotest.Tree | nil discover_positions = function(file_path) + local is_groovy = file_path:match("%.groovy$") + local query = is_groovy and get_groovy_query() or get_java_query() + local tree = lib.treesitter.parse_positions(file_path, query, { require_namespaces = true, nested_tests = false, diff --git a/scripts/minimal_init.lua b/scripts/minimal_init.lua index 5e1201bf..0a468584 100644 --- a/scripts/minimal_init.lua +++ b/scripts/minimal_init.lua @@ -103,6 +103,61 @@ end ensure_java_parser() +local function ensure_groovy_parser() + local parser_dir = DEPENDENCIES_DIR .. "/nvim-treesitter/parser" + local groovy_so = parser_dir .. "/groovy.so" + + if vim.fn.filereadable(groovy_so) == 1 then + return + end + + -- Fast path: copy from old deps/ directory if it exists + local old_so = "deps/nvim-treesitter/parser/groovy.so" + if vim.fn.filereadable(old_so) == 1 then + vim.fn.mkdir(parser_dir, "p") + vim.fn.system({ "cp", old_so, groovy_so }) + if vim.fn.filereadable(groovy_so) == 1 then + return + end + end + + -- Fallback: clone tree-sitter-groovy and compile with cc + print("Installing Groovy treesitter parser (one-time setup)...") + local tmp_dir = vim.fn.tempname() .. "-ts-groovy" + vim.fn.system({ + "git", + "clone", + "--depth=1", + "https://github.com/tree-sitter/tree-sitter-groovy", + tmp_dir, + }) + vim.fn.mkdir(parser_dir, "p") + + -- Check if scanner.c exists (some grammars need it) + local scanner_path = tmp_dir .. "/src/scanner.c" + local compile_cmd = { + "cc", + "-shared", + "-fPIC", + "-O2", + "-o", + groovy_so, + tmp_dir .. "/src/parser.c", + "-I" .. tmp_dir .. "/src", + } + if vim.fn.filereadable(scanner_path) == 1 then + table.insert(compile_cmd, scanner_path) + end + vim.fn.system(compile_cmd) + vim.fn.system({ "rm", "-rf", tmp_dir }) + + if vim.fn.filereadable(groovy_so) ~= 1 then + print("Warning: Failed to compile Groovy treesitter parser. Groovy position discovery will be unavailable.") + end +end + +ensure_groovy_parser() + -- ───────────────────────────────────────────────────────────── -- Runtime path setup (plugin roots, NOT /lua/ subdirectories) -- ───────────────────────────────────────────────────────────── From f70b414c66fc08152cb781624d173373feed97d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Cas=C3=ADa?= <31012661+rcasia@users.noreply.github.com> Date: Fri, 22 May 2026 01:40:11 +0200 Subject: [PATCH 7/7] test: add Groovy position discovery tests Add unit tests for Groovy position discovery: - Spock feature methods with string literal names (def "test"()) - JUnit-style annotated methods in Groovy (@Test) Tests skip gracefully when Groovy treesitter parser is not compiled. Fixes #194 --- tests/unit/test_positions_discoverer_spec.lua | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/tests/unit/test_positions_discoverer_spec.lua b/tests/unit/test_positions_discoverer_spec.lua index 1c63d3b1..bd3e0c98 100644 --- a/tests/unit/test_positions_discoverer_spec.lua +++ b/tests/unit/test_positions_discoverer_spec.lua @@ -59,6 +59,17 @@ describe("PositionsDiscoverer", function() return tmp_file end + ---@param content string + ---@return string filename + local function create_tmp_groovyfile(content) + local tmp_file = os.tmpname() .. ".groovy" + table.insert(tmp_files, tmp_file) + local file = assert(io.open(tmp_file, "w")) + file:write(content) + file:close() + return tmp_file + end + it( "method FQN with inner classes", async(function() @@ -294,4 +305,106 @@ public class SomeTest { }, remove_ref_field(actual:to_list())) end) ) + + it( + "should discover Spock feature methods with string literal names", + async(function() + -- Skip if Groovy parser is not available + local parser_dir = "./.dependencies/nvim-treesitter/parser" + local groovy_so = parser_dir .. "/groovy.so" + if vim.fn.filereadable(groovy_so) ~= 1 then + print("Skipping: Groovy treesitter parser not available") + return + end + + local file_path = create_tmp_groovyfile([[ +package com.example + +import spock.lang.Specification + +class CalculatorSpec extends Specification { + + def "addition of two positive numbers"() { + expect: + 2 + 3 == 5 + } + + def "subtraction returns correct result"() { + expect: + 10 - 4 == 6 + } +} +]]) + + local result = assert(positions_discoverer.discover_positions(file_path)) + local actual_list = result:to_list() + + -- Should have file -> namespace (CalculatorSpec) -> tests + local namespace = actual_list[2][1] + eq("namespace", namespace.type) + eq("CalculatorSpec", namespace.name) + + -- Should have 2 test methods + local test_count = 0 + for _, child in ipairs(actual_list[2]) do + if #child > 0 then + for _, test in ipairs(child) do + if test.type == "test" then + test_count = test_count + 1 + end + end + end + end + eq(2, test_count, "Should discover 2 Spock feature methods") + end) + ) + + it( + "should discover JUnit-style annotated methods in Groovy", + async(function() + -- Skip if Groovy parser is not available + local parser_dir = "./.dependencies/nvim-treesitter/parser" + local groovy_so = parser_dir .. "/groovy.so" + if vim.fn.filereadable(groovy_so) ~= 1 then + print("Skipping: Groovy treesitter parser not available") + return + end + + local file_path = create_tmp_groovyfile([[ +package com.example + +import org.junit.jupiter.api.Test +import static org.junit.jupiter.api.Assertions.* + +class UserServiceTest { + + @Test + void "should create user with valid name"() { + assertNotNull(user) + } + + @Test + void shouldReturnUserCount() { + assertEquals(2, userCount) + } +} +]]) + + local result = assert(positions_discoverer.discover_positions(file_path)) + local actual_list = result:to_list() + + -- Should have 2 test methods + local test_count = 0 + for _, child in ipairs(actual_list[2]) do + if #child > 0 then + for _, test in ipairs(child) do + if test.type == "test" then + test_count = test_count + 1 + end + end + end + end + eq(2, test_count, "Should discover 2 JUnit-style Groovy tests") + end) + ) end)