├── .circleci
└── config.yml
├── .gitignore
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── renovate.json
├── settings.gradle
└── src
├── main
├── groovy
│ └── de
│ │ └── jansauer
│ │ └── printcoverage
│ │ ├── PrintCoverageExtension.groovy
│ │ ├── PrintCoveragePlugin.groovy
│ │ └── PrintCoverageTask.groovy
└── resources
│ └── META-INF
│ └── gradle-plugins
│ └── de.jansauer.printcoverage.properties
└── test
├── groovy
└── de
│ └── jansauer
│ └── printcoverage
│ └── PrintCoveragePluginTest.groovy
└── resources
├── Calculator.java
├── CalculatorTest.java
└── jacocoTestReport.xml
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | # CircleCI 2.0 configuration file
2 | version: 2
3 | jobs:
4 | build:
5 | docker:
6 | - image: circleci/openjdk:11-jdk
7 | environment:
8 | GRADLE_OPTS: -Dorg.gradle.daemon=false
9 | steps:
10 | - checkout
11 | - restore_cache:
12 | key: gradle-{{ checksum "build.gradle" }}
13 | - run:
14 | name: Run gradle build tasks
15 | command: ./gradlew clean build codeCoverageReport
16 | - save_cache:
17 | paths:
18 | - ~/.gradle
19 | key: gradle-{{ checksum "build.gradle" }}
20 | - persist_to_workspace:
21 | root: ./
22 | paths:
23 | - build
24 | - store_artifacts:
25 | path: build/libs
26 | destination: libs
27 | - store_artifacts:
28 | path: build/reports
29 | destination: reports
30 | - run:
31 | name: Save test results
32 | command: |
33 | mkdir -p ~/junit/
34 | find . -type f -regex ".*/build/test-results/.*xml" -exec cp {} ~/junit/ \;
35 | when: always
36 | - store_test_results:
37 | path: ~/junit
38 | - run:
39 | name: Publish code coverage to codecov.io
40 | command: bash <(curl -s https://codecov.io/bash)
41 |
42 | deploy:
43 | docker:
44 | - image: circleci/openjdk:11-jdk
45 | steps:
46 | - checkout
47 | - restore_cache:
48 | key: gradle-{{ checksum "build.gradle" }}
49 | - attach_workspace:
50 | at: ./
51 | - run:
52 | name: Setup gradle plugins credentials
53 | command: echo -e $GRADLE_LOGIN > ~/.gradle/gradle.properties
54 | - run:
55 | name: Run gradle publish plugins task
56 | command: ./gradlew publishPlugins
57 | - save_cache:
58 | paths:
59 | - ~/.gradle
60 | key: gradle-{{ checksum "build.gradle" }}
61 |
62 | workflows:
63 | version: 2
64 | commit:
65 | jobs:
66 | - build:
67 | filters:
68 | tags:
69 | only: /^\d+\.\d+\.\d+$/
70 | - deploy:
71 | requires:
72 | - build
73 | filters:
74 | branches:
75 | ignore: /.*/
76 | tags:
77 | only: /^\d+\.\d+\.\d+$/
78 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | .idea
3 | build
4 | out
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Gradle Print Codecoverage Plugin
2 |
3 | Scraps [jacoco](http://www.eclemma.org/jacoco/) test reports and prints the
4 | code coverage to the console. Tools like [GitLab](https://about.gitlab.com/)
5 | can then parse for it for better integration.
6 |
7 | For more information see [Gitalb test coverage parsing](https://docs.gitlab.com/ee/user/project/pipelines/settings.html#test-coverage-parsing)
8 |
9 | ## Getting Started
10 |
11 | Add this snippet to yout build script.
12 |
13 | ```
14 | plugins {
15 | id 'jacoco'
16 | id 'de.jansauer.printcoverage' version '2.0.0'
17 | }
18 | ```
19 |
20 | Extend your ci job configuration.
21 |
22 | ```
23 | build-gradle:
24 | stage: build
25 | script:
26 | - ./gradlew build printCoverage
27 | coverage: '/^Coverage:\s(\d+\.\d+%)/'
28 | ```
29 |
30 | ## Tasks
31 |
32 | * `printCoverage` The one that prints the coverage ;-)
33 |
34 | ## Configuration
35 |
36 | ```
37 | printcoverage {
38 | coverageType = 'INSTRUCTION'
39 | }
40 | ```
41 |
42 | * `coverageType`: Type of [coverage metric](http://www.eclemma.org/jacoco/trunk/doc/counters.html) to be printed.
43 | One of 'INSTRUCTION', 'BRANCH', 'LINE', 'COMPLEXITY', 'METHOD' or 'CLASS'
44 | Default: 'INSTRUCTION'
45 |
46 | ## Publishing Workflow
47 |
48 | Every commit on this repository gets tested via [circleci](https://circleci.com/gh/jansauer/gradle-print-coverage-plugin).
49 | Commits that are tagged with a semantic version are also automatically
50 | published to the gradle plugin directory as a new version.
51 |
52 | ## Contributing
53 |
54 | Pull requests are always welcome. I'm grateful for any help or inspiration.
55 |
56 | ## License and Authors
57 |
58 | Author: Jan Sauer
59 | <[jan@jansauer.de](mailto:jan@jansauer.de)>
60 | ([https://jansauer.de](https://jansauer.de))
61 |
62 | ```text
63 | Copyright 2018, Jan Sauer (https://jansauer.de)
64 |
65 | Permission is hereby granted, free of charge, to any person obtaining a copy of
66 | this software and associated documentation files (the "Software"), to deal in
67 | the Software without restriction, including without limitation the rights to
68 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
69 | the Software, and to permit persons to whom the Software is furnished to do so,
70 | subject to the following conditions:
71 |
72 | The above copyright notice and this permission notice shall be included in all
73 | copies or substantial portions of the Software.
74 |
75 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
76 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
77 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
78 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
79 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
80 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
81 | ```
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.palantir.git-version' version '0.11.0'
3 | id 'groovy'
4 | id 'java-gradle-plugin'
5 | id 'jacoco'
6 | id 'com.gradle.plugin-publish' version '0.10.1'
7 | }
8 |
9 | description = 'Gradle print coverage plugin'
10 | group = 'de.jansauer.printcoverage'
11 | version = gitVersion()
12 |
13 | sourceCompatibility = 1.8
14 | targetCompatibility = 1.8
15 |
16 | repositories {
17 | mavenCentral()
18 | }
19 |
20 | dependencies {
21 | testCompile('org.spockframework:spock-core:1.2-groovy-2.5') {
22 | exclude(module: 'groovy-all')
23 | }
24 | }
25 |
26 | pluginBundle {
27 | website = 'https://github.com/jansauer/gradle-print-coverage-plugin'
28 | vcsUrl = 'https://github.com/jansauer/gradle-print-coverage-plugin'
29 | description = 'Gradle print coverage plugin.'
30 | tags = ['coverage', 'jacoco', 'gitlab']
31 |
32 | plugins {
33 | greetingsPlugin {
34 | id = 'de.jansauer.printcoverage'
35 | displayName = 'Gradle print coverage plugin'
36 | }
37 | }
38 | }
39 |
40 | task codeCoverageReport(type: JacocoReport) {
41 | executionData fileTree(project.rootDir.absolutePath).include('**/build/jacoco/*.exec')
42 | sourceSets sourceSets.main
43 |
44 | reports {
45 | xml.enabled true
46 | xml.destination file("${buildDir}/reports/jacoco/report.xml")
47 | html.enabled false
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jansauer/gradle-print-coverage-plugin/7605f2f7366d760807a931e0e5324081b963f3db/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
4 | distributionSha256Sum=53b71812f18cdb2777e9f1b2a0f2038683907c90bdc406bc64d8b400e1fb2c3b
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS='"-Xmx64m"'
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS="-Xmx64m"
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "labels": ["renovate"],
3 | "rangeStrategy": "pin",
4 | "gradle": true
5 | }
6 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'printcoverage'
2 |
3 |
--------------------------------------------------------------------------------
/src/main/groovy/de/jansauer/printcoverage/PrintCoverageExtension.groovy:
--------------------------------------------------------------------------------
1 | package de.jansauer.printcoverage
2 |
3 | import org.gradle.api.Project
4 | import org.gradle.api.provider.Property
5 |
6 | class PrintCoverageExtension {
7 |
8 | final Property coverageType
9 |
10 | PrintCoverageExtension(Project project) {
11 | coverageType = project.objects.property(String)
12 | coverageType.set('INSTRUCTION')
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/groovy/de/jansauer/printcoverage/PrintCoveragePlugin.groovy:
--------------------------------------------------------------------------------
1 | package de.jansauer.printcoverage
2 |
3 | import org.gradle.api.Plugin
4 | import org.gradle.api.Project
5 | import org.gradle.api.Task
6 | import org.gradle.testing.jacoco.tasks.JacocoReport
7 |
8 | class PrintCoveragePlugin implements Plugin {
9 |
10 | void apply(Project target) {
11 | target.tasks.withType(JacocoReport) {
12 | reports {
13 | xml.enabled true
14 | }
15 | }
16 |
17 | def extension = target.extensions.create('printcoverage', PrintCoverageExtension, target)
18 | Task task = target.tasks.create('printCoverage', PrintCoverageTask) {
19 | coverageType = extension.coverageType
20 | }
21 | task.dependsOn(target.tasks.withType(JacocoReport))
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/groovy/de/jansauer/printcoverage/PrintCoverageTask.groovy:
--------------------------------------------------------------------------------
1 | package de.jansauer.printcoverage
2 |
3 | import org.gradle.api.DefaultTask
4 | import org.gradle.api.GradleException
5 | import org.gradle.api.provider.Property
6 | import org.gradle.api.tasks.Input
7 | import org.gradle.api.tasks.TaskAction
8 |
9 | class PrintCoverageTask extends DefaultTask {
10 |
11 | @Input
12 | final Property coverageType = project.objects.property(String)
13 |
14 | PrintCoverageTask() {
15 | setDescription('Prints code coverage for gitlab.')
16 | setGroup('coverage')
17 | }
18 |
19 | @TaskAction
20 | def printcoverage() {
21 | def slurper = new XmlSlurper()
22 | slurper.setFeature('http://apache.org/xml/features/disallow-doctype-decl', false)
23 | slurper.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd', false)
24 |
25 | File jacocoTestReport = new File("${project.buildDir}/reports/jacoco/test/jacocoTestReport.xml")
26 | if (!jacocoTestReport.exists()) {
27 | logger.error('Jacoco test report is missing.')
28 | throw new GradleException('Jacoco test report is missing.')
29 | }
30 |
31 | def report = slurper.parse(jacocoTestReport)
32 | double missed = report.counter.find { it.'@type' == coverageType.get() }.@missed.toDouble()
33 | double covered = report.counter.find { it.'@type' == coverageType.get() }.@covered.toDouble()
34 | def coverage = (100 / (missed + covered) * covered).round(2)
35 | println 'Coverage: ' + coverage + '%'
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/gradle-plugins/de.jansauer.printcoverage.properties:
--------------------------------------------------------------------------------
1 | implementation-class=de.jansauer.printcoverage.PrintCoveragePlugin
--------------------------------------------------------------------------------
/src/test/groovy/de/jansauer/printcoverage/PrintCoveragePluginTest.groovy:
--------------------------------------------------------------------------------
1 | package de.jansauer.printcoverage
2 |
3 | import org.gradle.internal.impldep.org.junit.Rule
4 | import org.gradle.internal.impldep.org.junit.rules.TemporaryFolder
5 | import org.gradle.testkit.runner.GradleRunner
6 | import org.gradle.testkit.runner.UnexpectedBuildFailure
7 | import spock.lang.Specification
8 |
9 | import static org.gradle.testkit.runner.TaskOutcome.FAILED
10 | import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
11 |
12 | class PrintCoveragePluginTest extends Specification {
13 |
14 | final static String[] SUPPORTED_GRADLE_VERSIONS = ['4.10', '4.10.1', '4.10.2', '5.0', '4.10.3', '5.1', '5.1.1']
15 |
16 | TemporaryFolder temporaryFolder
17 |
18 | File propertiesFile
19 |
20 | File buildFile
21 |
22 | File reportFile
23 |
24 | def setup() {
25 | temporaryFolder = new TemporaryFolder()
26 | temporaryFolder.create()
27 | propertiesFile = temporaryFolder.newFile('gradle.properties')
28 | propertiesFile << """
29 | org.gradle.daemon=false
30 | org.gradle.jvmargs=-Xmx512m -Xms256m
31 | """
32 | buildFile = temporaryFolder.newFile('build.gradle')
33 | reportFile = temporaryFolder
34 | .newFolder('build', 'reports', 'jacoco', 'test')
35 | .toPath()
36 | .resolve('jacocoTestReport.xml')
37 | .toFile()
38 | }
39 |
40 | def "should fail if the jacoco plugin is missing"() {
41 | given:
42 | buildFile << """
43 | plugins {
44 | id 'de.jansauer.printcoverage'
45 | }
46 | """
47 |
48 | when:
49 | GradleRunner.create()
50 | .withGradleVersion(gradleVersion)
51 | .withProjectDir(temporaryFolder.root)
52 | .withArguments('printCoverage')
53 | .withPluginClasspath()
54 | .build()
55 |
56 | then:
57 | thrown UnexpectedBuildFailure
58 |
59 | where:
60 | gradleVersion << SUPPORTED_GRADLE_VERSIONS
61 | }
62 |
63 | def "should print the coverage for a example jacoco report"() {
64 | given:
65 | buildFile << """
66 | plugins {
67 | id 'jacoco'
68 | id 'de.jansauer.printcoverage'
69 | }
70 | """
71 | reportFile << new File("src/test/resources/jacocoTestReport.xml").text
72 |
73 | when:
74 | def result = GradleRunner.create()
75 | .withGradleVersion(gradleVersion)
76 | .withProjectDir(temporaryFolder.root)
77 | .withArguments('printCoverage')
78 | .withPluginClasspath()
79 | .build()
80 |
81 | then:
82 | result.output.contains('Coverage: 3.13%')
83 | result.task(":printCoverage").outcome == SUCCESS
84 |
85 | where:
86 | gradleVersion << SUPPORTED_GRADLE_VERSIONS
87 | }
88 |
89 | def "should print from a example class with tests"() {
90 | given:
91 | buildFile << """
92 | plugins {
93 | id 'java'
94 | id 'jacoco'
95 | id 'de.jansauer.printcoverage'
96 | }
97 |
98 | repositories {
99 | mavenCentral()
100 | }
101 |
102 | dependencies {
103 | testCompile 'junit:junit:4.12'
104 | }
105 | """
106 | File classFile = temporaryFolder
107 | .newFolder('src', 'main', 'java', 'sample')
108 | .toPath()
109 | .resolve('Calculator.java')
110 | .toFile()
111 | classFile << new File("src/test/resources/Calculator.java").text
112 | File junitFile = temporaryFolder
113 | .newFolder('src', 'test', 'java', 'sample')
114 | .toPath()
115 | .resolve('CalculatorTest.java')
116 | .toFile()
117 | junitFile << new File("src/test/resources/CalculatorTest.java").text
118 |
119 | when:
120 | def result = GradleRunner.create()
121 | .withGradleVersion(gradleVersion)
122 | .withProjectDir(temporaryFolder.root)
123 | .withArguments('build', 'printCoverage')
124 | .withPluginClasspath()
125 | .build()
126 |
127 | then:
128 | result.output.contains('Coverage: 79.49%')
129 | result.task(":printCoverage").outcome == SUCCESS
130 |
131 | where:
132 | gradleVersion << SUPPORTED_GRADLE_VERSIONS.findAll { !(it =~ /4\.*/) }
133 | }
134 |
135 | def "should print from a example class with tests with gradle 4.x"() {
136 | given:
137 | buildFile << """
138 | plugins {
139 | id 'java'
140 | id 'jacoco'
141 | id 'de.jansauer.printcoverage'
142 | }
143 |
144 | repositories {
145 | mavenCentral()
146 | }
147 |
148 | dependencies {
149 | testCompile 'junit:junit:4.12'
150 | }
151 |
152 | // default version does not work with jdk11
153 | // https://github.com/vaskoz/core-java9-impatient/issues/11
154 | // https://github.com/jacoco/jacoco/releases/tag/v0.8.2
155 | jacoco {
156 | toolVersion = "0.8.2"
157 | }
158 | """
159 | File classFile = temporaryFolder
160 | .newFolder('src', 'main', 'java', 'sample')
161 | .toPath()
162 | .resolve('Calculator.java')
163 | .toFile()
164 | classFile << new File("src/test/resources/Calculator.java").text
165 | File junitFile = temporaryFolder
166 | .newFolder('src', 'test', 'java', 'sample')
167 | .toPath()
168 | .resolve('CalculatorTest.java')
169 | .toFile()
170 | junitFile << new File("src/test/resources/CalculatorTest.java").text
171 |
172 | when:
173 | def result = GradleRunner.create()
174 | .withGradleVersion(gradleVersion)
175 | .withProjectDir(temporaryFolder.root)
176 | .withArguments('build', 'printCoverage')
177 | .withPluginClasspath()
178 | .build()
179 |
180 | then:
181 | result.output.contains('Coverage: 79.49%')
182 | result.task(":printCoverage").outcome == SUCCESS
183 |
184 | where:
185 | gradleVersion << SUPPORTED_GRADLE_VERSIONS.findAll { it =~ /4\.*/ }
186 | }
187 |
188 |
189 |
190 |
191 |
192 |
193 | def "should fail if jacoco test report is missing"() {
194 | given:
195 | buildFile << """
196 | plugins {
197 | id 'jacoco'
198 | id 'de.jansauer.printcoverage'
199 | }
200 | """
201 |
202 | when:
203 | def result = GradleRunner.create()
204 | .withGradleVersion(gradleVersion)
205 | .withProjectDir(temporaryFolder.root)
206 | .withArguments('printCoverage')
207 | .withPluginClasspath()
208 | .buildAndFail()
209 |
210 | then:
211 | result.output.contains('Jacoco test report is missing.')
212 | result.task(':printCoverage').outcome == FAILED
213 |
214 | where:
215 | gradleVersion << SUPPORTED_GRADLE_VERSIONS
216 | }
217 |
218 | def "should print the configured coverage type"() {
219 | expect:
220 | buildFile << """
221 | plugins {
222 | id 'jacoco'
223 | id 'de.jansauer.printcoverage'
224 | }
225 |
226 | printcoverage {
227 | coverageType = '${type}'
228 | }
229 | """
230 | reportFile << new File("src/test/resources/jacocoTestReport.xml").text
231 |
232 | def result = GradleRunner.create()
233 | .withProjectDir(temporaryFolder.root)
234 | .withArguments('printCoverage')
235 | .withPluginClasspath()
236 | .build()
237 |
238 | result.output.contains("Coverage: ${coverage}")
239 |
240 | where:
241 | type | coverage
242 | 'INSTRUCTION' | '3.13%'
243 | 'BRANCH' | '20.0%'
244 | 'LINE' | '40.0%'
245 | 'COMPLEXITY' | '60.0%'
246 | 'METHOD' | '66.67%'
247 | 'CLASS' | '100.0%'
248 | }
249 | }
250 |
--------------------------------------------------------------------------------
/src/test/resources/Calculator.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | public class Calculator {
4 |
5 | public static void main(String[] args) {
6 | System.out.println(new Calculator().evaluate("1+1"));
7 | }
8 |
9 | public int evaluate(String expression) {
10 | int sum = 0;
11 | for (String summand: expression.split("\\+"))
12 | sum += Integer.valueOf(summand);
13 | return sum;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/resources/CalculatorTest.java:
--------------------------------------------------------------------------------
1 | package sample;
2 |
3 | import org.junit.Test;
4 | import static org.junit.Assert.*;
5 |
6 | public class CalculatorTest {
7 |
8 | @Test
9 | public void evaluatesExpression() {
10 | Calculator calculator = new Calculator();
11 | int sum = calculator.evaluate("1+2+3");
12 | assertEquals(6, sum);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/resources/jacocoTestReport.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------