Gradle - how to exclude Findbugs on /src/test/java - gradle

Is there a way to exclude Findbugs execution on classes under /src/test/java. I tried the following but it doesn't seem to work.
classes = classes.filter {
!it.path.contains("**classes\\test\\org*")
}

Sure. The documentation of the Findbugs extension says:
sourceSets : The source sets to be analyzed as part of the check and build tasks.
And the example just above shows an example doing exactly what you want:
apply plugin: "findbugs"
findbugs {
sourceSets = [sourceSets.main]
}
i.e. only analyze the main sourceSet, and not the test sourceSet.

For Gradle 4.5.1
apply plugin: 'findbugs'
findbugs {
findbugsTest.enabled = false
}
It isn't mentioned anywhere in documentation, at least I, as 1 day gradle user, don't find it, but it works.

Related

How to integrate jacoco plugin with gradle?

I need to integrate jacoco plugin in to build.gradle or grade.properties file. anyone help me with setting this
Please check documentation of JaCoCo Gradle Plugin - https://docs.gradle.org/current/userguide/jacoco_plugin.html
For example you can add
apply plugin: 'jacoco'
// ...
test {
jacoco {
enabled = true
destinationFile = file("$buildDir/jacoco/jacoco.exec");
}
}
to your build.gradle file.

How to upload test reports of Kotlin sources to Coveralls?

I want to upload my Jacoco test report to Coveralls automatically after my Travis build finishes. It works for Java, but how to configure it for Kotlin?
Error message
I can generate a Jacoco test report locally and on Travis, but when Travis tries to submit to coveralls it fails with message
> Task :coveralls
No source file found on the project: "kotlin-template-project"
With coverage file: /home/travis/build/myname/myreponame/build/reports/jacoco/test/jacocoTestReport.xml
Google links me to the Gradle plugin implementation which shows where it throws this message, which tells me (I think) that the Jacoco report file is found but not the source files which coveralls apparently needs.
What I tried
Hence, I tried pointing the coveralls task to my source files, in all of these ways:
coveralls {
sourceDirs += allprojects.sourceSets.main.allSource.srcDirs.flatten()
sourceDirs += files(sourceSets.main.kotlin.srcDirs).files.absolutePath
project.extensions.coveralls.sourceDirs += project.sourceSets.main.kotlin.srcDirs
sourceDirs += ['src/main/kotlin']
jacocoReportPath = 'build/reports/jacoco/test/jacocoTestReport.xml'
sourceDirs += ['src/test/kotlin']
sourceDirs += ["${projectDir}/src/main/kotlin"]
}
I also tried adding sourceSets project.sourceSets.main to the jacocoTestReport task.
Project setup
My minimal build.gradle file:
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.2.50'
id 'java' // Required by at least JUnit.
// Test coverage
id 'jacoco'
// Upload jacoco coverage reports to coveralls
id 'com.github.kt3k.coveralls' version '2.8.2'
}
dependencies {
compile 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
// JUnit 5
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.2.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.2.0'
testRuntime 'org.junit.platform:junit-platform-console:1.2.0'
// Kotlintest
testCompile 'io.kotlintest:kotlintest-core:3.1.6'
testCompile 'io.kotlintest:kotlintest-assertions:3.1.6'
testCompile 'io.kotlintest:kotlintest-runner-junit5:3.1.6'
// Spek
testCompile 'org.jetbrains.spek:spek-api:1.1.5'
testRuntime 'org.jetbrains.spek:spek-junit-platform-engine:1.1.5'
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
}
test {
// Enable JUnit 5 (Gradle 4.6+).
useJUnitPlatform()
// Always run tests, even when nothing changed.
dependsOn 'cleanTest'
// Show test results.
testLogging {
events "passed", "skipped", "failed"
}
}
// Test coverage reporting
jacocoTestReport {
// Enable xml for coveralls.
reports {
html.enabled = true
xml.enabled = true
xml.setDestination(file("${buildDir}/reports/jacoco/test/jacocoTestReport.xml"))
}
}
coveralls {
sourceDirs += ['src/main/kotlin']
jacocoReportPath = 'build/reports/jacoco/test/jacocoTestReport.xml'
}
Related issues
Essentially the same issue is on https://github.com/kt3k/coveralls-gradle-plugin/issues/32 but the solution is to set sourceDirs and jacocoReportPath which I already have tried.
At https://github.com/kt3k/coveralls-gradle-plugin/issues/39 and https://github.com/kt3k/coveralls-gradle-plugin/issues/63 it is suggested to add sourceDirs += ['src/main/kotlin'] which sounds sensible but doesn't help. Same for, from the first link, sourceDirs = files(sourceSets.main.kotlin.srcDirs).files.absolutePath.
From https://github.com/kt3k/coveralls-gradle-plugin/issues/77 the solution is project.extensions.coveralls.sourceDirs += project.sourceSets.main.kotlin.srcDirs which I tried.
The question Kotlin code coverage in CI pipeline is phrased rather generally, but a comment points to discuss.kotlinlang.org where someone shows a way to improve the Jacoco result regarding kotlin, and the answer links to the Jacoco Gradle plugin which I use and works: when I run the jacocoTestReport task a report is generated in build/reports/jacoco/test/, both in xml and html.
The question Kotlin Test Coverage is also phrased general and answered with an unnecessarily complex build file from which I learned nothing new.
The question Measure test coverage for Kotlin code? claims that the Jacoco report does not work, but for me this is not the case as I said.
There are similar questions for Java, like Tool for java code coverage on GitHub but for me when I use Java it all works fine.
PS Actually I want to use the Gradle Kotlin DSL, but since nobody seems to use it I'm asking this question for Gradle. But in the end I want this question solved for the Kotlin DSL as well.
[edit August 2020] #nbaztec wrote a plugin to support Kotlin, please see his answer.
Old answer:
Kotlin is not supported by Coveralls, see for example this open isse that was mentioned in the question as well (in the question it was also mentioned that the workaround presented there does not work): https://github.com/kt3k/coveralls-gradle-plugin/issues/77
Solution: try Codecov.io instead.
Install it to GitHub using the Marketplace and add to your .travis.yml
after_success:
- bash <(curl -s https://codecov.io/bash)
Then commit and push, done!
You can view the result (after the build finished) at https://codecov.io/gh/githubaccountname/reponame
Had a similar experience with a variety of QA products not supporting or only partially supporting Kotlin codebases. Tried submitting support PRs to a couple of projects to no avail.
In the end ended up going with Coveralls and contributed a Kotlin focused plugin for the platform
https://github.com/nbaztec/coveralls-jacoco-gradle-plugin
Usage
Include the plugin in your build.gradle.kts (similar for build.gradle files):
plugins {
jacoco
id("com.github.nbaztec.coveralls-jacoco")
}
Then set the environment variable COVERALLS_REPO_TOKEN to the token from your Coveralls page.
Now you can use the coverallsJacoco task to publish a coverage report.
For more information and usage in CI, see
https://github.com/nbaztec/coveralls-jacoco-gradle-plugin
Not an answer, but in case anyone else is struggling with nbaztec like me, I want to give an alternative that worked for me: https://github.com/kt3k/coveralls-gradle-plugin
And besides what is in README.md, I needed this detail in build.gradle:
coveralls {
sourceDirs += ['src/main/kotlin']
jacocoReportPath "${buildDir}/reports/jacoco/report.xml"
}

Different ways to apply plugins ? (Gradle Kotlin DSL)

Trying to migrate this one project's build to GSK.
We have this in Groovy:
allprojects {
apply plugin: 'java'
...
sourceSets {
...
}
sourceCompatibility = ...
}
So while figuring out how to access the plugin convention in Kotlin, I found out that:
allprojects {
plugins {
java apply true
}
...
println("Project $name, plugins: ${plugins}") // empty list
val java = the<JavaPluginConvention>() // throws exception
}
but if you do it like this:
allprojects {
apply {
plugin(JavaPlugin::class.java)
}
}
plugin is applied and convention becomes accessible
WTH?
This issue isn't specific to Kotlin, and is due to a race condition. While the script is being evaluated, it may not have added the plugin to the classpath yet. This is one of many reasons why the plugins block was created, as it's specifically evaluated prior to the rest of the scripts evaluation during a buildscript phase. That said however, this special treatment is only done if this block is at the top of the script, and not when it's within a subprojects or allprojects block, as those blocks are technically arbitrary and are evaluated later to ensure the buildscript is idempotent. In your case, you are just moving up the race by placing it in allprojects block, and are getting lucky.
When dealing with multi-project builds, this is problematic, however if possible, the best is to declare the plugin in the plugins block with the apply false constrained syntax to add it to your build's classpath in the buildscript phase. You will then be able to apply the plugin later via the plugin's id during script evaluation (version isn't necessary, as it's used for fetching the dependency only).
An example:
plugins {
id("org.gradle.sample.hello") version "1.0.0" apply false
}
subprojects {
apply(plugin = "org.gradle.sample.hello")
}
The Gradle User Guide does a great job at explaining how these should be used, and the balance you will need to consider in multi-module projects.
Due to the nature of how some plugins are written, there may be cases where other issues will arise, but if plugin authors are following best practice guidelines, you'll be fine.
If your plugins are for Kotlin, then the best way for now is:
plugins {
kotlin("jvm") version "1.7.21"
kotlin("plugin.serialization") version "1.7.21"
}

sonarqube gradle plugin excluding jacoco integration tests

I'm trying to integrate the sonarqube gradle plugin with the jacoco plugin:
classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.1'
apply plugin: 'org.sonarqube'
apply plugin: 'jacoco'
My build/jacoco folder contains:
integrationTest.exec
test.exec
However, the sonarqube plugin only recognises the 'test.exec' file:
18:20:45.130 INFO - JaCoCoItSensor: JaCoCo IT report not found: C:\Users\abc3\Downloads\sme-letter\target\jacoco-it.exec
:
18:05:55.609 INFO - Analysing C:\Users\abc3\Downloads\sme-letter\build\jacoco\test.exec
How do I get the sonarqube plugin to recognise 'integrationTest.exec'
Thanks
Mark
I'm not really sure, whether this will work for Gradle plugun, but you may try.
Sonar has a property to specify the name of the integration tests JaCoCo report. This property is called sonar.jacoco.itReportPath (sonar.jacoco.reportPath for unit tests report).
And as far as I know, gradle sonar plugin let you add custom properties to it. So you can change IT report name via properties as follows:
sonarqube {
properties {
property "sonar.jacoco.itReportPath", "build/jacoco/ integrationTest.exec"
}
}
It works for me, but only after merging all jacoco reports into one file AND (important) deleting all other reports
property "sonar.java.coveragePlugin", "jacoco"
property "sonar.junit.reportsPath", "$projectDir/build/test-results"
property 'sonar.jacoco.reportPaths', "${rootProject.buildDir}/jacoco/mergeJacoco.exec"
And you need a merge jacoco task
Task mergeJacoco = tasks.create('mergeJacoco', JacocoMerge, {
doFirst {
delete "$buildDir/jacoco/mergeJacoco.exec"
}
destinationFile(new File(buildDir, 'jacoco/mergeJacoco.exec'))
executionData fileTree('./').include('**/*.exec-partial')
doLast {
delete fileTree('./').include('**/test.exec-partial')
}
})
mergeJacoco.outputs.upToDateWhen { false }
project.tasks["sonarqube"].dependsOn mergeJacoco
mergeJacoco.mustRunAfter ":myProject:test"
And setup jacoco to use those "partial" files
subprojects {
....
jacoco {
destinationFile file("$buildDir/jacoco/test.exec-partial")
append = false
includes = ['com.mypackage.*']
}
}
You'll get unit and IT reports mixed in one, but that's the best I could get

Applying Gradle Dependency-Check plugin

I am trying to use the dependency.check from the following link and have been unable to get it to run properly (at all) when following the instructions given.
https://github.com/jeremylong/DependencyCheck/tree/master/dependency-check-gradle
When trying to build with the apply plugin and additional dependency the fails on startup and it throws the following error.
Where:
Build file '/Users/aaron/work/backups/eiss/build.gradle' line: 25
What went wrong:
A problem occurred evaluating root project 'eiss'.
Failed to apply plugin [id 'dependency.check']
Plugin with id 'dependency.check' not found.
I made a little progress when making some changes but was still ultimately unsuccessful.
First, I commented out the apply plugin line.
Next, I switched:
classpath "com.thoughtworks.tools:dependency-check:0.0.7"
over to:
compile "com.thoughtworks.tools:dependency-check:0.0.7"
After these two changes it began recognizing the path and I was able to see it grabbing the items from the repository.
Even with the path correct I am still having issues with the apply plugin line with it throwing the same error whenever I place it into the script or even try to change the '.' in it into a '-' (both are used in the instructions and in different repository examples).
Any help on this issue would be appreciated! Thanks
lastly here is the build.gradle script. I didn't want to just leave this blob right in the center of the post.
defaultTasks 'assemble'
// For third party libs that are widely used, keep versions in one place
ext {
MONGO_JAVA_DRIVER = "org.mongodb:mongo-java-driver:2.12.3"
RABBITMQ_VERSION = "com.rabbitmq:amqp-client:3.4.3"
LOG4J = "log4j:log4j:1.2.16"
// For groovy there are multiple libs, just capture version number and use lib-name-$GROOVY_VERSION
GROOVY_VERSION = "2.3.6"
}
//
// Common settings for all projects
//
subprojects {
defaultTasks 'assemble'
apply plugin: 'groovy'
apply plugin: 'maven'
apply plugin: 'codenarc'
apply plugin: 'dependency.check'
targetCompatibility = "1.6"
sourceCompatibility = "1.6"
repositories {
mavenCentral()
}
dependencies {
compile LOG4J
compile "org.codehaus.groovy:groovy:${GROOVY_VERSION}"
compile "org.codehaus.groovy:groovy-json:${GROOVY_VERSION}"
compile "org.codehaus.groovy:groovy-templates:${GROOVY_VERSION}"
compile "com.thoughtworks.tools:dependency-check:0.0.7"
testCompile group: 'junit', name: 'junit', version: '4.+'
testCompile "org.codehaus.groovy:groovy-test:${GROOVY_VERSION}"
testCompile "org.hamcrest:hamcrest-core:1.3"
}
clean.doLast {
// The archive path is configured via the jar tasks. Can't use
// delete jar.archivePath because that will configure the delete with
// the wrong (default) path of build/libs/<component.jar>
jar.archivePath.delete()
jarSources.archivePath.delete()
}
//--------------------------------------------------------------------
// Run and test
//--------------------------------------------------------------------
test {
// Uncomment to see standard output when running tests
testLogging.showStandardStreams = true
// This causes tests to run even when nothing has changed
outputs.upToDateWhen { false }
maxParallelForks = 1
}
task runClass(dependsOn: 'classes', type: JavaExec) {
if (project.hasProperty('classToRun')) {
if (project.hasProperty('arguments')) {
args(arguments.split(','))
}
classpath = sourceSets.main.runtimeClasspath
main=classToRun
}
}
//run this task to create source jars
task jarSources(type:Jar){
destinationDir = new File(projectDir.parent + "/sourcelibs")
from sourceSets.main.allSource
classifier 'sources'
}
}
You added plugin dependency in a wrong place, to the dependencies of your project, not a build script itself, which will use it. Try to add buildscript dependencies, as it's made in the example of plugin installation
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.thoughtworks.tools:dependency-check:0.0.7'
}
}
And then return your apply plugin
apply plugin: 'dependency.check'
Though this is very old post, accepted answer is using legacy plugin application, whereas below could be used while using the plugins DSL: https://plugins.gradle.org/plugin/org.owasp.dependencycheck
plugins {
id "org.owasp.dependencycheck" version "7.3.0"
}
With recent version of gradle it is below steps
add id 'com.diffplug.spotless' version '6.3.0' in plugins section like
plugins {
id 'com.diffplug.spotless' version '6.3.0'
}
And define your task to generate required format reports. Here for e.g. xml and json will be generated along with the html report
dependencyCheck{
formats=['xml','json']
check.dependsOn(dependencyCheckAnalyze)
}
And this can be integrated with Sonar by adding below properties to sonare.properties file (Provide dependency plugin is installed already on the sonar)
sonar.dependencyCheck.xmlReportPath=build/reports/dependency-check-report.xml
sonar.dependencyCheck.jsonReportPath=build/reports/dependency-check-report.json
sonar.dependencyCheck.htmlReportPath=build/reports/dependency-check-report.html

Resources