Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions grails-gradle/plugins/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-gradle-plugin'
implementation 'org.springframework.boot:spring-boot-loader-tools'
implementation 'io.spring.gradle:dependency-management-plugin'

// Testing - Gradle TestKit is auto-added by java-gradle-plugin
testImplementation('org.spockframework:spock-core') { transitive = false }
testImplementation 'org.codehaus.groovy:groovy-test-junit5'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}

configurations {
testCompileClasspath.exclude group: 'org.apache.groovy', module: 'groovy'
testRuntimeClasspath.exclude group: 'org.apache.groovy', module: 'groovy'
}

gradlePlugin {
Expand Down Expand Up @@ -129,6 +139,12 @@ tasks.withType(Copy) {
}
}

tasks.withType(Test).configureEach {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest we move this to test-config. The additional properties don't hurt and it' sbest to be consistent.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Moved projectVersion and currentJdk system properties into test-config.gradle and removed the standalone block from plugins/build.gradle. All 8 tests pass.

systemProperty 'projectVersion', projectVersion
systemProperty 'currentJdk', JavaVersion.current().majorVersion
}

apply {
from rootProject.layout.projectDirectory.file('gradle/docs-config.gradle')
from rootProject.layout.projectDirectory.file('gradle/test-config.gradle')
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.GroovyCompile
import org.gradle.api.tasks.testing.Test
import org.gradle.jvm.toolchain.JavaToolchainService
import org.gradle.language.jvm.tasks.ProcessResources
import org.gradle.process.JavaForkOptions
import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry
Expand Down Expand Up @@ -556,6 +557,44 @@ class GrailsGradlePlugin extends GroovyPlugin {
String grailsEnvSystemProperty = System.getProperty(Environment.KEY)
tasks.withType(Test).configureEach(systemPropertyConfigurer.curry(grailsEnvSystemProperty ?: Environment.TEST.getName()))
tasks.withType(JavaExec).configureEach(systemPropertyConfigurer.curry(grailsEnvSystemProperty ?: Environment.DEVELOPMENT.getName()))

configureToolchainForForkTasks(project)
}

/**
* Configures {@link JavaExec} tasks to inherit the project's Java toolchain.
*
* <p>Gradle's {@code JavaPlugin} already sets toolchain conventions on
* {@code JavaCompile}, {@code Javadoc}, and {@code Test} tasks, but does
* <strong>not</strong> set them on {@code JavaExec} tasks. This means forked
* JVM processes (dbm-* migration tasks, console, shell, and application
* context commands) use the JDK running Gradle instead of the project's
* configured toolchain. When the project targets a different JDK version
* than the one running Gradle, this causes {@code UnsupportedClassVersionError}
* or silent runtime failures.</p>
*
* <p>This method only acts when the user has explicitly configured a toolchain
* via {@code java.toolchain.languageVersion}. When no toolchain is configured,
* behavior is unchanged - tasks use the JDK running Gradle as before.</p>
*
* <p>Uses {@code convention()} so that individual tasks can still override
* the launcher via {@code javaLauncher.set(...)} if needed.</p>
*
* @param project the Gradle project
* @since 7.0.8
*/
protected void configureToolchainForForkTasks(Project project) {
project.afterEvaluate {
def javaExtension = project.extensions.findByType(org.gradle.api.plugins.JavaPluginExtension)
if (javaExtension?.toolchain?.languageVersion?.isPresent()) {
def toolchainService = project.extensions.getByType(JavaToolchainService)
def launcher = toolchainService.launcherFor(javaExtension.toolchain)

project.tasks.withType(JavaExec).configureEach { JavaExec task ->
task.javaLauncher.convention(launcher)
}
}
}
}

protected void configureConsoleTask(Project project) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* 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
*
* https://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.
*/
package org.grails.gradle.plugin.core

import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import spock.lang.Specification

import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes

/**
* Base class for Gradle plugin functional tests using TestKit.
*
* <p>Adapted from the {@code GradleSpecification} in the
* {@code apache/grails-gradle-publish} project. Handles temp directory
* management, GradleRunner setup, test resource project copying, and
* common build assertions.</p>
*
* @since 7.0.8
*/
abstract class GradleSpecification extends Specification {

private static Path basePath
private static GradleRunner gradleRunner

/** Project version injected by Gradle test config. */
protected static final String PROJECT_VERSION = System.getProperty('projectVersion')

/** Current JDK major version injected by Gradle test config. */
protected static final int CURRENT_JDK = Integer.parseInt(System.getProperty('currentJdk'))

void setupSpec() {
basePath = Files.createTempDirectory('gradle-projects')
Path testKitDir = Files.createDirectories(basePath.resolve('.gradle'))
gradleRunner = GradleRunner.create()
.withPluginClasspath()
.withTestKitDir(testKitDir.toFile())
}

void cleanup() {
basePath?.toFile()?.listFiles()?.each {
if (it.name == '.gradle') {
return
}
it.deleteDir()
}
}

void cleanupSpec() {
basePath?.toFile()?.deleteDir()
}

/**
* Sets up a test project from resource files under
* {@code src/test/resources/test-projects/{projectName}}.
*
* <p>Files are copied to a temp directory. Any occurrence of
* {@code __CURRENT_JDK__} in {@code .gradle} files is replaced
* with the actual current JDK version, and {@code __PROJECT_VERSION__}
* is replaced with the actual project version.</p>
*/
protected GradleRunner setupTestResourceProject(String projectName) {
Path destination = basePath.resolve(projectName)
Files.createDirectories(destination)

Path source = Path.of("src/test/resources/test-projects/${projectName}")
copyDirectory(source, destination)

gradleRunner.withProjectDir(destination.toFile())
}

/**
* Executes a Gradle task and returns the build result.
*/
protected BuildResult executeTask(String taskName, List<String> otherArgs = []) {
List<String> args = [taskName, '--stacktrace']
args.addAll(otherArgs)
gradleRunner.withArguments(args).forwardOutput().build()
}

/**
* Asserts that the given task succeeded.
*/
protected void assertTaskSuccess(String taskName, BuildResult result) {
def task = result.tasks.find { it.path.endsWith(":${taskName}") }
assert task != null : "Task '${taskName}' not found in build result"
assert task.outcome == TaskOutcome.SUCCESS : "Task '${taskName}' outcome was ${task.outcome}"
}

private void copyDirectory(Path source, Path destination) {
Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
@Override
FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
Files.createDirectories(destination.resolve(source.relativize(dir)))
FileVisitResult.CONTINUE
}

@Override
FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Path target = destination.resolve(source.relativize(file))
if (file.toString().endsWith('.gradle') || file.toString().endsWith('.properties')) {
String content = Files.readString(file)
.replace('__CURRENT_JDK__', String.valueOf(CURRENT_JDK))
.replace('__PROJECT_VERSION__', PROJECT_VERSION)
Files.writeString(target, content)
} else {
Files.copy(file, target)
}
FileVisitResult.CONTINUE
}
})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* 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
*
* https://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.
*/
package org.grails.gradle.plugin.core

/**
* Tests that {@link GrailsGradlePlugin} propagates the project's Java toolchain
* to JavaExec tasks via {@code javaLauncher.convention()}.
*
* <p>Without the fix, JavaExec tasks spawned by Grails (dbm-* migration
* commands, console, shell, application context commands) use the JDK
* running Gradle instead of the project's configured toolchain.</p>
*
* @since 7.0.8
* @see GrailsGradlePlugin#configureToolchainForForkTasks
*/
class GrailsGradlePluginToolchainSpec extends GradleSpecification {

// ----------------------------------------------------------------
// Toolchain propagation
// ----------------------------------------------------------------

def "JavaExec tasks inherit project toolchain"() {
given:
setupTestResourceProject('toolchain-javaexec')

when:
def result = executeTask('checkToolchain')

then:
result.output.contains("TOOLCHAIN_VERSION=${CURRENT_JDK}")
}

def "Test tasks inherit project toolchain"() {
given:
setupTestResourceProject('toolchain-test')

when:
def result = executeTask('checkTestToolchain')

then:
result.output.contains("TEST_TOOLCHAIN_VERSION=${CURRENT_JDK}")
}

def "ApplicationContextCommandTask inherits toolchain via grails-web plugin"() {
given:
setupTestResourceProject('toolchain-command')

when:
def result = executeTask('checkCommandToolchain')

then:
result.output.contains("CMD_TOOLCHAIN_VERSION=${CURRENT_JDK}")
}

def "convention allows individual task override via set()"() {
given:
setupTestResourceProject('toolchain-override')

when:
def result = executeTask('checkOverride')

then:
result.output.contains("OVERRIDE_VERSION=${CURRENT_JDK}")
}

// ----------------------------------------------------------------
// Backwards compatibility (no toolchain configured)
// ----------------------------------------------------------------

def "JavaExec tasks work without errors when no toolchain configured"() {
given:
setupTestResourceProject('no-toolchain-javaexec')

when:
def result = executeTask('checkToolchain')

then:
result.output.contains('HAS_LAUNCHER=')
}

def "GrailsWebGradlePlugin works without errors when no toolchain configured"() {
given:
setupTestResourceProject('no-toolchain-web')

when:
def result = executeTask('checkNoError')

then:
result.output.contains('WEB_PLUGIN_OK=true')
}

// ----------------------------------------------------------------
// Fork settings preservation
// ----------------------------------------------------------------

def "configureForkSettings applies system properties and default heap sizes"() {
given:
setupTestResourceProject('fork-settings-defaults')

when:
def result = executeTask('inspectSysProps')

then:
result.output.contains('HAS_ENV=true')
result.output.contains('MIN_HEAP=768m')
result.output.contains('MAX_HEAP=768m')
}

def "custom heap sizes are not overridden by fork settings"() {
given:
setupTestResourceProject('fork-settings-custom')

when:
def result = executeTask('inspectHeap')

then:
result.output.contains('MIN_HEAP=512m')
result.output.contains('MAX_HEAP=2g')
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
plugins {
id 'org.apache.grails.gradle.grails-app'
}

tasks.register('customHeap', JavaExec) {
classpath = files()
mainClass = 'does.not.Matter'
minHeapSize = '512m'
maxHeapSize = '2g'
}

tasks.register('inspectHeap') {
doLast {
def task = tasks.named('customHeap', JavaExec).get()
println "MIN_HEAP=${task.minHeapSize}"
println "MAX_HEAP=${task.maxHeapSize}"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
grailsVersion=__PROJECT_VERSION__
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'test-toolchain'
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
plugins {
id 'org.apache.grails.gradle.grails-app'
}

tasks.register('checkSysProps', JavaExec) {
classpath = files()
mainClass = 'does.not.Matter'
}

tasks.register('inspectSysProps') {
doLast {
def task = tasks.named('checkSysProps', JavaExec).get()
def sysProps = task.systemProperties
println "HAS_ENV=${sysProps.containsKey('grails.env')}"
println "MIN_HEAP=${task.minHeapSize}"
println "MAX_HEAP=${task.maxHeapSize}"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
grailsVersion=__PROJECT_VERSION__
Loading
Loading