Gradle play plugin property testClassesDirs missing in gradle 3.1 - gradle

I want to use Gradle 3.1 and Gradle play plugin. I have to add a task.
Can you help me to parse below snippet from version 4.0 to 3.1?
I can't find the analogous property testClassesDirs in Gradle 3.1
task doesNotWorkIn3_1(type: Test) {
dependsOn { tasks.compilePlayBinaryTests }
testClassesDirs = project.files { [tasks.compilePlayBinaryTests.destinationDir] }
classpath = project.files { testPlayBinary.classpath }
include '**/SwaggerControllerJsonTest.class'
outputs.upToDateWhen { false }
}

Like you said, the problem is with testClassesDirs, it exists in Gradle 4.x but not in Gradle 3.1.
So please update
testClassesDirs = project.files { [tasks.compilePlayBinaryTests.destinationDir] }
to
testClassesDir = tasks.compilePlayBinaryTests.destinationDir
Let me know if this works.

task genSwaggerJson(type: Test) {
dependsOn { tasks.compilePlayBinaryTests }
testClassesDir = file("$buildDir/genSwaggerJson_testClasses")
classpath = files({ tasks.testPlayBinary.classpath })
outputs.upToDateWhen { false }
include '**/MySingleTest.class'
}
This one works fine for 3.1

Related

Generalising compile* task in Gradle

How do I generalise``compile` task in a multi-language project?
E.g. I can to generalise this to run on all compile* tasks for each language used.
compileJava {
ajc {
enabled = true
classpath = configurations.aspectj
options {
aspectpath = configurations.aspect
compilerArgs = []
}
}
}
compileTestJava {
ajc {
enabled = true
classpath = configurations.aspectj
options {
aspectpath = configurations.testAspect
compilerArgs = []
}
}
}
Source: FreeFair Gradle Plugin Collection
How can the above be modified so that it can run with any compile* task, e.g. compileGroovy, compileKotlin, compileScala etc. in a multi-language project?
You can use the method matching(...) of the TaskContainer that is available via tasks in your build.gradle:
tasks.matching { task -> task.name.startsWith('compile') }.all {
ajc {
enabled = true
classpath = configurations.aspectj
options {
aspectpath = configurations.testAspect
compilerArgs = []
}
}
}
Please note that this solution will only work if all tasks that start with 'compile' actually have an extension ajc. It also only works because of Groovy, as whether afc is available or not will be evaluated dynamically. This won't work in a Kotlin build script.

JaCoCo gradle plugin ignoring version

Gradle Version: 6.1.1
Android Gradle Plugin: 4.0.0
When trying to run my jacoco coverage it does not appear to be taking into account the version. When I look at the HTML report it states "Created with JaCoCo 0.7.9.201702052155" despite me having toolVersion = "0.8.5" in my setup. The report also does not have fixes that I expect in 0.8.3 relating to Kotlin as a secondary confirmation this isn't working.
apply plugin: 'jacoco'
jacoco {
toolVersion = "0.8.5"
reportsDir = file("$buildDir/reports")
}
tasks.withType(Test) {
jacoco.includeNoLocationClasses = true
jacoco.excludes = ['jdk.internal.*']
}
project.afterEvaluate {
(android.hasProperty('applicationVariants')
? android.'applicationVariants'
: android.'libraryVariants').all { variant ->
def variantName = variant.name
def unitTestTask = "test${variantName.capitalize()}UnitTest"
def uiTestCoverageTask = "create${variantName.capitalize()}CoverageReport"
tasks.create(name: "${unitTestTask}Coverage", type: JacocoReport, dependsOn: [
"$unitTestTask",
"$uiTestCoverageTask"
]) {
group = "Reporting"
description = "Generate Jacoco coverage reports for the ${variantName.capitalize()} build"
reports {
html.enabled = true
xml.enabled = true
csv.enabled = false
}
def fileFilter = [
'**/R.class',
'**/R$*.class',
'**/BuildConfig.*',
'**/Manifest*.*',
'**/*Test*.*',
'**/com/example/databinding/*',
'**/com/example/generated/callback/*',
'**/android/databinding/*',
'**/androidx/databinding/*',
'**/di/module/*',
'**/*MapperImpl*.*',
'**/*$ViewInjector*.*',
'**/*$ViewBinder*.*',
'**/BuildConfig.*',
'**/*Component*.*',
'**/*BR*.*',
'**/Manifest*.*',
'**/*$Lambda$*.*',
'**/*Companion*.*',
'**/*Module.*',
'**/*Dagger*.*',
'**/*MembersInjector*.*',
'**/*_Factory*.*',
'**/*_Provide*Factory*.*',
'**/*Extensions*.*',
'**/*$Result.*', /* filtering `sealed` and `data` classes */
'**/*$Result$*.*'/* filtering `sealed` and `data` classes */
]
classDirectories.setFrom(files([
fileTree(dir: "${buildDir}/tmp/kotlin-classes/${variantName}", excludes: fileFilter)
]))
def coverageSourceDirs = [
"$project.rootDir/app/src/main/java",
"$project.projectDir/src/${variantName}/java"
]
additionalSourceDirs.setFrom(files(coverageSourceDirs))
sourceDirectories.setFrom(files(coverageSourceDirs))
def uiTestsData = fileTree(dir: "${buildDir}/outputs/code_coverage/${variantName}AndroidTest/connected/", includes: ["**/*.ec"])
executionData(files([
"$project.buildDir/jacoco/${unitTestTask}.exec",
uiTestsData
]))
}
}
}
As stated from #Bilgehan KALKAN here, as of Gradle 7, this seems to be resolved.
android {
//Other configurations...
testCoverage.jacocoVersion = "0.8.7"
}
For lower gradle version try adding this to your Project Gradle file.
subprojects {
configurations.all {
resolutionStrategy {
eachDependency { details ->
if ('org.jacoco' == details.requested.group) {
details.useVersion "0.8.6"
}
}
}
}
}
You don't need to override version as mentioned on #LethalMaus's answer. You only need to specify jacoco version under android as testCoverage.jacocoVersion, jacoco.version approach on #Alexy Nikitin's answer has been deprecated and replaced with testCoverage.jacocoVersion.
If you do not specify any version, it will use DEFAULT_VERSION under JacocoOptions class. Which is "0.8.3" for Android Gradle Plugin version 7.0.2.
You should declare jacoco version in the android gradle plugin too:
android {
jacoco {
version "<your jacoco version>"
}
}

Spring Boot 2 - Change Jar Name

I am using Spring Boot 2 in my Gradle project to do a build to jar in Jenkins, and I would like to change the name of that jar file.
By default, Spring Boot 2 used the Gradle property rootProject.name, which can be set in the /settings.gradle file.
However, I would like to change the jar file name, without changing the rootProject.name.
Here are my bootJar and springBoot sections of the build.gradle file:
bootJar {
launchScript()
}
.
springBoot {
buildInfo {
properties {
artifact = "jarName"
group = "groupName"
name = "projectName"
version = "1.0"
}
}
}
Note: artifact is not setting the jar name, as I expected it to, after reading: https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/#integrating-with-actuator
archiveFileName is the new hotness. Everything else is deprecated.
bootJar {
archiveFileName = "${archiveBaseName.get()}.${archiveExtension.get()}"
}
or the Kotlin DSL equivalent:
tasks.getByName<org.springframework.boot.gradle.tasks.bundling.BootJar>("bootJar") {
this.archiveFileName.set("${archiveBaseName.get()}.${archiveExtension.get()}")
}
See:
https://docs.gradle.org/current/dsl/org.gradle.api.tasks.bundling.Jar.html#org.gradle.api.tasks.bundling.Jar:archiveName
https://docs.gradle.org/current/userguide/lazy_configuration.html
Since bootJar tasks extends Jar you can use archiveName to set name the directly:
bootJar {
archiveName = 'whatever'
}
Have a look here.
Thanks to #AndyWilkinson for the answer!
bootJar {
baseName "jarName"
launchScript()
}
.
springBoot {
buildInfo {
properties {
group = "groupName"
name = "projectName"
version = "1.0"
}
}
}
For Gradle 6
bootJar {
archiveBaseName = 'freeway-server'
archiveVersion = '1.0.0'
archiveFileName = 'freeway-server.jar'
}
For get:-
System.out.print(bootJar.getArchiveBaseName().get())
System.out.print(bootJar.getArchiveVersion().get())
System.out.print(bootJar.getArchiveFileName().get())
My goal was to remove version from the archive name. I did it this way:
bootJar {
archiveName = "$baseName.$extension"
}
Now Gradle generates "project-name.jar" instead of "project-name-1.0-SNAPSHOT.jar". This solution is general and doesn't hardcode any particular archive name.
You can also use:
tasks.bootJar {
archiveFileName.set("app.jar")
}
Or with the jar-plugin
tasks.jar {
archiveFileName.set("app.jar")
}
Most people simply want to not have the version in the jar name, not change the name completely.
tasks.withType<org.springframework.boot.gradle.tasks.bundling.BootJar> {
archiveVersion.set("")
}
will do it using Kotlin DSL. The final name is given by tasks.bootJar.get().archiveFileName.get().
For me worked
project(':org.awseome.subproject') {
jar() {
archiveFileName = 'nameOfJar.jar'
}
}
inside of main build.gradle. Used
Gradle 6.X
Spring Boot 2.X

Running specific tests using gradle over multiple browsers

I'm using Geb/Spock for automated testing. I'm using Gradle as my build tool.
I'd like to call different gradle tasks to build and run a specific spec(test) or a suite of specs.
I dont know enough about the gradle build lifecycle to completely understand what is going on here: https://github.com/geb/geb-example-gradle/blob/master/build.gradle
plugins {
id "idea"
id "groovy"
id "com.energizedwork.webdriver-binaries" version "1.4"
id "com.energizedwork.idea-base" version "1.4"
}
ext {
// The drivers we want to use
drivers = ["firefox", "chrome", "chromeHeadless"]
ext {
groovyVersion = '2.4.12'
gebVersion = '2.2'
seleniumVersion = '3.6.0'
chromeDriverVersion = '2.32'
geckoDriverVersion = '0.18.0'
}
}
repositories {
mavenCentral()
}
dependencies {
// If using Spock, need to depend on geb-spock
testCompile "org.gebish:geb-spock:$gebVersion"
testCompile("org.spockframework:spock-core:1.1-groovy-2.4") {
exclude group: "org.codehaus.groovy"
}
testCompile "org.codehaus.groovy:groovy-all:$groovyVersion"
// If using JUnit, need to depend on geb-junit (3 or 4)
testCompile "org.gebish:geb-junit4:$gebVersion"
// Drivers
testCompile "org.seleniumhq.selenium:selenium-chrome-driver:$seleniumVersion"
testCompile "org.seleniumhq.selenium:selenium-firefox-driver:$seleniumVersion"
}
webdriverBinaries {
chromedriver chromeDriverVersion
geckodriver geckoDriverVersion
}
drivers.each { driver ->
task "${driver}Test"(type: Test) {
group JavaBasePlugin.VERIFICATION_GROUP
outputs.upToDateWhen { false } // Always run tests
systemProperty "geb.build.reportsDir", reporting.file("geb/$name")
systemProperty "geb.env", driver
}
}
test {
dependsOn drivers.collect { tasks["${it}Test"] }
enabled = false
}
tasks.withType(Test) {
maxHeapSize = "1g"
jvmArgs '-XX:MaxMetaspaceSize=128m'
testLogging {
exceptionFormat = 'full'
}
}
tasks.withType(GroovyCompile) {
groovyOptions.forkOptions.memoryMaximumSize = '256m'
}
I've tried inserting the following into build.gradle:
task dataGen {
include '**com.company.project.spec.util/DataGenerationUtilSpec.groovy'
}
task sanity {
include '**com.company.project.spec.sanity.*'
}
But calling these tasks (gradle sanity) results in a build failure:
Could not find method include() for arguments [**com.company.project.spec.util/DataGenerationUtilSpec.groovy] on task ':dataGen' of type org.gradle.api.DefaultTask
Obviously there's existing build instructions since I can call gradle build and all the specs run on Chrome, I'm just not sure how to add more tasks
I think these 2 tasks are test tasks so it should look like that :
task dataGen (type: Test) {
include '**com.company.project.spec.util/DataGenerationUtilSpec.groovy'
}
task sanity (type: Test) {
include '**com.company.project.spec.sanity.*'
}
You can use Spock annotation to control the test or the Spec, see example here.
You will have to define annotation classes and define the Spock config file to use that annotation. You then annotate the specific Specification (or test).
Now you will have to define the Spock config file in the task or from a parameter.

Excluding test classes for all analysis from gradle

I'm invoking sonar using sonar-runner plugin from gradle. I'm also using the reuse reports flag.
How can I exclude all test classes from all analyses (Checkstyle, Findbugs, Coverage)?
I'm currently using the following plugin configuration:
sonarRunner {
sonarProperties {
property "sonar.host.url", "<HOST>"
property "sonar.scm.disabled", "true"
property "sonar.login", "<USER>"
property "sonar.password", "<password>"
property "sonar.sources", "src"
property "sonar.exclusions", "**/test/**/*.java"
property "sonar.projectVersion", project.releaseDisplayName
// these should not change anything as sonar uses the defaults set for gradle
//property "sonar.tests", "test"
}
My source sets are as follows:
sourceSets {
main {
java {
srcDir 'src'
srcDir 'src-gen'
}
}
test {
java { srcDir 'test' }
}
Thanks
Try this:
jacocoTestReport {
afterEvaluate {
sourceDirectories = files(sourceDirectories.files.collect {
fileTree(dir: it, exclude: [ 'com/path/to/package/that/I/want/to/exclude/are/inside/thisfolder_or_dto/**' ])
})
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it, exclude: [ 'com/path/to/package/that/I/want/to/exclude/are/inside/thisfolder_or_dto/**' ])
})
}
}
sonarRunner {
sonarProperties {
property "sonar.exclusions", "com/path/to/package/that/I/want/to/exclude/are/inside/thisfolder_or_dto/**"
}
}
//Required with Gradle 2.0+ -- 2.0+ -- 2.3
pmd {
ruleSets = ["java-basic", "java-braces", "java-design" ]
ignoreFailures = true
}
codenarc {
ignoreFailures = true
//The following file should exist or build will fail, you can find one online a sample version
configFile = file("config/codenarc/codenarc.xml")
}
checkstyle {
configFile = new File(rootDir, "config/checkstyle.xml")
ignoreFailures = true
//sourceSets = [sourceSets.main, sourceSets.test, sourceSets.integrationTest]
//Just run checkstyle only on main source code
sourceSets = [sourceSets.main]
}
findbugs {
ignoreFailures = true
//Just run findbugs only on main source code
sourceSets = [sourceSets.main]
//You can use if statement in groovy to set which toolVersion 2.0.3 or 3.0.1 depending upon JAVA version used in the project
toolVersion = "3.0.1"
}
Similarly, you can use excludes property within test or test task's jacoco section directly.
def generatedSources = ['com/yahoo/**', 'com/amazon/**']
test {
jacoco {
excludes = generatedSources
}
}
jacocoTestReport {
doFirst {
classDirectories = fileTree(dir: "${buildDir}/classes/main/").exclude(generatedSources)
}
reports {
xml.enabled true
}
}
While publishing to SonarQube (sonar.exclusions=value should be relative from your WORKSPACE i.e. src/java/com/.../...)
sonarRunner plugin is deprecated. Please switch to the official SonarQube plugin: https://plugins.gradle.org/plugin/org.sonarqube

Resources