Jacoco | Gradle | Exclude from aggregated modules - gradle

I have a Java-Gradle project that has multiple modules, meaning multiple build.gradle files and multiple test folders.
I have a main build.gralde and I succeeded to aggregate all the multi jacoco reports to one main report using the configuration below at my main build.gradle.
but now I want to exclude some of packages / classes from the aggregated modules.
How do I do that?
you can see also my tries below
apply plugin: 'jacoco'
apply plugin: 'java'
def otherProjects = [':module1', ':module2']
otherProjects.each {
// ensure other projects evaluated first so sourceSets are configured
evaluationDependsOn it
}
jacoco {
toolVersion = "0.8.4"
reportsDir = file("$buildDir/jacoco")
}
jacocoTestReport {
FileTree sourceTree = files().asFileTree
FileTree classTree = files().asFileTree
otherProjects.each {
sourceTree += project(it).sourceSets.main.allJava
classTree += project(it).sourceSets.main.output.asFileTree
}
additionalSourceDirs = sourceTree
additionalClassDirs = classTree
reports {
html.enabled true
html.destination file("${buildDir}/jacocoHtml")
}
// try 1
afterEvaluate {
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it, exclude: '/com/packege_from_module1/**')
})
}
// try 2
afterEvaluate {
additionalSourceDirs = files(additionalSourceDirs.files.collect {
sourceTree(dir: it, exclude: 'com/packege_from__module1/**')
})
}
// try 3
afterEvaluate {
additionalSourceDirs = files(additionalSourceDirs.files.collect {
classTree(dir: it, exclude: 'com/packege_from__module1/**')
})
}
}

Given
a/src/main/java/A.java
class A {
}
a/src/test/java/ATest.java
import org.junit.Test;
public class ATest {
#Test
public void a() {
}
}
b/src/main/java/B.java
class B {
}
b/src/test/java/BTest.java
import org.junit.Test;
public class BTest {
#Test
public void b() {
}
}
settings.gradle
rootProject.name = 'example'
include 'a'
include 'b'
and build.gradle
allprojects {
apply plugin: 'java'
apply plugin: 'jacoco'
jacoco {
toolVersion = "0.8.3"
}
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.12'
}
}
task jacocoAggregateReport(type: org.gradle.testing.jacoco.tasks.JacocoReport) {
dependsOn = subprojects.test
sourceDirectories = files(subprojects.sourceSets.main.allSource.srcDirs)
classDirectories = files(subprojects.sourceSets.main.output)
executionData = files(subprojects.jacocoTestReport.executionData)
}
using Gradle 4.10.3 or 5.4.1 execution of gradle jacocoAggregateReport will produce following report in directory build/reports/jacoco/jacocoAggregateReport/html/index.html
Now let's exclude class file A.class from report by changing
classDirectories = files(subprojects.sourceSets.main.output)
in build.gradle on
classDirectories = files(subprojects.sourceSets.main.output).asFileTree.matching {
exclude 'A.class'
}
and execution of gradle jacocoAggregateReport will produce
Your attempts did not worked, because report is constructed for all class files from both classDirectories and additionalClassDirs - no exclusion from classDirectories and additionalClassDirs in attempts 2 and 3, no exclusion from additionalClassDirs in attempt 1.

Related

Problem with import and using SwingFXUtils in gradle project

I'm very new to gradle and javaFx.
I'm working on a gradle project (not mine) and I need to import SwingFXUtils to make some operations.
Importing it into the java file:
import javafx.embed.swing.SwingFXUtils;
cause the error: "Cannot resolve symbold SwingFXUtils".
I tried to add it to java-modules.java file
requires javafx.embed.swing;
but it is not recognized and I'm having the error message: "Module not found:javafx.embed.swing"
then, I updated my build.gradle for the missing module: like this:
plugins {
id 'application'
id 'org.beryx.jlink' version '2.19.0'
id 'com.google.osdetector' version '1.6.2'
}
repositories {
flatDir {
dirs "libs"
}
jcenter()
maven { url "https://maven.geotoolkit.org/" }
mavenCentral()
}
ext {
toolName = 'my project'
toolVersion = '1.0.0'
mainModuleName = 'com.myproject'
mainClassName = 'com.myproject.DcTool'
jfxVersion = '14.0.1'
pdfboxVersion = '2.0.27'
platform = osdetector.os == 'osx'?'mac':osdetector.os =='windows'?'win':osdetector.os
fixWayland = platform == 'mac' ? '' : platform == 'win' ? '' : '-Djdk.gtk.version=2'
}
version = "$toolVersion"
// Project dependencies.
dependencies {
compileOnly "org.jetbrains:annotations:19.0.0"
implementation "org.openjfx:javafx-base:$jfxVersion:$platform"
implementation "org.openjfx:javafx-graphics:$jfxVersion:$platform"
implementation "org.openjfx:javafx-controls:$jfxVersion:$platform"
implementation "org.openjfx:javafx-fxml:$jfxVersion:$platform"
implementation "com.fazecast:jSerialComm:2.6.2"
implementation "ch.qos.logback:logback-classic:1.3.0-alpha4"
implementation "de.skuzzle:semantic-version:2.1.0"
implementation "info.picocli:picocli:4.3.2"
annotationProcessor "info.picocli:picocli-codegen:4.3.2"
implementation "org.apache.pdfbox:pdfbox:${pdfboxVersion}"
implementation "org.apache.pdfbox:preflight:${pdfboxVersion}"
implementation "com.fasterxml.jackson.jr:jackson-jr-objects:2.11.0"
implementation group: 'org.openjfx', name: 'javafx-swing', version: '11-ea+24'
}
java {
modularity.inferModulePath = true
}
application {
mainModule.set("$mainModuleName")
mainClass.set("$mainClassName")
applicationDefaultJvmArgs = [
"-Dfile.encoding=UTF-8",
]
}
tasks.withType(JavaCompile) {
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath
]
classpath = files()
}
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_14
options.encoding = "UTF-8"
options.javaModuleVersion.set("$toolVersion")
options.javaModuleMainClass.set("$mainClassName")
}
run {
doFirst {
jvmArgs = [
"--module-path", classpath.asPath,
'--patch-module', "$mainModuleName=" + files(sourceSets.main.output.resourcesDir).asPath,
"--module", "$mainModuleName/$mainClassName"
]
jvmArgs += application.applicationDefaultJvmArgs
classpath = files()
}
doLast {
args = []
}
}
jar {
manifest {
attributes(
'Main-Class': "$mainClassName"
)
}
}
JAVA_HOME=$(/usr/libexec/java_home)
jlink {
moduleName.set("$mainModuleName")
mainClass.set("$mainClassName")
addOptions(
'--bind-services',
'--no-header-files',
'--no-man-pages',
'--strip-debug',
'--compress', '2')
launcher {
name = "$toolName"
jvmArgs += application.applicationDefaultJvmArgs
}
}
I also tried to download jars of SwingFx and add them in a "libs" folder into the project but I have no result and compiler doesn't find modules I need.
What can I do to make it find this module?
Thank you for your help.

Gradle does not copy jars to Maven .m2 folder

What could be missing in this build.gradle file that prevents the publishToMavenLocal not to copy files to the .m2 folder?
The script does have the 'maven-publish' plugin.
buildscript {
ext.kotlinVersion = '1.3.10'
ext.dokkaVersion = '0.9.17'
repositories { mavenLocal() }
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
classpath "org.jetbrains.dokka:dokka-gradle-plugin:$dokkaVersion"
}
}
plugins {
id 'com.github.hierynomus.license' version '0.15.0'
id 'io.codearte.nexus-staging' version '0.11.0'
id 'maven-publish'
}
group = 'org.jetbrains.xodus'
version = hasProperty('xodusVersion') ? project.xodusVersion : ''
def isSnapshot = version.endsWith('SNAPSHOT')
def isDailyBuild = hasProperty('dailyBuild') ? project.dailyBuild : false
def mavenPublishUrl = hasProperty('mavenPublishUrl') ? project.mavenPublishUrl : ''
def mavenPublishUsername = hasProperty('mavenPublishUsername') ? project.mavenPublishUsername : ''
def mavenPublishPassword = hasProperty('mavenPublishPassword') ? project.mavenPublishPassword : ''
def signingKeyId = hasProperty('signingKeyId') ? project.signingKeyId : ''
def signingPassword = hasProperty('signingPassword') ? project.signingPassword : ''
def signingSecretKeyRingFile = hasProperty('signingSecretKeyRingFile') ? project.signingSecretKeyRingFile : '../key.gpg'
static def shouldDeploy(project) {
return project.version.length() > 0 && !(project.name in ['benchmarks', 'samples'])
}
task wrapper(type: Wrapper) {
gradleVersion = '3.5.1'
}
defaultTasks 'assemble'
// Use nexus-staging-plugin to workaround https://issues.sonatype.org/browse/OSSRH-5454
nexusStaging {
username = mavenPublishUsername
password = mavenPublishPassword
delayBetweenRetriesInMillis = 30000
stagingProfileId = "89ee7caa6631c4"
}
subprojects {
apply plugin: 'license'
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'maven'
apply plugin: 'signing'
apply plugin: 'org.jetbrains.dokka'
sourceCompatibility = 1.7
compileJava.options.encoding = 'UTF-8'
group = rootProject.group
version = rootProject.version
archivesBaseName = rootProject.name + '-' + project.name
license {
header rootProject.file('license/copyright.ftl')
strictCheck true
ext.inceptionYear = 2010
ext.year = Calendar.getInstance().get(Calendar.YEAR)
ext.owner = 'JetBrains s.r.o.'
include "**/*.kt"
include "**/*.java"
mapping {
kt = 'JAVADOC_STYLE'
}
}
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
}
// tests for most of sub-projects run with database encryption turned on
if (!(project.name in ['benchmarks', 'compress', 'crypto', 'openAPI', 'samples', 'utils'])) {
test {
systemProperty 'exodus.cipherId', 'jetbrains.exodus.crypto.streamciphers.ChaChaStreamCipherProvider'
systemProperty 'exodus.cipherKey', '000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f'
systemProperty 'exodus.cipherBasicIV', '314159262718281828'
// uncomment the following line to run tests in-memory
//systemProperty 'exodus.log.readerWriterProvider', 'jetbrains.exodus.io.inMemory.MemoryDataReaderWriterProvider'
}
dependencies {
testCompile project(':crypto')
}
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
jar {
manifest {
attributes 'Implementation-Title': archivesBaseName, 'Implementation-Version': version
}
}
test {
minHeapSize = '1g'
maxHeapSize = '1g'
//jvmArgs = ['-ea', '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=2808']
//testLogging.showStandardStreams = true
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
duplicatesStrategy 'exclude'
includeEmptyDirs false
from javadoc.destinationDir
}
javadoc.failOnError = false
// work around for Java 8 javadoc which is too strict
if (JavaVersion.current().isJava8Compatible()) {
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
task sourceJar(type: Jar) {
classifier = 'sources'
duplicatesStrategy 'exclude'
includeEmptyDirs false
from project.sourceSets.main.java
from project.sourceSets.main.kotlin
}
// configuring projects with Kotlin sources
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
compile 'io.github.microutils:kotlin-logging:1.5.4'
}
compileKotlin {
kotlinOptions {
languageVersion = '1.2'
apiVersion = '1.2'
}
}
compileTestKotlin {
kotlinOptions {
languageVersion = '1.2'
apiVersion = '1.2'
}
}
dokka {
jdkVersion = 7
packageOptions {
reportUndocumented = false
}
}
task dokkaJavadoc(type: org.jetbrains.dokka.gradle.DokkaTask) {
outputFormat = 'javadoc'
outputDirectory = "$buildDir/javadoc"
}
javadocJar {
dependsOn dokkaJavadoc
from dokkaJavadoc.outputDirectory
}
artifacts {
archives jar, javadocJar, sourceJar
}
if (!isSnapshot && signingKeyId.length() > 0) {
ext.'signing.keyId' = signingKeyId
ext.'signing.password' = signingPassword
ext.'signing.secretKeyRingFile' = signingSecretKeyRingFile
}
afterEvaluate { project ->
if (shouldDeploy(project)) {
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
if (isDailyBuild) {
repository(url: "https://api.bintray.com/maven/jetbrains/xodus/" + archivesBaseName + "/;publish=1") {
authentication(userName: mavenPublishUsername, password: mavenPublishPassword)
}
} else {
repository(url: mavenPublishUrl) {
authentication(userName: mavenPublishUsername, password: mavenPublishPassword)
}
}
pom.project {
name 'Xodus'
description 'Xodus is pure Java transactional schema-less embedded database'
packaging 'jar'
url 'https://github.com/JetBrains/xodus'
scm {
url 'https://github.com/JetBrains/xodus'
connection 'scm:git:https://github.com/JetBrains/xodus.git'
developerConnection 'scm:git:https://github.com/JetBrains/xodus.git'
}
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/license/LICENSE-2.0.txt'
distribution 'repo'
}
}
developers {
developer {
id 'JetBrains'
name 'JetBrains Team'
organization 'JetBrains s.r.o'
organizationUrl 'http://www.jetbrains.com'
}
}
}
}
}
}
signing {
required { !isSnapshot && signingKeyId.length() > 0 && gradle.taskGraph.hasTask('uploadArchives') }
sign configurations.archives
}
}
}
}
Your build does not configure any publications, hence the publishToMavenLocal task is a noop:
$ ./gradlew --console=verbose publishToMavenLocal
> Task :publishToMavenLocal UP-TO-DATE
BUILD SUCCESSFUL in 0s
When you configure a publication as in this example …
task buildMyArtifact(type: Zip) {
// TODO using the build script as a sample file here; use whatever makes
// sense for your project
from 'build.gradle'
archiveBaseName = 'whateverNameInBuildDir'
destinationDirectory = buildDir
}
publishing {
publications {
myPublication(MavenPublication) {
artifact buildMyArtifact
groupId 'com.example'
artifactId 'my-module'
version '1.0.0'
}
}
}
… then the publishToMavenLocal task installs the publication into the local Maven repository:
$ ./gradlew --console=verbose publishToMavenLocal
> Task :buildMyArtifact
> Task :generatePomFileForMyPublicationPublication
> Task :publishMyPublicationPublicationToMavenLocal
> Task :publishToMavenLocal
BUILD SUCCESSFUL in 1s
3 actionable tasks: 3 executed
$ tree ~/.m2/repository/com/example/my-module/
/home/chriki/.m2/repository/com/example/my-module/
├── 1.0.0
│   ├── my-module-1.0.0.pom
│   └── my-module-1.0.0.zip
└── maven-metadata-local.xml
1 directory, 3 files

How to debug Kolin Vertx web app in IDE Intellij?

I have created a Kotlin Vertx web app which runs with Gradle. But When I try to debug it by running Intellij debug configuration, the breakpoints aren't hitting. How can I make those breakpoints work ?
buildscript {
ext {
kotlinVersion = '1.2.60'
}
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
}
plugins {
id 'java'
id 'application'
id 'com.github.johnrengelman.shadow' version '2.0.4'
id 'org.jetbrains.kotlin.jvm' version '1.3.11'
id 'jacoco'
id 'de.jansauer.printcoverage' version '2.0.0'}
jacoco{
toolVersion = '0.8.2'
}
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.1
}
}
}
}
jacocoTestReport {
reports {
csv.enabled true
xml.enabled true
html {
enabled true
destination file("$buildDir/reports/jacoco")
}
}
executionData(test)
}
tasks.build.dependsOn(jacocoTestReport)
printcoverage {
coverageType = 'INSTRUCTION'
}
apply plugin: 'kotlin'
ext {
kotlinVersion = '1.2.60'
vertxVersion = '3.6.2'
junitJupiterEngineVersion = '5.2.0'
}
repositories {
mavenLocal()
jcenter()
}
group 'com.joyfulyell'
version '1.0-SNAPSHOT'
sourceCompatibility = '1.8'
mainClassName = 'io.vertx.core.Launcher'
def mainVerticleName = 'io.vertx.starter.MainVerticle'
def watchForChange = 'src/**/*'
def doOnChange = './gradlew classes'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
compile "io.vertx:vertx-core:$vertxVersion"
compile "io.vertx:vertx-web:$vertxVersion"
compile "io.vertx:vertx-lang-kotlin:$vertxVersion"
compile "io.vertx:vertx-mongo-client:$vertxVersion"
implementation 'org.kodein.di:kodein-di-generic-jvm:6.0.1'
compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.+"
compile 'com.beust:klaxon:5.0.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0'
testImplementation "io.vertx:vertx-junit5:$vertxVersion"
testRuntime("org.junit.jupiter:junit-jupiter-engine:$junitJupiterEngineVersion")
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
shadowJar {
classifier = 'fat'
manifest {
attributes 'Main-Verticle': mainVerticleName
}
mergeServiceFiles {
include 'META-INF/services/io.vertx.core.spi.VerticleFactory'
}
}
test {
useJUnitPlatform()
testLogging {
events 'PASSED', 'FAILED', 'SKIPPED'
}
reports {
junitXml.enabled = true
html.enabled = true
}
jacoco{
append = false
destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
classDumpDir = file("$buildDir/jacoco/classpathdumps")
}
}
run {
args = ['run', mainVerticleName,
"--redeploy=$watchForChange",
"--launcher-class=$mainClassName",
"--on-redeploy=$doOnChange"
]
}
task wrapper(type: Wrapper) {
gradleVersion = '5.0'
}
You should be able to run debug just fine by configuring Gradle as follows:
And hitting the Debug button. Tested it using your configuration.
Just make sure that you specify the correct verticle name in your build.gradle:
def mainVerticleName = 'io.vertx.starter.MainVerticle'

Kotlin Test Coverage

Does anyone know if a good test coverage tool (preferably Gradle plugin) exists for Kotlin? I've looked into JaCoCo a bit, but it doesn't seem to reliably support Kotlin.
As requested, here is an example build.gradle that uses Kotlin, and incorporates both Jacoco and Sonarqube integration, produces a jar and sources, and ties in Detekt for static analysis.
I had to manually add a couple things as my work build has jacoco applied by an in-house plugin.
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.2.10'
id 'org.jetbrains.kotlin.plugin.spring' version '1.2.10'
id 'org.springframework.boot' version '1.5.9.RELEASE'
id 'io.spring.dependency-management' version '1.0.4.RELEASE'
id 'io.gitlab.arturbosch.detekt' version '1.0.0.RC6'
id "org.sonarqube" version "2.6.2".
}
apply plugin: 'jacoco'
ext {
springBootVersion = '1.5.9.RELEASE'
springCloudVersion = 'Dalston.SR4'
kotlinVersion = '1.2.10'
detektVersion = '1.0.0.RC6'.
}
//======================= Project Info =============================================
group = 'group'
version = '0.14'
dependencyManagement {
imports {
mavenBom("org.springframework.boot:spring-boot-starter- parent:$springBootVersion")
mavenBom "org.springframework.cloud:spring-cloud-dependencies:$springCloudVersion"
}
}
repositories {
jcenter()
}
//======================= Dependencies =============================================
dependencies {
// Version MUST be explicitly set here or else dependent projects will not be able to build as Gradle will not know
// what version to use
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion"
compile 'org.springframework.boot:spring-boot-starter-web'
compile('org.springframework.ws:spring-ws-support') {
exclude(module: 'javax.mail')
}
compile 'org.springframework.boot:spring-boot-starter-actuator'
// Spring security
compile 'org.springframework.security:spring-security-web'
compile 'org.springframework.security:spring-security-config'
compile 'javax.servlet:javax.servlet-api'
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml'
compile('org.apache.httpcomponents:httpclient')
compile 'com.nimbusds:nimbus-jose-jwt:4.23'
}
//======================= Tasks =============================================
defaultTasks 'build'
tasks.bootRepackage.enabled = false
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = 1.8
freeCompilerArgs = ["-Xjsr305=strict"]
}
}
compileJava.options.encoding = 'UTF-8'
test.testLogging.exceptionFormat = 'full'
// ********************************
ext.coverageExclusions = [
// Configuration
'com.bns.pm.config.*',
// data classes
'com.bns.pm.domain.*',
// Account Service domain objects
'com.bns.pm.account.domain.*',
// Other items
'com.bns.pm.exceptions.DataPowerFaultException.Companion',
'com.bns.pm.controllers.ServiceExceptionHandler*',
'com.bns.pm.service.callback.DPWebServiceMessageCallback',
'com.bns.pm.service.HealthCheckService',
'com.bns.pm.util.SystemPropertiesUtilKt',
]
check.dependsOn jacocoTestCoverageVerification
jacocoTestCoverageVerification {
violationRules {
rule {
element = 'CLASS'
// White list
excludes = coverageExclusions
limit {
minimum = 0.70
}
}
}
}
jacocoTestReport {
description 'Generates Code coverage report. Fails build if it does not meet minimum coverage.'
reports {
xml.enabled = true //XML required by coveralls and for the below coverage checks
html.enabled = true
csv.enabled = false
}
def reportExclusions = coverageExclusions.collect {
it.replaceAll('\\.', '/') + (it.endsWith('*') ? '' : '*')
}
afterEvaluate {
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it, excludes: reportExclusions)
})
}
}
test.finalizedBy jacocoTestReport
afterEvaluate {
sonarqube {
properties {
property 'sonar.jacoco.reportPath', "${buildDir}/jacoco/test.exec"
property "detekt.sonar.kotlin.config.path", "detekt.yml"
property 'sonar.java.binaries', "$projectDir/build/classes/kotlin"
property 'sonar.coverage.exclusions', coverageExclusions.collect {
'**/' + it.replaceAll('\\.', '/') + (it.endsWith('*') ? '' : '*')
}
}
}
}
// Ensure source code is published to Artifactory
// Have to redefine publishing with new name as Accelerator Plugin already defined mavenJava
task sourceJar(type: Jar) {
from sourceSets.main.allSource
classifier 'sources'
}
publishing {
publications {
mavenJava2(MavenPublication) {
from components.java
artifact(sourceJar) {
classifier = 'sources'
}
}
}
}
artifactory {
contextUrl = "${artifactory_contextUrl}"
publish {
repository {
repoKey = "${artifactory_projectRepoKey}"
username = "${artifactory_user}"
password = "${artifactory_password}"
maven = true
}
defaults {
publications('mavenJava2')
}
}
}
artifactoryPublish {
dependsOn jar
}
detekt {
version = detektVersion
profile("main") {
input = "$projectDir/src"
config = "$projectDir/detekt.yml"
filters = ".*/resources/.*,.*/tmp/.*"
output = "$project.buildDir/reports/detekt"
}
}
check.dependsOn detektCheck
Good news: there is a new kotlinx-kover Gradle plugin, compatible with JaCoCo and IntelliJ.
plugins {
id("org.jetbrains.kotlinx.kover") version "0.5.0"
}
Once applied, the plugin can be used out of the box without additional configuration.
Watch its YouTube announcement video and also track its roadmap from this youtrack issue.
As said in the video, it solves the problem with inline functions and more.

How to upload the gradle build java project into sonar server

I have added the sonar properties into my build.gradle file to upload the project into server when build the project using gradle. below is my build.gradle file.
import org.tmatesoft.svn.core.wc
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'findbugs'
apply plugin: 'sonar-runner'
apply plugin: "jacoco"
group = 'com.example.service'
sourceCompatibility = 1.5
version = '1.0'
jar {
manifest {
attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version
}
}
findbugs {
// make findbugs non build breaking
ignoreFailures = true
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
compile 'org.apache.commons:commons-lang3:3.1'
compile "org.codehaus.sonar.runner:sonar-runner-api:2.4"
testCompile group: 'junit', name: 'junit', version: '4.+'
}
test {
systemProperties 'property': 'value'
}
sonarRunner {
sonarProperties {
property "sonar.host.url", "http://localhost:9000"
property "sonar.sourceEncoding", "UTF-8"
property "sonar.projectName", "$project.name"
property "sonar.projectKey", "$project.group:$project.name"
property "sonar.projectBaseDir","$project.projectDir"
property "sonar.working.directory","$project.buildDir/sonar"
property "sonar.jacoco.reportPath", "${project.buildDir}/jacoco/test.exec"
}
}
test {
jacoco {
destinationFile = file("$buildDir/jacoco/test.exec")
}
}
uploadArchives {
repositories {
mavenLocal()
}
}
But when I build the project from eclipse nothing happens. No error message in the console, and project is also not uploaded to the sonar server.
Does anyone know how to upload the project into the Sonar Server when building with Gradle?
See couple of my posts and you'll find what you are looking for. Mainly, you have to use:
apply plugin: 'sonar-runner'
Then, I have following config in < YOUR_GRADLE_HOME >/init.d/someglobal.gradle file
allprojects {
apply plugin: 'java'
apply plugin: 'codenarc'
apply plugin: 'pmd'
apply plugin: 'findbugs'
apply plugin: 'checkstyle'
apply plugin: 'jacoco'
apply plugin: 'sonar-runner'
//JavaCompile(Works with recent Gradle versions) or Compile (works with Gradle 1.6)
//tasks.withType(Compile) {
tasks.withType(JavaCompile) {
options.debug = true
options.compilerArgs = ["-g"]
}
//You don't need sourceSets if your project is following Maven/Gradle standard structure. In my case, we don't follow src/main/java but have src/java thus, in the global file, I have dont_change_me as the value for sourceSets main java and I'm setting it to src/java in the Project's build.gradle. dont_change_me is required here as I'm/was using sourceSet.main.xx.xxx values in few of the tasks here.
sourceSets {
main {
java {
srcDir 'dont_change_me'
}
resources {
srcDir 'dont_change_me'
}
}
test {
java {
srcDir 'dont_change_me'
}
resources {
srcDir 'dont_change_me'
}
}
integrationTest {
java {
srcDir 'dont_change_me'
}
resources {
srcDir 'dont_change_me'
}
}
acceptanceTest {
java {
srcDir 'dont_change_me'
}
resources {
srcDir 'dont_change_me'
}
}
}
def sonarServerUrl = "kobalori.company.com"
sonarRunner {
sonarProperties {
property "sonar.host.url", "http://$sonarServerUrl:9000"
property "sonar.jdbc.url", "jdbc:h2:tcp://$sonarServerUrl:9092/sonar"
property "sonar.jdbc.driverClassName", "org.h2.Driver"
property "sonar.jdbc.username", "sonar"
property "sonar.jdbc.password", "sonar"
property "sonar.junit.reportsPath", "build/test-results/UT"
property "sonar.surefire.reportsPath", "build/test-results/UT"
//property "sonar.dynamicAnalysis", "reuseReports"
property "sonar.binaries", "build/classes/main"
property "sonar.java.binaries", "build/classes/main"
// property "sonar.libraries", "build/libs/*.jar"
property "sonar.sources", "src/java"
//property "sonar.sources", "src/main/groovy"
//property "sonar.sources", "src/java, src/main/groovy"
//property "sonar.tests", "test/java, src/test/groovy, src/groovy-test, src/java-test"
//property "sonar.tests", "src/test/groovy"
property "sonar.tests", "test/java, src/java-test"
//properties ["sonar.sources"] = sourceSets.main.allSource.srcDirs
//properties ["sonar.tests"] += sourceSets.test.allJava.srcDirs
//properties ["sonar.tests"] += sourceSets.integrationTest.allJava.srcDirs
}
}
//sonarRunner {
// toolVersion = '2.4'
//}
checkstyle {
configFile = new File(rootDir, "config/checkstyle.xml")
ignoreFailures = true
//sourceSets = [sourceSets.main, sourceSets.test, sourceSets.integrationTest]
sourceSets = [sourceSets.main]
}
findbugs {
ignoreFailures = true
sourceSets = [sourceSets.main]
//toolVersion = "2.0.3"
}
// pmd {
// ruleSets = ["basic", "braces", "design"]
// ignoreFailures = true
// }
//Required with Gradle 2.0+ -- 2.0+ -- 2.3
pmd {
ruleSets = ["java-basic", "java-braces", "java-design" ]
ignoreFailures = true
}
//Try this or later version too.
//pmd {
// toolVersion = '4.3'
//}
jacoco {
//toolVersion = "0.6.2.201302030002"
//toolVersion = "0.7.0.201403182114"
//toolVersion = "0.7.1.201404171759"
toolVersion = "0.7.2.201409121644"
reportsDir = file("$buildDir/customJacocoReportDir")
}
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/tests/allTests")
//testResultDirs = file("$buildDir/test-results/allTests")
}
test {
maxParallelForks = 5
forkEvery = 50
ignoreFailures = true
//testReportDir = file("$buildDir/reports/tests/UT")
//destinationDir = file("$buildDir/reports/tests/UT")
//testResultsDir = file("$buildDir/test-results/UT")
//testLogging.showStandardStreams = true
//onOutput { descriptor, event ->
// logger.lifecycle("Test: " + descriptor + " produced standard out/err: " + event.message )
//}
//Following Jacoco test section is required only in Jenkins instance extra common file
jacoco {
//The following vars works ONLY with 1.6 of Gradle
// destPath = file("$buildDir/jacoco/UT/jacocoUT.exec")
// classDumpPath = file("$buildDir/jacoco/UT/classpathdumps")
//Following vars works only with versions >= 1.7 version of Gradle
destinationFile = file("$buildDir/jacoco/UT/jacocoUT.exec")
// classDumpFile = file("$buildDir/jacoco/UT/classpathdumps")
}
}
task integrationTest( type: Test) {
//Always run tests
outputs.upToDateWhen { false }
ignoreFailures = true
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
//testReportDir = file("$buildDir/reports/tests/IT")
//testResultsDir = file("$buildDir/test-results/IT")
//Following Jacoco test section is required only in Jenkins instance extra common file
jacoco {
//This works with 1.6
//destPath = file("$buildDir/jacoco/IT/jacocoIT.exec")
// classDumpPath = file("$buildDir/jacoco/IT/classpathdumps")
//Following works only with versions >= 1.7 version of Gradle
destinationFile = file("$buildDir/jacoco/IT/jacocoIT.exec")
// classDumpFile = file("$buildDir/jacoco/IT/classpathdumps")
}
}
task acceptanceTest ( type: Test) {
//Always run tests
outputs.upToDateWhen { false }
ignoreFailures = true
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
//testReportDir = file("$buildDir/reports/tests/AT")
//testResultsDir = file("$buildDir/test-results/AT")
//Following Jacoco test section is required only in Jenkins instance extra common file
jacoco {
//This works with 1.6
//destPath = file("$buildDir/jacoco/AT/jacocoAT.exec")
// classDumpPath = file("$buildDir/jacoco/AT/classpathdumps")
//Following works only with versions >= 1.7 version of Gradle
destinationFile = file("$buildDir/jacoco/AT/jacocoAT.exec")
// classDumpFile = file("$buildDir/jacoco/AT/classpathdumps")
}
}
jacocoTestReport {
group = "Reporting"
description = "Generate Jacoco coverage reports after running tests."
//ignoreFailures = true
//executionData = files('build/jacoco/UT/jacocoUT.exec')
//executionData = files('build/jacoco/IT/jacocoIT.exec')
//executionData = files('build/jacoco/UT/jacocoUT.exec', 'build/jacoco/IT/jacocoIT.exec')
//executionData = files(['build/jacoco/UT/jacocoUT.exec', 'build/jacoco/IT/jacocoIT.exec'])
executionData = fileTree(dir: 'build/jacoco', include: '**/*.exec')
reports {
xml{
enabled true
//Following value is a file
destination "${buildDir}/reports/jacoco/xml/jacoco.xml"
}
csv.enabled false
html {
enabled true
//Following value is a folder
destination "${buildDir}/reports/jacoco/html"
}
}
//sourceDirectories = files(sourceSets.main.allJava.srcDirs)
sourceDirectories = files(['src/java','src/main/java', 'src/main/groovy'])
classDirectories = files('build/classes/main')
//------------------------------------------
//additionalSourceDirs = files(['test/java','test/groovy','src/java-test', 'src/groovy-test'])
//additionalSourceDirs = files(['src/test/groovy'])
//additionalSourceDirs += files('src/java-test')
//additionalClassDirs = files('build/classes/test')
//additionalClassDirs += files('build/classes/integrationTest')
//additionalClassDirs += files('build/classes/acceptanceTest')
//------------------------------------------
//IGNORE THE FOLLOWING
//------------------------------------------
//sourceDirectories = files(sourceSets.main.allJava.srcDirs)
//classDirectories = files(sourceSets.main.output.classesDir)
//classDirectories = files("build/classes/main")
//additionalSourceDirs = files("test/java")
//additionalSourceDirs += files("src/java-test")
//additionalClassDirs = files("build/classes/test")
//additionalClassDirs += files("build/classes/integrationTest")
//additionalSourceDirs = fileTree(dir: "test", include: "**/*.*")
//additionalSourceDirs += fileTree(dir: "src/java-test", include: "**/*.*")
//additionalClassDirs = fileTree(dir: "build/*est", include: "**/*.class")
//additionalClassDirs += fileTree(dir: "build/jacoco/*T/classpathdumps/com/thc", include: "**/*.class")
//additionalClassDirectories = fileTree(dir: "build/*est", include: "**/*.class")
//additionalClassDirectories += fileTree(dir: "build/jacoco/*T/classpathdumps/com/thc", include: "**/*.class")
//additionalSourceDirs = files(['test/java', 'src/java-test'])
//additionalSourceDirs = files(sourceSets.test.allJava.srcDirs)
//additionalSourceDirs += files(sourceSets.integrationTest.allJava.srcDirs)
//additionalSourceDirs += files(sourceSets.acceptanceTest.allJava.srcDirs)
// additionalClassDirs = files(['build/jacoco/UT/classpathdumps/com/thc', 'build/jacoco/IT/classpathdumps/com/thc'])
//additionalClassDirs = files(['build/jacoco/UT/classpathdumps/com/thc'])
//additionalSourceDirs = files('test/java', 'src/java-test')
// additionalClassDirs = files('build/jacoco/UT/classpathdumps/com/thc', 'build/jacoco/IT/classpathdumps/com/thc')
//sourceDirectories = files('src/main/java')
// classDirectories = files('build/classes/main')
//sourceDirectories = fileTree('src/main/java')
// classDirectories = fileTree('build/classes/main')
//additionalSourceDirectories = fileTree('test/java', 'test/resources', 'src/java-test')
// additionalClassDirectories = fileTree('build/classes/test', 'build/classes/integrationTest')
//additionalSourceDirs = files(sourceSets.test.allJava.srcDirs,sourceSets.integrationTest.allJava.srcDirs)
//additionalSourceDirs = files(sourceSets.*.allJava.srcDirs)
//additionalSourceDirs += files(sourceSets.test.allJava.srcDirs)
//additionalSourceDirs += files(sourceSets.integrationTest.allJava.srcDirs)
//additionalSourceDirs = files('src/java', 'test/java', 'test/resources', 'src/java-test', 'conf')
//additionalClasseDirs = files('build/classes')
//executionData = files('build/jacoco/test.exec', 'build/jacoco/integrationTest.exec', 'build/jacoco/acceptanceTest.exec')
//additionalSourceDirs = files(sourceSets.integrationTest.allSource.srcDirs)
//additionalSourceDirs = files('src/java', 'test/java', 'test/resources', 'src/java-test', 'conf')
//additionalSourceDirs = files(sourceSets.test.allJava.srcDirs)
//additionalSourceDirs = files(sourceSets.integrationTest.allJava.srcDirs)
//additionalSourceDirs = files([sourceSets.main.allJava.srcDirs)
}
}
You can ignore the // commented out lines as I was just playing around. Once your Gradle build is complete, you need to run jacocoTestReport task.
I run this:
gradle clean build jacocoTestReport
(This will get me a build, code coverage of source main code via Unit tests).
For getting, IT (Integration test code coverage or any non Unit tests coverage), I first run a external JVM (Tomcat etc). Then, I pass jacoco agent info to the external JVM (i.e. Tomcat in my case) like this (where I'm putting jacocoagent.jar inside some folder (tomcat in my case), and telling external JVM (Tomcat instance) to start populating Jacoco code coverage, this will create jacocoIT.exec file for code coverage of main source code via IT tests instead of Unit tests). NOTE: I have this PROJ_EXTRA_JVM_OPTS variable embedded in Tomcat startup script where I'm passing it to the Tomcat start command so that Tomcat instance know where to create jacocoIT.exec file:
export PROJ_EXTRA_JVM_OPTS=-javaagent:tomcat/jacocoagent.jar=destfile=build/jacoco/IT/jacocoIT.exec,append=false
Then I run Gradle task to run IT tests,
gradle integrationTest
Then, once they run successfully, you'll notice jacocoIT.exec has some file size (but it's still not complete). For Tomcat to flush the code coverage info into jacocoIT.exec file, you have to now STOP tomcat (target JVM) instance.
I run stop tomcat script and Tomcat is now stopped. At this point, I now find that my jacocoIT.exec file is now fully populated with more file size (than it what it had before Stop tomcat).
At this point, I run Gradle jacocoTestReport and SonarRunner task by running (which generates a COMBINED Unit + IT code coverage of main source code via both Unit+IT tests + also sends the info to Sonar by using/setting the -Dsonar.xx.yy=value (which you can easily pass at command line OR in Jenkins (Invoke Gradle Plugin > Switches/options box):
gradle jacocoTestReport -x test -x testClasses sonarRunner
NOTE: Make sure you pass -Dsonar.xx variable correctly.
For ex: I pass the following options/switches while calling sonarRunner task (this assumes in SonarQube instance, you have the project dashboard with required Widgets in place/enabled):
Here variable ${testType} has value=IT in it. All other variables are defined in Jenkins Global configuration (JENKINS_URL etc or they are available as Jenkins default environment variables). I'm using SVN (as source control tool) thus, SVN_URL is used (which is Jenkins default env variable if your Jenkins job is using SVN as Source control to checkout source code).
--stacktrace -x test -x testClasses -Dsonar.jacoco.itReportPath=build/jacoco/${testType}/jacoco${testType}.exec -Dsonar.sources=src/java -Dsonar.java.binaries=build/classes/main -Dsonar.binaries="build/classes/main" -Dsonar.tests=test/java,src/java-test -Dsonar.jacoco.reportPath=build/jacoco/UT/jacocoUT.exec -Dsonar.junit.reportsPath=build/test-results -Dsonar.surefire.reportsPath=build/test-results -Dsonar.dynamicAnalysis=reuseReports -Dsonar.build-stability.url=jenkins:${JENKINS_URL}/job/${JOB_NAME} -Dsonar.scm.url=scm:svn:${SVN_URL}

Resources