jacoco-0.7.8/000077500000000000000000000000001304217427400127705ustar00rootroot00000000000000jacoco-0.7.8/.appveyor.yml000066400000000000000000000013411304217427400154350ustar00rootroot00000000000000cache: - C:\Users\appveyor\apache-maven-3.3.9 -> appveyor.yml - C:\Users\appveyor\.m2 -> **\pom.xml install: - if not exist C:\Users\appveyor\apache-maven-3.3.9 ( curl -LsS "http://www.apache.org/dyn/closer.cgi?action=download&filename=maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.zip" > apache-maven-3.3.9-bin.zip && unzip apache-maven-3.3.9-bin.zip -d C:\Users\appveyor ) - SET PATH=C:\Users\appveyor\apache-maven-3.3.9\bin;%PATH% build_script: # Maven 3.3.9 requires Java >= 7, but generation of Javadocs requires Java <= 6 (https://github.com/jacoco/jacoco/issues/110) - mvn -V -B -e verify -Djdk.version=1.6 --toolchains=.travis\appveyor-toolchains.xml artifacts: - path: jacoco\target\*.zip jacoco-0.7.8/.github/000077500000000000000000000000001304217427400143305ustar00rootroot00000000000000jacoco-0.7.8/.github/ISSUE_TEMPLATE.md000066400000000000000000000005631304217427400170410ustar00rootroot00000000000000This is a issue tracker. Please use our mailing list for general questions: https://groups.google.com/forum/?fromgroups=#!forum/jacoco Also check FAQ before opening an issue: http://www.jacoco.org/jacoco/trunk/doc/faq.html ### Steps to reproduce JaCoCo version: Operating system: Tool integration: Maven/Ant/API/Other ### Expected behaviour ### Actual behaviour jacoco-0.7.8/.travis.sh000077500000000000000000000045571304217427400147300ustar00rootroot00000000000000#!/bin/bash set -euo pipefail # Prevent accidental execution outside of Travis: if [ -z "${TRAVIS+false}" ] then echo "TRAVIS environment variable is not set" exit 1 fi # Switch to desired JDK, download if required: function install_jdk { JDK_URL=$1 FILENAME="${JDK_URL##*/}" rm -rf /tmp/jdk/$JDK mkdir -p /tmp/jdk/$JDK if [ ! -f "/tmp/jdk/$FILENAME" ] then curl -L $JDK_URL -o /tmp/jdk/$FILENAME fi tar -xzf /tmp/jdk/$FILENAME -C /tmp/jdk/$JDK --strip-components 1 if [ -z "${2+false}" ] then export JAVA_HOME="/tmp/jdk/$JDK" export JDK_HOME="${JAVA_HOME}" export JAVAC="${JAVA_HOME}/bin/javac" export PATH="${JAVA_HOME}/bin:${PATH}" fi } source $HOME/.jdk_switcher_rc case "$JDK" in 5) jdk_switcher use oraclejdk8 install_jdk $JDK5_URL false ;; 6) jdk_switcher use openjdk6 ;; 7|8) jdk_switcher use oraclejdk${JDK} ;; 8-ea) install_jdk $JDK8_EA_URL ;; 9-ea) install_jdk $JDK9_EA_URL ;; 9-ea-stable) install_jdk $JDK9_EA_STABLE_URL ;; esac # Do not use "~/.mavenrc" set by Travis (https://github.com/travis-ci/travis-ci/issues/3893), # because it prevents execution of JaCoCo during integration tests for jacoco-maven-plugin, # and "-XMaxPermSize" not supported by JDK 9 export MAVEN_SKIP_RC=true # Build: # TODO(Godin): see https://github.com/jacoco/jacoco/issues/300 about "bytecode.version" case "$JDK" in 5) if [[ ${TRAVIS_PULL_REQUEST} == 'false' && ${TRAVIS_BRANCH} == 'master' ]] then # goal "deploy:deploy" used directly instead of "deploy" phase to avoid pollution of Maven repository by "install" phase mvn -V -B -e -f org.jacoco.build verify sonar:sonar deploy:deploy -DdeployAtEnd -Djdk.version=1.5 --toolchains=./.travis/toolchains.xml --settings=./.travis/settings.xml -Dsonar.host.url=${SONARQUBE_URL} -Dsonar.login=${SONARQUBE_TOKEN} python ./.travis/trigger-site-deployment.py else mvn -V -B -e verify -Djdk.version=1.5 --toolchains=./.travis/toolchains.xml fi ;; 6) mvn -V -B -e verify -Dbytecode.version=1.6 ;; 7) mvn -V -B -e verify -Dbytecode.version=1.7 ;; 8 | 8-ea) mvn -V -B -e verify -Dbytecode.version=1.8 ;; 9-ea | 9-ea-stable) # see https://bugs.openjdk.java.net/browse/JDK-8131041 about "java.locale.providers" mvn -V -B -e verify -Dbytecode.version=1.9 \ -DargLine=-Djava.locale.providers=JRE,SPI ;; *) echo "Incorrect JDK [$JDK]" exit 1; ;; esac jacoco-0.7.8/.travis.yml000066400000000000000000000006001304217427400150750ustar00rootroot00000000000000language: java # Skip "install" stage: install: true # Use container-based infrastructure: sudo: false # Keep Maven local repository between builds: cache: directories: - '$HOME/.m2/repository' env: - JDK=5 - JDK=6 - JDK=7 - JDK=8 - JDK=8-ea - JDK=9-ea - JDK=9-ea-stable matrix: allow_failures: - env: JDK=8-ea - env: JDK=9-ea script: ./.travis.sh jacoco-0.7.8/.travis/000077500000000000000000000000001304217427400143565ustar00rootroot00000000000000jacoco-0.7.8/.travis/appveyor-toolchains.xml000066400000000000000000000010341304217427400211040ustar00rootroot00000000000000 jdk java16 1.6 oracle C:\Program Files\Java\jdk1.6.0 jacoco-0.7.8/.travis/settings.xml000066400000000000000000000012461304217427400167430ustar00rootroot00000000000000 sonatype-nexus-snapshots ${env.SONATYPE_USERNAME} ${env.SONATYPE_PASSWORD} default TLSv1 default jacoco-0.7.8/.travis/toolchains.xml000066400000000000000000000010051304217427400172370ustar00rootroot00000000000000 jdk java15 1.5 sun /tmp/jdk/5 jacoco-0.7.8/.travis/trigger-site-deployment.py000066400000000000000000000014051304217427400215130ustar00rootroot00000000000000import os import urllib2 import json def request(url, data, token = None): req = urllib2.Request(url, data) req.add_header('User-Agent', 'MyClient/1.0.0') req.add_header('Accept', 'application/vnd.travis-ci.2+json') req.add_header('Content-Type', 'application/json; charset=UTF-8') if token: req.add_header('Travis-API-Version', '3') req.add_header('Authorization', 'token ' + travis_token) p = urllib2.urlopen(req) return json.loads(p.read()) travis_token = request('https://api.travis-ci.org/auth/github', '{"github_token":"' + os.environ['GH_TOKEN'] + '"}')['access_token'] print(request('https://api.travis-ci.org/repo/jacoco%2Fwww.eclemma.org/requests', '{ "request": { "branch": "master", "message": "New JaCoCo snapshot" } }', travis_token)) jacoco-0.7.8/LICENSE.md000066400000000000000000000012471304217427400144000ustar00rootroot00000000000000License ======= Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors The JaCoCo Java Code Coverage Library and all included documentation is made available by Mountainminds GmbH & Co. KG, Munich. Except indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at [http://www.eclipse.org/legal/epl-v10.html](http://www.eclipse.org/legal/epl-v10.html). Please visit [http://www.jacoco.org/jacoco/trunk/doc/license.html](http://www.jacoco.org/jacoco/trunk/doc/license.html) for the complete license information including third party licenses and trademarks. jacoco-0.7.8/README.md000066400000000000000000000022351304217427400142510ustar00rootroot00000000000000JaCoCo Java Code Coverage Library ================================= [![Build Status](https://travis-ci.org/jacoco/jacoco.svg?branch=master)](https://travis-ci.org/jacoco/jacoco) [![Build status](https://ci.appveyor.com/api/projects/status/g28egytv4tb898d7/branch/master?svg=true)](https://ci.appveyor.com/project/JaCoCo/jacoco/branch/master) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.jacoco/org.jacoco.core/badge.svg?style=flat)](http://search.maven.org/#search|ga|1|g%3Aorg.jacoco) JaCoCo is a free Java code coverage library distributed under the Eclipse Public License. Check the [project homepage](http://www.jacoco.org/jacoco) for downloads, documentation and feedback. Please use our [mailing list](https://groups.google.com/forum/?fromgroups=#!forum/jacoco) for questions regarding JaCoCo which are not already covered by the [extensive documentation](http://www.jacoco.org/jacoco/trunk/doc/). Note: We do not answer general questions in the project's issue tracker. Please use our [mailing list](https://groups.google.com/forum/?fromgroups=#!forum/jacoco) for this. ------------------------------------------------------------------------- jacoco-0.7.8/jacoco-maven-plugin.test/000077500000000000000000000000001304217427400176045ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/.gitignore000066400000000000000000000000231304217427400215670ustar00rootroot00000000000000/target /.settings jacoco-0.7.8/jacoco-maven-plugin.test/.project000066400000000000000000000010731304217427400212540ustar00rootroot00000000000000 jacoco-maven-plugin.test org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core.test/.settings jacoco-0.7.8/jacoco-maven-plugin.test/it/000077500000000000000000000000001304217427400202205ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/000077500000000000000000000000001304217427400237315ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/invoker.properties000066400000000000000000000000331304217427400275200ustar00rootroot00000000000000invoker.buildResult=failurejacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/pom.xml000066400000000000000000000042461304217427400252540ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-check-fails-halt @project.groupId@ jacoco-maven-plugin prepare-agent check check CLASS Example METHOD MISSEDCOUNT 0 jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/src/000077500000000000000000000000001304217427400245205ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/src/main/000077500000000000000000000000001304217427400254445ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/src/main/java/000077500000000000000000000000001304217427400263655ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/src/main/java/Example.java000066400000000000000000000013021304217427400306170ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/src/test/000077500000000000000000000000001304217427400254775ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/src/test/java/000077500000000000000000000000001304217427400264205ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/src/test/java/ExampleTest.java000066400000000000000000000013161304217427400315170ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-halt/verify.bsh000066400000000000000000000020641304217427400257350ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "Coverage checks have not been met." ) < 0 ) { throw new RuntimeException( "Coverage checks should not have been met." ); } if ( buildLog.indexOf( "methods missed count is 1, but expected maximum is 0" ) < 0 ) { throw new RuntimeException( "Should have displayed insufficient code coverage messages." ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/000077500000000000000000000000001304217427400243435ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/pom.xml000066400000000000000000000041631304217427400256640ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-check-fails-no-hault @project.groupId@ jacoco-maven-plugin prepare-agent check check false BUNDLE METHOD MISSEDCOUNT 0 jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/src/000077500000000000000000000000001304217427400251325ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/src/main/000077500000000000000000000000001304217427400260565ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/src/main/java/000077500000000000000000000000001304217427400267775ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/src/main/java/Example.java000066400000000000000000000013021304217427400312310ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/src/test/000077500000000000000000000000001304217427400261115ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/src/test/java/000077500000000000000000000000001304217427400270325ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/src/test/java/ExampleTest.java000066400000000000000000000013161304217427400321310ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-fails-no-halt/verify.bsh000066400000000000000000000020631304217427400263460ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "Coverage checks have not been met." ) < 0 ) { throw new RuntimeException( "Coverage checks should not have been met." ); } if ( buildLog.indexOf( "methods missed count is 1, but expected maximum is 0" ) < 0 ) { throw new RuntimeException( "Should have displayed insufficient code coverage messages." ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/000077500000000000000000000000001304217427400232035ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/pom.xml000066400000000000000000000045731304217427400245310ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-check-passes @project.groupId@ jacoco-maven-plugin prepare-agent check check BUNDLE INSTRUCTION COVEREDRATIO 0.90 CLASS MISSEDCOUNT 0 jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/src/000077500000000000000000000000001304217427400237725ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/src/main/000077500000000000000000000000001304217427400247165ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/src/main/java/000077500000000000000000000000001304217427400256375ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/src/main/java/Example.java000066400000000000000000000013021304217427400300710ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/src/test/000077500000000000000000000000001304217427400247515ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/src/test/java/000077500000000000000000000000001304217427400256725ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/src/test/java/ExampleTest.java000066400000000000000000000013311304217427400307660ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-check-passes/verify.bsh000066400000000000000000000015541304217427400252120ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "All coverage checks have been met." ) < 0 ) { throw new RuntimeException( "Coverage checks were not met." ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/000077500000000000000000000000001304217427400237505ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/pom.xml000066400000000000000000000051071304217427400252700ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-customize-agent coverageAgent ${project.build.directory}/coverage.exec false sun.reflect.DelegatingClassLoader:MyClassLoader true true session true file localhost 9999 ${project.build.directory}/classdumps true ${jacoco.destFile} @project.groupId@ jacoco-maven-plugin prepare-agent report * java.* sun.* org.apache.maven.plugins maven-surefire-plugin ${coverageAgent} jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/src/000077500000000000000000000000001304217427400245375ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/src/main/000077500000000000000000000000001304217427400254635ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/src/main/java/000077500000000000000000000000001304217427400264045ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/src/main/java/Example.java000066400000000000000000000012221304217427400306370ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/src/test/000077500000000000000000000000001304217427400255165ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/src/test/java/000077500000000000000000000000001304217427400264375ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/src/test/java/ExampleTest.java000066400000000000000000000012511304217427400315340ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-customize-agent/verify.bsh000066400000000000000000000034031304217427400257520ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String agentOptions = "destfile=" + basedir + File.separator + "target" + File.separator + "coverage.exec" + ",append=false" + ",includes=*" + ",excludes=java.*:sun.*" + ",exclclassloader=sun.reflect.DelegatingClassLoader:MyClassLoader" + ",inclbootstrapclasses=true" + ",inclnolocationclasses=true" + ",sessionid=session" + ",dumponexit=true" + ",output=file" + ",address=localhost" + ",port=9999" + ",classdumpdir=" + basedir + File.separator + "target" + File.separator + "classdumps" + ",jmx=true"; //backslashes will be escaped agentOptions = agentOptions.replace("\\","\\\\"); String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( agentOptions ) < 0 ) { throw new RuntimeException( "Property was not configured, expected " + agentOptions ); } File file = new File( basedir, "target/coverage.exec" ); if ( !file.isFile() ) { throw new FileNotFoundException( "Could not find generated dump: " + file ); } File reportDir = new File( basedir, "target/site/jacoco" ); if ( !reportDir.isDirectory() ) { throw new RuntimeException( "Could not find generated report" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-dump/000077500000000000000000000000001304217427400215775ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-dump/pom.xml000066400000000000000000000066411304217427400231230ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-dump @project.groupId@ jacoco-maven-plugin prepare-agent prepare-agent tcpserver dump integration-test dump check check BUNDLE CLASS COVEREDCOUNT 1 org.apache.maven.plugins maven-antrun-plugin 1.6 launch-server pre-integration-test run stop-server post-integration-test run jacoco-0.7.8/jacoco-maven-plugin.test/it/it-dump/src/000077500000000000000000000000001304217427400223665ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-dump/src/main/000077500000000000000000000000001304217427400233125ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-dump/src/main/java/000077500000000000000000000000001304217427400242335ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-dump/src/main/java/Server.java000066400000000000000000000020671304217427400263510ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ import java.io.File; /** * Simple server which runs as long a termination file is created. */ public class Server { public static void main(String[] args) throws Exception { System.out.println("Test server started"); // Wait for termination file to turn up // This option puts the target in a pseudo 'server' mode if (args.length == 1) { final File termFile = new File(args[0]); while (!termFile.exists()) { Thread.sleep(100); } } System.out.println("Test server stopped"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-dump/verify.bsh000066400000000000000000000015541304217427400236060ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "All coverage checks have been met." ) < 0 ) { throw new RuntimeException( "Coverage checks were not met." ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/000077500000000000000000000000001304217427400242525ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/pom.xml000066400000000000000000000031501304217427400255660ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-includes-excludes @project.groupId@ jacoco-maven-plugin **/FileUtil* **/TestUtil* prepare-agent prepare-agent report prepare-package report jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/000077500000000000000000000000001304217427400250415ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/main/000077500000000000000000000000001304217427400257655ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/main/java/000077500000000000000000000000001304217427400267065ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/main/java/org/000077500000000000000000000000001304217427400274755ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/main/java/org/project/000077500000000000000000000000001304217427400311435ustar00rootroot00000000000000DatabaseUtil.java000066400000000000000000000012651304217427400342750ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/main/java/org/project/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.project; public class DatabaseUtil { public void doStuff() { System.out.println("Do DatabaseUtil Stuff"); } } FileUtil.java000066400000000000000000000012551304217427400334470ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/main/java/org/project/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.project; public class FileUtil { public void doStuff() { System.out.println("Do FileUtil Stuff"); } } TestUtil.java000066400000000000000000000012551304217427400335070ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/main/java/org/project/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.project; public class TestUtil { public void doStuff() { System.out.println("Do TestUtil Stuff"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/test/000077500000000000000000000000001304217427400260205ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/test/java/000077500000000000000000000000001304217427400267415ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/test/java/org/000077500000000000000000000000001304217427400275305ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/test/java/org/project/000077500000000000000000000000001304217427400311765ustar00rootroot00000000000000TestDatabaseUtil.java000066400000000000000000000013151304217427400351640ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/src/test/java/org/project/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.project; import org.junit.Test; public class TestDatabaseUtil { @Test public void testDoStuff() { new DatabaseUtil().doStuff(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-includes-excludes/verify.bsh000066400000000000000000000025111304217427400262530ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String agentOptions = "excludes=**/FileUtil*:**/TestUtil*"; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( agentOptions ) < 0 ) { throw new RuntimeException("Include/Exclude was not configured correct" ); } File databaseUtilReportFile = new File( basedir, "target/site/jacoco/org.project/DatabaseUtil.html" ); if ( !databaseUtilReportFile.isFile() ) { throw new FileNotFoundException( "DatabaseUtil should NOT be excluded: " + databaseUtilReportFile ); } File testUtilReportFile = new File( basedir, "target/site/jacoco/org.project/TestUtil.html" ); if ( testUtilReportFile.isFile() ) { throw new RuntimeException( "TestUtil SHOULD be excluded: " + testUtilReportFile ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/000077500000000000000000000000001304217427400216445ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/invoker.properties000066400000000000000000000000341304217427400254340ustar00rootroot00000000000000invoker.java.version = 1.9+ jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/pom.xml000066400000000000000000000044641304217427400231710ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT ../setup-parent it-java9 org.apache.maven.plugins maven-compiler-plugin 1.9 @project.groupId@ jacoco-maven-plugin prepare-agent report check check INSTRUCTION COVEREDCOUNT 8 8 jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/src/000077500000000000000000000000001304217427400224335ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/src/main/000077500000000000000000000000001304217427400233575ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/src/main/java/000077500000000000000000000000001304217427400243005ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/src/main/java/Example.java000066400000000000000000000013101304217427400265310ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello(String name) { // http://openjdk.java.net/jeps/280 System.out.println("Hello, " + name); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/src/test/000077500000000000000000000000001304217427400234125ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/src/test/java/000077500000000000000000000000001304217427400243335ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-java9/src/test/java/ExampleTest.java000066400000000000000000000012571304217427400274360ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello("test"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/000077500000000000000000000000001304217427400232255ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-merge/000077500000000000000000000000001304217427400273275ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-merge/pom.xml000066400000000000000000000031761304217427400306530ustar00rootroot00000000000000 4.0.0 jacoco it-merge-passes 1.0-SNAPSHOT it-merge-passes-merge @project.groupId@ jacoco-maven-plugin merge merge ${project.parent.build.directory} *.exec jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/000077500000000000000000000000001304217427400277575ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/pom.xml000066400000000000000000000015761304217427400313050ustar00rootroot00000000000000 4.0.0 jacoco it-merge-passes 1.0-SNAPSHOT it-merge-passes-project1 jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/src/000077500000000000000000000000001304217427400305465ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/src/main/000077500000000000000000000000001304217427400314725ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/src/main/java/000077500000000000000000000000001304217427400324135ustar00rootroot00000000000000Example.java000066400000000000000000000012241304217427400345710ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/src/main/java/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mads Mohr Christensen - implementation of MergeMojo * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/src/test/000077500000000000000000000000001304217427400315255ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/src/test/java/000077500000000000000000000000001304217427400324465ustar00rootroot00000000000000ExampleTest.java000066400000000000000000000012531304217427400354660ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project1/src/test/java/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mads Mohr Christensen - implementation of MergeMojo * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/000077500000000000000000000000001304217427400277605ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/pom.xml000066400000000000000000000015761304217427400313060ustar00rootroot00000000000000 4.0.0 jacoco it-merge-passes 1.0-SNAPSHOT it-merge-passes-project2 jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/src/000077500000000000000000000000001304217427400305475ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/src/main/000077500000000000000000000000001304217427400314735ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/src/main/java/000077500000000000000000000000001304217427400324145ustar00rootroot00000000000000Example.java000066400000000000000000000012241304217427400345720ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/src/main/java/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mads Mohr Christensen - implementation of MergeMojo * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/src/test/000077500000000000000000000000001304217427400315265ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/src/test/java/000077500000000000000000000000001304217427400324475ustar00rootroot00000000000000ExampleTest.java000066400000000000000000000012531304217427400354670ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/it-merge-passes-project2/src/test/java/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mads Mohr Christensen - implementation of MergeMojo * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/pom.xml000066400000000000000000000034551304217427400245510ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-merge-passes pom it-merge-passes-project1 it-merge-passes-project2 it-merge-passes-merge @project.groupId@ jacoco-maven-plugin prepare-agent prepare-agent ${project.parent.build.directory}/${project.artifactId}.exec org.apache.maven.plugins maven-surefire-plugin ${argLine} jacoco-0.7.8/jacoco-maven-plugin.test/it/it-merge-passes/verify.bsh000066400000000000000000000017251304217427400252340ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mads Mohr Christensen - implementation of MergeMojo * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "Loading execution data file" ) < 0 ) { throw new RuntimeException( "Could not load execution data file" ); } if ( buildLog.indexOf( "Writing merged execution data to" ) < 0 ) { throw new RuntimeException( "Could not write merged execution data" ); }jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/000077500000000000000000000000001304217427400232475ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child-jar-without-sources/000077500000000000000000000000001304217427400302665ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child-jar-without-sources/pom.xml000066400000000000000000000016441304217427400316100ustar00rootroot00000000000000 4.0.0 jacoco it-multi-module 1.0-SNAPSHOT child-jar-without-sources jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/000077500000000000000000000000001304217427400243325ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/pom.xml000066400000000000000000000015501304217427400256500ustar00rootroot00000000000000 4.0.0 jacoco it-multi-module 1.0-SNAPSHOT child jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/000077500000000000000000000000001304217427400251215ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/main/000077500000000000000000000000001304217427400260455ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/main/java/000077500000000000000000000000001304217427400267665ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/main/java/Example.java000066400000000000000000000012221304217427400312210ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/main/java/somepackage/000077500000000000000000000000001304217427400312455ustar00rootroot00000000000000Example.java000066400000000000000000000012501304217427400334220ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/main/java/somepackage/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package somepackage; public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/test/000077500000000000000000000000001304217427400261005ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/test/java/000077500000000000000000000000001304217427400270215ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/child/src/test/java/ExampleTest.java000066400000000000000000000012511304217427400321160ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/pom.xml000066400000000000000000000034671304217427400245760ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-multi-module pom child child-jar-without-sources skip-child @project.groupId@ jacoco-maven-plugin prepare-agent prepare-agent report prepare-package report org.apache.maven.plugins maven-surefire-plugin -ea ${argLine} jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/skip-child/000077500000000000000000000000001304217427400252765ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/skip-child/pom.xml000066400000000000000000000016611304217427400266170ustar00rootroot00000000000000 4.0.0 jacoco it-multi-module 1.0-SNAPSHOT skip-child true jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/skip-child/src/000077500000000000000000000000001304217427400260655ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/skip-child/src/test/000077500000000000000000000000001304217427400270445ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/skip-child/src/test/ExampleTest.java000066400000000000000000000012131304217427400321370ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multi-module/verify.bsh000066400000000000000000000037231304217427400252560ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "Skipping JaCoCo execution due to missing classes directory." ) < 0 ) { throw new RuntimeException( "Execution should be skipped when target/classes does not exist." ); } File dump2 = new File( basedir, "skip-child/target/jacoco.exec" ); if ( dump2.isFile() ) { throw new RuntimeException( "Should not be executed for module 'skip-child', but dump found : " + dump2 ); } if ( !buildLog.contains( "argLine set to empty" ) ) { throw new RuntimeException( "Property not set to empty when skipping." ); } File file = new File( basedir, "child/target/jacoco.exec" ); if ( !file.isFile() ) { throw new FileNotFoundException( "Could not find generated dump: " + file ); } File xmlReport = new File( basedir, "child/target/site/jacoco/jacoco.xml" ); if ( !xmlReport.isFile() ) { throw new FileNotFoundException( "Could not find generated XML report: " + xmlReport ); } File csvReport = new File( basedir, "child/target/site/jacoco/jacoco.csv" ); if ( !csvReport.isFile() ) { throw new FileNotFoundException( "Could not find generated CSV report: " + csvReport ); } File htmlReport = new File( basedir, "child/target/site/jacoco/index.html" ); if ( !htmlReport.isFile() ) { throw new FileNotFoundException( "Could not find generated HTML report: " + htmlReport ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/000077500000000000000000000000001304217427400246515ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/pom.xml000066400000000000000000000041441304217427400261710ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-multiple-executions "-Da=\"1\"" -Db=2 @project.groupId@ jacoco-maven-plugin first prepare-agent ${project.build.directory}/nospace.exec second prepare-agent ${project.build.directory}/with space.exec "my" session third prepare-agent ${project.build.directory}/third.exec jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/src/000077500000000000000000000000001304217427400254405ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/src/main/000077500000000000000000000000001304217427400263645ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/src/main/java/000077500000000000000000000000001304217427400273055ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/src/main/java/Example.java000066400000000000000000000012221304217427400315400ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/src/test/000077500000000000000000000000001304217427400264175ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/src/test/java/000077500000000000000000000000001304217427400273405ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/src/test/java/ExampleTest.java000066400000000000000000000012511304217427400324350ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-multiple-executions/verify.bsh000066400000000000000000000024411304217427400266540ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; File file = new File( basedir, "target/nospace.exec" ); if ( file.isFile() ) { throw new FileNotFoundException( "Found unwanted dump: " + file ); } File file = new File( basedir, "target/with space.exec" ); if ( file.isFile() ) { throw new FileNotFoundException( "Found unwanted dump: " + file ); } file = new File( basedir, "target/third.exec" ); if ( !file.isFile() ) { throw new FileNotFoundException( "Could not find generated dump: " + file ); } String argLine = "\"-Da=\\\"1\\\"\" -Db=2"; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( argLine ) < 0 ) { throw new RuntimeException( "Original argLine was overwritten" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/000077500000000000000000000000001304217427400255155ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child-without-main-classes/000077500000000000000000000000001304217427400326565ustar00rootroot00000000000000pom.xml000066400000000000000000000016111304217427400341130ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child-without-main-classes 4.0.0 jacoco it-offline-instrumentation 1.0-SNAPSHOT child-without-main-classes jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child-without-main-classes/src/000077500000000000000000000000001304217427400334455ustar00rootroot00000000000000test/000077500000000000000000000000001304217427400343455ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child-without-main-classes/srcjava/000077500000000000000000000000001304217427400352665ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child-without-main-classes/src/testExampleTest.java000066400000000000000000000012131304217427400403610ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child-without-main-classes/src/test/java/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/000077500000000000000000000000001304217427400266005ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/pom.xml000066400000000000000000000015641304217427400301230ustar00rootroot00000000000000 4.0.0 jacoco it-offline-instrumentation 1.0-SNAPSHOT child jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/000077500000000000000000000000001304217427400273675ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/main/000077500000000000000000000000001304217427400303135ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/main/java/000077500000000000000000000000001304217427400312345ustar00rootroot00000000000000DoNotInstrument.java000066400000000000000000000012321304217427400351320ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/main/java/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class DoNotInstrument { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/main/java/Example.java000066400000000000000000000012221304217427400334670ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/test/000077500000000000000000000000001304217427400303465ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/test/java/000077500000000000000000000000001304217427400312675ustar00rootroot00000000000000ExampleTest.java000066400000000000000000000012511304217427400343050ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/child/src/test/java/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/pom.xml000066400000000000000000000052411304217427400270340ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-offline-instrumentation pom child child-without-main-classes @project.groupId@ org.jacoco.agent runtime @project.version@ test @project.groupId@ jacoco-maven-plugin instrument-classes instrument **/DoNotInstrument.class restore-instrumented-classes restore-instrumented-classes report prepare-package report ${project.build.directory}/coverage.exec org.apache.maven.plugins maven-surefire-plugin ${project.build.directory}/coverage.exec jacoco-0.7.8/jacoco-maven-plugin.test/it/it-offline-instrumentation/verify.bsh000066400000000000000000000022441304217427400275210ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; File file = new File( basedir, "child/target/generated-classes/jacoco/Example.class" ); if ( !file.isFile() ) { throw new RuntimeException( "Could not find backup of instrumented class: " + file ); } file = new File( basedir, "child/target/generated-classes/jacoco/DoNotInstrument.class" ); if ( file.isFile() ) { throw new RuntimeException( "Excluded file should not be instrumented: " + file ); } file = new File( basedir, "child/target/coverage.exec" ); if ( !file.isFile() ) { throw new FileNotFoundException( "Could not find generated dump: " + file ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-prepend-property/000077500000000000000000000000001304217427400241515ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-prepend-property/pom.xml000066400000000000000000000024141304217427400254670ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-prepend-property -ea @project.groupId@ jacoco-maven-plugin prepare-agent jacoco-0.7.8/jacoco-maven-plugin.test/it/it-prepend-property/verify.bsh000066400000000000000000000017561304217427400261640ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String agentOptions = "jacoco.exec -ea"; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( agentOptions ) < 0 ) { throw new RuntimeException( "Property was not configured" ); } File file = new File( basedir, "target/jacoco.exec" ); if ( !file.isFile() ) { throw new FileNotFoundException( "Could not find generated dump: " + file ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/000077500000000000000000000000001304217427400267775ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/000077500000000000000000000000001304217427400301435ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/pom.xml000066400000000000000000000020021304217427400314520ustar00rootroot00000000000000 4.0.0 jacoco it-report-aggregate-customization 1.0-SNAPSHOT child1 jar target/child1.coverage jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/000077500000000000000000000000001304217427400307325ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/main/000077500000000000000000000000001304217427400316565ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/main/java/000077500000000000000000000000001304217427400325775ustar00rootroot00000000000000package1/000077500000000000000000000000001304217427400341745ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/main/javaExample1.java000066400000000000000000000012031304217427400365070ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/main/java/package1/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package1; public class Example1 { public void a() { } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/test/000077500000000000000000000000001304217427400317115ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/test/java/000077500000000000000000000000001304217427400326325ustar00rootroot00000000000000package1/000077500000000000000000000000001304217427400342275ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/test/javaExample1Test.java000066400000000000000000000013021304217427400374020ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child1/src/test/java/package1/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package1; import org.junit.Test; public class Example1Test { @Test public void test() { new Example1().a(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/000077500000000000000000000000001304217427400301445ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/pom.xml000066400000000000000000000020021304217427400314530ustar00rootroot00000000000000 4.0.0 jacoco it-report-aggregate-customization 1.0-SNAPSHOT child2 jar target/child2.coverage jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/000077500000000000000000000000001304217427400307335ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/main/000077500000000000000000000000001304217427400316575ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/main/java/000077500000000000000000000000001304217427400326005ustar00rootroot00000000000000package2/000077500000000000000000000000001304217427400341765ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/main/javaExample2.java000066400000000000000000000012031304217427400365120ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/main/java/package2/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package2; public class Example2 { public void a() { } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/test/000077500000000000000000000000001304217427400317125ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/test/java/000077500000000000000000000000001304217427400326335ustar00rootroot00000000000000package2/000077500000000000000000000000001304217427400342315ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/test/javaExample2Test.java000066400000000000000000000013021304217427400374050ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/child2/src/test/java/package2/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package2; import org.junit.Test; public class Example2Test { @Test public void test() { new Example2().a(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/pom.xml000066400000000000000000000026271304217427400303230ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-report-aggregate-customization pom child1 child2 report @project.groupId@ jacoco-maven-plugin prepare-agent prepare-agent jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/report/000077500000000000000000000000001304217427400303125ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/report/pom.xml000066400000000000000000000041331304217427400316300ustar00rootroot00000000000000 4.0.0 jacoco it-report-aggregate-customization 1.0-SNAPSHOT report Aggregate Report ${project.groupId} child1 ${project.version} ${project.groupId} child2 ${project.version} @project.groupId@ jacoco-maven-plugin report-aggregate verify report-aggregate target/*.coverage target/child2.coverage target/jacoco-aggregate-customization jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate-customization/verify.bsh000066400000000000000000000031221304217427400307770ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ import org.codehaus.plexus.util.*; import java.util.regex.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); // Test customization of dataFileIncludes and dataFileExcludes if ( !Pattern.compile( "Loading execution data file \\S*child1.target.child1.coverage").matcher( buildLog ).find() ) { throw new RuntimeException( "Execution data from child1 was not loaded." ); } if ( Pattern.compile( "Loading execution data file \\S*child2").matcher( buildLog ).find() ) { throw new RuntimeException( "Execution data from child2 was loaded." ); } // Test customization of outputDirectory File reportChild1 = new File( basedir, "report/target/jacoco-aggregate-customization/child1/index.html" ); if ( !reportChild1.isFile() ) { throw new RuntimeException( "Report for child1 was not created." ); } File reportChild2 = new File( basedir, "report/target/jacoco-aggregate-customization/child2/index.html" ); if ( !reportChild2.isFile() ) { throw new RuntimeException( "Report for child2 was not created." ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/000077500000000000000000000000001304217427400240715ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1-test/000077500000000000000000000000001304217427400262125ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1-test/pom.xml000066400000000000000000000021261304217427400275300ustar00rootroot00000000000000 4.0.0 jacoco it-report-aggregate 1.0-SNAPSHOT child1-test jar jacoco child1 ${project.version} jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1-test/src/000077500000000000000000000000001304217427400270015ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1-test/src/test/000077500000000000000000000000001304217427400277605ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1-test/src/test/java/000077500000000000000000000000001304217427400307015ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1-test/src/test/java/package1/000077500000000000000000000000001304217427400323555ustar00rootroot00000000000000Example1bTest.java000066400000000000000000000013041304217427400356150ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1-test/src/test/java/package1/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package1; import org.junit.Test; public class Example1bTest { @Test public void test() { new Example1b().b(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/000077500000000000000000000000001304217427400252355ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/pom.xml000066400000000000000000000016301304217427400265520ustar00rootroot00000000000000 4.0.0 jacoco it-report-aggregate 1.0-SNAPSHOT child1 jar jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/000077500000000000000000000000001304217427400260245ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/main/000077500000000000000000000000001304217427400267505ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/main/java/000077500000000000000000000000001304217427400276715ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/main/java/package1/000077500000000000000000000000001304217427400313455ustar00rootroot00000000000000Example1a.java000066400000000000000000000012041304217427400337430ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/main/java/package1/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package1; public class Example1a { public void a() { } } Example1b.java000066400000000000000000000012041304217427400337440ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/main/java/package1/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package1; public class Example1b { public void b() { } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/test/000077500000000000000000000000001304217427400270035ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/test/java/000077500000000000000000000000001304217427400277245ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/test/java/package1/000077500000000000000000000000001304217427400314005ustar00rootroot00000000000000Example1aTest.java000066400000000000000000000013041304217427400346370ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child1/src/test/java/package1/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package1; import org.junit.Test; public class Example1aTest { @Test public void test() { new Example1a().a(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/000077500000000000000000000000001304217427400252365ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/pom.xml000066400000000000000000000016301304217427400265530ustar00rootroot00000000000000 4.0.0 jacoco it-report-aggregate 1.0-SNAPSHOT child2 jar jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/000077500000000000000000000000001304217427400260255ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/main/000077500000000000000000000000001304217427400267515ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/main/java/000077500000000000000000000000001304217427400276725ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/main/java/package2/000077500000000000000000000000001304217427400313475ustar00rootroot00000000000000Example2.java000066400000000000000000000012031304217427400336040ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/main/java/package2/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package2; public class Example2 { public void a() { } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/test/000077500000000000000000000000001304217427400270045ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/test/java/000077500000000000000000000000001304217427400277255ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/test/java/package2/000077500000000000000000000000001304217427400314025ustar00rootroot00000000000000Example2Test.java000066400000000000000000000013021304217427400344770ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/child2/src/test/java/package2/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package package2; import org.junit.Test; public class Example2Test { @Test public void test() { new Example2().a(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/pom.xml000066400000000000000000000026521304217427400254130ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-report-aggregate pom child1 child1-test child2 report @project.groupId@ jacoco-maven-plugin prepare-agent prepare-agent jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/report/000077500000000000000000000000001304217427400254045ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/report/pom.xml000066400000000000000000000035061304217427400267250ustar00rootroot00000000000000 4.0.0 jacoco it-report-aggregate 1.0-SNAPSHOT report Aggregate Report jacoco child1 ${project.version} jacoco child1-test ${project.version} test jacoco child2 ${project.version} @project.groupId@ jacoco-maven-plugin report-aggregate verify report-aggregate jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/report/src/000077500000000000000000000000001304217427400261735ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/report/src/test/000077500000000000000000000000001304217427400271525ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/report/src/test/java/000077500000000000000000000000001304217427400300735ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/report/src/test/java/packagereport/000077500000000000000000000000001304217427400327225ustar00rootroot00000000000000ReportTest.java000066400000000000000000000012421304217427400356200ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/report/src/test/java/packagereport/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package packagereport; import org.junit.Test; public class ReportTest { @Test public void test() { } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-aggregate/verify.bsh000066400000000000000000000041441304217427400260760ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ import org.codehaus.plexus.util.*; import java.util.regex.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( !Pattern.compile( "Loading execution data file \\S*child1.target.jacoco.exec").matcher( buildLog ).find() ) { throw new RuntimeException( "Execution data from child1 was not loaded." ); } if ( !Pattern.compile( "Loading execution data file \\S*child1-test.target.jacoco.exec").matcher( buildLog ).find() ) { throw new RuntimeException( "Execution data from child1-test was not loaded." ); } if ( !Pattern.compile( "Loading execution data file \\S*child2.target.jacoco.exec").matcher( buildLog ).find() ) { throw new RuntimeException( "Execution data from child2 was not loaded." ); } if ( !Pattern.compile( "Loading execution data file \\S*report.target.jacoco.exec").matcher( buildLog ).find() ) { throw new RuntimeException( "Execution data from report was not loaded." ); } File reportChild1 = new File( basedir, "report/target/site/jacoco-aggregate/child1/index.html" ); if ( !reportChild1.isFile() ) { throw new RuntimeException( "Report for child1 was not created." ); } File reportChild1test = new File( basedir, "report/target/site/jacoco-aggregate/child1-test/index.html" ); if ( reportChild1test.isFile() ) { throw new RuntimeException( "Report for child1-test should not be created." ); } File reportChild2 = new File( basedir, "report/target/site/jacoco-aggregate/child2/index.html" ); if ( !reportChild2.isFile() ) { throw new RuntimeException( "Report for child2 was not created." ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/000077500000000000000000000000001304217427400235745ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/nomatch.exec000066400000000000000000000000301304217427400260640ustar00rootroot00000000000000ÀÀExamplejacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/pom.xml000066400000000000000000000025701304217427400251150ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-report-nomatch @project.groupId@ jacoco-maven-plugin report prepare-package report nomatch.exec jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/src/000077500000000000000000000000001304217427400243635ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/src/main/000077500000000000000000000000001304217427400253075ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/src/main/java/000077500000000000000000000000001304217427400262305ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/src/main/java/Example.java000066400000000000000000000011131304217427400304620ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ public class Example { } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-nomatch/verify.bsh000066400000000000000000000022461304217427400256020ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "Classes in bundle " ) < 0 || buildLog.indexOf(" do no match with execution data." ) < 0 ) { throw new RuntimeException( "Warning 1 was not printed" ); } if ( buildLog.indexOf( "For report generation the same class files must be used as at runtime." ) < 0 ) { throw new RuntimeException( "Warning 2 was not printed" ); } if ( buildLog.indexOf( "Execution data for class Example does not match." ) < 0 ) { throw new RuntimeException( "Warning 3 was not printed" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/000077500000000000000000000000001304217427400252105ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/data.txt000066400000000000000000000000151304217427400266560ustar00rootroot00000000000000Invalid data jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/invoker.properties000066400000000000000000000000361304217427400310020ustar00rootroot00000000000000invoker.buildResult = failure jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/pom.xml000066400000000000000000000025741304217427400265350ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-report-unreadable-dump @project.groupId@ jacoco-maven-plugin report prepare-package report data.txt jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/src/000077500000000000000000000000001304217427400257775ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/src/main/000077500000000000000000000000001304217427400267235ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/src/main/resources/000077500000000000000000000000001304217427400307355ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/src/main/resources/empty-file.txt000066400000000000000000000000001304217427400335370ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-unreadable-dump/verify.bsh000066400000000000000000000014561304217427400272200ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "Invalid execution data file." ) < 0 ) { throw new RuntimeException( "Error was not printed" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/000077500000000000000000000000001304217427400247325ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/pom.xml000066400000000000000000000032701304217427400262510ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-report-without-debug @project.groupId@ jacoco-maven-plugin prepare-agent prepare-agent report prepare-package report org.apache.maven.plugins maven-compiler-plugin true none jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/src/000077500000000000000000000000001304217427400255215ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/src/main/000077500000000000000000000000001304217427400264455ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/src/main/java/000077500000000000000000000000001304217427400273665ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/src/main/java/Example.java000066400000000000000000000012221304217427400316210ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/src/test/000077500000000000000000000000001304217427400265005ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/src/test/java/000077500000000000000000000000001304217427400274215ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/src/test/java/ExampleTest.java000066400000000000000000000012511304217427400325160ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-debug/verify.bsh000066400000000000000000000014651304217427400267420ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "with debug information" ) < 0 ) { throw new RuntimeException( "No warning about debug information" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-dump/000077500000000000000000000000001304217427400246115ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-dump/pom.xml000066400000000000000000000024241304217427400261300ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-report-without-dump @project.groupId@ jacoco-maven-plugin report prepare-package report jacoco-0.7.8/jacoco-maven-plugin.test/it/it-report-without-dump/verify.bsh000066400000000000000000000015221304217427400266130ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String buildLog = FileUtils.fileRead( new File( basedir, "build.log" ) ); if ( buildLog.indexOf( "Skipping JaCoCo execution due to missing execution data file" ) < 0 ) { throw new RuntimeException( "Execution was not skipped" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/000077500000000000000000000000001304217427400233465ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/invoker.properties000066400000000000000000000001731304217427400271420ustar00rootroot00000000000000invoker.goals = clean verify site # maven-site-plugin 3.3 works with at least Maven 2.2.1+ invoker.maven.version = 2.2.1+ jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/pom.xml000066400000000000000000000056671304217427400247010ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-site-failsafe org.apache.maven.plugins maven-failsafe-plugin 2.14.1 org.apache.maven.plugins maven-surefire-plugin 2.14.1 @project.groupId@ jacoco-maven-plugin default-prepare-agent prepare-agent default-prepare-agent-integration prepare-agent-integration default-report-integration report-integration org.apache.maven.plugins maven-failsafe-plugin default-integration-test integration-test org.apache.maven.plugins maven-site-plugin 3.3 true @project.groupId@ jacoco-maven-plugin @project.version@ jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/000077500000000000000000000000001304217427400241355ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/main/000077500000000000000000000000001304217427400250615ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/main/java/000077500000000000000000000000001304217427400260025ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/main/java/Example.java000066400000000000000000000013331304217427400302400ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } public void sayHelloIT() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/test/000077500000000000000000000000001304217427400251145ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/test/java/000077500000000000000000000000001304217427400260355ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/test/java/ExampleIT.java000066400000000000000000000012511304217427400305270ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleIT { @Test public void test() { new Example().sayHelloIT(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/src/test/java/ExampleTest.java000066400000000000000000000012511304217427400311320ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site-failsafe/verify.bsh000066400000000000000000000041771304217427400253610ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String projectReportsPage = FileUtils.fileRead( new File( basedir, "target/site/project-reports.html" ) ); if ( projectReportsPage.indexOf( "JaCoCo Coverage Report." ) < 0 ) { throw new RuntimeException( "project-reports.html does not contain link to JaCoCo report" ); } File htmlReportFile = new File( basedir, "target/site/jacoco/index.html" ); if ( !htmlReportFile.isFile() ) { throw new RuntimeException( "HTML report was not created" ); } File xmlReportFile = new File( basedir, "target/site/jacoco/jacoco.xml" ); if ( !xmlReportFile.isFile() ) { throw new RuntimeException( "XML report was not created" ); } File csvReportFile = new File( basedir, "target/site/jacoco/jacoco.csv" ); if ( !csvReportFile.isFile() ) { throw new RuntimeException( "CSV report was not created" ); } if ( projectReportsPage.indexOf( "JaCoCo IT Coverage Report." ) < 0 ) { throw new RuntimeException( "project-reports.html does not contain link to JaCoCo Integration report" ); } File htmlReportFile = new File( basedir, "target/site/jacoco-it/index.html" ); if ( !htmlReportFile.isFile() ) { throw new RuntimeException( "Integration HTML report was not created" ); } File xmlReportFile = new File( basedir, "target/site/jacoco-it/jacoco.xml" ); if ( !xmlReportFile.isFile() ) { throw new RuntimeException( "Integration XML report was not created" ); } File csvReportFile = new File( basedir, "target/site/jacoco-it/jacoco.csv" ); if ( !csvReportFile.isFile() ) { throw new RuntimeException( "Integration CSV report was not created" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/000077500000000000000000000000001304217427400215765ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/invoker.properties000066400000000000000000000001661304217427400253740ustar00rootroot00000000000000invoker.goals = clean test site # maven-site-plugin 3.0 requires at least Maven 2.2.0 invoker.maven.version = 2.2.0+ jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/pom.xml000066400000000000000000000031771304217427400231230ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT it-site @project.groupId@ jacoco-maven-plugin prepare-agent org.apache.maven.plugins maven-site-plugin 3.3 true @project.groupId@ jacoco-maven-plugin @project.version@ jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/src/000077500000000000000000000000001304217427400223655ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/src/main/000077500000000000000000000000001304217427400233115ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/src/main/java/000077500000000000000000000000001304217427400242325ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/src/main/java/Example.java000066400000000000000000000012221304217427400264650ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ public class Example { public void sayHello() { System.out.println("Hello world"); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/src/test/000077500000000000000000000000001304217427400233445ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/src/test/java/000077500000000000000000000000001304217427400242655ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/src/test/java/ExampleTest.java000066400000000000000000000012511304217427400273620ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import org.junit.Test; public class ExampleTest { @Test public void test() { new Example().sayHello(); } } jacoco-0.7.8/jacoco-maven-plugin.test/it/it-site/verify.bsh000066400000000000000000000026121304217427400236010ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ import java.io.*; import org.codehaus.plexus.util.*; String projectReportsPage = FileUtils.fileRead( new File( basedir, "target/site/project-reports.html" ) ); if ( projectReportsPage.indexOf( "JaCoCo Coverage Report." ) < 0 ) { throw new RuntimeException( "project-reports.html does not contain link to JaCoCo report" ); } File htmlReportFile = new File( basedir, "target/site/jacoco/index.html" ); if ( !htmlReportFile.isFile() ) { throw new RuntimeException( "HTML report was not created" ); } File xmlReportFile = new File( basedir, "target/site/jacoco/jacoco.xml" ); if ( !xmlReportFile.isFile() ) { throw new RuntimeException( "XML report was not created" ); } File csvReportFile = new File( basedir, "target/site/jacoco/jacoco.csv" ); if ( !csvReportFile.isFile() ) { throw new RuntimeException( "CSV report was not created" ); } jacoco-0.7.8/jacoco-maven-plugin.test/it/settings.xml000066400000000000000000000024201304217427400226000ustar00rootroot00000000000000 it-repo true local.central @localRepositoryUrl@ true true local.central @localRepositoryUrl@ true true jacoco-0.7.8/jacoco-maven-plugin.test/it/setup-parent/000077500000000000000000000000001304217427400226475ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin.test/it/setup-parent/pom.xml000066400000000000000000000037341304217427400241730ustar00rootroot00000000000000 4.0.0 jacoco setup-parent 1.0-SNAPSHOT pom junit junit 4.8.2 test @project.groupId@ jacoco-maven-plugin @project.version@ org.apache.maven.plugins maven-compiler-plugin 2.3.2 @maven.compiler.source@ @maven.compiler.target@ org.apache.maven.plugins maven-surefire-plugin 2.9 org.apache.maven.plugins maven-jar-plugin 2.3.1 jacoco-0.7.8/jacoco-maven-plugin.test/pom.xml000066400000000000000000000047121304217427400211250ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.tests 0.7.8 ../org.jacoco.tests jacoco-maven-plugin.test jar JaCoCo :: Test :: Maven Plugin invoker.mavenOpts org.jacoco.maven.* org.apache.maven.plugins maven-invoker-plugin ${skipTests} it ${project.build.directory}/it */pom.xml verify ${project.build.directory}/local-repo clean install it/settings.xml org.jacoco:org.jacoco.agent:${project.version}:jar:runtime install run jacoco-0.7.8/jacoco-maven-plugin/000077500000000000000000000000001304217427400166265ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin/.classpath000066400000000000000000000014151304217427400206120ustar00rootroot00000000000000 jacoco-0.7.8/jacoco-maven-plugin/.gitignore000066400000000000000000000000301304217427400206070ustar00rootroot00000000000000/target /bin /.settings jacoco-0.7.8/jacoco-maven-plugin/.project000066400000000000000000000013271304217427400203000ustar00rootroot00000000000000 jacoco-maven-plugin org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core/.settings jacoco-0.7.8/jacoco-maven-plugin/META-INF/000077500000000000000000000000001304217427400177665ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin/META-INF/m2e/000077500000000000000000000000001304217427400204515ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin/META-INF/m2e/lifecycle-mapping-metadata.xml000066400000000000000000000020431304217427400263400ustar00rootroot00000000000000 prepare-agent prepare-agent-integration merge report report-integration report-aggregate check dump instrument restore-instrumented-classes jacoco-0.7.8/jacoco-maven-plugin/pom.xml000066400000000000000000000105461304217427400201510ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.build 0.7.8 ../org.jacoco.build jacoco-maven-plugin maven-plugin JaCoCo :: Maven Plugin The JaCoCo Maven Plugin provides the JaCoCo runtime agent to your tests and allows basic report creation. 2.2.1 org.apache.maven maven-plugin-api ${project.prerequisites.maven} org.apache.maven maven-project ${project.prerequisites.maven} org.codehaus.plexus plexus-utils 3.0.22 org.apache.maven.shared file-management 1.2.1 org.apache.maven.reporting maven-reporting-api ${project.prerequisites.maven} org.apache.maven.reporting maven-reporting-impl 2.1 ${project.groupId} org.jacoco.agent runtime ${project.groupId} org.jacoco.core ${project.groupId} org.jacoco.report org.apache.maven.plugin-tools maven-plugin-annotations 3.4 provided src META-INF META-INF org.apache.maven.plugins maven-javadoc-plugin org.apache.maven.plugin-tools maven-plugin-tools-javadoc 2.8 org.apache.maven.plugins maven-plugin-plugin default-descriptor process-classes descriptor help-mojo process-classes helpmojo report package report jacoco-0.7.8/jacoco-maven-plugin/src/000077500000000000000000000000001304217427400174155ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin/src/org/000077500000000000000000000000001304217427400202045ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/000077500000000000000000000000001304217427400214425ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/000077500000000000000000000000001304217427400225505ustar00rootroot00000000000000jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/AbstractAgentMojo.java000066400000000000000000000174511304217427400267720ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.util.Map; import java.util.Properties; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugins.annotations.Parameter; import org.codehaus.plexus.util.StringUtils; import org.jacoco.core.runtime.AgentOptions; /** * Base class for preparing a property pointing to the JaCoCo runtime agent that * can be passed as a VM argument to the application under test. */ public abstract class AbstractAgentMojo extends AbstractJacocoMojo { /** * Name of the JaCoCo Agent artifact. */ static final String AGENT_ARTIFACT_NAME = "org.jacoco:org.jacoco.agent"; /** * Name of the property used in maven-osgi-test-plugin. */ static final String TYCHO_ARG_LINE = "tycho.testArgLine"; /** * Name of the property used in maven-surefire-plugin. */ static final String SUREFIRE_ARG_LINE = "argLine"; /** * Map of plugin artifacts. */ @Parameter(property = "plugin.artifactMap", required = true, readonly = true) Map pluginArtifactMap; /** * Allows to specify property which will contains settings for JaCoCo Agent. * If not specified, then "argLine" would be used for "jar" packaging and * "tycho.testArgLine" for "eclipse-test-plugin". */ @Parameter(property = "jacoco.propertyName") String propertyName; /** * If set to true and the execution data file already exists, coverage data * is appended to the existing file. If set to false, an existing execution * data file will be replaced. */ @Parameter(property = "jacoco.append") Boolean append; /** * A list of class loader names, that should be excluded from execution * analysis. The list entries are separated by a colon (:) and may use * wildcard characters (* and ?). This option might be required in case of * special frameworks that conflict with JaCoCo code instrumentation, in * particular class loaders that do not have access to the Java runtime * classes. */ @Parameter(property = "jacoco.exclClassLoaders") String exclClassLoaders; /** * Specifies whether also classes from the bootstrap classloader should be * instrumented. Use this feature with caution, it needs heavy * includes/excludes tuning. */ @Parameter(property = "jacoco.inclBootstrapClasses") Boolean inclBootstrapClasses; /** * Specifies whether classes without source location should be instrumented. */ @Parameter(property = "jacoco.inclNoLocationClasses") Boolean inclNoLocationClasses; /** * A session identifier that is written with the execution data. Without * this parameter a random identifier is created by the agent. */ @Parameter(property = "jacoco.sessionId") String sessionId; /** * If set to true coverage data will be written on VM shutdown. */ @Parameter(property = "jacoco.dumpOnExit") Boolean dumpOnExit; /** * Output method to use for writing coverage data. Valid options are: * */ @Parameter(property = "jacoco.output") String output; /** * IP address or hostname to bind to when the output method is tcpserver or * connect to when the output method is tcpclient. In tcpserver mode the * value "*" causes the agent to accept connections on any local address. */ @Parameter(property = "jacoco.address") String address; /** * Port to bind to when the output method is tcpserver or connect to when * the output method is tcpclient. In tcpserver mode the port must be * available, which means that if multiple JaCoCo agents should run on the * same machine, different ports have to be specified. */ @Parameter(property = "jacoco.port") Integer port; /** * If a directory is specified for this parameter the JaCoCo agent dumps all * class files it processes to the given location. This can be useful for * debugging purposes or in case of dynamically created classes for example * when scripting engines are used. */ @Parameter(property = "jacoco.classDumpDir") File classDumpDir; /** * If set to true the agent exposes functionality via JMX. */ @Parameter(property = "jacoco.jmx") Boolean jmx; @Override public void executeMojo() { final String name = getEffectivePropertyName(); final Properties projectProperties = getProject().getProperties(); final String oldValue = projectProperties.getProperty(name); final String newValue = createAgentOptions().prependVMArguments( oldValue, getAgentJarFile()); getLog().info(name + " set to " + newValue); projectProperties.setProperty(name, newValue); } @Override protected void skipMojo() { final String name = getEffectivePropertyName(); final Properties projectProperties = getProject().getProperties(); getLog().info(name + " set to empty"); projectProperties.setProperty(name, ""); } File getAgentJarFile() { final Artifact jacocoAgentArtifact = pluginArtifactMap .get(AGENT_ARTIFACT_NAME); return jacocoAgentArtifact.getFile(); } AgentOptions createAgentOptions() { final AgentOptions agentOptions = new AgentOptions(); agentOptions.setDestfile(getDestFile().getAbsolutePath()); if (append != null) { agentOptions.setAppend(append.booleanValue()); } if (getIncludes() != null && !getIncludes().isEmpty()) { final String agentIncludes = StringUtils.join(getIncludes() .iterator(), ":"); agentOptions.setIncludes(agentIncludes); } if (getExcludes() != null && !getExcludes().isEmpty()) { final String agentExcludes = StringUtils.join(getExcludes() .iterator(), ":"); agentOptions.setExcludes(agentExcludes); } if (exclClassLoaders != null) { agentOptions.setExclClassloader(exclClassLoaders); } if (inclBootstrapClasses != null) { agentOptions.setInclBootstrapClasses(inclBootstrapClasses .booleanValue()); } if (inclNoLocationClasses != null) { agentOptions.setInclNoLocationClasses(inclNoLocationClasses .booleanValue()); } if (sessionId != null) { agentOptions.setSessionId(sessionId); } if (dumpOnExit != null) { agentOptions.setDumpOnExit(dumpOnExit.booleanValue()); } if (output != null) { agentOptions.setOutput(output); } if (address != null) { agentOptions.setAddress(address); } if (port != null) { agentOptions.setPort(port.intValue()); } if (classDumpDir != null) { agentOptions.setClassDumpDir(classDumpDir.getAbsolutePath()); } if (jmx != null) { agentOptions.setJmx(jmx.booleanValue()); } return agentOptions; } String getEffectivePropertyName() { if (isPropertyNameSpecified()) { return propertyName; } if (isEclipseTestPluginPackaging()) { return TYCHO_ARG_LINE; } return SUREFIRE_ARG_LINE; } boolean isPropertyNameSpecified() { return propertyName != null && !"".equals(propertyName); } boolean isEclipseTestPluginPackaging() { return "eclipse-test-plugin".equals(getProject().getPackaging()); } /** * @return the destFile */ abstract File getDestFile(); } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/AbstractJacocoMojo.java000066400000000000000000000056411304217427400271300ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; /** * Base class for JaCoCo Mojos. */ public abstract class AbstractJacocoMojo extends AbstractMojo { /** * Maven project. */ @Parameter(property = "project", readonly = true) private MavenProject project; /** * A list of class files to include in instrumentation/analysis/reports. May * use wildcard characters (* and ?). When not specified everything will be * included. */ @Parameter private List includes; /** * A list of class files to exclude from instrumentation/analysis/reports. * May use wildcard characters (* and ?). When not specified nothing will be * excluded. */ @Parameter private List excludes; /** * Flag used to suppress execution. */ @Parameter(property = "jacoco.skip", defaultValue = "false") private boolean skip; public final void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info( "Skipping JaCoCo execution because property jacoco.skip is set."); skipMojo(); return; } executeMojo(); } /** * Executes Mojo. * * @throws MojoExecutionException * if an unexpected problem occurs. Throwing this exception * causes a "BUILD ERROR" message to be displayed. * @throws MojoFailureException * if an expected problem (such as a compilation failure) * occurs. Throwing this exception causes a "BUILD FAILURE" * message to be displayed. */ protected abstract void executeMojo() throws MojoExecutionException, MojoFailureException; /** * Skips Mojo. */ protected void skipMojo() { } /** * @return Maven project */ protected final MavenProject getProject() { return project; } /** * Returns the list of class files to include. * * @return class files to include, may contain wildcard characters */ protected List getIncludes() { return includes; } /** * Returns the list of class files to exclude. * * @return class files to exclude, may contain wildcard characters */ protected List getExcludes() { return excludes; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/AbstractReportMojo.java000066400000000000000000000120361304217427400272010ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.io.IOException; import java.util.List; import java.util.Locale; import org.apache.maven.doxia.siterenderer.Renderer; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.reporting.AbstractMavenReport; import org.apache.maven.reporting.MavenReportException; import org.jacoco.report.IReportGroupVisitor; import org.jacoco.report.IReportVisitor; /** * Base class for creating a code coverage report for tests of a single project * in multiple formats (HTML, XML, and CSV). */ public abstract class AbstractReportMojo extends AbstractMavenReport { /** * Encoding of the generated reports. */ @Parameter(property = "project.reporting.outputEncoding", defaultValue = "UTF-8") String outputEncoding; /** * Name of the root node HTML report pages. * * @since 0.7.7 */ @Parameter(defaultValue = "${project.name}") String title; /** * Footer text used in HTML report pages. * * @since 0.7.7 */ @Parameter String footer; /** * Encoding of the source files. */ @Parameter(property = "project.build.sourceEncoding", defaultValue = "UTF-8") String sourceEncoding; /** * A list of class files to include in the report. May use wildcard * characters (* and ?). When not specified everything will be included. */ @Parameter List includes; /** * A list of class files to exclude from the report. May use wildcard * characters (* and ?). When not specified nothing will be excluded. */ @Parameter List excludes; /** * Flag used to suppress execution. */ @Parameter(property = "jacoco.skip", defaultValue = "false") boolean skip; /** * Maven project. */ @Parameter(property = "project", readonly = true) MavenProject project; /** * Doxia Site Renderer. */ @Component Renderer siteRenderer; public String getDescription(final Locale locale) { return getName(locale) + " Coverage Report."; } @Override public boolean isExternalReport() { return true; } @Override protected MavenProject getProject() { return project; } @Override protected Renderer getSiteRenderer() { return siteRenderer; } /** * Returns the list of class files to include in the report. * * @return class files to include, may contain wildcard characters */ List getIncludes() { return includes; } /** * Returns the list of class files to exclude from the report. * * @return class files to exclude, may contain wildcard characters */ List getExcludes() { return excludes; } @Override public boolean canGenerateReport() { if (skip) { getLog().info( "Skipping JaCoCo execution because property jacoco.skip is set."); return false; } if (!canGenerateReportRegardingDataFiles()) { getLog().info( "Skipping JaCoCo execution due to missing execution data file."); return false; } if (!canGenerateReportRegardingClassesDirectory()) { getLog().info( "Skipping JaCoCo execution due to missing classes directory."); return false; } return true; } abstract boolean canGenerateReportRegardingDataFiles(); abstract boolean canGenerateReportRegardingClassesDirectory(); /** * This method is called when the report generation is invoked directly as a * standalone Mojo. */ @Override public void execute() throws MojoExecutionException { if (!canGenerateReport()) { return; } try { executeReport(Locale.getDefault()); } catch (final MavenReportException e) { throw new MojoExecutionException("An error has occurred in " + getName(Locale.ENGLISH) + " report generation.", e); } } @Override protected void executeReport(final Locale locale) throws MavenReportException { try { final ReportSupport support = new ReportSupport(getLog()); loadExecutionData(support); addFormatters(support, locale); final IReportVisitor visitor = support.initRootVisitor(); createReport(visitor, support); visitor.visitEnd(); } catch (final IOException e) { throw new MavenReportException("Error while creating report: " + e.getMessage(), e); } } abstract void loadExecutionData(final ReportSupport support) throws IOException; abstract void addFormatters(final ReportSupport support, final Locale locale) throws IOException; abstract void createReport(final IReportGroupVisitor visitor, final ReportSupport support) throws IOException; } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/AgentITMojo.java000066400000000000000000000031461304217427400255370ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; /** * Same as prepare-agent, but provides default values suitable for * integration-tests: *
    *
  • bound to pre-integration-test phase
  • *
  • different destFile
  • *
* * @since 0.6.4 */ @Mojo(name = "prepare-agent-integration", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) public class AgentITMojo extends AbstractAgentMojo { /** * Path to the output file for execution data. */ @Parameter(property = "jacoco.destFile", defaultValue = "${project.build.directory}/jacoco-it.exec") private File destFile; /** * @return the destFile */ @Override File getDestFile() { return destFile; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/AgentMojo.java000066400000000000000000000064131304217427400253020ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; /** *

* Prepares a property pointing to the JaCoCo runtime agent that can be passed * as a VM argument to the application under test. Depending on the project * packaging type by default a property with the following name is set: *

* *
    *
  • tycho.testArgLine for packaging type eclipse-test-plugin and
  • *
  • argLine otherwise.
  • *
* *

* If your project already defines VM arguments for test execution, be sure that * they will include property defined by JaCoCo. *

* *

* One of the ways to do this in case of maven-surefire-plugin - is to use * syntax for late property evaluation: *

* *
 *   <plugin>
 *     <groupId>org.apache.maven.plugins</groupId>
 *     <artifactId>maven-surefire-plugin</artifactId>
 *     <configuration>
 *       <argLine>@{argLine} -your -extra -arguments</argLine>
 *     </configuration>
 *   </plugin>
 * 
* *

* You can define empty property to avoid JVM startup error Could not find or load main class @{argLine} * when using late property evaluation and jacoco-maven-plugin not executed. *

* *

* Another way is to define "argLine" as a Maven property rather than * as part of the configuration of maven-surefire-plugin: *

* *
 *   <properties>
 *     <argLine>-your -extra -arguments</argLine>
 *   </properties>
 *   ...
 *   <plugin>
 *     <groupId>org.apache.maven.plugins</groupId>
 *     <artifactId>maven-surefire-plugin</artifactId>
 *     <configuration>
 *       <!-- no argLine here -->
 *     </configuration>
 *   </plugin>
 * 
* *

* Resulting coverage information is collected during execution and by default * written to a file when the process terminates. *

* * @since 0.5.3 */ @Mojo(name = "prepare-agent", defaultPhase = LifecyclePhase.INITIALIZE, requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) public class AgentMojo extends AbstractAgentMojo { /** * Path to the output file for execution data. */ @Parameter(property = "jacoco.destFile", defaultValue = "${project.build.directory}/jacoco.exec") private File destFile; /** * @return the destFile */ @Override File getDestFile() { return destFile; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/CheckMojo.java000066400000000000000000000136301304217427400252600ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * Marc Hoffmann - redesign using report APIs * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.jacoco.core.analysis.ICoverageNode; import org.jacoco.report.IReportVisitor; import org.jacoco.report.check.IViolationsOutput; import org.jacoco.report.check.Limit; import org.jacoco.report.check.Rule; /** * Checks that the code coverage metrics are being met. * * @since 0.6.1 */ @Mojo(name = "check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) public class CheckMojo extends AbstractJacocoMojo implements IViolationsOutput { private static final String MSG_SKIPPING = "Skipping JaCoCo execution due to missing execution data file:"; private static final String CHECK_SUCCESS = "All coverage checks have been met."; private static final String CHECK_FAILED = "Coverage checks have not been met. See log for details."; /** *

* Check configuration used to specify rules on element types (BUNDLE, * PACKAGE, CLASS, SOURCEFILE or METHOD) with a list of limits. Each limit * applies to a certain counter (INSTRUCTION, LINE, BRANCH, COMPLEXITY, * METHOD, CLASS) and defines a minimum or maximum for the corresponding * value (TOTALCOUNT, COVEREDCOUNT, MISSEDCOUNT, COVEREDRATIO, MISSEDRATIO). * If a limit refers to a ratio the range is from 0.0 to 1.0 where the * number of decimal places will also determine the precision in error * messages. *

* *

* If not specified the following defaults are assumed: *

* *
    *
  • rule element: BUNDLE
  • *
  • limit counter: INSTRUCTION
  • *
  • limit value: COVEREDRATIO
  • *
* *

* Note that you must use implementation hints for * rule and limit when using Maven 2, with Maven 3 you do * not need to specify the attributes. *

* *

* This example requires an overall instruction coverage of 80% and no class * must be missed: *

* *
	 * {@code
	 * 
	 *   
	 *     BUNDLE
	 *     
	 *       
	 *         INSTRUCTION
	 *         COVEREDRATIO
	 *         0.80
	 *       
	 *       
	 *         CLASS
	 *         MISSEDCOUNT
	 *         0
	 *       
	 *     
	 *   
	 * }
	 * 
* *

* This example requires a line coverage minimum of 50% for every class * except test classes: *

* *
	 * {@code
	 * 
	 *   
	 *     CLASS
	 *     
	 *       *Test
	 *     
	 *     
	 *       
	 *         LINE
	 *         COVEREDRATIO
	 *         0.50
	 *       
	 *     
	 *   
	 * }
	 * 
*/ @Parameter(required = true) private List rules; /** * Halt the build if any of the checks fail. */ @Parameter(property = "jacoco.haltOnFailure", defaultValue = "true", required = true) private boolean haltOnFailure; /** * File with execution data. */ @Parameter(defaultValue = "${project.build.directory}/jacoco.exec") private File dataFile; private boolean violations; private boolean canCheckCoverage() { if (!dataFile.exists()) { getLog().info(MSG_SKIPPING + dataFile); return false; } final File classesDirectory = new File(getProject().getBuild() .getOutputDirectory()); if (!classesDirectory.exists()) { getLog().info( "Skipping JaCoCo execution due to missing classes directory:" + classesDirectory); return false; } return true; } @Override public void executeMojo() throws MojoExecutionException, MojoExecutionException { if (!canCheckCoverage()) { return; } executeCheck(); } private void executeCheck() throws MojoExecutionException { violations = false; final ReportSupport support = new ReportSupport(getLog()); final List checkerrules = new ArrayList(); for (final RuleConfiguration r : rules) { checkerrules.add(r.rule); } support.addRulesChecker(checkerrules, this); try { final IReportVisitor visitor = support.initRootVisitor(); support.loadExecutionData(dataFile); support.processProject(visitor, getProject(), this.getIncludes(), this.getExcludes()); visitor.visitEnd(); } catch (final IOException e) { throw new MojoExecutionException( "Error while checking code coverage: " + e.getMessage(), e); } if (violations) { if (this.haltOnFailure) { throw new MojoExecutionException(CHECK_FAILED); } else { this.getLog().warn(CHECK_FAILED); } } else { this.getLog().info(CHECK_SUCCESS); } } public void onViolation(final ICoverageNode node, final Rule rule, final Limit limit, final String message) { this.getLog().warn(message); violations = true; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/DumpMojo.java000066400000000000000000000073541304217427400251560ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Chas Honton, Marc R. Hoffmann - initial implementation * *******************************************************************************/ package org.jacoco.maven; import static java.lang.String.format; import java.io.File; import java.io.IOException; import java.net.InetAddress; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.jacoco.core.tools.ExecDumpClient; import org.jacoco.core.tools.ExecFileLoader; /** *

* Request a dump over TCP/IP from a JaCoCo agent running in * tcpserver mode. *

* *

* Note concerning parallel builds: While the dump goal as such is thread safe, * it has to be considered that TCP/IP server ports of the agents are a shared * resource. *

* * @since 0.6.4 */ @Mojo(name = "dump", defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST, threadSafe = true) public class DumpMojo extends AbstractJacocoMojo { /** * Path to the output file for execution data. */ @Parameter(property = "jacoco.destFile", defaultValue = "${project.build.directory}/jacoco.exec") private File destFile; /** * If set to true and the execution data file already exists, coverage data * is appended to the existing file. If set to false, an existing execution * data file will be replaced. */ @Parameter(property = "jacoco.append", defaultValue = "true") private boolean append; /** * Sets whether execution data should be downloaded from the remote host. */ @Parameter(property = "jacoco.dump", defaultValue = "true") private boolean dump; /** * Sets whether a reset command should be sent after the execution data has * been dumped. */ @Parameter(property = "jacoco.reset", defaultValue = "false") private boolean reset; /** * IP address or hostname to connect to. */ @Parameter(property = "jacoco.address") private String address; /** * Port number to connect to. If multiple JaCoCo agents should run on the * same machine, different ports have to be specified for the agents. */ @Parameter(property = "jacoco.port", defaultValue = "6300") private int port; /** * Number of retries which the goal will attempt to establish a connection. * This can be used to wait until the target JVM is successfully launched. */ @Parameter(property = "jacoco.retryCount", defaultValue = "10") private int retryCount; @Override public void executeMojo() throws MojoExecutionException { final ExecDumpClient client = new ExecDumpClient() { @Override protected void onConnecting(final InetAddress address, final int port) { getLog().info( format("Connecting to %s:%s", address, Integer.valueOf(port))); } @Override protected void onConnectionFailure(final IOException exception) { getLog().info(exception.getMessage()); } }; client.setDump(dump); client.setReset(reset); client.setRetryCount(retryCount); try { final ExecFileLoader loader = client.dump(address, port); if (dump) { getLog().info( format("Dumping execution data to %s", destFile.getAbsolutePath())); loader.save(destFile, append); } } catch (final IOException e) { throw new MojoExecutionException("Unable to dump coverage data", e); } } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/FileFilter.java000066400000000000000000000052471304217427400254500ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.StringUtils; /** * A file filter using includes/excludes patterns. */ public class FileFilter { private static final String DEFAULT_INCLUDES = "**"; private static final String DEFAULT_EXCLUDES = ""; private final List includes; private final List excludes; /** * Construct a new FileFilter * * @param includes * list of includes patterns * @param excludes * list of excludes patterns */ public FileFilter(final List includes, final List excludes) { this.includes = includes; this.excludes = excludes; } /** * Returns a list of file names. * * @param directory * the directory to scan * @return a list of files * @throws IOException * if file system access fails */ public List getFileNames(final File directory) throws IOException { return FileUtils.getFileNames(directory, getIncludes(), getExcludes(), false); } /** * Returns a list of files. * * @param directory * the directory to scan * @return a list of files * @throws IOException * if file system access fails */ public List getFiles(final File directory) throws IOException { return FileUtils.getFiles(directory, getIncludes(), getExcludes()); } /** * Get the includes pattern * * @return the pattern */ public String getIncludes() { return this.buildPattern(this.includes, DEFAULT_INCLUDES); } /** * Get the excludes pattern * * @return the pattern */ public String getExcludes() { return this.buildPattern(this.excludes, DEFAULT_EXCLUDES); } private String buildPattern(final List patterns, final String defaultPattern) { String pattern = defaultPattern; if (CollectionUtils.isNotEmpty(patterns)) { pattern = StringUtils.join(patterns.iterator(), ","); } return pattern; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/InstrumentMojo.java000066400000000000000000000065651304217427400264240ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.OfflineInstrumentationAccessGenerator; /** * Performs offline instrumentation. Note that after execution of test you must * restore original classes with help of "restore-instrumented-classes" goal. *

* Warning: The preferred way for code coverage analysis with * JaCoCo is on-the-fly instrumentation. Offline instrumentation has several * drawbacks and should only be used if a specific scenario explicitly requires * this mode. Please consult documentation about * offline instrumentation before using this mode. *

* * @since 0.6.2 */ @Mojo(name = "instrument", defaultPhase = LifecyclePhase.PROCESS_CLASSES, threadSafe = true) public class InstrumentMojo extends AbstractJacocoMojo { @Override public void executeMojo() throws MojoExecutionException, MojoFailureException { final File originalClassesDir = new File(getProject().getBuild() .getDirectory(), "generated-classes/jacoco"); originalClassesDir.mkdirs(); final File classesDir = new File( getProject().getBuild().getOutputDirectory()); if (!classesDir.exists()) { getLog().info( "Skipping JaCoCo execution due to missing classes directory:" + classesDir); return; } final List fileNames; try { fileNames = new FileFilter(this.getIncludes(), this.getExcludes()) .getFileNames(classesDir); } catch (final IOException e1) { throw new MojoExecutionException( "Unable to get list of files to instrument.", e1); } final Instrumenter instrumenter = new Instrumenter( new OfflineInstrumentationAccessGenerator()); for (final String fileName : fileNames) { if (fileName.endsWith(".class")) { final File source = new File(classesDir, fileName); final File backup = new File(originalClassesDir, fileName); InputStream input = null; OutputStream output = null; try { FileUtils.copyFile(source, backup); input = new FileInputStream(backup); output = new FileOutputStream(source); instrumenter.instrument(input, output, source.getPath()); } catch (final IOException e2) { throw new MojoExecutionException( "Unable to instrument file.", e2); } finally { IOUtil.close(input); IOUtil.close(output); } } } } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/MergeMojo.java000066400000000000000000000076111304217427400253040ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mads Mohr Christensen - implementation of MergeMojo * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.shared.model.fileset.FileSet; import org.apache.maven.shared.model.fileset.util.FileSetManager; import org.jacoco.core.tools.ExecFileLoader; /** * Mojo for merging a set of execution data files (*.exec) into a single file * * @since 0.6.4 */ @Mojo(name = "merge", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true) public class MergeMojo extends AbstractJacocoMojo { private static final String MSG_SKIPPING = "Skipping JaCoCo merge execution due to missing execution data files"; /** * Path to the output file for execution data. */ @Parameter(property = "jacoco.destFile", defaultValue = "${project.build.directory}/jacoco.exec") private File destFile; /** * This mojo accepts any number of execution data file sets. * * Note that you need an implementation hint on fileset * with Maven 2 (not needed with Maven 3): * *
	 * 
	 * <fileSets>
	 *   <fileSet implementation="org.apache.maven.shared.model.fileset.FileSet">
	 *     <directory>${project.build.directory}</directory>
	 *     <includes>
	 *       <include>*.exec</include>
	 *     </includes>
	 *   </fileSet>
	 * </fileSets>
	 * 
	 * 
*/ @Parameter(property = "jacoco.fileSets", required = true) private List fileSets; @Override protected void executeMojo() throws MojoExecutionException, MojoFailureException { if (!canMergeReports()) { return; } executeMerge(); } private boolean canMergeReports() { if (fileSets == null || fileSets.isEmpty()) { getLog().info(MSG_SKIPPING); return false; } return true; } private void executeMerge() throws MojoExecutionException { final ExecFileLoader loader = new ExecFileLoader(); load(loader); save(loader); } private void load(final ExecFileLoader loader) throws MojoExecutionException { final FileSetManager fileSetManager = new FileSetManager(getLog()); for (final FileSet fileSet : fileSets) { for (final String includedFilename : fileSetManager .getIncludedFiles(fileSet)) { final File inputFile = new File(fileSet.getDirectory(), includedFilename); if (inputFile.isDirectory()) { continue; } try { getLog().info( "Loading execution data file " + inputFile.getAbsolutePath()); loader.load(inputFile); } catch (final IOException e) { throw new MojoExecutionException("Unable to read " + inputFile.getAbsolutePath(), e); } } } } private void save(final ExecFileLoader loader) throws MojoExecutionException { if (loader.getExecutionDataStore().getContents().isEmpty()) { getLog().info(MSG_SKIPPING); return; } getLog().info( "Writing merged execution data to " + destFile.getAbsolutePath()); try { loader.save(destFile, false); } catch (final IOException e) { throw new MojoExecutionException("Unable to write merged file " + destFile.getAbsolutePath(), e); } } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/ReportAggregateMojo.java000066400000000000000000000137331304217427400273310ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * John Oliver, Marc R. Hoffmann, Jan Wloka - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Dependency; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.jacoco.report.IReportGroupVisitor; /** *

* Creates a structured code coverage report (HTML, XML, and CSV) from multiple * projects within reactor. The report is created from all modules this project * depends on. From those projects class and source files as well as JaCoCo * execution data files will be collected. In addition execution data is * collected from the project itself. This also allows to create coverage * reports when tests are in separate projects than the code under test, for * example in case of integration tests. *

* *

* Using the dependency scope allows to distinguish projects which contribute * execution data but should not become part of the report: *

* *
    *
  • compile: Project source and execution data is included in * the report.
  • *
  • test: Only execution data is considered for the report.
  • *
* * @since 0.7.7 */ @Mojo(name = "report-aggregate", threadSafe = true) public class ReportAggregateMojo extends AbstractReportMojo { /** * A list of execution data files to include in the report from each * project. May use wildcard characters (* and ?). When not specified all * *.exec files from the target folder will be included. */ @Parameter List dataFileIncludes; /** * A list of execution data files to exclude from the report. May use * wildcard characters (* and ?). When not specified nothing will be * excluded. */ @Parameter List dataFileExcludes; /** * Output directory for the reports. Note that this parameter is only * relevant if the goal is run from the command line or from the default * build lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is * used instead. */ @Parameter(defaultValue = "${project.reporting.outputDirectory}/jacoco-aggregate") private File outputDirectory; /** * The projects in the reactor. */ @Parameter(property = "reactorProjects", readonly = true) private List reactorProjects; @Override boolean canGenerateReportRegardingDataFiles() { return true; } @Override boolean canGenerateReportRegardingClassesDirectory() { return true; } @Override void loadExecutionData(final ReportSupport support) throws IOException { // https://issues.apache.org/jira/browse/MNG-5440 if (dataFileIncludes == null) { dataFileIncludes = Arrays.asList("target/*.exec"); } final FileFilter filter = new FileFilter(dataFileIncludes, dataFileExcludes); loadExecutionData(support, filter, getProject().getBasedir()); for (final MavenProject dependency : findDependencies( Artifact.SCOPE_COMPILE, Artifact.SCOPE_TEST)) { loadExecutionData(support, filter, dependency.getBasedir()); } } private void loadExecutionData(final ReportSupport support, final FileFilter filter, final File basedir) throws IOException { for (final File execFile : filter.getFiles(basedir)) { support.loadExecutionData(execFile); } } @Override void addFormatters(final ReportSupport support, final Locale locale) throws IOException { support.addAllFormatters(outputDirectory, outputEncoding, footer, locale); } @Override void createReport(final IReportGroupVisitor visitor, final ReportSupport support) throws IOException { final IReportGroupVisitor group = visitor.visitGroup(title); for (final MavenProject dependency : findDependencies(Artifact.SCOPE_COMPILE)) { support.processProject(group, dependency.getArtifactId(), dependency, getIncludes(), getExcludes(), sourceEncoding); } } @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } @Override public void setReportOutputDirectory(final File reportOutputDirectory) { if (reportOutputDirectory != null && !reportOutputDirectory.getAbsolutePath().endsWith( "jacoco-aggregate")) { outputDirectory = new File(reportOutputDirectory, "jacoco-aggregate"); } else { outputDirectory = reportOutputDirectory; } } public String getOutputName() { return "jacoco-aggregate/index"; } public String getName(final Locale locale) { return "JaCoCo Aggregate"; } private List findDependencies(final String... scopes) { final List result = new ArrayList(); final List scopeList = Arrays.asList(scopes); for (final Object dependencyObject : getProject().getDependencies()) { final Dependency dependency = (Dependency) dependencyObject; if (scopeList.contains(dependency.getScope())) { final MavenProject project = findProjectFromReactor(dependency); if (project != null) { result.add(project); } } } return result; } private MavenProject findProjectFromReactor(final Dependency d) { for (final MavenProject p : reactorProjects) { if (p.getGroupId().equals(d.getGroupId()) && p.getArtifactId().equals(d.getArtifactId()) && p.getVersion().equals(d.getVersion())) { return p; } } return null; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/ReportITMojo.java000066400000000000000000000062361304217427400257570ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.IOException; import java.util.Locale; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.jacoco.report.IReportGroupVisitor; /** * Same as report, but provides default values suitable for * integration-tests: *
    *
  • bound to report-integration phase
  • *
  • different dataFile
  • *
* * @since 0.6.4 */ @Mojo(name = "report-integration", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) public class ReportITMojo extends AbstractReportMojo { /** * Output directory for the reports. Note that this parameter is only * relevant if the goal is run from the command line or from the default * build lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is * used instead. */ @Parameter(defaultValue = "${project.reporting.outputDirectory}/jacoco-it") private File outputDirectory; /** * File with execution data. */ @Parameter(defaultValue = "${project.build.directory}/jacoco-it.exec") private File dataFile; @Override boolean canGenerateReportRegardingDataFiles() { return dataFile.exists(); } @Override boolean canGenerateReportRegardingClassesDirectory() { return new File(getProject().getBuild().getOutputDirectory()).exists(); } @Override void loadExecutionData(final ReportSupport support) throws IOException { support.loadExecutionData(dataFile); } @Override void addFormatters(final ReportSupport support, final Locale locale) throws IOException { support.addAllFormatters(outputDirectory, outputEncoding, footer, locale); } @Override void createReport(final IReportGroupVisitor visitor, final ReportSupport support) throws IOException { support.processProject(visitor, title, getProject(), getIncludes(), getExcludes(), sourceEncoding); } @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } @Override public void setReportOutputDirectory(final File reportOutputDirectory) { if (reportOutputDirectory != null && !reportOutputDirectory.getAbsolutePath().endsWith( "jacoco-it")) { outputDirectory = new File(reportOutputDirectory, "jacoco-it"); } else { outputDirectory = reportOutputDirectory; } } public String getOutputName() { return "jacoco-it/index"; } public String getName(final Locale locale) { return "JaCoCo IT"; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/ReportMojo.java000066400000000000000000000057731304217427400255270ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.IOException; import java.util.Locale; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.jacoco.report.IReportGroupVisitor; /** * Creates a code coverage report for tests of a single project in multiple * formats (HTML, XML, and CSV). * * @since 0.5.3 */ @Mojo(name = "report", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) public class ReportMojo extends AbstractReportMojo { /** * Output directory for the reports. Note that this parameter is only * relevant if the goal is run from the command line or from the default * build lifecycle. If the goal is run indirectly as part of a site * generation, the output directory configured in the Maven Site Plugin is * used instead. */ @Parameter(defaultValue = "${project.reporting.outputDirectory}/jacoco") private File outputDirectory; /** * File with execution data. */ @Parameter(property = "jacoco.dataFile", defaultValue = "${project.build.directory}/jacoco.exec") private File dataFile; @Override boolean canGenerateReportRegardingDataFiles() { return dataFile.exists(); } @Override boolean canGenerateReportRegardingClassesDirectory() { return new File(getProject().getBuild().getOutputDirectory()).exists(); } @Override void loadExecutionData(final ReportSupport support) throws IOException { support.loadExecutionData(dataFile); } @Override void addFormatters(final ReportSupport support, final Locale locale) throws IOException { support.addAllFormatters(outputDirectory, outputEncoding, footer, locale); } @Override void createReport(final IReportGroupVisitor visitor, final ReportSupport support) throws IOException { support.processProject(visitor, title, getProject(), getIncludes(), getExcludes(), sourceEncoding); } @Override protected String getOutputDirectory() { return outputDirectory.getAbsolutePath(); } @Override public void setReportOutputDirectory(final File reportOutputDirectory) { if (reportOutputDirectory != null && !reportOutputDirectory.getAbsolutePath().endsWith("jacoco")) { outputDirectory = new File(reportOutputDirectory, "jacoco"); } else { outputDirectory = reportOutputDirectory; } } public String getOutputName() { return "jacoco/index"; } public String getName(final Locale locale) { return "JaCoCo"; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/ReportSupport.java000066400000000000000000000227631304217427400262750ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * *******************************************************************************/ package org.jacoco.maven; import static java.lang.String.format; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.jacoco.core.analysis.Analyzer; import org.jacoco.core.analysis.CoverageBuilder; import org.jacoco.core.analysis.IBundleCoverage; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.tools.ExecFileLoader; import org.jacoco.report.FileMultiReportOutput; import org.jacoco.report.IReportGroupVisitor; import org.jacoco.report.IReportVisitor; import org.jacoco.report.ISourceFileLocator; import org.jacoco.report.MultiReportVisitor; import org.jacoco.report.check.IViolationsOutput; import org.jacoco.report.check.Rule; import org.jacoco.report.check.RulesChecker; import org.jacoco.report.csv.CSVFormatter; import org.jacoco.report.html.HTMLFormatter; import org.jacoco.report.xml.XMLFormatter; /** * Encapsulates the tasks to create reports for Maven projects. Instances are * supposed to be used in the following sequence: * *
    *
  1. Create an instance
  2. *
  3. Load one or multiple exec files with loadExecutionData()
  4. *
  5. Add one or multiple formatters with addXXX() methods
  6. *
  7. Create the root visitor with initRootVisitor()
  8. *
  9. Process one or multiple projects with processProject()
  10. *
*/ final class ReportSupport { private final Log log; private final ExecFileLoader loader; private final List formatters; /** * Construct a new instance with the given log output. * * @param log * for log output */ public ReportSupport(final Log log) { this.log = log; this.loader = new ExecFileLoader(); this.formatters = new ArrayList(); } /** * Loads the given execution data file. * * @param execFile * execution data file to load * @throws IOException * if the file can't be loaded */ public void loadExecutionData(final File execFile) throws IOException { log.info("Loading execution data file " + execFile); loader.load(execFile); } public void addXmlFormatter(final File targetfile, final String encoding) throws IOException { final XMLFormatter xml = new XMLFormatter(); xml.setOutputEncoding(encoding); formatters.add(xml.createVisitor(new FileOutputStream(targetfile))); } public void addCsvFormatter(final File targetfile, final String encoding) throws IOException { final CSVFormatter csv = new CSVFormatter(); csv.setOutputEncoding(encoding); formatters.add(csv.createVisitor(new FileOutputStream(targetfile))); } public void addHtmlFormatter(final File targetdir, final String encoding, final String footer, final Locale locale) throws IOException { final HTMLFormatter htmlFormatter = new HTMLFormatter(); htmlFormatter.setOutputEncoding(encoding); htmlFormatter.setLocale(locale); if (footer != null) { htmlFormatter.setFooterText(footer); } formatters.add(htmlFormatter.createVisitor(new FileMultiReportOutput( targetdir))); } public void addAllFormatters(final File targetdir, final String encoding, final String footer, final Locale locale) throws IOException { targetdir.mkdirs(); addXmlFormatter(new File(targetdir, "jacoco.xml"), encoding); addCsvFormatter(new File(targetdir, "jacoco.csv"), encoding); addHtmlFormatter(targetdir, encoding, footer, locale); } public void addRulesChecker(final List rules, final IViolationsOutput output) { final RulesChecker checker = new RulesChecker(); checker.setRules(rules); formatters.add(checker.createVisitor(output)); } public IReportVisitor initRootVisitor() throws IOException { final IReportVisitor visitor = new MultiReportVisitor(formatters); visitor.visitInfo(loader.getSessionInfoStore().getInfos(), loader .getExecutionDataStore().getContents()); return visitor; } /** * Calculates coverage for the given project and emits it to the report * group without source references * * @param visitor * group visitor to emit the project's coverage to * @param project * the MavenProject * @param includes * list of includes patterns * @param excludes * list of excludes patterns * @throws IOException * if class files can't be read */ public void processProject(final IReportGroupVisitor visitor, final MavenProject project, final List includes, final List excludes) throws IOException { processProject(visitor, project.getArtifactId(), project, includes, excludes, new NoSourceLocator()); } /** * Calculates coverage for the given project and emits it to the report * group including source references * * @param visitor * group visitor to emit the project's coverage to * @param bundeName * name for this project in the report * @param project * the MavenProject * @param includes * list of includes patterns * @param excludes * list of excludes patterns * @param srcEncoding * encoding of the source files within this project * @throws IOException * if class files can't be read */ public void processProject(final IReportGroupVisitor visitor, final String bundeName, final MavenProject project, final List includes, final List excludes, final String srcEncoding) throws IOException { processProject(visitor, bundeName, project, includes, excludes, new SourceFileCollection(project, srcEncoding)); } private void processProject(final IReportGroupVisitor visitor, final String bundeName, final MavenProject project, final List includes, final List excludes, final ISourceFileLocator locator) throws IOException { final CoverageBuilder builder = new CoverageBuilder(); final File classesDir = new File(project.getBuild() .getOutputDirectory()); if (classesDir.isDirectory()) { final Analyzer analyzer = new Analyzer( loader.getExecutionDataStore(), builder); final FileFilter filter = new FileFilter(includes, excludes); for (final File file : filter.getFiles(classesDir)) { analyzer.analyzeAll(file); } } final IBundleCoverage bundle = builder.getBundle(bundeName); logBundleInfo(bundle, builder.getNoMatchClasses()); visitor.visitBundle(bundle, locator); } private void logBundleInfo(final IBundleCoverage bundle, final Collection nomatch) { log.info(format("Analyzed bundle '%s' with %s classes", bundle.getName(), Integer.valueOf(bundle.getClassCounter().getTotalCount()))); if (!nomatch.isEmpty()) { log.warn(format( "Classes in bundle '%s' do no match with execution data. " + "For report generation the same class files must be used as at runtime.", bundle.getName())); for (final IClassCoverage c : nomatch) { log.warn(format("Execution data for class %s does not match.", c.getName())); } } if (bundle.getClassCounter().getTotalCount() > 0 && bundle.getLineCounter().getTotalCount() == 0) { log.warn("To enable source code annotation class files have to be compiled with debug information."); } } private class NoSourceLocator implements ISourceFileLocator { public Reader getSourceFile(final String packageName, final String fileName) { return null; } public int getTabWidth() { return 0; } } private class SourceFileCollection implements ISourceFileLocator { private final List sourceRoots; private final String encoding; public SourceFileCollection(final MavenProject project, final String encoding) { this.sourceRoots = getCompileSourceRoots(project); this.encoding = encoding; } public Reader getSourceFile(final String packageName, final String fileName) throws IOException { final String r; if (packageName.length() > 0) { r = packageName + '/' + fileName; } else { r = fileName; } for (final File sourceRoot : sourceRoots) { final File file = new File(sourceRoot, r); if (file.exists() && file.isFile()) { return new InputStreamReader(new FileInputStream(file), encoding); } } return null; } public int getTabWidth() { return 4; } } private static List getCompileSourceRoots(final MavenProject project) { final List result = new ArrayList(); for (final Object path : project.getCompileSourceRoots()) { result.add(resolvePath(project, (String) path)); } return result; } private static File resolvePath(final MavenProject project, final String path) { File file = new File(path); if (!file.isAbsolute()) { file = new File(project.getBasedir(), path); } return file; } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/RestoreMojo.java000066400000000000000000000031731304217427400256670ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.maven; import java.io.File; import java.io.IOException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.codehaus.plexus.util.FileUtils; /** * Restores original classes as they were before offline instrumentation. * * @since 0.6.2 */ @Mojo(name = "restore-instrumented-classes", defaultPhase = LifecyclePhase.PREPARE_PACKAGE, threadSafe = true) public class RestoreMojo extends AbstractJacocoMojo { @Override protected void executeMojo() throws MojoExecutionException, MojoFailureException { final File originalClassesDir = new File(getProject().getBuild() .getDirectory(), "generated-classes/jacoco"); final File classesDir = new File(getProject().getBuild() .getOutputDirectory()); try { FileUtils.copyDirectoryStructure(originalClassesDir, classesDir); } catch (final IOException e) { throw new MojoFailureException("Unable to restore classes.", e); } } } jacoco-0.7.8/jacoco-maven-plugin/src/org/jacoco/maven/RuleConfiguration.java000066400000000000000000000036221304217427400270550ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * Kyle Lieber - implementation of CheckMojo * Marc Hoffmann - redesign using report APIs * *******************************************************************************/ package org.jacoco.maven; import java.util.List; import org.codehaus.plexus.util.StringUtils; import org.jacoco.core.analysis.ICoverageNode.ElementType; import org.jacoco.report.check.Limit; import org.jacoco.report.check.Rule; /** * Wrapper for {@link Rule} objects to allow Maven style includes/excludes lists * */ public class RuleConfiguration { final Rule rule; /** * Create a new configuration instance. */ public RuleConfiguration() { rule = new Rule(); } /** * @param element * element type this rule applies to * TODO: use ElementType directly once Maven 3 is required. */ public void setElement(final String element) { rule.setElement(ElementType.valueOf(element)); } /** * @param includes * includes patterns */ public void setIncludes(final List includes) { rule.setIncludes(StringUtils.join(includes.iterator(), ":")); } /** * * @param excludes * excludes patterns */ public void setExcludes(final List excludes) { rule.setExcludes(StringUtils.join(excludes.iterator(), ":")); } /** * @param limits * list of {@link Limit}s configured for this rule */ public void setLimits(final List limits) { rule.setLimits(limits); } } jacoco-0.7.8/jacoco/000077500000000000000000000000001304217427400142265ustar00rootroot00000000000000jacoco-0.7.8/jacoco/.gitignore000066400000000000000000000000101304217427400162050ustar00rootroot00000000000000/target jacoco-0.7.8/jacoco/.project000066400000000000000000000005611304217427400156770ustar00rootroot00000000000000 jacoco org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature jacoco-0.7.8/jacoco/assembly.xml000066400000000000000000000075101304217427400165720ustar00rootroot00000000000000 distribution zip false ${basedir}/../org.jacoco.doc/docroot / true **/*.html ${basedir}/../org.jacoco.doc/target/generated-resources/xml/xslt /doc false *.html ${basedir}/../org.jacoco.doc/docroot / **/*.html ${basedir}/../org.jacoco.doc/target/site/jacoco-aggregate /coverage ${basedir}/../org.jacoco.doc/target/junit /test ${basedir}/../org.jacoco.report/src/org/jacoco/report/xml/report.dtd /coverage lib jacocoant.jar false ${project.groupId}:org.jacoco.ant:jar:nodeps lib jacocoagent.jar false ${project.groupId}:org.jacoco.agent:*:runtime lib ${artifact.artifactId}-${qualified.bundle.version}.${artifact.extension} false ${project.groupId}:org.jacoco.core ${project.groupId}:org.jacoco.report ${project.groupId}:org.jacoco.agent ${project.groupId}:org.jacoco.ant ${project.groupId}:org.jacoco.agent:*:runtime ${project.groupId}:org.jacoco.ant:*:nodeps /doc true false ${project.groupId}:org.jacoco.examples:zip /doc/api true false META-INF/ ${project.groupId}:org.jacoco.doc:*:javadoc jacoco-0.7.8/jacoco/pom.xml000066400000000000000000000074571304217427400155600ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.build 0.7.8 ../org.jacoco.build jacoco pom JaCoCo :: Distribution JaCoCo Standalone Distribution ${project.groupId} org.jacoco.core ${project.groupId} org.jacoco.report ${project.groupId} org.jacoco.agent ${project.groupId} org.jacoco.agent ${project.version} runtime ${project.groupId} org.jacoco.ant ${project.groupId} org.jacoco.ant nodeps ${project.groupId} org.jacoco.examples ${project.version} zip ${project.groupId} org.jacoco.doc ${project.version} javadoc src org.apache.maven.plugins maven-assembly-plugin package single jacoco-${qualified.bundle.version} false assembly.xml org.apache.maven.plugins maven-enforcer-plugin enforce-distribution-size enforce verify 3500000 2500000 ${project.build.directory}/jacoco-${qualified.bundle.version}.zip jacoco-0.7.8/org.jacoco.agent.rt.test/000077500000000000000000000000001304217427400175135ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/.classpath000066400000000000000000000014151304217427400214770ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.agent.rt.test/.gitignore000066400000000000000000000000301304217427400214740ustar00rootroot00000000000000/target /bin /.settings jacoco-0.7.8/org.jacoco.agent.rt.test/.project000066400000000000000000000013771304217427400211720ustar00rootroot00000000000000 org.jacoco.agent.rt.test org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core.test/.settings jacoco-0.7.8/org.jacoco.agent.rt.test/about.html000066400000000000000000000014761304217427400215230ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

jacoco-0.7.8/org.jacoco.agent.rt.test/pom.xml000066400000000000000000000024671304217427400210410ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.tests 0.7.8 ../org.jacoco.tests org.jacoco.agent.rt.test JaCoCo :: Test :: Agent RT org.jacoco.agent.rt.* ${project.groupId} org.jacoco.agent.rt junit junit jacoco-0.7.8/org.jacoco.agent.rt.test/src/000077500000000000000000000000001304217427400203025ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/000077500000000000000000000000001304217427400210715ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/000077500000000000000000000000001304217427400223275ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/000077500000000000000000000000001304217427400234255ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/000077500000000000000000000000001304217427400240525ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/000077500000000000000000000000001304217427400256665ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/AgentTest.java000066400000000000000000000172071304217427400304360ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.ObjectName; import org.jacoco.agent.rt.internal.output.IAgentOutput; import org.jacoco.agent.rt.internal.output.FileOutput; import org.jacoco.agent.rt.internal.output.NoneOutput; import org.jacoco.agent.rt.internal.output.TcpClientOutput; import org.jacoco.agent.rt.internal.output.TcpServerOutput; import org.jacoco.core.JaCoCo; import org.jacoco.core.data.ExecutionDataReader; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.AgentOptions.OutputMode; import org.jacoco.core.runtime.RuntimeData; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link Agent}. */ public class AgentTest implements IExceptionLogger { @Rule public TemporaryFolder folder = new TemporaryFolder(); private AgentOptions options; private File execfile; private Exception exception; @Before public void setup() { options = new AgentOptions(); execfile = new File(folder.getRoot(), "jacoco.exec"); options.setOutput(OutputMode.file); options.setDestfile(execfile.getAbsolutePath()); } @Test public void testCreateController() { Agent agent = new Agent(options, this); options.setOutput(OutputMode.file); assertEquals(FileOutput.class, agent.createAgentOutput() .getClass()); options.setOutput(OutputMode.tcpserver); assertEquals(TcpServerOutput.class, agent.createAgentOutput() .getClass()); options.setOutput(OutputMode.tcpclient); assertEquals(TcpClientOutput.class, agent.createAgentOutput() .getClass()); options.setOutput(OutputMode.none); assertEquals(NoneOutput.class, agent.createAgentOutput() .getClass()); } @Test public void testStartupShutdown() throws Exception { options.setSessionId("testsession"); Agent agent = new Agent(options, this); agent.startup(); assertEquals("testsession", agent.getData().getSessionId()); agent.shutdown(); assertTrue(execfile.isFile()); assertTrue(execfile.length() > 0); assertNull(exception); } @Test public void testShutdownWithException() throws Exception { final Exception expected = new Exception(); Agent agent = new Agent(options, this) { @Override IAgentOutput createAgentOutput() { return new IAgentOutput() { public void startup(AgentOptions options, RuntimeData data) { } public void shutdown() throws Exception { throw expected; } public void writeExecutionData(boolean reset) { } }; } }; agent.startup(); agent.shutdown(); assertSame(expected, exception); } @Test public void testNoSessionId() throws Exception { Agent agent = new Agent(options, this); final String defaultId = agent.getData().getSessionId(); agent.startup(); assertFalse(defaultId.equals(agent.getData().getSessionId())); assertNull(exception); } @Test public void testNoDumpOnExit() throws Exception { options.setDumpOnExit(false); Agent agent = new Agent(options, this); agent.startup(); agent.shutdown(); assertEquals(0, execfile.length()); assertNull(exception); } @Test public void testInvalidExecFile() throws Exception { options.setDestfile(folder.getRoot().getAbsolutePath()); Agent agent = new Agent(options, this); agent.startup(); assertTrue(exception instanceof IOException); } @Test public void testGetVersion() { Agent agent = new Agent(options, this); assertEquals(JaCoCo.VERSION, agent.getVersion()); } @Test public void testGetSetSessionId() throws IOException { Agent agent = new Agent(options, this); agent.startup(); agent.setSessionId("agenttestid"); assertEquals("agenttestid", agent.getSessionId()); SessionInfoStore sessionStore = new SessionInfoStore(); ExecutionDataReader reader = new ExecutionDataReader( new ByteArrayInputStream(agent.getExecutionData(false))); reader.setSessionInfoVisitor(sessionStore); reader.read(); assertEquals("agenttestid", sessionStore.getInfos().get(0).getId()); } @Test public void testReset() { Agent agent = new Agent(options, this); boolean[] probes = agent.getData() .getExecutionData(Long.valueOf(0x12345678), "Foo", 1) .getProbes(); probes[0] = true; agent.reset(); assertFalse(probes[0]); } @Test public void testGetExecutionData() throws IOException { options.setSessionId("agenttestid"); Agent agent = new Agent(options, this); agent.startup(); boolean[] probes = agent.getData() .getExecutionData(Long.valueOf(0x12345678), "Foo", 1) .getProbes(); probes[0] = true; byte[] data = agent.getExecutionData(true); // ensure reset has been executed assertFalse(probes[0]); ExecutionDataStore execStore = new ExecutionDataStore(); SessionInfoStore sessionStore = new SessionInfoStore(); ExecutionDataReader reader = new ExecutionDataReader( new ByteArrayInputStream(data)); reader.setExecutionDataVisitor(execStore); reader.setSessionInfoVisitor(sessionStore); reader.read(); assertEquals("Foo", execStore.get(0x12345678).getName()); assertEquals(1, sessionStore.getInfos().size()); assertEquals("agenttestid", sessionStore.getInfos().get(0).getId()); } @Test public void testDump() throws Exception { final boolean[] called = new boolean[1]; Agent agent = new Agent(options, this) { @Override IAgentOutput createAgentOutput() { return new IAgentOutput() { public void startup(AgentOptions options, RuntimeData data) { } public void shutdown() throws Exception { } public void writeExecutionData(boolean reset) { assertTrue(reset); called[0] = true; } }; } }; agent.startup(); agent.dump(true); assertTrue(called[0]); } @Test public void testJmx() throws Exception { options.setJmx(true); Agent agent = new Agent(options, this); agent.startup(); ObjectName objectName = new ObjectName("org.jacoco:type=Runtime"); final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); assertEquals(JaCoCo.VERSION, server.getAttribute(objectName, "Version")); agent.shutdown(); try { server.getMBeanInfo(objectName); fail("InstanceNotFoundException expected"); } catch (InstanceNotFoundException expected) { } } @Test(expected = InstanceNotFoundException.class) public void testNoJmx() throws Exception { Agent agent = new Agent(options, this); agent.startup(); ObjectName objectName = new ObjectName("org.jacoco:type=Runtime"); ManagementFactory.getPlatformMBeanServer().getMBeanInfo(objectName); } // === IExceptionLogger === public void logExeption(Exception ex) { exception = ex; } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/ClassFileDumperTest.java000066400000000000000000000045021304217427400324140ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import static org.junit.Assert.assertArrayEquals; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link ClassFileDumper}. */ public class ClassFileDumperTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); private byte[] contents; @Before public void setup() throws IOException { contents = "just some bytes".getBytes("UTF-8"); } @Test public void testDumpClassWithPackage() throws IOException { final File location = new File(folder.getRoot(), "classes"); final ClassFileDumper dumper = new ClassFileDumper(location.toString()); dumper.dump("org/jacoco/examples/Foo$Inner", contents); assertContents(location, "org/jacoco/examples/Foo$Inner.aff06045a340cd62.class"); } @Test public void testDumpClassInDefaultPackage() throws IOException { final File location = new File(folder.getRoot(), "classes"); final ClassFileDumper dumper = new ClassFileDumper(location.toString()); dumper.dump("Main", contents); assertContents(location, "Main.aff06045a340cd62.class"); } @Test public void testNoDumps() throws IOException { final ClassFileDumper dumper = new ClassFileDumper(null); dumper.dump("Main", contents); } private void assertContents(File location, String filename) throws IOException { InputStream in = new FileInputStream(new File(location, filename)); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int b; while ((b = in.read()) != -1) { buffer.write(b); } in.close(); assertArrayEquals(contents, buffer.toByteArray()); } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/ConfigLoaderTest.java000066400000000000000000000045251304217427400317330ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Properties; import org.junit.Test; /** * Unit tests for {@link ConfigLoader}. */ public class ConfigLoaderTest { @Test public void testResource() { Properties system = new Properties(); Properties config = ConfigLoader.load( "/org/jacoco/agent/rt/internal/agent-test.properties", system); assertEquals("tcpclient", config.get("output")); } @Test public void testNoResource() { Properties system = new Properties(); Properties config = ConfigLoader.load("does-not-exist.properties", system); assertTrue(config.isEmpty()); } @Test public void testSystemProperties() { Properties system = new Properties(); system.setProperty("jacoco-agent.output", "mbean"); system.setProperty("output", "tcpserver"); // no prefix system.setProperty("jacoco-agent.sessionid", "testid"); Properties config = ConfigLoader.load( "/org/jacoco/agent/rt/internal/agent-test.properties", system); assertEquals("mbean", config.get("output")); assertEquals("3333", config.get("port")); assertEquals("testid", config.get("sessionid")); } @Test public void testSubstituteProperties() { Properties system = new Properties(); system.setProperty("user.home", "/home/jacoco"); system.setProperty("java.version", "1.5.0"); Properties config = ConfigLoader.load( "/org/jacoco/agent/rt/internal/agent-subst-test.properties", system); assertEquals("no$replace}", config.get("key0")); assertEquals("/home/jacoco/coverage/jacoco-1.5.0.exec", config.get("key1")); assertEquals("$/home/jacoco", config.get("key2")); assertEquals("/home/jacoco}}", config.get("key3")); assertEquals("${does.not.exist}", config.get("key4")); } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/CoverageTransformerTest.java000066400000000000000000000177401304217427400333600ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.IllegalClassFormatException; import java.security.CodeSource; import java.security.ProtectionDomain; import java.security.cert.Certificate; import org.jacoco.core.JaCoCo; import org.jacoco.core.runtime.AbstractRuntime; import org.jacoco.core.runtime.AgentOptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.MethodVisitor; /** * Unit tests for {@link CoverageTransformer}. */ public class CoverageTransformerTest { private ExceptionRecorder recorder; private AgentOptions options; private ClassLoader classLoader; private ProtectionDomain protectionDomain; private StubRuntime runtime; @Before public void setup() { recorder = new ExceptionRecorder(); options = new AgentOptions(); classLoader = getClass().getClassLoader(); protectionDomain = getClass().getProtectionDomain(); runtime = new StubRuntime(); } @After public void teardown() { recorder.assertNoException(); } @Test public void testFilterAgentClass() { CoverageTransformer t = createTransformer(); assertFalse(t.filter(classLoader, "org/jacoco/agent/rt/internal/somepkg/SomeClass", protectionDomain)); } @Test public void testFilterInclBootstrapClassesPositive() { options.setInclBootstrapClasses(true); CoverageTransformer t = createTransformer(); assertTrue(t.filter(null, "java/util/TreeSet", protectionDomain)); } @Test public void testFilterInclBootstrapClassesNegative() { options.setInclBootstrapClasses(false); CoverageTransformer t = createTransformer(); assertFalse(t.filter(null, "java/util/TreeSet", protectionDomain)); } @Test public void testFilterClassLoaderPositive1() { options.setInclBootstrapClasses(false); options.setExclClassloader("org.jacoco.agent.SomeWhere$*"); CoverageTransformer t = createTransformer(); assertTrue(t.filter(classLoader, "org/example/Foo", protectionDomain)); } @Test public void testFilterClassLoaderPositive2() { options.setInclBootstrapClasses(true); options.setExclClassloader("org.jacoco.agent.SomeWhere$*"); CoverageTransformer t = createTransformer(); assertTrue(t.filter(classLoader, "org/example/Foo", protectionDomain)); } @Test public void testFilterClassLoaderNegative1() { options.setInclBootstrapClasses(false); options.setExclClassloader("org.jacoco.agent.rt.internal.CoverageTransformerTest$*"); CoverageTransformer t = createTransformer(); ClassLoader myClassLoader = new ClassLoader(null) { }; assertFalse(t .filter(myClassLoader, "org/example/Foo", protectionDomain)); } @Test public void testFilterClassLoaderNegative2() { options.setInclBootstrapClasses(true); options.setExclClassloader("org.jacoco.agent.rt.internal.CoverageTransformerTest$*"); CoverageTransformer t = createTransformer(); ClassLoader myClassLoader = new ClassLoader(null) { }; assertFalse(t .filter(myClassLoader, "org/example/Foo", protectionDomain)); } @Test public void testFilterIncludedClassPositive() { options.setIncludes("org.jacoco.core.*:org.jacoco.agent.rt.*"); CoverageTransformer t = createTransformer(); assertTrue(t.filter(classLoader, "org/jacoco/core/Foo", protectionDomain)); } @Test public void testFilterIncludedClassNegative() { options.setIncludes("org.jacoco.core.*:org.jacoco.agent.rt.*"); CoverageTransformer t = createTransformer(); assertFalse(t.filter(classLoader, "org/jacoco/report/Foo", protectionDomain)); } @Test public void testFilterExcludedClassPositive() { options.setExcludes("*Test"); CoverageTransformer t = createTransformer(); assertFalse(t.filter(classLoader, "org/jacoco/core/FooTest", protectionDomain)); } @Test public void testFilterExcludedClassPositiveInner() { options.setExcludes("org.jacoco.example.Foo$Inner"); CoverageTransformer t = createTransformer(); assertFalse(t.filter(classLoader, "org/jacoco/example/Foo$Inner", protectionDomain)); } @Test public void testFilterExcludedClassNegative() { options.setExcludes("*Test"); CoverageTransformer t = createTransformer(); assertTrue(t.filter(classLoader, "org/jacoco/core/Foo", protectionDomain)); } @Test public void testFilterSourceLocationPositive1() { CoverageTransformer t = createTransformer(); assertFalse(t.filter(classLoader, "org/jacoco/core/Foo", null)); } @Test public void testFilterSourceLocationPositive2() { CoverageTransformer t = createTransformer(); ProtectionDomain pd = new ProtectionDomain(null, null); assertFalse(t.filter(classLoader, "org/jacoco/core/Foo", pd)); } @Test public void testFilterSourceLocationPositive3() { CoverageTransformer t = createTransformer(); CodeSource cs = new CodeSource(null, new Certificate[0]); ProtectionDomain pd = new ProtectionDomain(cs, null); assertFalse(t.filter(classLoader, "org/jacoco/core/Foo", pd)); } @Test public void testFilterSourceLocationNegative() { options.setInclNoLocationClasses(true); CoverageTransformer t = createTransformer(); assertTrue(t.filter(classLoader, "org/jacoco/core/Foo", null)); } @Test public void testTransformFiltered1() throws IllegalClassFormatException { CoverageTransformer t = createTransformer(); assertNull(t.transform(classLoader, "org.jacoco.Sample", null, null, new byte[0])); } @Test public void testTransformFiltered2() throws IllegalClassFormatException { CoverageTransformer t = createTransformer(); assertNull(t.transform((ClassLoader) null, "org.jacoco.Sample", null, protectionDomain, new byte[0])); } @Test public void testTransformFailure() { CoverageTransformer t = createTransformer(); try { t.transform(classLoader, "org.jacoco.Sample", null, protectionDomain, null); fail("IllegalClassFormatException expected."); } catch (IllegalClassFormatException e) { assertEquals("Error while instrumenting class org.jacoco.Sample.", e.getMessage()); } recorder.assertException(IllegalClassFormatException.class, "Error while instrumenting class org.jacoco.Sample.", IOException.class); recorder.clear(); } @Test public void testRedefinedClass() throws Exception { CoverageTransformer t = createTransformer(); // Just pick any non-system class outside our namespace final Class target = JaCoCo.class; assertNull(t.transform(classLoader, target.getName(), target, protectionDomain, getClassData(target))); } private CoverageTransformer createTransformer() { return new CoverageTransformer(runtime, options, recorder); } private static byte[] getClassData(Class clazz) throws IOException { final String resource = "/" + clazz.getName().replace('.', '/') + ".class"; final InputStream in = clazz.getResourceAsStream(resource); final ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[0x100]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } in.close(); return out.toByteArray(); } private static class StubRuntime extends AbstractRuntime { public StubRuntime() { } public int generateDataAccessor(long classid, String classname, int probecount, MethodVisitor mv) { return 0; } public void shutdown() { } } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/ExceptionRecorder.java000066400000000000000000000034621304217427400321620ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.jacoco.agent.rt.internal.IExceptionLogger; /** * {@link IExceptionLogger} implementation for testing purposes. */ public class ExceptionRecorder implements IExceptionLogger { private Class exceptionType; private String message; private Class causeType; public void logExeption(Exception ex) { assertNull("multiple exeptions", exceptionType); exceptionType = ex.getClass(); message = ex.getMessage(); causeType = ex.getCause() == null ? null : ex.getCause().getClass(); } public void clear() { exceptionType = null; message = null; causeType = null; } public void assertNoException() { assertNull(exceptionType); } public void assertException(final Class exceptionType, final String message) { assertEquals(exceptionType, this.exceptionType); assertEquals(message, this.message); } public void assertException(final Class exceptionType, final String message, final Class causeType) { assertEquals(exceptionType, this.exceptionType); assertEquals(message, this.message); assertEquals(causeType, this.causeType); } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/agent-subst-test.properties000066400000000000000000000002051304217427400332120ustar00rootroot00000000000000key0=no$replace} key1=${user.home}/coverage/jacoco-${java.version}.exec key2=$${user.home} key3=${user.home}}} key4=${does.not.exist}jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/agent-test.properties000066400000000000000000000000321304217427400320520ustar00rootroot00000000000000output=tcpclient port=3333jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/000077500000000000000000000000001304217427400272265ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/ExecutorTestBase.java000066400000000000000000000031361304217427400333250ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import static org.junit.Assert.fail; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.After; import org.junit.Before; /** * Unit tests base for tests that need an {@link Executor} for multithreaded * test scenarios. */ public abstract class ExecutorTestBase { protected ExecutorService executor; @Before public void setup() throws Exception { executor = Executors.newSingleThreadExecutor(); } @After public void teardown() throws Exception { executor.shutdown(); } /** * Asserts that the given future blocks. * * @param future * future to test * @throws Exception */ protected void assertBlocks(final Future future) throws Exception { try { future.get(10, TimeUnit.MILLISECONDS); fail("Operation should block"); } catch (TimeoutException e) { } } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/FileOutputTest.java000066400000000000000000000046541304217427400330420ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.jacoco.agent.rt.internal.output.FileOutput; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RuntimeData; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link FileOutput}. */ public class FileOutputTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testCreateDestFileOnStartup() throws Exception { File destFile = folder.newFile("jacoco.exec"); AgentOptions options = new AgentOptions(); options.setDestfile(destFile.getAbsolutePath()); FileOutput controller = new FileOutput(); controller.startup(options, new RuntimeData()); assertTrue("Execution data file should be created", destFile.exists()); assertEquals("Execution data file should be empty", 0, destFile.length()); } @Test public void testWriteData() throws Exception { File destFile = folder.newFile("jacoco.exec"); AgentOptions options = new AgentOptions(); options.setDestfile(destFile.getAbsolutePath()); FileOutput controller = new FileOutput(); controller.startup(options, new RuntimeData()); controller.writeExecutionData(false); controller.shutdown(); assertTrue("Execution data file should be created", destFile.exists()); assertTrue("Execution data file should have contents", destFile.length() > 0); } @Test(expected = IOException.class) public void testInvalidDestFile() throws Exception { AgentOptions options = new AgentOptions(); options.setDestfile(folder.newFolder("folder").getAbsolutePath()); FileOutput controller = new FileOutput(); // Startup should fail as the file can not be created: controller.startup(options, new RuntimeData()); } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/MockServerSocket.java000066400000000000000000000100611304217427400333200ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.ServerSocketChannel; /** * Emulation of a {@link ServerSocket} for testing purposes without any physical * tcp/ip connections. */ public class MockServerSocket extends ServerSocket { private final Object lock = new Object(); private boolean closed; private Socket connection; private boolean inAccept; public MockServerSocket() throws IOException { super(); closed = false; inAccept = false; } /** * Establishes a new mock connection. This method blocks until the other end * of the connection has been accepted. * * @return remote end of the mock connection */ public Socket connect() throws Exception { synchronized (lock) { final MockSocketConnection c = new MockSocketConnection(); connection = c.getSocketA(); lock.notifyAll(); while (connection != null) { lock.wait(); } return c.getSocketB(); } } /** * Blocks until another thread calls the {@link #accept()} method. */ public void waitForAccept() throws Exception { synchronized (lock) { while (!inAccept) { lock.wait(); } } } @Override public void close() throws IOException { synchronized (lock) { closed = true; lock.notifyAll(); } } @Override public boolean isClosed() { return closed; } @Override public Socket accept() throws IOException { synchronized (lock) { inAccept = true; lock.notifyAll(); try { while (connection == null) { if (closed) { throw new SocketException("socket closed"); } lock.wait(); } return connection; } catch (InterruptedException e) { throw new InterruptedIOException(); } finally { connection = null; inAccept = false; lock.notifyAll(); } } } // unsupported server socket methods: @Override public void bind(SocketAddress endpoint, int backlog) throws IOException { throw new AssertionError(); } @Override public void bind(SocketAddress endpoint) throws IOException { throw new AssertionError(); } @Override public ServerSocketChannel getChannel() { throw new AssertionError(); } @Override public InetAddress getInetAddress() { throw new AssertionError(); } @Override public int getLocalPort() { throw new AssertionError(); } @Override public SocketAddress getLocalSocketAddress() { throw new AssertionError(); } @Override public synchronized int getReceiveBufferSize() throws SocketException { throw new AssertionError(); } @Override public boolean getReuseAddress() throws SocketException { throw new AssertionError(); } @Override public synchronized int getSoTimeout() throws IOException { throw new AssertionError(); } @Override public boolean isBound() { throw new AssertionError(); } @Override public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { throw new AssertionError(); } @Override public synchronized void setReceiveBufferSize(int size) throws SocketException { throw new AssertionError(); } @Override public void setReuseAddress(boolean on) throws SocketException { throw new AssertionError(); } @Override public synchronized void setSoTimeout(int timeout) throws SocketException { throw new AssertionError(); } @Override public String toString() { throw new AssertionError(); } } MockServerSocketTest.java000066400000000000000000000077231304217427400341140ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link MockServerSocket}. */ public class MockServerSocketTest extends ExecutorTestBase { private ServerSocket serverSocket; /** * To verify that the tests reflect the behavior of real TCP sockets this * flag can be set to true. */ private static final boolean REAL_SOCKETS = Boolean .getBoolean("MockServerSocketTest.realSockets"); @Before @Override public void setup() throws Exception { super.setup(); if (REAL_SOCKETS) { System.err.println("Using Real Sockets!"); final InetAddress addr = InetAddress.getByName("localhost"); serverSocket = new ServerSocket(16300, 1, addr); } else { serverSocket = new MockServerSocket(); } } @After @Override public void teardown() throws Exception { serverSocket.close(); super.teardown(); } private Socket connect() throws Exception { if (REAL_SOCKETS) { final InetAddress addr = InetAddress.getByName("localhost"); return new Socket(addr, 16300); } else { return ((MockServerSocket) serverSocket).connect(); } } @Test public void testClose() throws Exception { assertFalse(serverSocket.isClosed()); serverSocket.close(); assertTrue(serverSocket.isClosed()); } @Test(expected = SocketException.class) public void testCloseWhileAccept() throws Throwable { final Future f = executor.submit(new Callable() { public Socket call() throws Exception { return serverSocket.accept(); } }); assertBlocks(f); serverSocket.close(); try { f.get(); } catch (ExecutionException e) { throw e.getCause(); } } @Test public void testAccept() throws Exception { final Future f = executor.submit(new Callable() { public Socket call() throws Exception { return serverSocket.accept(); } }); assertBlocks(f); connect().getOutputStream().write(123); final Socket socket = f.get(); assertNotNull(socket); assertEquals(123, socket.getInputStream().read()); } @Test(expected = SocketException.class) public void testAcceptOnClosedServerSocket() throws Exception { serverSocket.close(); serverSocket.accept(); } @Test public void testConnect() throws Exception { if (!REAL_SOCKETS) { final Future f = executor.submit(new Callable() { public Socket call() throws Exception { return ((MockServerSocket) serverSocket).connect(); } }); assertBlocks(f); serverSocket.accept().getOutputStream().write(42); final Socket socket = f.get(); assertNotNull(socket); assertEquals(42, socket.getInputStream().read()); } } @Test public void testWaitForAccept() throws Exception { if (!REAL_SOCKETS) { final Future f = executor.submit(new Callable() { public Void call() throws Exception { ((MockServerSocket) serverSocket).waitForAccept(); connect(); return null; } }); assertBlocks(f); serverSocket.accept(); f.get(); } } } MockSocketConnection.java000066400000000000000000000163311304217427400341000ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketImpl; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * Simulates two connected {@link Socket} objects. No physical connection is * established for this. The behavior includes the (inconsistent) exception * messages have been derived from Sun JDK 1.5.0_18-b02. */ public class MockSocketConnection { private final MockSocket socketA; private final MockSocket socketB; public MockSocketConnection() throws SocketException { socketA = new MockSocket(); socketB = new MockSocket(); socketA.connect(socketB); } public Socket getSocketA() { return socketA; } public Socket getSocketB() { return socketB; } private class MockSocket extends Socket { private MockSocket other; private boolean closed; private final Queue buffer = new ConcurrentLinkedQueue(); private final OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { if (closed) { throw new SocketException("Socket closed"); } synchronized (other.buffer) { other.buffer.add(Byte.valueOf((byte) b)); other.buffer.notifyAll(); } } }; private final InputStream in = new InputStream() { @Override public int read() throws IOException { synchronized (buffer) { try { while (true) { if (closed) { throw new SocketException("socket closed"); } if (other.closed) { return -1; } final Byte b = buffer.poll(); if (b != null) { return 0xff & b.intValue(); } buffer.wait(); } } catch (InterruptedException e) { throw new InterruptedIOException(); } } } @Override public int available() throws IOException { return buffer.size(); } }; public MockSocket() throws SocketException { super((SocketImpl) null); closed = false; } void connect(MockSocket other) { this.other = other; other.other = this; } // socket methods with mocking behavior: @Override public OutputStream getOutputStream() throws IOException { if (closed) { throw new SocketException("Socket is closed"); } return out; } @Override public InputStream getInputStream() throws IOException { if (closed) { throw new SocketException("Socket is closed"); } return in; } @Override public void close() throws IOException { closed = true; synchronized (buffer) { buffer.notifyAll(); } synchronized (other.buffer) { other.buffer.notifyAll(); } } @Override public boolean isClosed() { return closed; } // unsupported socket methods: @Override public void bind(SocketAddress bindpoint) throws IOException { throw new AssertionError(); } @Override public void connect(SocketAddress endpoint, int timeout) throws IOException { throw new AssertionError(); } @Override public void connect(SocketAddress endpoint) throws IOException { throw new AssertionError(); } @Override public SocketChannel getChannel() { throw new AssertionError(); } @Override public InetAddress getInetAddress() { throw new AssertionError(); } @Override public boolean getKeepAlive() throws SocketException { throw new AssertionError(); } @Override public InetAddress getLocalAddress() { throw new AssertionError(); } @Override public int getLocalPort() { throw new AssertionError(); } @Override public SocketAddress getLocalSocketAddress() { throw new AssertionError(); } @Override public boolean getOOBInline() throws SocketException { throw new AssertionError(); } @Override public int getPort() { throw new AssertionError(); } @Override public synchronized int getReceiveBufferSize() throws SocketException { throw new AssertionError(); } @Override public SocketAddress getRemoteSocketAddress() { throw new AssertionError(); } @Override public boolean getReuseAddress() throws SocketException { throw new AssertionError(); } @Override public synchronized int getSendBufferSize() throws SocketException { throw new AssertionError(); } @Override public int getSoLinger() throws SocketException { throw new AssertionError(); } @Override public synchronized int getSoTimeout() throws SocketException { throw new AssertionError(); } @Override public boolean getTcpNoDelay() throws SocketException { throw new AssertionError(); } @Override public int getTrafficClass() throws SocketException { throw new AssertionError(); } @Override public boolean isBound() { throw new AssertionError(); } @Override public boolean isConnected() { throw new AssertionError(); } @Override public boolean isInputShutdown() { throw new AssertionError(); } @Override public boolean isOutputShutdown() { throw new AssertionError(); } @Override public void sendUrgentData(int data) throws IOException { throw new AssertionError(); } @Override public void setKeepAlive(boolean on) throws SocketException { throw new AssertionError(); } @Override public void setOOBInline(boolean on) throws SocketException { throw new AssertionError(); } @Override public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { throw new AssertionError(); } @Override public synchronized void setReceiveBufferSize(int size) throws SocketException { throw new AssertionError(); } @Override public void setReuseAddress(boolean on) throws SocketException { throw new AssertionError(); } @Override public synchronized void setSendBufferSize(int size) throws SocketException { throw new AssertionError(); } @Override public void setSoLinger(boolean on, int linger) throws SocketException { throw new AssertionError(); } @Override public synchronized void setSoTimeout(int timeout) throws SocketException { throw new AssertionError(); } @Override public void setTcpNoDelay(boolean on) throws SocketException { throw new AssertionError(); } @Override public void setTrafficClass(int tc) throws SocketException { throw new AssertionError(); } @Override public void shutdownInput() throws IOException { throw new AssertionError(); } @Override public void shutdownOutput() throws IOException { throw new AssertionError(); } } } MockSocketConnectionTest.java000066400000000000000000000111271304217427400347360ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link MockSocketConnection}. */ public class MockSocketConnectionTest extends ExecutorTestBase { /** * To verify that the tests reflect the behavior of real TCP sockets this * flag can be set to true. */ private static final boolean REAL_SOCKETS = Boolean .getBoolean("MockSocketConnectionTest.realSockets"); private Socket a; private Socket b; @Before @Override public void setup() throws Exception { super.setup(); if (REAL_SOCKETS) { createRealSockets(); } else { createMockSockets(); } } private void createMockSockets() throws Exception { final MockSocketConnection con = new MockSocketConnection(); a = con.getSocketA(); b = con.getSocketB(); } private void createRealSockets() throws Exception { System.err.println("Using Real Sockets!"); final InetAddress addr = InetAddress.getByName("localhost"); ServerSocket ssocket = new ServerSocket(16300, 1, addr); a = new Socket(addr, 16300); b = ssocket.accept(); ssocket.close(); } @Test public void testIsClosed() throws Exception { assertFalse(a.isClosed()); a.close(); assertTrue(a.isClosed()); } @Test(expected = SocketException.class) public void testGetInputStreamOnClosedSocket() throws Exception { a.close(); a.getInputStream(); } @Test(expected = SocketException.class) public void testReadOnClosedSocket() throws Exception { final InputStream in = a.getInputStream(); a.close(); in.read(); } @Test(expected = SocketException.class) public void testReadOnClosedSocketAsync() throws Throwable { final InputStream in = a.getInputStream(); final Future f = executor.submit(new Callable() { public Void call() throws Exception { in.read(); return null; } }); assertBlocks(f); a.close(); try { f.get(); } catch (ExecutionException e) { throw e.getCause(); } } @Test(expected = SocketException.class) public void testGetOutputStreamOnClosedSocket() throws Exception { a.close(); a.getOutputStream(); } @Test(expected = SocketException.class) public void testWriteOnClosedSocket() throws Exception { final OutputStream out = a.getOutputStream(); a.close(); out.write(123); } @Test public void testContents() throws Exception { final InputStream in = a.getInputStream(); final OutputStream out = b.getOutputStream(); assertEquals(0, in.available()); out.write(0); out.write(1); out.write(2); out.write(255); if (!REAL_SOCKETS) { // Real sockets will have a delay assertEquals(4, in.available()); } assertEquals(0, in.read()); assertEquals(1, in.read()); assertEquals(2, in.read()); assertEquals(255, in.read()); } @Test public void testWaitForContents() throws Exception { final InputStream in = a.getInputStream(); final OutputStream out = b.getOutputStream(); final Future f = executor.submit(new Callable() { public Byte call() throws Exception { return Byte.valueOf((byte) in.read()); } }); assertBlocks(f); out.write(123); assertEquals(123, f.get().byteValue()); } @Test public void testCloseOtherSocket() throws Exception { b.close(); final InputStream in = a.getInputStream(); assertEquals(-1, in.read()); } @Test public void testCloseOtherSocketAsync() throws Exception { final InputStream in = a.getInputStream(); final Future f = executor.submit(new Callable() { public Byte call() throws Exception { return Byte.valueOf((byte) in.read()); } }); assertBlocks(f); b.close(); assertEquals(-1, f.get().byteValue()); } } TcpClientOutputTest.java000066400000000000000000000066721304217427400337730ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/******************************************************************************* /******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * Marc R. Hoffmann - migration to mock socket * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.IOException; import java.net.Socket; import java.util.List; import org.jacoco.agent.rt.internal.ExceptionRecorder; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.SessionInfo; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RemoteControlReader; import org.jacoco.core.runtime.RemoteControlWriter; import org.jacoco.core.runtime.RuntimeData; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link TcpClientOutput}. */ public class TcpClientOutputTest { private ExceptionRecorder logger; private IAgentOutput controller; private Socket remoteSocket; private RemoteControlWriter remoteWriter; private RemoteControlReader remoteReader; private RuntimeData data; @Before public void setup() throws Exception { logger = new ExceptionRecorder(); final MockSocketConnection con = new MockSocketConnection(); remoteSocket = con.getSocketB(); remoteWriter = new RemoteControlWriter(remoteSocket.getOutputStream()); controller = new TcpClientOutput(logger) { @Override protected Socket createSocket(AgentOptions options) throws IOException { return con.getSocketA(); } }; data = new RuntimeData(); controller.startup(new AgentOptions(), data); remoteReader = new RemoteControlReader(remoteSocket.getInputStream()); } @Test public void testShutdown() throws Exception { controller.shutdown(); assertFalse(remoteReader.read()); logger.assertNoException(); } @Test public void testRemoteClose() throws Exception { remoteSocket.close(); controller.shutdown(); logger.assertNoException(); } @Test public void testInvalidCommand() throws Exception { remoteWriter.visitSessionInfo(new SessionInfo("info", 1, 2)); while (remoteReader.read()) { } controller.shutdown(); logger.assertException(IOException.class, "No session info visitor."); } @Test public void testWriteExecutionData() throws Exception { data.getExecutionData(Long.valueOf(0x12345678), "Foo", 42).getProbes()[0] = true; data.setSessionId("stubid"); controller.writeExecutionData(false); final ExecutionDataStore execStore = new ExecutionDataStore(); remoteReader.setExecutionDataVisitor(execStore); final SessionInfoStore infoStore = new SessionInfoStore(); remoteReader.setSessionInfoVisitor(infoStore); remoteReader.read(); assertEquals("Foo", execStore.get(0x12345678).getName()); final List infos = infoStore.getInfos(); assertEquals(1, infos.size()); assertEquals("stubid", infos.get(0).getId()); logger.assertNoException(); controller.shutdown(); } } jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/TcpConnectionTest.java000066400000000000000000000163131304217427400335030ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.ExecutionDataWriter; import org.jacoco.core.data.SessionInfo; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.runtime.RemoteControlReader; import org.jacoco.core.runtime.RemoteControlWriter; import org.jacoco.core.runtime.RuntimeData; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link TcpConnection}. */ public class TcpConnectionTest extends ExecutorTestBase { private MockSocketConnection mockConnection; private RuntimeData data; @Before @Override public void setup() throws Exception { super.setup(); mockConnection = new MockSocketConnection(); data = new RuntimeData(); } @Test(expected = IOException.class) public void testInvalidHeader() throws Exception { final OutputStream remoteOut = mockConnection.getSocketB() .getOutputStream(); remoteOut.write(0x01); remoteOut.write(0xC0); remoteOut.write(0xCA); final TcpConnection connection = new TcpConnection( mockConnection.getSocketA(), data); connection.init(); connection.run(); } @Test(expected = IOException.class) public void testInvalidContent() throws Exception { final OutputStream remoteOut = mockConnection.getSocketB() .getOutputStream(); new ExecutionDataWriter(remoteOut); final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); con.init(); remoteOut.write(123); con.run(); } /** * Remote endpoint is closed after a valid header has been send. */ @Test public void testRemoteClose() throws Exception { final OutputStream remoteOut = mockConnection.getSocketB() .getOutputStream(); new ExecutionDataWriter(remoteOut); final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); con.init(); final Future f = executor.submit(new Callable() { public Void call() throws Exception { con.run(); return null; } }); assertBlocks(f); mockConnection.getSocketB().close(); f.get(); } /** * Remote endpoint is closed before even a valid header was send. */ public void testRemoteCloseWithoutHeader() throws Throwable { final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); final Future f = executor.submit(new Callable() { public Void call() throws Exception { con.init(); return null; } }); assertBlocks(f); mockConnection.getSocketB().close(); f.get(); } /** * Local socket is closed while waiting for commands. * * @throws Exception */ @Test public void testLocalClose() throws Exception { final OutputStream remoteOut = mockConnection.getSocketB() .getOutputStream(); new ExecutionDataWriter(remoteOut); final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); con.init(); final Future f = executor.submit(new Callable() { public Void call() throws Exception { con.run(); return null; } }); assertBlocks(f); con.close(); f.get(); } @Test public void testRemoteDump() throws Exception { data.getExecutionData(Long.valueOf(0x12345678), "Foo", 42).getProbes()[0] = true; data.setSessionId("stubid"); final RemoteControlWriter remoteWriter = new RemoteControlWriter( mockConnection.getSocketB().getOutputStream()); final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); con.init(); final Future f = executor.submit(new Callable() { public Void call() throws Exception { con.run(); return null; } }); assertBlocks(f); remoteWriter.visitDumpCommand(true, false); readAndAssertData(); con.close(); f.get(); } @Test public void testLocalDump() throws Exception { data.getExecutionData(Long.valueOf(0x12345678), "Foo", 42).getProbes()[0] = true; data.setSessionId("stubid"); new RemoteControlWriter(mockConnection.getSocketB().getOutputStream()); final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); con.init(); final Future f = executor.submit(new Callable() { public Void call() throws Exception { con.run(); return null; } }); assertBlocks(f); con.writeExecutionData(false); readAndAssertData(); con.close(); f.get(); } @Test public void testLocalDumpWithoutInit() throws Exception { final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); // Must not write any data as we're not initialized: con.writeExecutionData(false); assertEquals(0, mockConnection.getSocketB().getInputStream() .available()); } private void readAndAssertData() throws IOException { final RemoteControlReader remoteReader = new RemoteControlReader( mockConnection.getSocketB().getInputStream()); final ExecutionDataStore execStore = new ExecutionDataStore(); remoteReader.setExecutionDataVisitor(execStore); final SessionInfoStore infoStore = new SessionInfoStore(); remoteReader.setSessionInfoVisitor(infoStore); assertTrue(remoteReader.read()); final List infos = infoStore.getInfos(); assertEquals(1, infos.size()); assertEquals("stubid", infos.get(0).getId()); assertEquals("Foo", execStore.get(0x12345678).getName()); } @Test public void testRemoteReset() throws Exception { data.getExecutionData(Long.valueOf(123), "Foo", 1).getProbes()[0] = true; final RemoteControlWriter remoteWriter = new RemoteControlWriter( mockConnection.getSocketB().getOutputStream()); final TcpConnection con = new TcpConnection( mockConnection.getSocketA(), data); con.init(); final Future f = executor.submit(new Callable() { public Void call() throws Exception { con.run(); return null; } }); assertBlocks(f); remoteWriter.visitDumpCommand(false, true); final RemoteControlReader remoteReader = new RemoteControlReader( mockConnection.getSocketB().getInputStream()); final ExecutionDataStore execStore = new ExecutionDataStore(); remoteReader.setExecutionDataVisitor(execStore); final SessionInfoStore infoStore = new SessionInfoStore(); remoteReader.setSessionInfoVisitor(infoStore); assertTrue(remoteReader.read()); assertTrue(infoStore.getInfos().isEmpty()); assertTrue(execStore.getContents().isEmpty()); assertFalse(data.getExecutionData(Long.valueOf(123), "Foo", 1) .getProbes()[0]); con.close(); f.get(); } } TcpServerOutputTest.java000066400000000000000000000104741304217427400340160ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt.test/src/org/jacoco/agent/rt/internal/output/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * Marc R. Hoffmann - migration to mock socket * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.List; import org.jacoco.agent.rt.internal.ExceptionRecorder; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.ExecutionDataWriter; import org.jacoco.core.data.SessionInfo; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RemoteControlReader; import org.jacoco.core.runtime.RemoteControlWriter; import org.jacoco.core.runtime.RuntimeData; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link TcpServerOutput}. */ public class TcpServerOutputTest { private ExceptionRecorder logger; private AgentOptions options; private MockServerSocket serverSocket; private TcpServerOutput controller; private RuntimeData data; @Before public void setup() throws Exception { options = new AgentOptions(); logger = new ExceptionRecorder(); serverSocket = new MockServerSocket(); controller = new TcpServerOutput(logger) { @Override protected ServerSocket createServerSocket(AgentOptions options) throws IOException { return serverSocket; } }; data = new RuntimeData(); controller.startup(options, data); } @Test public void testShutdownWithoutConnection() throws Exception { serverSocket.waitForAccept(); controller.shutdown(); logger.assertNoException(); } @Test public void testShutdownWithConnection() throws Exception { serverSocket.waitForAccept(); new ExecutionDataWriter(serverSocket.connect().getOutputStream()); controller.shutdown(); logger.assertNoException(); } @Test public void testWriteExecutionData() throws Exception { data.getExecutionData(Long.valueOf(0x12345678), "Foo", 42).getProbes()[0] = true; data.setSessionId("stubid"); final Socket socket = serverSocket.connect(); final RemoteControlWriter remoteWriter = new RemoteControlWriter( socket.getOutputStream()); final RemoteControlReader remoteReader = new RemoteControlReader( socket.getInputStream()); // First process a NOP command to ensure the connection is initialized: remoteWriter.visitDumpCommand(false, false); remoteReader.read(); // Now the actual test starts: controller.writeExecutionData(false); final ExecutionDataStore execStore = new ExecutionDataStore(); remoteReader.setExecutionDataVisitor(execStore); final SessionInfoStore infoStore = new SessionInfoStore(); remoteReader.setSessionInfoVisitor(infoStore); remoteReader.read(); assertEquals("Foo", execStore.get(0x12345678).getName()); final List infos = infoStore.getInfos(); assertEquals(1, infos.size()); assertEquals("stubid", infos.get(0).getId()); logger.assertNoException(); controller.shutdown(); } @Test public void testInvalidHeader() throws Exception { final Socket socket = serverSocket.connect(); final OutputStream out = socket.getOutputStream(); out.write(0xca); out.write(0xfe); out.write(0xba); out.write(0xbe); serverSocket.waitForAccept(); logger.assertException(IOException.class, "Invalid execution data file."); controller.shutdown(); } @Test public void testGetInetAddressLoopback() throws UnknownHostException { final InetAddress addr = controller.getInetAddress(null); assertTrue(addr.isLoopbackAddress()); } @Test public void testGetInetAddressAny() throws UnknownHostException { final InetAddress addr = controller.getInetAddress("*"); assertNull(addr); } } jacoco-0.7.8/org.jacoco.agent.rt/000077500000000000000000000000001304217427400165355ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/.classpath000066400000000000000000000014151304217427400205210ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.agent.rt/.gitignore000066400000000000000000000000301304217427400205160ustar00rootroot00000000000000/target /bin /.settings jacoco-0.7.8/org.jacoco.agent.rt/.project000066400000000000000000000013651304217427400202110ustar00rootroot00000000000000 org.jacoco.agent.rt org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core/.settings jacoco-0.7.8/org.jacoco.agent.rt/about.html000066400000000000000000000051541304217427400205420ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

Third Party Content

The Content includes items that have been sourced from third parties as set out below.

ASM 3.x

This plug-in contains the ASM library which is subject to the terms and conditions of the following license:

Copyright (c) 2000-2005 INRIA, France Telecom
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holders nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
jacoco-0.7.8/org.jacoco.agent.rt/pom.xml000066400000000000000000000060171304217427400200560ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.build 0.7.8 ../org.jacoco.build org.jacoco.agent.rt JaCoCo :: Agent RT JaCoCo Java Agent true true ${project.groupId} org.jacoco.core src org.apache.maven.plugins maven-shade-plugin package shade true all true org.jacoco.agent.rt.internal ${jacoco.runtime.package.name} org.jacoco.core ${jacoco.runtime.package.name}.core org.objectweb.asm ${jacoco.runtime.package.name}.asm ${jacoco.runtime.package.name}.PreMain jacoco-0.7.8/org.jacoco.agent.rt/src/000077500000000000000000000000001304217427400173245ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/com/000077500000000000000000000000001304217427400201025ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/com/vladium/000077500000000000000000000000001304217427400215435ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/com/vladium/emma/000077500000000000000000000000001304217427400224625ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/com/vladium/emma/rt/000077500000000000000000000000001304217427400231075ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/com/vladium/emma/rt/RT.java000066400000000000000000000044721304217427400243060ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package com.vladium.emma.rt; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Compatibility layer for the EMMA runtime which allows to trigger dumps * through EMMA APIs. Note that even this class emulates an EMMA API the files * written are in JaCoCo execution data format. * * @deprecated Use {@link org.jacoco.agent.rt.IAgent} instead. */ @Deprecated public final class RT { private RT() { } /** * Writes the current execution data to the given file in JaCoCo execution * data format. * * @param outFile * file to write execution data to * @param merge * if true, execution data is appended to an * existing file * @param stopDataCollection * ignored * @throws IOException * in case of problems with the file output */ @SuppressWarnings("unused") public static void dumpCoverageData(final File outFile, final boolean merge, final boolean stopDataCollection) throws IOException { final OutputStream out = new FileOutputStream(outFile, merge); try { out.write(org.jacoco.agent.rt.RT.getAgent().getExecutionData(false)); } finally { out.close(); } } /** * Writes the current execution data to the given file in JaCoCo execution * data format. If the file already exists new data is appended. * * @param outFile * file to write execution data to * @param stopDataCollection * ignored * @throws IOException * in case of problems with the file output */ public static synchronized void dumpCoverageData(final File outFile, final boolean stopDataCollection) throws IOException { dumpCoverageData(outFile, true, stopDataCollection); } } jacoco-0.7.8/org.jacoco.agent.rt/src/com/vladium/emma/rt/package-info.java000066400000000000000000000012011304217427400262700ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ /** * Compatibility API for EMMA runtime. */ package com.vladium.emma.rt;jacoco-0.7.8/org.jacoco.agent.rt/src/org/000077500000000000000000000000001304217427400201135ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/000077500000000000000000000000001304217427400213515ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/000077500000000000000000000000001304217427400224475ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/000077500000000000000000000000001304217427400230745ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/IAgent.java000066400000000000000000000033061304217427400251100ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt; import java.io.IOException; /** * Runtime API and MBean agent interface. */ public interface IAgent { /** * Returns version of JaCoCo. * * @return version of JaCoCo */ String getVersion(); /** * Returns current a session identifier. * * @return current session identifier */ String getSessionId(); /** * Sets a session identifier. * * @param id * new session identifier */ void setSessionId(String id); /** * Resets all coverage information. */ void reset(); /** * Returns current execution data. * * @param reset * if true the current execution data is cleared * afterwards * @return dump of current execution data in JaCoCo binary format */ byte[] getExecutionData(boolean reset); /** * Triggers a dump of the current execution data through the configured * output. * * @param reset * if true the current execution data is cleared * afterwards * @throws IOException * if the output can't write execution data */ void dump(boolean reset) throws IOException; } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/RT.java000066400000000000000000000020121304217427400242570ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt; import org.jacoco.agent.rt.internal.Agent; /** * Entry point to access the JaCoCo agent runtime. */ public final class RT { private RT() { } /** * Returns the agent instance of the JaCoCo runtime in this JVM. * * @return agent instance * @throws IllegalStateException * if no Agent has been started yet */ public static IAgent getAgent() throws IllegalStateException { return Agent.getInstance(); } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/000077500000000000000000000000001304217427400247105ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/Agent.java000066400000000000000000000127371304217427400266230ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.InetAddress; import java.util.concurrent.Callable; import org.jacoco.agent.rt.IAgent; import org.jacoco.agent.rt.internal.output.FileOutput; import org.jacoco.agent.rt.internal.output.IAgentOutput; import org.jacoco.agent.rt.internal.output.NoneOutput; import org.jacoco.agent.rt.internal.output.TcpClientOutput; import org.jacoco.agent.rt.internal.output.TcpServerOutput; import org.jacoco.core.JaCoCo; import org.jacoco.core.data.ExecutionDataWriter; import org.jacoco.core.runtime.AbstractRuntime; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.AgentOptions.OutputMode; import org.jacoco.core.runtime.RuntimeData; /** * The agent manages the life cycle of JaCoCo runtime. */ public class Agent implements IAgent { private static Agent singleton; /** * Returns a global instance which is already started. If the method is * called the first time the instance is created with the given options. * * @param options * options to configure the instance * @return global instance */ public static synchronized Agent getInstance(final AgentOptions options) { if (singleton == null) { final Agent agent = new Agent(options, IExceptionLogger.SYSTEM_ERR); agent.startup(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { agent.shutdown(); } }); singleton = agent; } return singleton; } /** * Returns a global instance which is already started. If a agent has not * been initialized before this method will fail. * * @return global instance * @throws IllegalStateException * if no Agent has been started yet */ public static synchronized Agent getInstance() throws IllegalStateException { if (singleton == null) { throw new IllegalStateException("JaCoCo agent not started."); } return singleton; } private final AgentOptions options; private final IExceptionLogger logger; private final RuntimeData data; private IAgentOutput output; private Callable jmxRegistration; /** * Creates a new agent with the given agent options. * * @param options * agent options * @param logger * logger used by this agent */ Agent(final AgentOptions options, final IExceptionLogger logger) { this.options = options; this.logger = logger; this.data = new RuntimeData(); } /** * Returns the runtime data object created by this agent * * @return runtime data for this agent instance */ public RuntimeData getData() { return data; } /** * Initializes this agent. * */ public void startup() { try { String sessionId = options.getSessionId(); if (sessionId == null) { sessionId = createSessionId(); } data.setSessionId(sessionId); output = createAgentOutput(); output.startup(options, data); if (options.getJmx()) { jmxRegistration = new JmxRegistration(this); } } catch (final Exception e) { logger.logExeption(e); } } /** * Shutdown the agent again. */ public void shutdown() { try { if (options.getDumpOnExit()) { output.writeExecutionData(false); } output.shutdown(); if (jmxRegistration != null) { jmxRegistration.call(); } } catch (final Exception e) { logger.logExeption(e); } } /** * Create output implementation as given by the agent options. * * @return configured controller implementation */ IAgentOutput createAgentOutput() { final OutputMode controllerType = options.getOutput(); switch (controllerType) { case file: return new FileOutput(); case tcpserver: return new TcpServerOutput(logger); case tcpclient: return new TcpClientOutput(logger); case none: return new NoneOutput(); default: throw new AssertionError(controllerType); } } private String createSessionId() { String host; try { host = InetAddress.getLocalHost().getHostName(); } catch (final Exception e) { // Also catch platform specific exceptions (like on Android) to // avoid bailing out here host = "unknownhost"; } return host + "-" + AbstractRuntime.createRandomId(); } // === IAgent Implementation === public String getVersion() { return JaCoCo.VERSION; } public String getSessionId() { return data.getSessionId(); } public void setSessionId(final String id) { data.setSessionId(id); } public void reset() { data.reset(); } public byte[] getExecutionData(final boolean reset) { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { final ExecutionDataWriter writer = new ExecutionDataWriter(buffer); data.collect(writer, writer, reset); } catch (final IOException e) { // Must not happen with ByteArrayOutputStream throw new AssertionError(e); } return buffer.toByteArray(); } public void dump(final boolean reset) throws IOException { output.writeExecutionData(reset); } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/ClassFileDumper.java000066400000000000000000000042471304217427400306040ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.jacoco.core.internal.data.CRC64; /** * Internal dumper for class files. */ class ClassFileDumper { private final File location; /** * Create a new dumper for the given location. * * @param location * relative path to dump directory. null if no dumps * should be written */ ClassFileDumper(final String location) { if (location == null) { this.location = null; } else { this.location = new File(location); } } /** * Dumps the given binary content under the given name if a non- * null location has been specified. * * @param name * qualified class name in VM notation * @param contents * binary contents * @throws IOException * in case of problems while dumping the file */ void dump(final String name, final byte[] contents) throws IOException { if (location != null) { final File outputdir; final String localname; final int pkgpos = name.lastIndexOf('/'); if (pkgpos != -1) { outputdir = new File(location, name.substring(0, pkgpos)); localname = name.substring(pkgpos + 1); } else { outputdir = location; localname = name; } outputdir.mkdirs(); final Long id = Long.valueOf(CRC64.checksum(contents)); final File file = new File(outputdir, String.format( "%s.%016x.class", localname, id)); final OutputStream out = new FileOutputStream(file); out.write(contents); out.close(); } } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/ConfigLoader.java000066400000000000000000000053521304217427400301140ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Internal utility to load runtime configuration from a classpath resource and * from system properties. System property keys are prefixed with * jacoco.. If the same property is defined twice the system * property takes precedence. */ final class ConfigLoader { private static final String SYS_PREFIX = "jacoco-agent."; private static final Pattern SUBST_PATTERN = Pattern .compile("\\$\\{([^\\}]+)\\}"); static Properties load(final String resource, final Properties system) { final Properties result = new Properties(); loadResource(resource, result); loadSystemProperties(system, result); substSystemProperties(result, system); return result; } private static void loadResource(final String resource, final Properties result) { final InputStream file = Offline.class.getResourceAsStream(resource); if (file != null) { try { result.load(file); } catch (final IOException e) { throw new RuntimeException(e); } } } private static void loadSystemProperties(final Properties system, final Properties result) { for (final Map.Entry entry : system.entrySet()) { final String keystr = entry.getKey().toString(); if (keystr.startsWith(SYS_PREFIX)) { result.put(keystr.substring(SYS_PREFIX.length()), entry.getValue()); } } } private static void substSystemProperties(final Properties result, final Properties system) { for (final Map.Entry entry : result.entrySet()) { final String oldValue = (String) entry.getValue(); final StringBuilder newValue = new StringBuilder(); final Matcher m = SUBST_PATTERN.matcher(oldValue); int pos = 0; while (m.find()) { newValue.append(oldValue.substring(pos, m.start())); final String sub = system.getProperty(m.group(1)); newValue.append(sub == null ? m.group(0) : sub); pos = m.end(); } newValue.append(oldValue.substring(pos)); entry.setValue(newValue.toString()); } } private ConfigLoader() { } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/CoverageTransformer.java000066400000000000000000000113721304217427400315350ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.CodeSource; import java.security.ProtectionDomain; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.WildcardMatcher; /** * Class file transformer to instrument classes for code coverage analysis. */ public class CoverageTransformer implements ClassFileTransformer { private static final String AGENT_PREFIX; static { final String name = CoverageTransformer.class.getName(); AGENT_PREFIX = toVMName(name.substring(0, name.lastIndexOf('.'))); } private final Instrumenter instrumenter; private final IExceptionLogger logger; private final WildcardMatcher includes; private final WildcardMatcher excludes; private final WildcardMatcher exclClassloader; private final ClassFileDumper classFileDumper; private final boolean inclBootstrapClasses; private final boolean inclNoLocationClasses; /** * New transformer with the given delegates. * * @param runtime * coverage runtime * @param options * configuration options for the generator * @param logger * logger for exceptions during instrumentation */ public CoverageTransformer(final IRuntime runtime, final AgentOptions options, final IExceptionLogger logger) { this.instrumenter = new Instrumenter(runtime); this.logger = logger; // Class names will be reported in VM notation: includes = new WildcardMatcher(toVMName(options.getIncludes())); excludes = new WildcardMatcher(toVMName(options.getExcludes())); exclClassloader = new WildcardMatcher(options.getExclClassloader()); classFileDumper = new ClassFileDumper(options.getClassDumpDir()); inclBootstrapClasses = options.getInclBootstrapClasses(); inclNoLocationClasses = options.getInclNoLocationClasses(); } public byte[] transform(final ClassLoader loader, final String classname, final Class classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] classfileBuffer) throws IllegalClassFormatException { // We do not support class retransformation: if (classBeingRedefined != null) { return null; } if (!filter(loader, classname, protectionDomain)) { return null; } try { classFileDumper.dump(classname, classfileBuffer); return instrumenter.instrument(classfileBuffer, classname); } catch (final Exception ex) { final IllegalClassFormatException wrapper = new IllegalClassFormatException( ex.getMessage()); wrapper.initCause(ex); // Report this, as the exception is ignored by the JVM: logger.logExeption(wrapper); throw wrapper; } } /** * Checks whether this class should be instrumented. * * @param loader * loader for the class * @param classname * VM name of the class to check * @param protectionDomain * protection domain for the class * @return true if the class should be instrumented */ boolean filter(final ClassLoader loader, final String classname, final ProtectionDomain protectionDomain) { if (loader == null) { if (!inclBootstrapClasses) { return false; } } else { if (!inclNoLocationClasses && !hasSourceLocation(protectionDomain)) { return false; } if (exclClassloader.matches(loader.getClass().getName())) { return false; } } return !classname.startsWith(AGENT_PREFIX) && includes.matches(classname) && !excludes.matches(classname); } /** * Checks whether this protection domain is associated with a source * location. * * @param protectionDomain * protection domain to check (or null) * @return true if a source location is defined */ private boolean hasSourceLocation(final ProtectionDomain protectionDomain) { if (protectionDomain == null) { return false; } final CodeSource codeSource = protectionDomain.getCodeSource(); if (codeSource == null) { return false; } return codeSource.getLocation() != null; } private static String toVMName(final String srcName) { return srcName.replace('.', '/'); } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/IExceptionLogger.java000066400000000000000000000021651304217427400307660ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; /** * At several places exception might occur that should be reported. For * testability these exceptions are emitted against this interface. */ public interface IExceptionLogger { /** * Default implementation which dumps the stack trace to System.err. */ IExceptionLogger SYSTEM_ERR = new IExceptionLogger() { public void logExeption(final Exception ex) { ex.printStackTrace(); } }; /** * Logs the given exception. * * @param ex * exception to log */ public void logExeption(Exception ex); } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/JmxRegistration.java000066400000000000000000000027611304217427400307120ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import java.lang.management.ManagementFactory; import java.util.concurrent.Callable; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.StandardMBean; import org.jacoco.agent.rt.IAgent; /** * Access to JMX APIs are encapsulated in this class to allow the JaCoCo runtime * on platforms without JMX support (e.g Android). */ class JmxRegistration implements Callable { private static final String JMX_NAME = "org.jacoco:type=Runtime"; private final MBeanServer server; private final ObjectName name; JmxRegistration(final IAgent agent) throws Exception { server = ManagementFactory.getPlatformMBeanServer(); name = new ObjectName(JMX_NAME); server.registerMBean(new StandardMBean(agent, IAgent.class), name); } /** * De-register the agent again. */ public Void call() throws Exception { server.unregisterMBean(name); return null; } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/Offline.java000066400000000000000000000032731304217427400271420ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import java.util.Properties; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RuntimeData; /** * The API for classes instrumented in "offline" mode. The agent configuration * is provided through system properties prefixed with jacoco.. */ public final class Offline { private static final RuntimeData DATA; private static final String CONFIG_RESOURCE = "/jacoco-agent.properties"; static { final Properties config = ConfigLoader.load(CONFIG_RESOURCE, System.getProperties()); DATA = Agent.getInstance(new AgentOptions(config)).getData(); } private Offline() { // no instances } /** * API for offline instrumented classes. * * @param classid * class identifier * @param classname * VM class name * @param probecount * probe count for this class * @return probe array instance for this class */ public static boolean[] getProbes(final long classid, final String classname, final int probecount) { return DATA.getExecutionData(Long.valueOf(classid), classname, probecount).getProbes(); } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/PreMain.java000066400000000000000000000035261304217427400271140ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal; import java.lang.instrument.Instrumentation; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.ModifiedSystemClassRuntime; /** * The agent which is referred as the Premain-Class. The agent * configuration is provided with the agent parameters in the command line. */ public final class PreMain { private PreMain() { // no instances } /** * This method is called by the JVM to initialize Java agents. * * @param options * agent options * @param inst * instrumentation callback provided by the JVM * @throws Exception * in case initialization fails */ public static void premain(final String options, final Instrumentation inst) throws Exception { final AgentOptions agentOptions = new AgentOptions(options); final Agent agent = Agent.getInstance(agentOptions); final IRuntime runtime = createRuntime(inst); runtime.startup(agent.getData()); inst.addTransformer(new CoverageTransformer(runtime, agentOptions, IExceptionLogger.SYSTEM_ERR)); } private static IRuntime createRuntime(final Instrumentation inst) throws Exception { return ModifiedSystemClassRuntime.createFor(inst, "java/util/UUID"); } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/output/000077500000000000000000000000001304217427400262505ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/output/FileOutput.java000066400000000000000000000041671304217427400312230ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.jacoco.core.data.ExecutionDataWriter; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RuntimeData; /** * Local only agent output that will write coverage data to the filesystem. This * controller uses the following agent options: *
    *
  • destfile
  • *
  • append
  • *
*/ public class FileOutput implements IAgentOutput { private RuntimeData data; private File destFile; private boolean append; public final void startup(final AgentOptions options, final RuntimeData data) throws IOException { this.data = data; this.destFile = new File(options.getDestfile()).getAbsoluteFile(); this.append = options.getAppend(); final File folder = destFile.getParentFile(); if (folder != null) { folder.mkdirs(); } // Make sure we can write to the file: openFile().close(); } public void writeExecutionData(final boolean reset) throws IOException { final OutputStream output = openFile(); try { final ExecutionDataWriter writer = new ExecutionDataWriter(output); data.collect(writer, writer, reset); } finally { output.close(); } } public void shutdown() throws IOException { // Nothing to do } private OutputStream openFile() throws IOException { final FileOutputStream file = new FileOutputStream(destFile, append); // Avoid concurrent writes from different agents running in parallel: file.getChannel().lock(); return file; } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/output/IAgentOutput.java000066400000000000000000000034731304217427400315120ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import java.io.IOException; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RuntimeData; /** * Common interface for different implementations that outputs execution data * dumps. */ public interface IAgentOutput { /** * Configure the agent controller with the supplied options and connect it * to the coverage runtime * * @param options * Options used to configure the agent controller * @param data * Execution data for this agent * @throws Exception * in case startup fails */ public void startup(final AgentOptions options, final RuntimeData data) throws Exception; /** * Shutdown the agent controller and clean up any resources it has created. * * @throws Exception * in case shutdown fails */ public void shutdown() throws Exception; /** * Write all execution data in the runtime to a location determined by the * agent controller. This method should only be called by the Agent * * @param reset * if true execution data is cleared afterwards * @throws IOException * in case writing fails */ public void writeExecutionData(boolean reset) throws IOException; } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/output/NoneOutput.java000066400000000000000000000017721304217427400312420ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mandrikov Evgeny - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RuntimeData; /** * Output that does nothing. */ public class NoneOutput implements IAgentOutput { public final void startup(final AgentOptions options, final RuntimeData data) { // Nothing to do } public void writeExecutionData(final boolean reset) { // Nothing to do } public void shutdown() { // Nothing to do } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/output/TcpClientOutput.java000066400000000000000000000044571304217427400322330ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import java.io.IOException; import java.net.Socket; import org.jacoco.agent.rt.internal.IExceptionLogger; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RuntimeData; /** * Output that connects to a TCP port. This controller uses the following * agent options: *
    *
  • address
  • *
  • port
  • *
*/ public class TcpClientOutput implements IAgentOutput { private final IExceptionLogger logger; private TcpConnection connection; private Thread worker; /** * New controller instance. * * @param logger * logger to use in case of exceptions is spawned threads */ public TcpClientOutput(final IExceptionLogger logger) { this.logger = logger; } public void startup(final AgentOptions options, final RuntimeData data) throws IOException { final Socket socket = createSocket(options); connection = new TcpConnection(socket, data); connection.init(); worker = new Thread(new Runnable() { public void run() { try { connection.run(); } catch (final IOException e) { logger.logExeption(e); } } }); worker.setName(getClass().getName()); worker.setDaemon(true); worker.start(); } public void shutdown() throws Exception { connection.close(); worker.join(); } public void writeExecutionData(final boolean reset) throws IOException { connection.writeExecutionData(reset); } /** * Open a socket based on the given configuration. * * @param options * address and port configuration * @return opened socket * @throws IOException */ protected Socket createSocket(final AgentOptions options) throws IOException { return new Socket(options.getAddress(), options.getPort()); } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/output/TcpConnection.java000066400000000000000000000055511304217427400316670ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import org.jacoco.core.runtime.IRemoteCommandVisitor; import org.jacoco.core.runtime.RemoteControlReader; import org.jacoco.core.runtime.RemoteControlWriter; import org.jacoco.core.runtime.RuntimeData; /** * Handler for a single socket based remote connection. */ class TcpConnection implements IRemoteCommandVisitor { private final RuntimeData data; private final Socket socket; private RemoteControlWriter writer; private RemoteControlReader reader; private boolean initialized; public TcpConnection(final Socket socket, final RuntimeData data) { this.socket = socket; this.data = data; this.initialized = false; } public void init() throws IOException { this.writer = new RemoteControlWriter(socket.getOutputStream()); this.reader = new RemoteControlReader(socket.getInputStream()); this.reader.setRemoteCommandVisitor(this); this.initialized = true; } /** * Processes all requests for this session until the socket is closed. * * @throws IOException * in case of problems whith the connection */ public void run() throws IOException { try { while (reader.read()) { } } catch (final SocketException e) { // If the local socket is closed while polling for commands the // SocketException is expected. if (!socket.isClosed()) { throw e; } } finally { close(); } } /** * Dumps the current execution data if the connection is already initialized * and the underlying socket is still open. * * @param reset * if true execution data is cleared afterwards * @throws IOException */ public void writeExecutionData(final boolean reset) throws IOException { if (initialized && !socket.isClosed()) { visitDumpCommand(true, reset); } } /** * Closes the underlying socket if not closed yet. * * @throws IOException */ public void close() throws IOException { if (!socket.isClosed()) { socket.close(); } } // === IRemoteCommandVisitor === public void visitDumpCommand(final boolean dump, final boolean reset) throws IOException { if (dump) { data.collect(writer, writer, reset); } else { if (reset) { data.reset(); } } writer.sendCmdOk(); } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/internal/output/TcpServerOutput.java000066400000000000000000000065021304217427400322540ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent.rt.internal.output; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import org.jacoco.agent.rt.internal.IExceptionLogger; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.RuntimeData; /** * Output that opens TCP server socket. This controller uses the following agent * options: *
    *
  • address
  • *
  • port
  • *
*/ public class TcpServerOutput implements IAgentOutput { private TcpConnection connection; private final IExceptionLogger logger; private ServerSocket serverSocket; private Thread worker; /** * New controller instance. * * @param logger * logger to use in case of exceptions is spawned threads */ public TcpServerOutput(final IExceptionLogger logger) { this.logger = logger; } public void startup(final AgentOptions options, final RuntimeData data) throws IOException { serverSocket = createServerSocket(options); worker = new Thread(new Runnable() { public void run() { while (!serverSocket.isClosed()) { try { synchronized (serverSocket) { connection = new TcpConnection( serverSocket.accept(), data); } connection.init(); connection.run(); } catch (final IOException e) { // If the serverSocket is closed while accepting // connections a SocketException is expected. if (!serverSocket.isClosed()) { logger.logExeption(e); } } } } }); worker.setName(getClass().getName()); worker.setDaemon(true); worker.start(); } public void shutdown() throws Exception { serverSocket.close(); synchronized (serverSocket) { if (connection != null) { connection.close(); } } worker.join(); } public void writeExecutionData(final boolean reset) throws IOException { if (connection != null) { connection.writeExecutionData(reset); } } /** * Open a server socket based on the given configuration. * * @param options * address and port configuration * @return opened server socket * @throws IOException */ protected ServerSocket createServerSocket(final AgentOptions options) throws IOException { final InetAddress inetAddr = getInetAddress(options.getAddress()); return new ServerSocket(options.getPort(), 1, inetAddr); } /** * Returns the {@link InetAddress} object to open the server socket on. * * @param address * address specified as a string * @return address to open the server socket * @throws UnknownHostException */ protected InetAddress getInetAddress(final String address) throws UnknownHostException { if ("*".equals(address)) { return null; } else { return InetAddress.getByName(address); } } } jacoco-0.7.8/org.jacoco.agent.rt/src/org/jacoco/agent/rt/package-info.java000066400000000000000000000012341304217427400262630ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ /** * API to access the JaCoCo agent from within the JVM under test. */ package org.jacoco.agent.rt;jacoco-0.7.8/org.jacoco.agent.test/000077500000000000000000000000001304217427400170675ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.test/.classpath000066400000000000000000000014151304217427400210530ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.agent.test/.gitignore000066400000000000000000000000301304217427400210500ustar00rootroot00000000000000/target /bin /.settings jacoco-0.7.8/org.jacoco.agent.test/.project000066400000000000000000000013361304217427400205410ustar00rootroot00000000000000 org.jacoco.agent.test org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core.test/.settings jacoco-0.7.8/org.jacoco.agent.test/META-INF/000077500000000000000000000000001304217427400202275ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.test/META-INF/MANIFEST.MF000066400000000000000000000005221304217427400216600ustar00rootroot00000000000000Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JaCoCo Agent Tests Bundle-SymbolicName: org.jacoco.agent.test Bundle-Version: 0.7.8.201612092310 Fragment-Host: org.jacoco.agent Bundle-RequiredExecutionEnvironment: J2SE-1.5 Bundle-Vendor: Mountainminds GmbH & Co. KG Import-Package: org.junit;version="[4.8.0,5.0.0)" jacoco-0.7.8/org.jacoco.agent.test/about.html000066400000000000000000000014761304217427400210770ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

jacoco-0.7.8/org.jacoco.agent.test/pom.xml000066400000000000000000000024531304217427400204100ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.tests 0.7.8 ../org.jacoco.tests org.jacoco.agent.test JaCoCo :: Test :: Agent org.jacoco.agent.* ${project.groupId} org.jacoco.agent junit junit jacoco-0.7.8/org.jacoco.agent.test/src/000077500000000000000000000000001304217427400176565ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.test/src/org/000077500000000000000000000000001304217427400204455ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.test/src/org/jacoco/000077500000000000000000000000001304217427400217035ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.test/src/org/jacoco/agent/000077500000000000000000000000001304217427400230015ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent.test/src/org/jacoco/agent/AgentJarTest.java000066400000000000000000000046741304217427400262120ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.junit.After; import org.junit.Test; /** * Unit tests for {@link AgentJar}. */ public class AgentJarTest { private File file; @After public void teardown() { if (file != null) { file.delete(); } } @Test public void testGetResource() throws IOException { final InputStream in = AgentJar.getResource().openStream(); assertAgentContents(in); } @Test public void testGetResourceAsStream() throws IOException { final InputStream in = AgentJar.getResourceAsStream(); assertAgentContents(in); } @Test public void testExtractTo() throws IOException { file = File.createTempFile("agent", ".jar"); AgentJar.extractTo(file); assertAgentContents(new FileInputStream(file)); } @Test(expected = IOException.class) public void testExtractToNegative() throws IOException { file = File.createTempFile("folder", null); file.delete(); file.mkdirs(); AgentJar.extractTo(file); } @Test public void testExtractToTempLocation() throws IOException { file = AgentJar.extractToTempLocation(); assertAgentContents(new FileInputStream(file)); file.delete(); } private void assertAgentContents(InputStream in) throws IOException { final ZipInputStream zip = new ZipInputStream(in); while (true) { final ZipEntry entry = zip.getNextEntry(); assertNotNull("Manifest not found.", entry); if ("META-INF/MANIFEST.MF".equals(entry.getName())) { final Manifest manifest = new Manifest(zip); assertEquals("JaCoCo Java Agent", manifest.getMainAttributes() .getValue("Implementation-Title")); in.close(); break; } } } } jacoco-0.7.8/org.jacoco.agent/000077500000000000000000000000001304217427400161115ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent/.classpath000066400000000000000000000014151304217427400200750ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.agent/.gitignore000066400000000000000000000000551304217427400201010ustar00rootroot00000000000000/target /bin /.settings /src/jacocoagent.jar jacoco-0.7.8/org.jacoco.agent/.project000066400000000000000000000016431304217427400175640ustar00rootroot00000000000000 org.jacoco.agent org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature src/jacocoagent.jar 1 PARENT-1-PROJECT_LOC/org.jacoco.agent/target/classes/jacocoagent.jar .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core/.settings jacoco-0.7.8/org.jacoco.agent/META-INF/000077500000000000000000000000001304217427400172515ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent/META-INF/MANIFEST.MF000066400000000000000000000004451304217427400207060ustar00rootroot00000000000000Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JaCoCo Agent Bundle-SymbolicName: org.jacoco.agent Bundle-Version: 0.7.8.201612092310 Bundle-Vendor: Mountainminds GmbH & Co. KG Bundle-RequiredExecutionEnvironment: J2SE-1.5 Export-Package: org.jacoco.agent;version="0.7.8" jacoco-0.7.8/org.jacoco.agent/README.TXT000066400000000000000000000010041304217427400174420ustar00rootroot00000000000000This bundle provides the coverage agent "jacocoagent.jar" as a resource. The agent JAR is created as part of the build process and therefore not available in the source tree. Which means this bundle is incomplete when directly used in the Eclise IDE. If you want to use the bundle org.jacoco.agent within the IDE, please run the local build (see documentation) first. The jacocoagent.jar file is created by the build at /org.jacoco.agent/target/classes/jacocoagent.jar and linked by this project. jacoco-0.7.8/org.jacoco.agent/about.html000066400000000000000000000051361304217427400201160ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

Third Party Content

The Content includes items that have been sourced from third parties as set out below.

ASM

This plug-in contains the ASM library which is subject to the terms and conditions of the following license:

Copyright (c) 2012 France Télécom
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holders nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
jacoco-0.7.8/org.jacoco.agent/pom.xml000066400000000000000000000054731304217427400174370ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.build 0.7.8 ../org.jacoco.build org.jacoco.agent JaCoCo :: Agent JaCoCo Agent src org.apache.maven.plugins maven-dependency-plugin prepare-package copy ${project.groupId} org.jacoco.agent.rt all ${project.version} jacocoagent.jar ${project.build.directory}/classes false false true org.codehaus.mojo build-helper-maven-plugin attach-artifacts package attach-artifact ${project.build.directory}/classes/jacocoagent.jar jar runtime jacoco-0.7.8/org.jacoco.agent/src/000077500000000000000000000000001304217427400167005ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent/src/org/000077500000000000000000000000001304217427400174675ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent/src/org/jacoco/000077500000000000000000000000001304217427400207255ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent/src/org/jacoco/agent/000077500000000000000000000000001304217427400220235ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.agent/src/org/jacoco/agent/AgentJar.java000066400000000000000000000067211304217427400243670ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.agent; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; /** * API to access the agent JAR file as a resource. While the agent is a JAR file * it is considered as a plain resource that must be configured for the * application under test (target JVM). The agent JAR does not provide any * public Java API. */ public final class AgentJar { /** * Name of the agent JAR file resource within this bundle. */ private static final String RESOURCE = "/jacocoagent.jar"; private AgentJar() { } /** * Returns a URL pointing to the JAR file. * * @return URL of the JAR file */ public static URL getResource() { final URL url = AgentJar.class.getResource(RESOURCE); if (url == null) { throw new AssertionError(ERRORMSG); } return url; } /** * Returns the content of the JAR file as a stream. * * @return content of the JAR file */ public static InputStream getResourceAsStream() { final InputStream stream = AgentJar.class.getResourceAsStream(RESOURCE); if (stream == null) { throw new AssertionError(ERRORMSG); } return stream; } /** * Extract the JaCoCo agent JAR and put it into a temporary location. This * file should be deleted on exit, but may not if the VM is terminated * * @return Location of the Agent Jar file in the local file system. The file * should exist and be readable. * @throws IOException * Unable to unpack agent jar */ public static File extractToTempLocation() throws IOException { final File agentJar = File.createTempFile("jacocoagent", ".jar"); agentJar.deleteOnExit(); extractTo(agentJar); return agentJar; } /** * Extract the JaCoCo agent JAR and put it into the specified location. * * @param destination * Location to write JaCoCo Agent Jar to. Must be writeable * @throws IOException * Unable to unpack agent jar */ public static void extractTo(File destination) throws IOException { InputStream inputJarStream = getResourceAsStream(); OutputStream outputJarStream = null; try { outputJarStream = new FileOutputStream(destination); final byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = inputJarStream.read(buffer)) != -1) { outputJarStream.write(buffer, 0, bytesRead); } } finally { safeClose(inputJarStream); safeClose(outputJarStream); } } /** * Close a stream ignoring any error * * @param closeable * stream to be closed */ private static void safeClose(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { } } private static final String ERRORMSG = String.format( "The resource %s has not been found. Please see " + "/org.jacoco.agent/README.TXT for details.", RESOURCE); } jacoco-0.7.8/org.jacoco.agent/src/org/jacoco/agent/package-info.java000066400000000000000000000012241304217427400252110ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ /** * Provides the runtime Java agent (JAR file) as a resource. */ package org.jacoco.agent;jacoco-0.7.8/org.jacoco.ant.test/000077500000000000000000000000001304217427400165535ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant.test/.classpath000066400000000000000000000014151304217427400205370ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.ant.test/.gitignore000066400000000000000000000000301304217427400205340ustar00rootroot00000000000000/target /bin /.settings jacoco-0.7.8/org.jacoco.ant.test/.project000066400000000000000000000013721304217427400202250ustar00rootroot00000000000000 org.jacoco.ant.test org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core.test/.settings jacoco-0.7.8/org.jacoco.ant.test/META-INF/000077500000000000000000000000001304217427400177135ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant.test/META-INF/MANIFEST.MF000066400000000000000000000005321304217427400213450ustar00rootroot00000000000000Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JaCoCo Ant Tasks Tests Bundle-SymbolicName: org.jacoco.ant.test Bundle-Version: 0.7.8.201612092310 Bundle-RequiredExecutionEnvironment: J2SE-1.5 Bundle-Vendor: Mountainminds GmbH & Co. KG and Contributors Fragment-Host: org.jacoco.ant Import-Package: org.junit;version="[4.8.0,5.0.0)" jacoco-0.7.8/org.jacoco.ant.test/about.html000066400000000000000000000262541304217427400205640ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

Third Party Content

The Content includes items that have been sourced from third parties as set out below.

Apache AntUnit 1.1

This plug-in contains the AntUnit library developed by The Apache Software Foundation (http://www.apache.org/) which is subject to the terms and conditions of the following license:

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.
jacoco-0.7.8/org.jacoco.ant.test/pom.xml000066400000000000000000000035101304217427400200670ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.tests 0.7.8 ../org.jacoco.tests org.jacoco.ant.test JaCoCo :: Test :: Ant org.jacoco.ant.* ${project.groupId} org.jacoco.ant junit junit org.apache.ant ant-antunit org.apache.ant ant-junit org.apache.maven.plugins maven-surefire-plugin ${project.build.outputDirectory}/org/jacoco/ant jacoco-0.7.8/org.jacoco.ant.test/src/000077500000000000000000000000001304217427400173425ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant.test/src/TestTargetInDefault.java000066400000000000000000000012111304217427400240620ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ /** * Test target in default directory. */ public class TestTargetInDefault { } jacoco-0.7.8/org.jacoco.ant.test/src/org/000077500000000000000000000000001304217427400201315ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/000077500000000000000000000000001304217427400213675ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/000077500000000000000000000000001304217427400221515ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/AgentTaskTest.java000066400000000000000000000017711304217427400255430ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.junit.runner.RunWith; @RunWith(AntUnitSuiteRunner.class) public class AgentTaskTest { public static TestSuite suite() { final File file = new File("src/org/jacoco/ant/AgentTaskTest.xml"); return new AntUnitSuite(file, AgentTaskTest.class); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/AgentTaskTest.xml000066400000000000000000000060301304217427400254130ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/AntFilesLocatorTest.java000066400000000000000000000045271304217427400267150ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.resources.FileResource; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link AntFilesLocator}. */ public class AntFilesLocatorTest { @Rule public final TemporaryFolder folder = new TemporaryFolder(); private AntFilesLocator locator; @Before public void setup() { locator = new AntFilesLocator("UTF-8", 4); } @Test public void testGetSourceFileNegative() throws IOException { assertNull(locator.getSourceFile("org/jacoco/somewhere", "DoesNotExist.java")); } @Test public void testGetSourceFile() throws IOException { locator.add(createFile("org/jacoco/example/Test.java")); final Reader source = locator.getSourceFile("org/jacoco/example", "Test.java"); assertContent(source); } private Resource createFile(String path) throws IOException { final File file = new File(folder.getRoot(), path); file.getParentFile().mkdirs(); final Writer writer = new OutputStreamWriter( new FileOutputStream(file), "UTF-8"); writer.write("Source"); writer.close(); return new FileResource(folder.getRoot(), path); } private void assertContent(Reader source) throws IOException { assertNotNull(source); final BufferedReader buffer = new BufferedReader(source); assertEquals("Source", buffer.readLine()); assertNull(buffer.readLine()); buffer.close(); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/AntResourcesLocatorTest.java000066400000000000000000000104521304217427400276170ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.resources.FileResource; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link AntResourcesLocator}. */ public class AntResourcesLocatorTest { @Rule public final TemporaryFolder folder = new TemporaryFolder(); private AntResourcesLocator locator; @Before public void setup() { locator = new AntResourcesLocator("UTF-8", 8); } @Test public void testGetTabWidth() { assertEquals(8, locator.getTabWidth()); } @Test public void testEmpty() { assertTrue(locator.isEmpty()); } @Test public void testFile() throws IOException { locator.add(createFile("org/jacoco/example/Test.java", "AAA")); assertFalse(locator.isEmpty()); final Reader source = locator.getSourceFile("org/jacoco/example", "Test.java"); assertContent("AAA", source); } @Test public void testDirectory() throws IOException { createFile("src/org/jacoco/example/Test.java", "AAA"); locator.add(new FileResource(folder.getRoot(), "src")); assertFalse(locator.isEmpty()); final Reader source = locator.getSourceFile("org/jacoco/example", "Test.java"); assertContent("AAA", source); } @Test public void testFilePrecedence() throws IOException { createFile("src/org/jacoco/example/Test.java", "DDD"); locator.add(new FileResource(folder.getRoot(), "src")); locator.add(createFile("org/jacoco/example/Test.java", "FFF")); final Reader source = locator.getSourceFile("org/jacoco/example", "Test.java"); assertContent("FFF", source); } @Test public void testDirectoryOrdering() throws IOException { createFile("src1/org/jacoco/example/Test.java", "AAA"); locator.add(new FileResource(folder.getRoot(), "src1")); createFile("src2/org/jacoco/example/Test.java", "BBB"); locator.add(new FileResource(folder.getRoot(), "src2")); createFile("src3/org/jacoco/example/Test.java", "CCC"); locator.add(new FileResource(folder.getRoot(), "src3")); final Reader source = locator.getSourceFile("org/jacoco/example", "Test.java"); assertContent("AAA", source); } @Test public void testAddAll() throws IOException { List resources = new ArrayList(); resources.add(createFile("org/jacoco/example/Test1.java", "AAA")); resources.add(createFile("org/jacoco/example/Test2.java", "BBB")); locator.addAll(resources.iterator()); assertFalse(locator.isEmpty()); Reader source = locator.getSourceFile("org/jacoco/example", "Test1.java"); assertContent("AAA", source); source = locator.getSourceFile("org/jacoco/example", "Test2.java"); assertContent("BBB", source); } private Resource createFile(String path, String content) throws IOException { final File file = new File(folder.getRoot(), path); file.getParentFile().mkdirs(); final Writer writer = new OutputStreamWriter( new FileOutputStream(file), "UTF-8"); writer.write(content); writer.close(); return new FileResource(folder.getRoot(), path); } private void assertContent(String expected, Reader source) throws IOException { assertNotNull(source); final BufferedReader buffer = new BufferedReader(source); assertEquals(expected, buffer.readLine()); assertNull(buffer.readLine()); buffer.close(); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/CoverageTaskTest.java000066400000000000000000000021461304217427400262350ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.junit.runner.RunWith; @RunWith(AntUnitSuiteRunner.class) public class CoverageTaskTest { public static TestSuite suite() { System.setProperty("org.jacoco.ant.coverageTaskTest.classes.dir", TestTarget.getClassPath()); final File file = new File("src/org/jacoco/ant/CoverageTaskTest.xml"); return new AntUnitSuite(file, CoverageTaskTest.class); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/CoverageTaskTest.xml000066400000000000000000000132611304217427400261140ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/CreateExecFiles.java000066400000000000000000000027401304217427400260120ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.jacoco.core.data.ExecutionData; import org.jacoco.core.data.ExecutionDataWriter; /** * Utility class to create exec files required for some Ant tests. */ public class CreateExecFiles { private static final String BASE_LOCATION = "./src/org/jacoco/ant/data/"; public static void main(String[] args) throws IOException { OutputStream out; out = new FileOutputStream(BASE_LOCATION + "sample1.exec"); new ExecutionDataWriter(out); out.close(); out = new FileOutputStream(BASE_LOCATION + "sample2.exec"); new ExecutionDataWriter(out); out.close(); out = new FileOutputStream(BASE_LOCATION + "nomatch.exec"); ExecutionDataWriter writer = new ExecutionDataWriter(out); writer.visitClassExecution(new ExecutionData(0, "org/jacoco/ant/TestTarget", new boolean[0])); out.close(); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/DumpExecClassNames.java000066400000000000000000000020771304217427400265060ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import org.jacoco.core.data.ExecutionData; import org.jacoco.core.tools.ExecFileLoader; /** * Test utility to dump class names from exec file. */ public class DumpExecClassNames { public static void main(String[] args) throws Exception { final ExecFileLoader loader = new ExecFileLoader(); for (String f : args) { loader.load(new File(f)); } for (ExecutionData d : loader.getExecutionDataStore().getContents()) { System.out.println(d.getName()); } } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/DumpTaskTest.java000066400000000000000000000017651304217427400254150ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.junit.runner.RunWith; @RunWith(AntUnitSuiteRunner.class) public class DumpTaskTest { public static TestSuite suite() { final File file = new File("src/org/jacoco/ant/DumpTaskTest.xml"); return new AntUnitSuite(file, DumpTaskTest.class); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/DumpTaskTest.xml000066400000000000000000000037441304217427400252730ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/DumpTaskWithServerTest.java000066400000000000000000000022021304217427400274230ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.junit.runner.RunWith; @RunWith(AntUnitSuiteRunner.class) public class DumpTaskWithServerTest { public static TestSuite suite() { System.setProperty("org.jacoco.ant.dumpTaskWithServerTest.classes.dir", TestTarget.getClassPath()); final File file = new File( "src/org/jacoco/ant/DumpTaskWithServerTest.xml"); return new AntUnitSuite(file, DumpTaskWithServerTest.class); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/DumpTaskWithServerTest.xml000066400000000000000000000045121304217427400273100ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/InstrumentTaskTest.java000066400000000000000000000024751304217427400266570ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import java.io.IOException; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.jacoco.agent.AgentJar; import org.junit.runner.RunWith; @RunWith(AntUnitSuiteRunner.class) public class InstrumentTaskTest { public static TestSuite suite() throws IOException { System.setProperty("org.jacoco.ant.instrumentTaskTest.classes.dir", TestTarget.getClassPath()); System.setProperty("org.jacoco.ant.instrumentTaskTest.agent.file", AgentJar.extractToTempLocation().getAbsolutePath()); final File file = new File("src/org/jacoco/ant/InstrumentTaskTest.xml"); return new AntUnitSuite(file, InstrumentTaskTest.class); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/InstrumentTaskTest.xml000066400000000000000000000121411304217427400265250ustar00rootroot00000000000000 destfile=test.exec jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/MergeTaskTest.java000066400000000000000000000017711304217427400255440ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.junit.runner.RunWith; @RunWith(AntUnitSuiteRunner.class) public class MergeTaskTest { public static TestSuite suite() { final File file = new File("src/org/jacoco/ant/MergeTaskTest.xml"); return new AntUnitSuite(file, MergeTaskTest.class); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/MergeTaskTest.xml000066400000000000000000000046761304217427400254320ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/RemoveDebugInfos.java000066400000000000000000000024051304217427400262200ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; /** * Test utility to remove debug information from class files. */ public class RemoveDebugInfos { public static void main(String[] args) throws Exception { final InputStream in = new FileInputStream(args[0]); final ClassReader reader = new ClassReader(in); in.close(); final ClassWriter writer = new ClassWriter(0); reader.accept(writer, ClassReader.SKIP_DEBUG); final OutputStream out = new FileOutputStream(args[1]); out.write(writer.toByteArray()); out.close(); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/ReportTaskLocaleTest.java000066400000000000000000000032461304217427400270770ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static org.junit.Assert.assertEquals; import java.util.Locale; import org.junit.Test; /** * Unit tests for the locale conversion built into {@link ReportTask}. */ public class ReportTaskLocaleTest { @Test public void testNone() { Locale locale = ReportTask.parseLocale(""); assertEquals("", locale.getLanguage()); assertEquals("", locale.getCountry()); assertEquals("", locale.getVariant()); } @Test public void testLanguage() { Locale locale = ReportTask.parseLocale("fr"); assertEquals("fr", locale.getLanguage()); assertEquals("", locale.getCountry()); assertEquals("", locale.getVariant()); } @Test public void testLanguageCountry() { Locale locale = ReportTask.parseLocale("fr_FR"); assertEquals("fr", locale.getLanguage()); assertEquals("FR", locale.getCountry()); assertEquals("", locale.getVariant()); } @Test public void testLanguageCountryVariant() { Locale locale = ReportTask.parseLocale("de_CH_Matte"); assertEquals("de", locale.getLanguage()); assertEquals("CH", locale.getCountry()); assertEquals("Matte", locale.getVariant()); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/ReportTaskTest.java000066400000000000000000000023121304217427400257500ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.junit.runner.RunWith; @RunWith(AntUnitSuiteRunner.class) public class ReportTaskTest { public static TestSuite suite() { System.setProperty("org.jacoco.ant.reportTaskTest.classes.dir", TestTarget.getClassPath()); System.setProperty("org.jacoco.ant.reportTaskTest.sources.dir", new File("./src").getAbsolutePath()); final File file = new File("src/org/jacoco/ant/ReportTaskTest.xml"); return new AntUnitSuite(file, ReportTaskTest.class); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/ReportTaskTest.xml000066400000000000000000000417571304217427400256470ustar00rootroot00000000000000 Source Code jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/TestTarget.java000066400000000000000000000035431304217427400251070ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import org.junit.Test; /** * Simple test target for Java applications ant JUnit4 tests. To assert * execution it creates an empty file target.txt in the working * directory. */ public class TestTarget { @Test public void testNothing() throws IOException { System.out.println("Target executed"); } public static void main(String[] args) throws Exception { // Load some class from the bootstrap classloader: new java.sql.Timestamp(0); System.out.println("Target executed"); // Wait for termination file to turn up // This option puts the target in a pseudo 'server' mode if (args.length == 1) { final File termFile = new File(args[0]); while (!termFile.exists()) { Thread.sleep(100); } } } /** * @return location where this class is located */ public static String getClassPath() { final String name = TestTarget.class.getName(); final String res = "/" + name.replace('.', '/') + ".class"; String loc = TestTarget.class.getResource(res).getFile(); try { loc = URLDecoder.decode(loc, "UTF-8"); } catch (UnsupportedEncodingException e) { } return loc.substring(0, loc.length() - res.length()); } } jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/data/000077500000000000000000000000001304217427400230625ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/data/keystore.jks000066400000000000000000000043001304217427400254350ustar00rootroot00000000000000þíþítestDVVb±0‚ü0 +*‚èY4tÐ’Òàâ/•ºM5áb약‡ ™;·Ôk`PÏ‚«R¿ËU¬|·wA#KQ”…¾,}\ŒfDÊRe[69ÓÂeû’œŒJÔÒ@­‘µçW‰(ì£kÈ!ƒé­ÇQ× (¢‹Äz'õqñX¦©¸a²çË}¦ÏýDÎr ¿ui¦«Ÿ†•`™yC(Ó# Ï9&£ª&ü»¡z­^D'qQiÑ5¦,Ézì2u43<)§¸m@[´hVyXóSë.g‰€Dr»þb[©ò«o\ÙÓÆÁúÓ’_9("¬ Êͺ o°Pwfâ·©ÖÞü×WkŠ8Ÿ¤¡•ÓY 0q% ÍK¯~Sö¥–‡î.óç–æf æolÍéaÔÙ°wà,“CÔ3èa»ß²‹i.’'ì_D\Äg†ó)ÇQ^î 4œãij—tx°Š´A¨û¡­‡ù·Êãêž«[ÿ‡¼IPëÓÐ}D7„Ú¶,p°’˄ǛèOÓ§²$tãªÍضJ샡uåTãaÞ²{"Y:퀦³¦™Ï¿­v¢û¥½~¨xmùÛ”·‚²”)˜}R3ÙÈc83·§³¦ôvîá¥ÓGÀžš¾µ±ê%B6²ŒõÑ"‡Ð[VøÖD³W,K#âûñHÈký‰ÛŒ´AZ©þÿ‹çÑ‹%CTï„ßöSÛ8%Ï\Æ£µÙÑ„›»o0+É“àê;ç0ÆÖhRÍÇŠ]n(í'•wÇâ51 QÿZ¡ ÐŽ¶éˆê£T]¶|ŠKPÒf/ %hHÃãµPÆßQÃì`Böžƒ©az“)½÷do»§Y›÷€+q~±ßIÝÖÛ³* œF‰eðÃ_V×z$m£üc$4ÖUØbÝÕ¢ Í”¯‚ÿa„ßÓð;æ(„²ÛÇe)BþùäS¼r;ª¯¬s÷[n¬Åè[#WuÅjš_‘sp…^9U¬©:SšñŽbÁŽkÙU¶ÇØá_‹çºø-êD‡€Þ|~²Á+–?R?¢#*ù–ñYÜa!RvyÁÂpÌÀwˆ tÛ}Õ8!+0=Àh6_òÓ]Ì€~ô{RvÖÌ´G#¤Òÿ:[5[–Ù™ä?UŸg[@XޝY>‡à½6?nà›¹šÿ<-ûVX)…“ªCÃ!¿˜÷ö}oͤýkÖ‰ÅDé42T Ž! ŒÇr›%¶m¹K¥Ii03CfÚ&ÛM ƒ{‹jˆTƒØÚ Œün¸øð°¼Ê^œØÐÊ…(RѦu!°µça½¢µ6Mt“(ÎÔªûÓø”ž€Ä8{[ê1Љj+QòÐè;VÙŒñKjÞâ”Fä1^HQ±«²¢œÎ|ዘ*C blj‘»ïY‹DÉ^@Îj[º0w :ÀŽWþ ´/©â¥=- ÏíÁîݶùnp="ªè- «q-sŒ o‚ñfeÉn<‘Êù ¬¿nmU†ä˜ÇšÌôØt­;M5úíyÎ<<w5æŠ2„.ÍèXõ‚E*X.509{0‚w0‚_ Â\Z0  *†H†÷  0l10UUnknown10UUnknown10UUnknown10U Unknown10U Unknown10UUnknown0 140221212454Z 231231212454Z0l10UUnknown10UUnknown10UUnknown10U Unknown10U Unknown10UUnknown0‚"0  *†H†÷ ‚0‚ ‚©ªŒËÊvê3÷“´ýnEòâ¬Â×§«tÁe𴦥[ï’¾V顤Sœþ•Ð1åp žü¡Ä9"‘ZÎ}Xਗw=Å7ôx}”šŸ œ`ï*ÁÕÿÛ‚t¥¢è\±¤_:Ñ –D°’Î/%óºl‘EU+3À‘Ýp%í’΂>Ù2z!—©E=€¨ƒšÁF(»¨ò¡GÌöcÆN<¢ž<5ò–G%5/~lÐˤB5)*.VRÈUŒÂÚ‹Ö󲎒ƒO›*¸Õê*ixý×øêŸvX94sMZñ×}o°d݈nœGMI ¯R̨è«Ù’sq;£!00U%"O ƒ:aØh9ÛB¿¦j%x0  *†H†÷  ‚‹ÌXÉ+ ì‘Ü!hmËV_ú1‹>¯6ŒÙåðpN8\ úÿaBخɹ;m¥’ŬGº P(”ñLBº@)&L-oS¸¦!N~#«f…—oÝsml¦ŽÚúóBd¼ºFr¨S »ÉŒ©‰ÿî^ßÊ—o.Æ+dû`ÂxI`[O ´)åáãðRÿ¼…ÿ¤†!æå[ ÿTOò–Gvþ3M» ”°6Õ·ÕjK!bMzeH/6ßž›‚—õâY“ìZ†§6Vx€½áF, ÙÅi®YDËE‡uf,·-‘ÔîvÖ©ñð[ ƒ¼Å¤ÐìLÊKÃU¡€³Rz]²Í¨þ7ûANÒé=«œ›ï^-^¦‡RÏjacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/data/nomatch.exec000066400000000000000000000000521304217427400253560ustar00rootroot00000000000000ÀÀorg/jacoco/ant/TestTargetjacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/data/sample.bad000066400000000000000000000000151304217427400250070ustar00rootroot00000000000000No exec file.jacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/data/sample1.exec000066400000000000000000000000051304217427400252650ustar00rootroot00000000000000ÀÀjacoco-0.7.8/org.jacoco.ant.test/src/org/jacoco/ant/data/sample2.exec000066400000000000000000000000051304217427400252660ustar00rootroot00000000000000ÀÀjacoco-0.7.8/org.jacoco.ant/000077500000000000000000000000001304217427400155755ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant/.classpath000066400000000000000000000014151304217427400175610ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.ant/.gitignore000066400000000000000000000000301304217427400175560ustar00rootroot00000000000000/target /bin /.settings jacoco-0.7.8/org.jacoco.ant/.project000066400000000000000000000013601304217427400172440ustar00rootroot00000000000000 org.jacoco.ant org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature .settings 2 PARENT-1-PROJECT_LOC/org.jacoco.core/.settings jacoco-0.7.8/org.jacoco.ant/META-INF/000077500000000000000000000000001304217427400167355ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant/META-INF/MANIFEST.MF000066400000000000000000000017461304217427400203770ustar00rootroot00000000000000Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JaCoCo Ant Tasks Bundle-SymbolicName: org.jacoco.ant Bundle-Version: 0.7.8.201612092310 Bundle-RequiredExecutionEnvironment: J2SE-1.5 Bundle-Vendor: Mountainminds GmbH & Co. KG and Contributors Require-Bundle: org.apache.ant;bundle-version="[1.7.0,2.0.0)" Import-Package: org.jacoco.agent;bundle-version="[0.7.8,0.7.9)", org.jacoco.core.analysis;bundle-version="[0.7.8,0.7.9)", org.jacoco.core.data;bundle-version="[0.7.8,0.7.9)", org.jacoco.core.instr;bundle-version="[0.7.8,0.7.9)", org.jacoco.core.runtime;bundle-version="[0.7.8,0.7.9)", org.jacoco.core.tools;bundle-version="[0.7.8,0.7.9)", org.jacoco.report;bundle-version="[0.7.8,0.7.9)", org.jacoco.report.check;bundle-version="[0.7.8,0.7.9)", org.jacoco.report.csv;bundle-version="[0.7.8,0.7.9)", org.jacoco.report.html;bundle-version="[0.7.8,0.7.9)", org.jacoco.report.xml;bundle-version="[0.7.8,0.7.9)", org.objectweb.asm;version="[5.1.0,5.2.0)" jacoco-0.7.8/org.jacoco.ant/about.html000066400000000000000000000051361304217427400176020ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

Third Party Content

The Content includes items that have been sourced from third parties as set out below.

ASM

This plug-in contains the ASM library which is subject to the terms and conditions of the following license:

Copyright (c) 2012 France Télécom
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holders nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
jacoco-0.7.8/org.jacoco.ant/pom.xml000066400000000000000000000046241304217427400171200ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.build 0.7.8 ../org.jacoco.build org.jacoco.ant JaCoCo :: Ant JaCoCo Ant Tasks ${project.groupId} org.jacoco.core ${project.groupId} org.jacoco.report ${project.groupId} org.jacoco.agent org.apache.ant ant provided src org.apache.maven.plugins maven-shade-plugin package shade true nodeps true org.objectweb.asm org.jacoco.asm jacoco-0.7.8/org.jacoco.ant/src/000077500000000000000000000000001304217427400163645ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant/src/org/000077500000000000000000000000001304217427400171535ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/000077500000000000000000000000001304217427400204115ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/000077500000000000000000000000001304217427400211735ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/AbstractCoverageTask.java000066400000000000000000000146531304217427400261110ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import java.io.IOException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.jacoco.agent.AgentJar; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.runtime.AgentOptions.OutputMode; /** * Base class for all coverage tasks that require agent options */ public class AbstractCoverageTask extends Task { private final AgentOptions agentOptions; private File destfile; private boolean enabled; /** * Create default agent options */ protected AbstractCoverageTask() { super(); agentOptions = new AgentOptions(); destfile = new File(AgentOptions.DEFAULT_DESTFILE); enabled = true; } /** * @return Whether or not the current task is enabled */ public boolean isEnabled() { return enabled; } /** * Sets whether or not the current task is enabled * * @param enabled * Enablement state of the task */ public void setEnabled(final boolean enabled) { this.enabled = enabled; } /** * Sets the location to write coverage execution data to. Default is * jacoco.exec. * * @param file * Location to write coverage execution data to */ public void setDestfile(final File file) { destfile = file; } /** * Append execution coverage data if a coverage file is already present. * Default is true * * @param append * true to append execution data to an existing file */ public void setAppend(final boolean append) { agentOptions.setAppend(append); } /** * List of wildcard patterns classes to include for instrumentation. Default * is * * * @param includes * Wildcard pattern of included classes */ public void setIncludes(final String includes) { agentOptions.setIncludes(includes); } /** * List of wildcard patterns classes to exclude from instrumentation. * Default is the empty string, no classes excluded * * @param excludes * Wildcard pattern of excluded classes */ public void setExcludes(final String excludes) { agentOptions.setExcludes(excludes); } /** * List of wildcard patterns for classloaders that JaCoCo will not * instrument classes from. Default is * sun.reflect.DelegatingClassLoader * * @param exclClassLoader * Wildcard pattern of class loaders to exclude */ public void setExclClassLoader(final String exclClassLoader) { agentOptions.setExclClassloader(exclClassLoader); } /** * Sets whether classes from the bootstrap classloader should be * instrumented. * * @param include * true if bootstrap classes should be instrumented */ public void setInclBootstrapClasses(final boolean include) { agentOptions.setInclBootstrapClasses(include); } /** * Sets whether classes without source location should be instrumented. * * @param include * true if classes without source location should be * instrumented */ public void setInclNoLocationClasses(final boolean include) { agentOptions.setInclNoLocationClasses(include); } /** * Sets the session identifier. Default is a auto-generated id * * @param id * session identifier */ public void setSessionId(final String id) { agentOptions.setSessionId(id); } /** * Dump coverage data on VM termination. Default is true * * @param dumpOnExit * true to write coverage data on VM termination */ public void setDumpOnExit(final boolean dumpOnExit) { agentOptions.setDumpOnExit(dumpOnExit); } /** * Sets the output method. Default is file * * @param output * Output method */ public void setOutput(final String output) { agentOptions.setOutput(output); } /** * Sets the IP address or hostname to bind to when output method is tcp * server or connect to when the output method is tcp client. Default is * localhost * * @param address * Address to bind or connect to */ public void setAddress(final String address) { agentOptions.setAddress(address); } /** * Sets the Port to bind to when the output method is tcp server or connect * to when the output method is tcp client. Default is 6300 * * @param port * port to bind to or connect to */ public void setPort(final int port) { agentOptions.setPort(port); } /** * Sets the directory where all class files seen by the agent should be * dumped to. * * @param dir * dump output location */ public void setClassdumpdir(final File dir) { agentOptions.setClassDumpDir(dir.getAbsolutePath()); } /** * Sets whether the agent should expose functionality via JMX. * * @param jmx * true if JMX should be enabled */ public void setJmx(final boolean jmx) { agentOptions.setJmx(jmx); } /** * Creates JVM argument to launch with the specified JaCoCo agent jar and * the current options * * @return JVM Argument to pass to new VM */ protected String getLaunchingArgument() { return prepareAgentOptions().getVMArgument(getAgentFile()); } private AgentOptions prepareAgentOptions() { if (OutputMode.file.equals(agentOptions.getOutput())) { agentOptions.setDestfile(destfile.getAbsolutePath()); } return agentOptions; } private File getAgentFile() { try { File agentFile = null; final String agentFileLocation = getProject().getProperty( "_jacoco.agentFile"); if (agentFileLocation != null) { agentFile = new File(agentFileLocation); } else { agentFile = AgentJar.extractToTempLocation(); getProject().setProperty("_jacoco.agentFile", agentFile.toString()); } return agentFile; } catch (final IOException e) { throw new BuildException("Unable to extract agent jar", e, getLocation()); } } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/AgentTask.java000066400000000000000000000031641304217427400237230ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import org.apache.tools.ant.BuildException; /** * Ant task that will unpack the coverage agent jar and generate the JVM options * required to use it */ public class AgentTask extends AbstractCoverageTask { private String property; /** * Sets the name of the property to hold the agent JVM options * * @param property * Name of the property to be populated */ public void setProperty(final String property) { this.property = property; } /** * Unpacks a private copy of the JaCoCo agent and populates * property with the JVM arguments required to use it. The * value set into the property is only valid for the lifetime of the current * JVM. The agent jar will be removed on termination of the JVM. */ @Override public void execute() throws BuildException { if (property == null || property.length() == 0) { throw new BuildException("Property is mandatory", getLocation()); } final String jvmArg = isEnabled() ? getLaunchingArgument() : ""; getProject().setNewProperty(property, jvmArg); } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/AntFilesLocator.java000066400000000000000000000031031304217427400250640ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.tools.ant.types.Resource; import org.jacoco.report.InputStreamSourceFileLocator; /** * Source locator based on Ant file resources. */ class AntFilesLocator extends InputStreamSourceFileLocator { private final Map resources; public AntFilesLocator(final String encoding, final int tabWidth) { super(encoding, tabWidth); this.resources = new HashMap(); } /** * Adds the given file resource as a potential source file. * * @param file * file resource to add */ void add(final Resource file) { resources.put(file.getName().replace(File.separatorChar, '/'), file); } @Override protected InputStream getSourceStream(final String path) throws IOException { final Resource file = resources.get(path); if (file == null) { return null; } else { return file.getInputStream(); } } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/AntResourcesLocator.java000066400000000000000000000045021304217427400260000ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * Dominik Stadler - source folder support * *******************************************************************************/ package org.jacoco.ant; import java.util.Iterator; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.resources.FileResource; import org.jacoco.report.DirectorySourceFileLocator; import org.jacoco.report.MultiSourceFileLocator; /** * Source file locator based on Ant resources. The locator supports files as * well as directories. The lookup is first performed on files (matching the * local file name) and afterwards on directories, by the order the directory * resources have been added. The directories are considered as source folders * that are searched for source files with the fully qualified name (package and * local name). */ class AntResourcesLocator extends MultiSourceFileLocator { private final String encoding; private final AntFilesLocator filesLocator; private boolean empty; AntResourcesLocator(final String encoding, final int tabWidth) { super(tabWidth); this.encoding = encoding; this.filesLocator = new AntFilesLocator(encoding, tabWidth); this.empty = true; super.add(filesLocator); } /** * Adds the given file or directory resource to the locator. * * @param resource * resource to add */ void add(final Resource resource) { empty = false; if (resource.isDirectory()) { final FileResource dir = (FileResource) resource; super.add(new DirectorySourceFileLocator(dir.getFile(), encoding, getTabWidth())); } else { filesLocator.add(resource); } } void addAll(final Iterator iterator) { while (iterator.hasNext()) { add((Resource) iterator.next()); } } /** * Checks, whether resources have been added. * * @return true, if no resources have been added */ boolean isEmpty() { return empty; } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/CoverageTask.java000066400000000000000000000130661304217427400244220ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - TestNG support * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static java.lang.String.format; import java.util.ArrayList; import java.util.Collection; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.RuntimeConfigurable; import org.apache.tools.ant.Task; import org.apache.tools.ant.TaskContainer; import org.apache.tools.ant.UnknownElement; /** * Container task to run Java/JUnit tasks with the JaCoCo agent jar. Coverage * will only be applied if all of the following are true: *
    *
  • Exactly one sub task may be present
  • *
  • Task must be either Java or JUnit
  • *
  • Task must be using a forked VM (so vm args can be passed)
  • *
*/ public class CoverageTask extends AbstractCoverageTask implements TaskContainer { private final Collection taskEnhancers = new ArrayList(); private Task childTask; /** * Creates a new default coverage task */ public CoverageTask() { super(); taskEnhancers.add(new JavaLikeTaskEnhancer("java")); taskEnhancers.add(new JavaLikeTaskEnhancer("junit")); taskEnhancers.add(new TestNGTaskEnhancer("testng")); } /** * Add child task to this container and reconfigure it to run with coverage * enabled */ public void addTask(final Task task) { if (childTask != null) { throw new BuildException( "Only one child task can be supplied to the coverge task", getLocation()); } this.childTask = task; final String subTaskTypeName = task.getTaskType(); final TaskEnhancer enhancer = findEnhancerForTask(subTaskTypeName); if (enhancer == null) { throw new BuildException(format( "%s is not a valid child of the coverage task", subTaskTypeName), getLocation()); } if (isEnabled()) { log(format("Enhancing %s with coverage", childTask.getTaskName())); enhancer.enhanceTask(task); } task.maybeConfigure(); } private TaskEnhancer findEnhancerForTask(final String taskName) { for (final TaskEnhancer enhancer : taskEnhancers) { if (enhancer.supportsTask(taskName)) { return enhancer; } } return null; } /** * Executes subtask and performs any required cleanup */ @Override public void execute() throws BuildException { if (childTask == null) { throw new BuildException( "A child task must be supplied for the coverage task", getLocation()); } childTask.execute(); } /** * Task enhancer for TestNG. TestNG task always run in a forked VM and has * nested jvmargs elements */ private class TestNGTaskEnhancer extends JavaLikeTaskEnhancer { public TestNGTaskEnhancer(final String supportedTaskName) { super(supportedTaskName); } @Override public void enhanceTask(final Task task) { addJvmArgs(task); } } /** * Basic task enhancer that can handle all 'java like' tasks. That is, tasks * that have a top level fork attribute and nested jvmargs elements */ private class JavaLikeTaskEnhancer implements TaskEnhancer { private final String supportedTaskName; public JavaLikeTaskEnhancer(final String supportedTaskName) { this.supportedTaskName = supportedTaskName; } public boolean supportsTask(final String taskname) { return taskname.equals(supportedTaskName); } public void enhanceTask(final Task task) { final RuntimeConfigurable configurableWrapper = task .getRuntimeConfigurableWrapper(); final String forkValue = getProject().replaceProperties( (String) configurableWrapper.getAttributeMap().get("fork")); if (!Project.toBoolean(forkValue)) { throw new BuildException( "Coverage can only be applied on a forked VM", getLocation()); } addJvmArgs(task); } public void addJvmArgs(final Task task) { final UnknownElement el = new UnknownElement("jvmarg"); el.setTaskName("jvmarg"); el.setQName("jvmarg"); final RuntimeConfigurable runtimeConfigurableWrapper = el .getRuntimeConfigurableWrapper(); runtimeConfigurableWrapper.setAttribute("value", getLaunchingArgument()); task.getRuntimeConfigurableWrapper().addChild( runtimeConfigurableWrapper); ((UnknownElement) task).addChild(el); } } /** * The task enhancer is responsible for potentially reconfiguring a task to * support running with code coverage enabled */ private interface TaskEnhancer { /** * @param taskname * Task type to enhance * @return true if this enhancer is capable of enhancing * the requested task type */ public boolean supportsTask(String taskname); /** * Attempt to enhance the supplied task with coverage information. This * operation may fail if the task is being executed in the current VM * * @param task * Task instance to enhance (usually an * {@link UnknownElement}) * @throws BuildException * Thrown if this enhancer can handle this type of task, but * this instance can not be enhanced for some reason. */ public void enhanceTask(Task task) throws BuildException; } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/DumpTask.java000066400000000000000000000104031304217427400235640ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static java.lang.String.format; import java.io.File; import java.io.IOException; import java.net.InetAddress; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.jacoco.core.runtime.AgentOptions; import org.jacoco.core.tools.ExecDumpClient; import org.jacoco.core.tools.ExecFileLoader; /** * Ant task for remotely controlling an application that is running with the * tcpserver output mode */ public class DumpTask extends Task { private boolean dump = true; private boolean reset = false; private File destfile = null; private String address = AgentOptions.DEFAULT_ADDRESS; private int port = AgentOptions.DEFAULT_PORT; private int retryCount = 10; private boolean append = true; /** * Sets the location of the execution data file to write. This parameter is * required when dump is true. Default is * jacoco.exec * * @param destfile * Location to write execution data to */ public void setDestfile(final File destfile) { this.destfile = destfile; } /** * IP Address or hostname to connect to. Defaults to localhost * * @param address * IP Address or hostname to connect to */ public void setAddress(final String address) { this.address = address; } /** * Port number to connect to. Default is 6300 * * @param port * Port to connect to */ public void setPort(final int port) { this.port = port; } /** * Number of retries which the goal will attempt to establish a connection. * This can be used to wait until the target JVM is successfully launched. * * @param retryCount * number of retries */ public void setRetryCount(final int retryCount) { this.retryCount = retryCount; } /** * true if the destination file it to be appended to. * false if the file is to be overwritten * * @param append * true if the destination file should be appended * to */ public void setAppend(final boolean append) { this.append = append; } /** * Sets whether execution data should be downloaded from the remote host. * Defaults to true * * @param dump * true to download execution data */ public void setDump(final boolean dump) { this.dump = dump; } /** * Sets whether a reset command should be sent after the execution data has * been dumped. Defaults to false * * @param reset * true to reset execution data */ public void setReset(final boolean reset) { this.reset = reset; } @Override public void execute() throws BuildException { if (port <= 0) { throw new BuildException("Invalid port value", getLocation()); } if (dump && destfile == null) { throw new BuildException( "Destination file is required when dumping execution data", getLocation()); } final ExecDumpClient client = new ExecDumpClient() { @Override protected void onConnecting(final InetAddress address, final int port) { log(format("Connecting to %s:%s", address, Integer.valueOf(port))); } @Override protected void onConnectionFailure(final IOException exception) { log(exception.getMessage()); } }; client.setDump(dump); client.setReset(reset); client.setRetryCount(retryCount); try { final ExecFileLoader loader = client.dump(address, port); if (dump) { log(format("Dumping execution data to %s", destfile.getAbsolutePath())); loader.save(destfile, append); } } catch (final IOException e) { throw new BuildException("Unable to dump coverage data", e, getLocation()); } } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/InstrumentTask.java000066400000000000000000000066251304217427400250420ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static java.lang.String.format; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.Union; import org.apache.tools.ant.util.FileUtils; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.OfflineInstrumentationAccessGenerator; /** * Task for offline instrumentation of class files. */ public class InstrumentTask extends Task { private File destdir; private final Union files = new Union(); private boolean removesignatures = true; /** * Sets the location of the instrumented classes. * * @param destdir * destination folder for instrumented classes */ public void setDestdir(final File destdir) { this.destdir = destdir; } /** * Sets whether signatures should be removed from JAR files. * * @param removesignatures * true if signatures should be removed */ public void setRemovesignatures(final boolean removesignatures) { this.removesignatures = removesignatures; } /** * This task accepts any number of class file resources. * * @param resources * Execution data resources */ public void addConfigured(final ResourceCollection resources) { files.add(resources); } @Override public void execute() throws BuildException { if (destdir == null) { throw new BuildException("Destination directory must be supplied", getLocation()); } int total = 0; final Instrumenter instrumenter = new Instrumenter( new OfflineInstrumentationAccessGenerator()); instrumenter.setRemoveSignatures(removesignatures); final Iterator resourceIterator = files.iterator(); while (resourceIterator.hasNext()) { final Resource resource = (Resource) resourceIterator.next(); if (resource.isDirectory()) { continue; } total += instrument(instrumenter, resource); } log(format("Instrumented %s classes to %s", Integer.valueOf(total), destdir.getAbsolutePath())); } private int instrument(final Instrumenter instrumenter, final Resource resource) { final File file = new File(destdir, resource.getName()); file.getParentFile().mkdirs(); try { InputStream input = null; OutputStream output = null; try { input = resource.getInputStream(); output = new FileOutputStream(file); return instrumenter.instrumentAll(input, output, resource.getName()); } finally { FileUtils.close(input); FileUtils.close(output); } } catch (final Exception e) { file.delete(); throw new BuildException(format("Error while instrumenting %s", resource), e, getLocation()); } } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/MergeTask.java000066400000000000000000000055731304217427400237320ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brock Janiczak - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static java.lang.String.format; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.Union; import org.apache.tools.ant.util.FileUtils; import org.jacoco.core.tools.ExecFileLoader; /** * Task for merging a set of execution data files (*.exec) into a single file */ public class MergeTask extends Task { private File destfile; private final Union files = new Union(); /** * Sets the location of the merged data store * * @param destfile * Destination data store location */ public void setDestfile(final File destfile) { this.destfile = destfile; } /** * This task accepts any number of execution data resources. * * @param resources * Execution data resources */ public void addConfigured(final ResourceCollection resources) { files.add(resources); } @Override public void execute() throws BuildException { if (destfile == null) { throw new BuildException("Destination file must be supplied", getLocation()); } final ExecFileLoader loader = new ExecFileLoader(); load(loader); save(loader); } private void load(final ExecFileLoader loader) { final Iterator resourceIterator = files.iterator(); while (resourceIterator.hasNext()) { final Resource resource = (Resource) resourceIterator.next(); if (resource.isDirectory()) { continue; } log(format("Loading execution data file %s", resource)); InputStream resourceStream = null; try { resourceStream = resource.getInputStream(); loader.load(resourceStream); } catch (final IOException e) { throw new BuildException(format("Unable to read %s", resource), e, getLocation()); } finally { FileUtils.close(resourceStream); } } } private void save(final ExecFileLoader loader) { log(format("Writing merged execution data to %s", destfile.getAbsolutePath())); try { loader.save(destfile, false); } catch (final IOException e) { throw new BuildException(format("Unable to write merged file %s", destfile.getAbsolutePath()), e, getLocation()); } } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/ReportTask.java000066400000000000000000000406221304217427400241400ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.ant; import static java.lang.String.format; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.resources.FileResource; import org.apache.tools.ant.types.resources.Union; import org.apache.tools.ant.util.FileUtils; import org.jacoco.core.analysis.Analyzer; import org.jacoco.core.analysis.CoverageBuilder; import org.jacoco.core.analysis.IBundleCoverage; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.ICoverageNode; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.tools.ExecFileLoader; import org.jacoco.report.FileMultiReportOutput; import org.jacoco.report.IMultiReportOutput; import org.jacoco.report.IReportGroupVisitor; import org.jacoco.report.IReportVisitor; import org.jacoco.report.MultiReportVisitor; import org.jacoco.report.ZipMultiReportOutput; import org.jacoco.report.check.IViolationsOutput; import org.jacoco.report.check.Limit; import org.jacoco.report.check.Rule; import org.jacoco.report.check.RulesChecker; import org.jacoco.report.csv.CSVFormatter; import org.jacoco.report.html.HTMLFormatter; import org.jacoco.report.xml.XMLFormatter; /** * Task for coverage report generation. */ public class ReportTask extends Task { /** * The source files are specified in a resource collection with additional * attributes. */ public static class SourceFilesElement extends Union { String encoding = null; int tabWidth = 4; /** * Defines the optional source file encoding. If not set the platform * default is used. * * @param encoding * source file encoding */ public void setEncoding(final String encoding) { this.encoding = encoding; } /** * Sets the tab stop width for the source pages. Default value is 4. * * @param tabWidth * number of characters per tab stop */ public void setTabwidth(final int tabWidth) { if (tabWidth <= 0) { throw new BuildException("Tab width must be greater than 0"); } this.tabWidth = tabWidth; } } /** * Container element for class file groups. */ public static class GroupElement { private final List children = new ArrayList(); private final Union classfiles = new Union(); private final SourceFilesElement sourcefiles = new SourceFilesElement(); private String name; /** * Sets the name of the group. * * @param name * name of the group */ public void setName(final String name) { this.name = name; } /** * Creates a new child group. * * @return new child group */ public GroupElement createGroup() { final GroupElement group = new GroupElement(); children.add(group); return group; } /** * Returns the nested resource collection for class files. * * @return resource collection for class files */ public Union createClassfiles() { return classfiles; } /** * Returns the nested resource collection for source files. * * @return resource collection for source files */ public SourceFilesElement createSourcefiles() { return sourcefiles; } } /** * Interface for child elements that define formatters. */ private abstract class FormatterElement { abstract IReportVisitor createVisitor() throws IOException; void finish() { } } /** * Formatter element for HTML reports. */ public class HTMLFormatterElement extends FormatterElement { private File destdir; private File destfile; private String footer = ""; private String encoding = "UTF-8"; private Locale locale = Locale.getDefault(); /** * Sets the output directory for the report. * * @param destdir * output directory */ public void setDestdir(final File destdir) { this.destdir = destdir; } /** * Sets the Zip output file for the report. * * @param destfile * Zip output file */ public void setDestfile(final File destfile) { this.destfile = destfile; } /** * Sets an optional footer text that will be displayed on every report * page. * * @param text * footer text */ public void setFooter(final String text) { this.footer = text; } /** * Sets the output encoding for generated HTML files. Default is UTF-8. * * @param encoding * output encoding */ public void setEncoding(final String encoding) { this.encoding = encoding; } /** * Sets the locale for generated text output. By default the platform * locale is used. * * @param locale * text locale */ public void setLocale(final String locale) { this.locale = parseLocale(locale); } @Override public IReportVisitor createVisitor() throws IOException { final IMultiReportOutput output; if (destfile != null) { if (destdir != null) { throw new BuildException( "Either destination directory or file must be supplied, not both", getLocation()); } final FileOutputStream stream = new FileOutputStream(destfile); output = new ZipMultiReportOutput(stream); } else { if (destdir == null) { throw new BuildException( "Destination directory or file must be supplied for html report", getLocation()); } output = new FileMultiReportOutput(destdir); } final HTMLFormatter formatter = new HTMLFormatter(); formatter.setFooterText(footer); formatter.setOutputEncoding(encoding); formatter.setLocale(locale); return formatter.createVisitor(output); } } /** * Formatter element for CSV reports. */ public class CSVFormatterElement extends FormatterElement { private File destfile; private String encoding = "UTF-8"; /** * Sets the output file for the report. * * @param destfile * output file */ public void setDestfile(final File destfile) { this.destfile = destfile; } @Override public IReportVisitor createVisitor() throws IOException { if (destfile == null) { throw new BuildException( "Destination file must be supplied for csv report", getLocation()); } final CSVFormatter formatter = new CSVFormatter(); formatter.setOutputEncoding(encoding); return formatter.createVisitor(new FileOutputStream(destfile)); } /** * Sets the output encoding for generated XML file. Default is UTF-8. * * @param encoding * output encoding */ public void setEncoding(final String encoding) { this.encoding = encoding; } } /** * Formatter element for XML reports. */ public class XMLFormatterElement extends FormatterElement { private File destfile; private String encoding = "UTF-8"; /** * Sets the output file for the report. * * @param destfile * output file */ public void setDestfile(final File destfile) { this.destfile = destfile; } /** * Sets the output encoding for generated XML file. Default is UTF-8. * * @param encoding * output encoding */ public void setEncoding(final String encoding) { this.encoding = encoding; } @Override public IReportVisitor createVisitor() throws IOException { if (destfile == null) { throw new BuildException( "Destination file must be supplied for xml report", getLocation()); } final XMLFormatter formatter = new XMLFormatter(); formatter.setOutputEncoding(encoding); return formatter.createVisitor(new FileOutputStream(destfile)); } } /** * Formatter element for coverage checks. */ public class CheckFormatterElement extends FormatterElement implements IViolationsOutput { private final List rules = new ArrayList(); private boolean violations = false; private boolean failOnViolation = true; private String violationsPropery = null; /** * Creates and adds a new rule. * * @return new rule */ public Rule createRule() { final Rule rule = new Rule(); rules.add(rule); return rule; } /** * Sets whether the build should fail in case of a violation. Default is * true. * * @param flag * if true the build fails on violation */ public void setFailOnViolation(final boolean flag) { this.failOnViolation = flag; } /** * Sets the name of a property to append the violation messages to. * * @param property * name of a property */ public void setViolationsProperty(final String property) { this.violationsPropery = property; } @Override public IReportVisitor createVisitor() throws IOException { final RulesChecker formatter = new RulesChecker(); formatter.setRules(rules); return formatter.createVisitor(this); } public void onViolation(final ICoverageNode node, final Rule rule, final Limit limit, final String message) { log(message, Project.MSG_ERR); violations = true; if (violationsPropery != null) { final String old = getProject().getProperty(violationsPropery); final String value = old == null ? message : String.format( "%s\n%s", old, message); getProject().setProperty(violationsPropery, value); } } @Override void finish() { if (violations && failOnViolation) { throw new BuildException( "Coverage check failed due to violated rules.", getLocation()); } } } private final Union executiondataElement = new Union(); private SessionInfoStore sessionInfoStore; private ExecutionDataStore executionDataStore; private final GroupElement structure = new GroupElement(); private final List formatters = new ArrayList(); /** * Returns the nested resource collection for execution data files. * * @return resource collection for execution files */ public Union createExecutiondata() { return executiondataElement; } /** * Returns the root group element that defines the report structure. * * @return root group element */ public GroupElement createStructure() { return structure; } /** * Creates a new HTML report element. * * @return HTML report element */ public HTMLFormatterElement createHtml() { final HTMLFormatterElement element = new HTMLFormatterElement(); formatters.add(element); return element; } /** * Creates a new CSV report element. * * @return CSV report element */ public CSVFormatterElement createCsv() { final CSVFormatterElement element = new CSVFormatterElement(); formatters.add(element); return element; } /** * Creates a new coverage check element. * * @return coverage check element */ public CheckFormatterElement createCheck() { final CheckFormatterElement element = new CheckFormatterElement(); formatters.add(element); return element; } /** * Creates a new XML report element. * * @return CSV report element */ public XMLFormatterElement createXml() { final XMLFormatterElement element = new XMLFormatterElement(); formatters.add(element); return element; } @Override public void execute() throws BuildException { loadExecutionData(); try { final IReportVisitor visitor = createVisitor(); visitor.visitInfo(sessionInfoStore.getInfos(), executionDataStore.getContents()); createReport(visitor, structure); visitor.visitEnd(); for (final FormatterElement f : formatters) { f.finish(); } } catch (final IOException e) { throw new BuildException("Error while creating report", e, getLocation()); } } private void loadExecutionData() { final ExecFileLoader loader = new ExecFileLoader(); for (final Iterator i = executiondataElement.iterator(); i.hasNext();) { final Resource resource = (Resource) i.next(); log(format("Loading execution data file %s", resource)); InputStream in = null; try { in = resource.getInputStream(); loader.load(in); } catch (final IOException e) { throw new BuildException(format( "Unable to read execution data file %s", resource), e, getLocation()); } finally { FileUtils.close(in); } } sessionInfoStore = loader.getSessionInfoStore(); executionDataStore = loader.getExecutionDataStore(); } private IReportVisitor createVisitor() throws IOException { final List visitors = new ArrayList(); for (final FormatterElement f : formatters) { visitors.add(f.createVisitor()); } return new MultiReportVisitor(visitors); } private void createReport(final IReportGroupVisitor visitor, final GroupElement group) throws IOException { if (group.name == null) { throw new BuildException("Group name must be supplied", getLocation()); } if (group.children.isEmpty()) { final IBundleCoverage bundle = createBundle(group); final SourceFilesElement sourcefiles = group.sourcefiles; final AntResourcesLocator locator = new AntResourcesLocator( sourcefiles.encoding, sourcefiles.tabWidth); locator.addAll(sourcefiles.iterator()); if (!locator.isEmpty()) { checkForMissingDebugInformation(bundle); } visitor.visitBundle(bundle, locator); } else { final IReportGroupVisitor groupVisitor = visitor .visitGroup(group.name); for (final GroupElement child : group.children) { createReport(groupVisitor, child); } } } private IBundleCoverage createBundle(final GroupElement group) throws IOException { final CoverageBuilder builder = new CoverageBuilder(); final Analyzer analyzer = new Analyzer(executionDataStore, builder); for (final Iterator i = group.classfiles.iterator(); i.hasNext();) { final Resource resource = (Resource) i.next(); if (resource.isDirectory() && resource instanceof FileResource) { analyzer.analyzeAll(((FileResource) resource).getFile()); } else { final InputStream in = resource.getInputStream(); analyzer.analyzeAll(in, resource.getName()); in.close(); } } final IBundleCoverage bundle = builder.getBundle(group.name); logBundleInfo(bundle, builder.getNoMatchClasses()); return bundle; } private void logBundleInfo(final IBundleCoverage bundle, final Collection nomatch) { log(format("Writing bundle '%s' with %s classes", bundle.getName(), Integer.valueOf(bundle.getClassCounter().getTotalCount()))); if (!nomatch.isEmpty()) { log(format( "Classes in bundle '%s' do no match with execution data. " + "For report generation the same class files must be used as at runtime.", bundle.getName()), Project.MSG_WARN); for (final IClassCoverage c : nomatch) { log(format("Execution data for class %s does not match.", c.getName()), Project.MSG_WARN); } } } private void checkForMissingDebugInformation(final ICoverageNode node) { if (node.getClassCounter().getTotalCount() > 0 && node.getLineCounter().getTotalCount() == 0) { log(format( "To enable source code annotation class files for bundle '%s' have to be compiled with debug information.", node.getName()), Project.MSG_WARN); } } /** * Splits a given underscore "_" separated string and creates a Locale. This * method is implemented as the method Locale.forLanguageTag() was not * available in Java 5. * * @param locale * String representation of a Locate * @return Locale instance */ static Locale parseLocale(final String locale) { final StringTokenizer st = new StringTokenizer(locale, "_"); final String language = st.hasMoreTokens() ? st.nextToken() : ""; final String country = st.hasMoreTokens() ? st.nextToken() : ""; final String variant = st.hasMoreTokens() ? st.nextToken() : ""; return new Locale(language, country, variant); } } jacoco-0.7.8/org.jacoco.ant/src/org/jacoco/ant/antlib.xml000066400000000000000000000015361304217427400231730ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.build/000077500000000000000000000000001304217427400161125ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.build/.gitignore000066400000000000000000000000101304217427400200710ustar00rootroot00000000000000/target jacoco-0.7.8/org.jacoco.build/.project000066400000000000000000000007161304217427400175650ustar00rootroot00000000000000 org.jacoco.build org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature jacoco-0.7.8/org.jacoco.build/pom.xml000066400000000000000000001054241304217427400174350ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.build 0.7.8 pom JaCoCo JaCoCo - Java Code Coverage Library http://jacoco.org 2009 Mountainminds GmbH & Co. KG Eclipse Public License v1.0 http://www.eclipse.org/legal/epl-v10.html repo mtnminds Marc R. Hoffmann hoffmann@mountainminds.com +1 Project Lead brock_j Brock Janiczak brockj@gmail.com +10 Developer mandrikov Evgeny Mandrikov mandrikov@gmail.com http://godin.net.ru SonarSource http://www.sonarsource.com +3 Build and release manager mfriedenhagen Mirko Friedenhagen mfriedenhagen@gmail.com +1 Developer Radek Liba Christoph Beck 3.0 ../org.jacoco.core ../org.jacoco.report ../org.jacoco.agent.rt ../org.jacoco.agent ../org.jacoco.ant ../jacoco-maven-plugin ../org.jacoco.tests ../org.jacoco.examples ../org.jacoco.doc ../jacoco scm:git:git://github.com/jacoco/jacoco.git scm:git:ssh://git@github.com:jacoco/jacoco.git https://github.com/jacoco/jacoco GitHub https://github.com/jacoco/jacoco/issues sonatype-nexus-staging Nexus Release Repository https://oss.sonatype.org/service/local/staging/deploy/maven2/ sonatype-nexus-snapshots Sonatype Nexus Snapshots ${sonatypeOssDistMgmtSnapshotsUrl} UTF-8 https://oss.sonatype.org/content/repositories/snapshots/ yyyyMMddhhmm http://www.jacoco.org/jacoco ${project.inceptionYear}, 2016 1.5 1.5 ${jvm.args} 5.1 1.7.1 4.8.2 ../${project.artifactId}.test/target/jacoco.exec ../${project.artifactId}.test/target/surefire-reports/ 1.5 1.5 ${project.groupId} org.jacoco.core ${project.version} ${project.groupId} org.jacoco.report ${project.version} ${project.groupId} org.jacoco.agent ${project.version} ${project.groupId} org.jacoco.agent runtime ${project.version} ${project.groupId} org.jacoco.agent.rt ${project.version} ${project.groupId} org.jacoco.ant ${project.version} ${project.groupId} org.jacoco.ant nodeps ${project.version} ${project.groupId} org.jacoco.examples ${project.version} org.ow2.asm asm-debug-all ${asm.version} org.apache.ant ant ${ant.version} org.apache.ant ant-junit ${ant.version} org.apache.ant ant-antunit 1.2 junit junit ${junit.version} src false **/*.java **/*.properties src true **/*.properties . true about.html org.apache.maven.plugins maven-antrun-plugin 1.6 org.apache.maven.plugins maven-assembly-plugin 2.2.1 org.apache.maven.plugins maven-clean-plugin 2.4.1 org.apache.maven.plugins maven-compiler-plugin 2.3.2 org.apache.maven.plugins maven-dependency-plugin 2.2 org.apache.maven.plugins maven-deploy-plugin 2.8.2 org.apache.maven.plugins maven-enforcer-plugin 1.0.1 org.apache.maven.plugins maven-install-plugin 2.3.1 org.apache.maven.plugins maven-invoker-plugin 2.0.0 org.apache.maven.plugins maven-gpg-plugin 1.3 org.apache.maven.plugins maven-jar-plugin 2.3.1 org.apache.maven.plugins maven-javadoc-plugin 2.8 true false org.apache.maven.plugins maven-plugin-plugin 3.3 org.apache.maven.plugins maven-release-plugin 2.1 true forked-path false -Prelease org.apache.maven.plugins maven-resources-plugin 2.5 org.apache.maven.plugins maven-shade-plugin 2.4.3 org.apache.maven.plugins maven-source-plugin 2.1.2 org.apache.maven.plugins maven-surefire-plugin 2.9 org.apache.maven.plugins maven-site-plugin 3.3 org.apache.maven.plugins maven-toolchains-plugin 1.0 org.codehaus.mojo animal-sniffer-maven-plugin 1.6 org.codehaus.mojo build-helper-maven-plugin 1.5 org.codehaus.mojo buildnumber-maven-plugin 1.2 org.codehaus.mojo xml-maven-plugin 1.0 org.codehaus.groovy.maven gmaven-plugin 1.0 org.apache.maven.plugins maven-surefire-plugin ${project.build.sourceDirectory} ${project.build.outputDirectory} org.apache.maven.plugins maven-resources-plugin false @*@ $*$ org.apache.maven.plugins maven-shade-plugin *:* META-INF/*.SF META-INF/*.DSA META-INF/*.RSA ${project.description} ${project.organization.name} ${project.version} org.apache.maven.plugins maven-assembly-plugin 420 493 493 org.apache.maven.plugins maven-enforcer-plugin enforce validate enforce The rules for repo1.maven.org are that pom.xml files should not include repository definitions. true true No SNAPSHOT versions allowed for dependencies true [3.0.0,3.0.3),[3.0.4,) org.apache.maven.plugins maven-antrun-plugin check-license-header validate run org.codehaus.mojo build-helper-maven-plugin parse-version validate parse-version org.codehaus.mojo buildnumber-maven-plugin validate create false false true 0000000 org.codehaus.groovy.maven gmaven-plugin parse-version validate execute major = project.properties['parsedVersion.majorVersion'] minor = project.properties['parsedVersion.minorVersion'] incremental = project.properties['parsedVersion.incrementalVersion'] qualifier = "${maven.build.timestamp}" project.properties['buildQualifier'] = qualifier project.properties['unqualifiedVersion'] = major + '.' + minor + '.' + incremental project.properties['qualified.bundle.version'] = project.properties['unqualifiedVersion'] + '.' + project.properties['buildQualifier'] project.properties['build.date'] = qualifier.substring(0, 4) + '/' + qualifier.substring(4, 6) + '/' + qualifier.substring(6, 8) buildNumber = project.properties['buildNumber'] project.properties['jacoco.runtime.package.name'] = "org.jacoco.agent.rt.internal_" + buildNumber.substring(buildNumber.length() - 7, buildNumber.length()) integration-tests jdk.version org.apache.maven.plugins maven-toolchains-plugin validate toolchain ${jdk.version} bytecode bytecode.version ${bytecode.version} ${bytecode.version} java9-validation bytecode.version 1.9 1.8 1.8 jdk16 jdk.version 1.6 -XX:-FailOverToOldVerifier -Xverify:all jdk17 jdk.version 1.7 -XX:-FailOverToOldVerifier -Xverify:all jdk18 jdk.version 1.8 -XX:-FailOverToOldVerifier -Xverify:all jdk9 jdk.version 1.9 -XX:-FailOverToOldVerifier -Xverify:all manifest META-INF/MANIFEST.MF ${project.build.directory}/META-INF/MANIFEST.MF org.apache.maven.plugins maven-antrun-plugin translate-qualifier generate-resources run org.apache.maven.plugins maven-jar-plugin ${bundle-manifest} scm:git:git://github.com/jacoco/jacoco.git;path="${project.artifactId}";commitId=${buildNumber} sources src/ org.apache.maven.plugins maven-source-plugin attach-sources verify jar-no-fork org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar release org.apache.maven.plugins maven-enforcer-plugin false enforce-release-rules verify enforce buildNumber [0-9a-f]{40} org.codehaus.mojo animal-sniffer-maven-plugin enforce-java-api-compatibility verify check org.codehaus.mojo.signature java15 1.0 org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign m2e m2e.version org.eclipse.m2e lifecycle-mapping 1.0.0 org.apache.maven.plugins maven-antrun-plugin [0,) run org.apache.maven.plugins maven-invoker-plugin [0,) install org.apache.maven.plugins maven-dependency-plugin [0,) unpack copy-dependencies org.codehaus.groovy.maven gmaven-plugin [0,) execute org.codehaus.mojo xml-maven-plugin [0,) transform org.jacoco jacoco-maven-plugin [0,) prepare-agent org.apache.maven.plugins maven-enforcer-plugin [0,) enforce org.codehaus.mojo build-helper-maven-plugin [0,) parse-version jacoco-0.7.8/org.jacoco.build/publish.sh000077500000000000000000000004131304217427400201150ustar00rootroot00000000000000#!/bin/sh -e if [ "$1" = "" ]; then echo "Usage: $0 " exit 1 fi USERNAME=$1 ssh $USERNAME,eclemma@shell.sourceforge.net create ssh $USERNAME,eclemma@shell.sourceforge.net '/home/project-web/eclemma/scripts/publish-jacoco-snapshot.sh' jacoco-0.7.8/org.jacoco.core.test/000077500000000000000000000000001304217427400167215ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/.classpath000066400000000000000000000013671304217427400207130ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.core.test/.gitignore000066400000000000000000000000151304217427400207050ustar00rootroot00000000000000/target /bin jacoco-0.7.8/org.jacoco.core.test/.project000066400000000000000000000010741304217427400203720ustar00rootroot00000000000000 org.jacoco.core.test org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature jacoco-0.7.8/org.jacoco.core.test/.settings/000077500000000000000000000000001304217427400206375ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/.settings/org.eclipse.core.resources.prefs000066400000000000000000000001541304217427400270520ustar00rootroot00000000000000eclipse.preferences.version=1 encoding/src/test/resources=UTF-8 encoding/=UTF-8 encoding/src=UTF-8 jacoco-0.7.8/org.jacoco.core.test/.settings/org.eclipse.jdt.core.prefs000066400000000000000000000641711304217427400256320ustar00rootroot00000000000000#Sat Sep 05 17:52:24 CEST 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=warning org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=error org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_assignment=0 org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 org.eclipse.jdt.core.formatter.blank_lines_after_package=1 org.eclipse.jdt.core.formatter.blank_lines_before_field=0 org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 org.eclipse.jdt.core.formatter.blank_lines_before_method=1 org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 org.eclipse.jdt.core.formatter.blank_lines_before_package=0 org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false org.eclipse.jdt.core.formatter.comment.format_block_comments=true org.eclipse.jdt.core.formatter.comment.format_header=false org.eclipse.jdt.core.formatter.comment.format_html=true org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true org.eclipse.jdt.core.formatter.comment.format_line_comments=true org.eclipse.jdt.core.formatter.comment.format_source_code=true org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true org.eclipse.jdt.core.formatter.comment.indent_root_tags=true org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert org.eclipse.jdt.core.formatter.comment.line_length=80 org.eclipse.jdt.core.formatter.compact_else_if=true org.eclipse.jdt.core.formatter.continuation_indentation=2 org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_empty_lines=false org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false org.eclipse.jdt.core.formatter.indentation.size=4 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false org.eclipse.jdt.core.formatter.lineSplit=80 org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.size=4 org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true jacoco-0.7.8/org.jacoco.core.test/.settings/org.eclipse.jdt.ui.prefs000066400000000000000000000053271304217427400253150ustar00rootroot00000000000000#Thu Jul 02 08:45:19 CEST 2009 eclipse.preferences.version=1 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true formatter_profile=org.eclipse.jdt.ui.default.eclipse_profile formatter_settings_version=11 sp_cleanup.add_default_serial_version_id=true sp_cleanup.add_generated_serial_version_id=false sp_cleanup.add_missing_annotations=true sp_cleanup.add_missing_deprecated_annotations=true sp_cleanup.add_missing_methods=false sp_cleanup.add_missing_nls_tags=false sp_cleanup.add_missing_override_annotations=true sp_cleanup.add_serial_version_id=false sp_cleanup.always_use_blocks=true sp_cleanup.always_use_parentheses_in_expressions=false sp_cleanup.always_use_this_for_non_static_field_access=false sp_cleanup.always_use_this_for_non_static_method_access=false sp_cleanup.convert_to_enhanced_for_loop=false sp_cleanup.correct_indentation=false sp_cleanup.format_source_code=true sp_cleanup.format_source_code_changes_only=false sp_cleanup.make_local_variable_final=false sp_cleanup.make_parameters_final=false sp_cleanup.make_private_fields_final=true sp_cleanup.make_type_abstract_if_missing_method=false sp_cleanup.make_variable_declarations_final=true sp_cleanup.never_use_blocks=false sp_cleanup.never_use_parentheses_in_expressions=true sp_cleanup.on_save_use_additional_actions=true sp_cleanup.organize_imports=true sp_cleanup.qualify_static_field_accesses_with_declaring_class=false sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true sp_cleanup.qualify_static_member_accesses_with_declaring_class=false sp_cleanup.qualify_static_method_accesses_with_declaring_class=false sp_cleanup.remove_private_constructors=true sp_cleanup.remove_trailing_whitespaces=false sp_cleanup.remove_trailing_whitespaces_all=true sp_cleanup.remove_trailing_whitespaces_ignore_empty=false sp_cleanup.remove_unnecessary_casts=true sp_cleanup.remove_unnecessary_nls_tags=false sp_cleanup.remove_unused_imports=false sp_cleanup.remove_unused_local_variables=false sp_cleanup.remove_unused_private_fields=true sp_cleanup.remove_unused_private_members=false sp_cleanup.remove_unused_private_methods=true sp_cleanup.remove_unused_private_types=true sp_cleanup.sort_members=false sp_cleanup.sort_members_all=false sp_cleanup.use_blocks=false sp_cleanup.use_blocks_only_for_return_and_throw=false sp_cleanup.use_parentheses_in_expressions=false sp_cleanup.use_this_for_non_static_field_access=false sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true sp_cleanup.use_this_for_non_static_method_access=false sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true jacoco-0.7.8/org.jacoco.core.test/META-INF/000077500000000000000000000000001304217427400200615ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/META-INF/MANIFEST.MF000066400000000000000000000006541304217427400215200ustar00rootroot00000000000000Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JaCoCo Core Tests Bundle-SymbolicName: org.jacoco.core.test Bundle-Version: 0.7.8.201612092310 Bundle-Vendor: Mountainminds GmbH & Co. KG Fragment-Host: org.jacoco.core Bundle-RequiredExecutionEnvironment: J2SE-1.5 Import-Package: org.junit;version="[4.8.0,5.0.0)", org.junit.rules;version="[4.8.0,5.0.0)", org.objectweb.asm.util;version="[5.1.0,5.2.0)" jacoco-0.7.8/org.jacoco.core.test/about.html000066400000000000000000000014761304217427400207310ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

jacoco-0.7.8/org.jacoco.core.test/pom.xml000066400000000000000000000063401304217427400202410ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.tests 0.7.8 ../org.jacoco.tests org.jacoco.core.test JaCoCo :: Test :: Core org.jacoco.core.* ${project.groupId} org.jacoco.core junit junit java8-validation bytecode.version 1.8 org.codehaus.mojo build-helper-maven-plugin add-source generate-sources add-source src-java8 java9-validation bytecode.version 1.9 1.9 org.codehaus.mojo build-helper-maven-plugin add-source generate-sources add-source src-java8 jacoco-0.7.8/org.jacoco.core.test/src-java8/000077500000000000000000000000001304217427400205175ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/000077500000000000000000000000001304217427400213065ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/000077500000000000000000000000001304217427400225445ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/000077500000000000000000000000001304217427400234745ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/000077500000000000000000000000001304217427400244535ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/000077500000000000000000000000001304217427400266055ustar00rootroot00000000000000BadCycleInterfaceTest.java000066400000000000000000000033761304217427400335310ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.BadCycleInterface; import org.junit.Test; /** * Test of "bad cycles" with interfaces. */ public class BadCycleInterfaceTest extends ValidationTestBase { public BadCycleInterfaceTest() throws Exception { super("src-java8", BadCycleInterface.class); } @Test public void test() throws Exception { if (System.getProperty("java.version").startsWith("1.8")) { // Incorrect interpetation of JVMS 5.5 in JDK 8 causes a default // method to be called before the static initializer of an interface // (see JDK-8098557 and JDK-8164302): assertLine("baseclinit", ICounter.FULLY_COVERED); assertLine("childdefault", ICounter.FULLY_COVERED); assertLogEvents("baseclinit", "childdefaultmethod", "childclinit", "childstaticmethod"); } else { // This shouldn't happen with JDK 9 (see also JDK-8043275): assertLine("baseclinit", ICounter.EMPTY); assertLine("childdefault", ICounter.NOT_COVERED); assertLogEvents("childclinit", "childstaticmethod"); } assertLine("childclinit", ICounter.FULLY_COVERED); assertLine("childstatic", ICounter.FULLY_COVERED); } } InterfaceDefaultMethodsTest.java000066400000000000000000000022361304217427400347650ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.InterfaceDefaultMethodsTarget; import org.junit.Test; /** * Tests of static initializer and default methods in interfaces. */ public class InterfaceDefaultMethodsTest extends ValidationTestBase { public InterfaceDefaultMethodsTest() { super("src-java8", InterfaceDefaultMethodsTarget.class); } @Test public void testCoverageResult() { assertLine("clinit", ICounter.FULLY_COVERED); assertLine("m1", ICounter.FULLY_COVERED); assertLine("m2", ICounter.NOT_COVERED); } } InterfaceOnlyDefaultMethodsTest.java000066400000000000000000000021431304217427400356240ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.InterfaceOnlyDefaultMethodsTarget; import org.junit.Test; /** * Tests of default methods in interfaces. */ public class InterfaceOnlyDefaultMethodsTest extends ValidationTestBase { public InterfaceOnlyDefaultMethodsTest() { super("src-java8", InterfaceOnlyDefaultMethodsTarget.class); } @Test public void testCoverageResult() { assertLine("m1", ICounter.FULLY_COVERED); assertLine("m2", ICounter.NOT_COVERED); } } LambdaExpressionsTest.java000066400000000000000000000022031304217427400336510ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.LambdaExpressionsTarget; import org.junit.Test; /** * Tests for different lambda expressions. */ public class LambdaExpressionsTest extends ValidationTestBase { public LambdaExpressionsTest() { super("src-java8", LambdaExpressionsTarget.class); } @Test public void testCoverageResult() { // Coverage of lambda bodies assertLine("executedlambdabody", ICounter.FULLY_COVERED); assertLine("notexecutedlambdabody", ICounter.NOT_COVERED); } } LambdaInInterfaceTest.java000066400000000000000000000023301304217427400335170ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.LambdaInInterfaceTarget; import org.junit.Test; /** * Tests a constant with a lambda value in an interface. */ public class LambdaInInterfaceTest extends ValidationTestBase { public LambdaInInterfaceTest() { super("src-java8", LambdaInInterfaceTarget.class); } @Override protected void run(final Class targetClass) throws Exception { ((Runnable) targetClass.getField("RUN").get(null)).run(); } @Test public void testCoverageResult() { // Coverage of lambda body assertLine("lambdabody", ICounter.FULLY_COVERED); } } jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/targets/000077500000000000000000000000001304217427400302565ustar00rootroot00000000000000BadCycleInterface.java000066400000000000000000000024571304217427400343410ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/targets/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; public class BadCycleInterface { public interface Base { static final Object BASE_CONST = new Child() { { Stubs.logEvent("baseclinit"); // $line-baseclinit$ } }.childDefaultMethod(); default void baseDefaultMethod() { } } public interface Child extends Base { static final Object CHILD_CONST = new Object() { { Stubs.logEvent("childclinit"); // $line-childclinit$ } }; default Object childDefaultMethod() { Stubs.logEvent("childdefaultmethod"); // $line-childdefault$ return null; } static void childStaticMethod() { Stubs.logEvent("childstaticmethod"); // $line-childstatic$ } } public static void main(String[] args) { Child.childStaticMethod(); } } InterfaceDefaultMethodsTarget.java000066400000000000000000000021561304217427400367460ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/targets/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.i1; /** * This test target is an interface with a class initializer and default methods. */ public interface InterfaceDefaultMethodsTarget { public static final int CONST = i1(); // $line-clinit$ default void m1() { return; // $line-m1$ } default void m2() { return; // $line-m2$ } public class Impl implements InterfaceDefaultMethodsTarget { public Impl() { m1(); } } public static void main(String[] args) { new Impl(); } } InterfaceOnlyDefaultMethodsTarget.java000066400000000000000000000020141304217427400376010ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/targets/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; /** * This test target is an interface with only default methods. */ public interface InterfaceOnlyDefaultMethodsTarget { // no , only default methods: default void m1() { return; // $line-m1$ } default void m2() { return; // $line-m2$ } public class Impl implements InterfaceOnlyDefaultMethodsTarget { public Impl() { m1(); } } public static void main(String[] args) { new Impl(); } } LambdaExpressionsTarget.java000066400000000000000000000021141304217427400356320ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/targets/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.exec; import static org.jacoco.core.test.validation.targets.Stubs.noexec; import static org.jacoco.core.test.validation.targets.Stubs.nop; /** * This test target contains different lambda expressions. */ public class LambdaExpressionsTarget { public static void main(String[] args) { exec(() -> { nop(); // $line-executedlambdabody$ }); noexec(() -> { nop(); // $line-notexecutedlambdabody$ }); } } LambdaInInterfaceTarget.java000066400000000000000000000015711304217427400355050ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src-java8/org/jacoco/core/test/validation/targets/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.nop; /** * This test target builds a constant with a lambda value in an interface. */ public interface LambdaInInterfaceTarget { public static final Runnable RUN = () -> { nop(); // $line-lambdabody$ }; } jacoco-0.7.8/org.jacoco.core.test/src/000077500000000000000000000000001304217427400175105ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/000077500000000000000000000000001304217427400202775ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/000077500000000000000000000000001304217427400215355ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/000077500000000000000000000000001304217427400224655ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/JaCoCoTest.java000066400000000000000000000017061304217427400252720ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core; import static org.junit.Assert.assertNotNull; import org.junit.Test; /** * Unit tests for {@link JaCoCo}. */ public class JaCoCoTest { @Test public void testVERSION() { assertNotNull(JaCoCo.VERSION); } @Test public void testHOMEURL() { assertNotNull(JaCoCo.HOMEURL); } @Test public void testRUNTIMEPACKAGE() { assertNotNull(JaCoCo.RUNTIMEPACKAGE); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/analysis/000077500000000000000000000000001304217427400243105ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/analysis/AnalyzerTest.java000066400000000000000000000255431304217427400276110ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.jar.JarInputStream; import java.util.jar.Pack200; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.internal.Java9Support; import org.jacoco.core.internal.data.CRC64; import org.jacoco.core.test.TargetLoader; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link Analyzer}. */ public class AnalyzerTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); private Analyzer analyzer; private Map classes; private ExecutionDataStore executionData; private class EmptyStructureVisitor implements ICoverageVisitor { public void visitCoverage(IClassCoverage coverage) { final String name = coverage.getName(); assertNull("Class already processed: " + name, classes.put(name, coverage)); } } @Before public void setup() { classes = new HashMap(); executionData = new ExecutionDataStore(); analyzer = new Analyzer(executionData, new EmptyStructureVisitor()); } @Test public void testAnalyzeClassFromStream() throws IOException { analyzer.analyzeClass(TargetLoader.getClassData(AnalyzerTest.class), "Test"); assertClasses("org/jacoco/core/analysis/AnalyzerTest"); } @Test public void testAnalyzeClassFromByteArray() throws IOException { analyzer.analyzeClass( TargetLoader.getClassDataAsBytes(AnalyzerTest.class), "Test"); assertClasses("org/jacoco/core/analysis/AnalyzerTest"); assertFalse(classes.get("org/jacoco/core/analysis/AnalyzerTest") .isNoMatch()); } @Test public void testAnalyzeClassIdMatch() throws IOException { // class IDs are always calculated after downgrade of the version final byte[] bytes = Java9Support.downgradeIfRequired( TargetLoader.getClassDataAsBytes(AnalyzerTest.class)); executionData.get(Long.valueOf(CRC64.checksum(bytes)), "org/jacoco/core/analysis/AnalyzerTest", 200); analyzer.analyzeClass(bytes, "Test"); assertFalse(classes.get("org/jacoco/core/analysis/AnalyzerTest") .isNoMatch()); } @Test public void testAnalyzeClassNoIdMatch() throws IOException { executionData.get(Long.valueOf(0), "org/jacoco/core/analysis/AnalyzerTest", 200); analyzer.analyzeClass( TargetLoader.getClassDataAsBytes(AnalyzerTest.class), "Test"); assertTrue(classes.get("org/jacoco/core/analysis/AnalyzerTest") .isNoMatch()); } @Test public void testAnalyzeClass_Broken() throws IOException { final byte[] brokenclass = TargetLoader .getClassDataAsBytes(AnalyzerTest.class); brokenclass[10] = 0x23; try { analyzer.analyzeClass(brokenclass, "Broken.class"); fail("expected exception"); } catch (IOException e) { assertEquals("Error while analyzing Broken.class.", e.getMessage()); } } @Test public void testAnalyzeAll_Class() throws IOException { final int count = analyzer.analyzeAll( TargetLoader.getClassData(AnalyzerTest.class), "Test"); assertEquals(1, count); assertClasses("org/jacoco/core/analysis/AnalyzerTest"); } @Test public void testAnalyzeAll_Zip() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(buffer); zip.putNextEntry(new ZipEntry( "org/jacoco/core/analysis/AnalyzerTest.class")); zip.write(TargetLoader.getClassDataAsBytes(AnalyzerTest.class)); zip.finish(); final int count = analyzer.analyzeAll( new ByteArrayInputStream(buffer.toByteArray()), "Test"); assertEquals(1, count); assertClasses("org/jacoco/core/analysis/AnalyzerTest"); } @Test public void testAnalyzeAll_EmptyZipEntry() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(buffer); zip.putNextEntry(new ZipEntry("empty.txt")); zip.finish(); final int count = analyzer.analyzeAll( new ByteArrayInputStream(buffer.toByteArray()), "Test"); assertEquals(0, count); } /** * Triggers exception in * {@link Analyzer#analyzeAll(java.io.InputStream, String)}. */ @Test public void testAnalyzeAll_Broken() throws IOException { try { analyzer.analyzeAll(new InputStream() { @Override public int read() throws IOException { throw new IOException(); } }, "Test"); fail("expected exception"); } catch (IOException e) { assertEquals("Error while analyzing Test.", e.getMessage()); } } /** * Triggers exception in * {@link Analyzer#analyzeGzip(java.io.InputStream, String)}. */ @Test public void testAnalyzeAll_BrokenGZ() { final byte[] buffer = new byte[] { 0x1f, (byte) 0x8b, 0x00, 0x00 }; try { analyzer.analyzeAll(new ByteArrayInputStream(buffer), "Test.gz"); fail("expected exception"); } catch (IOException e) { assertEquals("Error while analyzing Test.gz.", e.getMessage()); } } @Test public void testAnalyzeAll_Pack200() throws IOException { final ByteArrayOutputStream zipbuffer = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(zipbuffer); zip.putNextEntry(new ZipEntry( "org/jacoco/core/analysis/AnalyzerTest.class")); zip.write(TargetLoader.getClassDataAsBytes(AnalyzerTest.class)); zip.finish(); final ByteArrayOutputStream pack200buffer = new ByteArrayOutputStream(); GZIPOutputStream gzipOutput = new GZIPOutputStream(pack200buffer); Pack200.newPacker().pack( new JarInputStream(new ByteArrayInputStream( zipbuffer.toByteArray())), gzipOutput); gzipOutput.finish(); final int count = analyzer.analyzeAll(new ByteArrayInputStream( pack200buffer.toByteArray()), "Test"); assertEquals(1, count); assertClasses("org/jacoco/core/analysis/AnalyzerTest"); } /** * Triggers exception in * {@link Analyzer#analyzePack200(java.io.InputStream, String)}. */ @Test public void testAnalyzeAll_BrokenPack200() { final byte[] buffer = new byte[] { (byte) 0xca, (byte) 0xfe, (byte) 0xd0, 0x0d }; try { analyzer.analyzeAll(new ByteArrayInputStream(buffer), "Test.pack200"); fail("expected exception"); } catch (IOException e) { assertEquals("Error while analyzing Test.pack200.", e.getMessage()); } } @Test public void testAnalyzeAll_Empty() throws IOException { final int count = analyzer.analyzeAll(new ByteArrayInputStream( new byte[0]), "Test"); assertEquals(0, count); assertEquals(Collections.emptyMap(), classes); } @Test public void testAnalyzeAll_Folder() throws IOException { createClassfile("bin1", AnalyzerTest.class); final int count = analyzer.analyzeAll(folder.getRoot()); assertEquals(1, count); assertClasses("org/jacoco/core/analysis/AnalyzerTest"); } @Test public void testAnalyzeAll_Path() throws IOException { createClassfile("bin1", Analyzer.class); createClassfile("bin2", AnalyzerTest.class); String path = "bin1" + File.pathSeparator + "bin2"; final int count = analyzer.analyzeAll(path, folder.getRoot()); assertEquals(2, count); assertClasses("org/jacoco/core/analysis/Analyzer", "org/jacoco/core/analysis/AnalyzerTest"); } /** * Triggers exception in * {@link Analyzer#nextEntry(java.util.zip.ZipInputStream, String)}. */ @Test public void testAnalyzeAll_BrokenZip() { final byte[] buffer = new byte[30]; buffer[0] = 0x50; buffer[1] = 0x4b; buffer[2] = 0x03; buffer[3] = 0x04; Arrays.fill(buffer, 4, buffer.length, (byte) 0x42); try { analyzer.analyzeAll(new ByteArrayInputStream(buffer), "Test.zip"); fail("expected exception"); } catch (IOException e) { assertEquals("Error while analyzing Test.zip.", e.getMessage()); } } /** * With JDK 5 triggers exception in * {@link Analyzer#nextEntry(ZipInputStream, String)}, * i.e. message will contain only "broken.zip". * * With JDK > 5 triggers exception in * {@link Analyzer#analyzeAll(java.io.InputStream, String)}, * i.e. message will contain only "broken.zip@brokenentry.txt". */ @Test public void testAnalyzeAll_BrokenZipEntry() throws IOException { File file = new File(folder.getRoot(), "broken.zip"); OutputStream out = new FileOutputStream(file); ZipOutputStream zip = new ZipOutputStream(out); zip.putNextEntry(new ZipEntry("brokenentry.txt")); out.write(0x23); // Unexpected data here zip.close(); try { analyzer.analyzeAll(file); fail("expected exception"); } catch (IOException e) { assertTrue(e.getMessage().startsWith("Error while analyzing")); assertTrue(e.getMessage().contains("broken.zip")); } } /** * Triggers exception in * {@link Analyzer#analyzeClass(java.io.InputStream, String)}. */ @Test public void testAnalyzeAll_BrokenClassFileInZip() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(buffer); zip.putNextEntry(new ZipEntry( "org/jacoco/core/analysis/AnalyzerTest.class")); final byte[] brokenclass = TargetLoader .getClassDataAsBytes(AnalyzerTest.class); brokenclass[10] = 0x23; zip.write(brokenclass); zip.finish(); try { analyzer.analyzeAll(new ByteArrayInputStream(buffer.toByteArray()), "test.zip"); fail("expected exception"); } catch (IOException e) { assertEquals( "Error while analyzing test.zip@org/jacoco/core/analysis/AnalyzerTest.class.", e.getMessage()); } } private void createClassfile(final String dir, final Class source) throws IOException { File file = new File(folder.getRoot(), dir); file.mkdirs(); file = new File(file, "some.class"); OutputStream out = new FileOutputStream(file); out.write(TargetLoader.getClassDataAsBytes(source)); out.close(); } private void assertClasses(String... classNames) { assertEquals(new HashSet(Arrays.asList(classNames)), classes.keySet()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/analysis/CounterComparatorTest.java000066400000000000000000000100531304217427400314610ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import static org.jacoco.core.analysis.ICoverageNode.ElementType.GROUP; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Comparator; import org.jacoco.core.analysis.ICoverageNode.CounterEntity; import org.jacoco.core.internal.analysis.CounterImpl; import org.junit.Test; /** * Unit tests for {@link CounterComparator}. */ public class CounterComparatorTest { @Test public void testTotalItemsComparator() { final Comparator cmp = CounterComparator.TOTALITEMS; assertCmpLess(cmp, 19, 5, 19, 6); assertCmpEquals(cmp, 20, 5, 19, 6); assertCmpGreater(cmp, 21, 5, 19, 6); } @Test public void testCoveredItemsComparator() { final Comparator cmp = CounterComparator.COVEREDITEMS; assertCmpLess(cmp, 73, 7, 42, 8); assertCmpEquals(cmp, 42, 8, 82, 8); assertCmpGreater(cmp, 21, 9, 32, 8); } @Test public void testMissedItemsComparator() { final Comparator cmp = CounterComparator.MISSEDITEMS; assertCmpLess(cmp, 10, 40, 11, 80); assertCmpEquals(cmp, 10, 40, 10, 80); assertCmpGreater(cmp, 11, 39, 10, 80); } @Test public void testCoveredRatioComparator() { final Comparator cmp = CounterComparator.COVEREDRATIO; assertCmpLess(cmp, 25, 25, 44, 46); assertCmpEquals(cmp, 40, 10, 64, 16); assertCmpGreater(cmp, 25, 25, 46, 44); } @Test public void testMissedRatioComparator() { final Comparator cmp = CounterComparator.MISSEDRATIO; assertCmpLess(cmp, 25, 25, 46, 44); assertCmpEquals(cmp, 40, 10, 64, 16); assertCmpGreater(cmp, 25, 25, 44, 46); } @Test public void testReverseComparator() { final Comparator cmp = CounterComparator.TOTALITEMS.reverse(); assertCmpGreater(cmp, 19, 5, 19, 6); assertCmpEquals(cmp, 20, 5, 19, 6); assertCmpLess(cmp, 21, 5, 19, 6); } @Test public void testReverseReverseComparator() { final Comparator cmp = CounterComparator.TOTALITEMS.reverse() .reverse(); assertCmpGreater(cmp, 21, 5, 19, 6); assertCmpEquals(cmp, 20, 5, 19, 6); assertCmpLess(cmp, 19, 5, 19, 6); } @Test public void testNodeComparator1() { ICoverageNode d1 = new MockNode(18); ICoverageNode d2 = new MockNode(15); final Comparator cmp = CounterComparator.TOTALITEMS .on(CounterEntity.INSTRUCTION); assertTrue(cmp.compare(d1, d2) > 0); } @Test public void testNodeComparator2() { ICoverageNode d1 = new MockNode(18); ICoverageNode d2 = new MockNode(15); final Comparator cmp = CounterComparator.TOTALITEMS .on(CounterEntity.LINE); assertEquals(0, cmp.compare(d1, d2), 0.0); } private void assertCmpEquals(Comparator cmp, int missed1, int covered1, int missed2, int covered2) { assertEquals(0, cmp.compare(ctr(missed1, covered1), ctr(missed2, covered2)), 0.0); } private void assertCmpLess(Comparator cmp, int missed1, int covered1, int missed2, int covered2) { assertTrue(cmp.compare(ctr(missed1, covered1), ctr(missed2, covered2)) < 0); } private void assertCmpGreater(Comparator cmp, int missed1, int covered1, int missed2, int covered2) { assertTrue(cmp.compare(ctr(missed1, covered1), ctr(missed2, covered2)) > 0); } private CounterImpl ctr(int missed, int covered) { return CounterImpl.getInstance(missed, covered); } private static final class MockNode extends CoverageNodeImpl { MockNode(int total) { super(GROUP, "mock"); instructionCounter = CounterImpl.getInstance(total, 0); } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/analysis/CoverageBuilderTest.java000066400000000000000000000235271304217427400310660ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.jacoco.core.internal.analysis.ClassCoverageImpl; import org.jacoco.core.internal.analysis.CounterImpl; import org.jacoco.core.internal.analysis.MethodCoverageImpl; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link CoverageBuilder}. */ public class CoverageBuilderTest { private CoverageBuilder coverageBuilder; @Before public void setup() { coverageBuilder = new CoverageBuilder(); } @Test public void testCreateClassMissed() { final MethodCoverageImpl method = new MethodCoverageImpl("doit", "()V", null); method.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 6); method.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 7); method.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 8); method.incrementMethodCounter(); addClass(123L, false, "Sample", null, method); final Collection classes = coverageBuilder.getClasses(); assertEquals(1, classes.size()); IClassCoverage c = classes.iterator().next(); assertEquals("Sample", c.getName()); assertEquals(1, c.getClassCounter().getTotalCount()); assertEquals(0, c.getClassCounter().getCoveredCount()); assertEquals(1, c.getMethodCounter().getTotalCount()); assertEquals(0, c.getMethodCounter().getCoveredCount()); assertEquals(3, c.getLineCounter().getTotalCount()); assertEquals(0, c.getLineCounter().getCoveredCount()); final Collection methods = c.getMethods(); assertEquals(1, methods.size()); IMethodCoverage m = methods.iterator().next(); assertEquals("doit", m.getName()); assertEquals("()V", m.getDesc()); assertEquals(1, m.getMethodCounter().getTotalCount()); assertEquals(0, m.getMethodCounter().getCoveredCount()); assertEquals(3, m.getLineCounter().getTotalCount()); assertEquals(0, m.getLineCounter().getCoveredCount()); } @Test public void testCreateClassCovered() { final MethodCoverageImpl method = new MethodCoverageImpl("doit", "()V", null); method.increment(CounterImpl.COUNTER_0_1, CounterImpl.COUNTER_0_0, 6); method.increment(CounterImpl.COUNTER_0_1, CounterImpl.COUNTER_0_0, 7); method.increment(CounterImpl.COUNTER_0_1, CounterImpl.COUNTER_0_0, 8); method.incrementMethodCounter(); addClass(123L, false, "Sample", null, method); final Collection classes = coverageBuilder.getClasses(); assertEquals(1, classes.size()); IClassCoverage c = classes.iterator().next(); assertEquals("Sample", c.getName()); assertEquals(1, c.getClassCounter().getTotalCount()); assertEquals(1, c.getClassCounter().getCoveredCount()); assertEquals(1, c.getMethodCounter().getTotalCount()); assertEquals(1, c.getMethodCounter().getCoveredCount()); assertEquals(3, c.getLineCounter().getTotalCount()); assertEquals(3, c.getLineCounter().getCoveredCount()); final Collection methods = c.getMethods(); assertEquals(1, methods.size()); IMethodCoverage m = methods.iterator().next(); assertEquals("doit", m.getName()); assertEquals("()V", m.getDesc()); assertEquals(1, m.getMethodCounter().getTotalCount()); assertEquals(1, m.getMethodCounter().getCoveredCount()); assertEquals(3, m.getLineCounter().getTotalCount()); assertEquals(3, m.getLineCounter().getCoveredCount()); } @Test public void testIgnoreClassesWithoutCode() { final MethodCoverageImpl method = new MethodCoverageImpl("doit", "()V", null); addClass(123L, false, "Sample", null, method); final Collection classes = coverageBuilder.getClasses(); assertTrue(classes.isEmpty()); } @Test(expected = IllegalStateException.class) public void testDuplicateClassNameDifferent() { MethodCoverageImpl method = new MethodCoverageImpl("doit", "()V", null); method.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(123L, false, "Sample", null, method); // Add class with different id must fail: method = new MethodCoverageImpl("doit", "()V", null); method.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(345L, false, "Sample", null, method); } @Test public void testDuplicateClassNameIdentical() { MethodCoverageImpl method = new MethodCoverageImpl("doit", "()V", null); method.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(123L, false, "Sample", null, method); // Add class with same id: method = new MethodCoverageImpl("doit", "()V", null); method.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(123L, false, "Sample", null, method); // Second add must be ignored: final Collection classes = coverageBuilder.getClasses(); assertEquals(1, classes.size()); } @Test public void testCreateSourceFile() { final MethodCoverageImpl method1 = new MethodCoverageImpl("doit", "()V", null); method1.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(123L, false, "Sample", "Sample.java", method1); final MethodCoverageImpl method2 = new MethodCoverageImpl("doit", "()V", null); method2.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 6); addClass(234L, false, "Second", "Sample.java", method2); final Collection sourcefiles = coverageBuilder .getSourceFiles(); assertEquals(1, sourcefiles.size()); ISourceFileCoverage s = sourcefiles.iterator().next(); assertEquals(2, s.getClassCounter().getTotalCount()); assertEquals(0, s.getClassCounter().getCoveredCount()); } @Test public void testCreateSourceFileDuplicateClassNameIdentical() { final MethodCoverageImpl method1 = new MethodCoverageImpl("doit", "()V", null); method1.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(123L, false, "Sample", "Sample.java", method1); final MethodCoverageImpl method2 = new MethodCoverageImpl("doit", "()V", null); method2.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(123L, false, "Sample", "Sample.java", method2); final Collection sourcefiles = coverageBuilder .getSourceFiles(); assertEquals(1, sourcefiles.size()); ISourceFileCoverage s = sourcefiles.iterator().next(); assertEquals(1, s.getClassCounter().getTotalCount()); assertEquals(0, s.getClassCounter().getCoveredCount()); } @Test public void testGetBundle() { final MethodCoverageImpl method1 = new MethodCoverageImpl("doit", "()V", null); method1.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(1, false, "org/jacoco/examples/Sample1", null, method1); final MethodCoverageImpl method2 = new MethodCoverageImpl("doit", "()V", null); method2.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 6); addClass(2, false, "org/jacoco/examples/Sample2", null, method2); final MethodCoverageImpl method3 = new MethodCoverageImpl("doit", "()V", null); method3.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 1); addClass(3, false, "Sample3", null, method3); IBundleCoverage bundle = coverageBuilder.getBundle("testbundle"); assertEquals("testbundle", bundle.getName()); final Collection packages = bundle.getPackages(); assertEquals(2, packages.size()); Map packagesByName = new HashMap(); for (IPackageCoverage p : packages) { packagesByName.put(p.getName(), p); } IPackageCoverage p1 = packagesByName.get("org/jacoco/examples"); assertNotNull(p1); assertEquals( new HashSet(Arrays.asList( "org/jacoco/examples/Sample1", "org/jacoco/examples/Sample2")), getNames(p1.getClasses())); IPackageCoverage p2 = packagesByName.get(""); assertNotNull(p2); assertEquals(Collections.singleton("Sample3"), getNames(p2.getClasses())); } @Test public void testGetNoMatchClasses() { MethodCoverageImpl m = new MethodCoverageImpl("doit", "()V", null); m.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 1); addClass(1, true, "Sample1", null, m); m = new MethodCoverageImpl("doit", "()V", null); m.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 2); addClass(2, true, "Sample2", null, m); m = new MethodCoverageImpl("doit", "()V", null); m.increment(CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, 3); addClass(3, false, "Sample3", null, m); final Set actual = getNames(coverageBuilder.getNoMatchClasses()); final Set expected = new HashSet(Arrays.asList( "Sample1", "Sample2")); assertEquals(expected, actual); } private Set getNames(Collection nodes) { Set result = new HashSet(); for (ICoverageNode n : nodes) { result.add(n.getName()); } return result; } private void addClass(long id, boolean nomatch, String name, String source, MethodCoverageImpl... methods) { final ClassCoverageImpl coverage = new ClassCoverageImpl(name, id, nomatch); coverage.setSourceFileName(source); for (MethodCoverageImpl m : methods) { coverage.addMethod(m); } coverageBuilder.visitCoverage(coverage); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/analysis/CoverageNodeImplTest.java000066400000000000000000000123041304217427400311760ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import static org.jacoco.core.analysis.ICoverageNode.CounterEntity.BRANCH; import static org.jacoco.core.analysis.ICoverageNode.CounterEntity.CLASS; import static org.jacoco.core.analysis.ICoverageNode.CounterEntity.COMPLEXITY; import static org.jacoco.core.analysis.ICoverageNode.CounterEntity.INSTRUCTION; import static org.jacoco.core.analysis.ICoverageNode.CounterEntity.LINE; import static org.jacoco.core.analysis.ICoverageNode.CounterEntity.METHOD; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.jacoco.core.analysis.ICoverageNode.ElementType; import org.jacoco.core.internal.analysis.CounterImpl; import org.junit.Test; /** * Unit tests for {@link CoverageNodeImpl}. */ public class CoverageNodeImplTest { @Test public void testProperties() { ICoverageNode node = new CoverageNodeImpl(ElementType.GROUP, "sample"); assertEquals(ElementType.GROUP, node.getElementType()); assertEquals("sample", node.getName()); } @Test public void testInit() { ICoverageNode node = new CoverageNodeImpl(ElementType.GROUP, "sample"); assertEquals(CounterImpl.COUNTER_0_0, node.getBranchCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getInstructionCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getLineCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getComplexityCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getMethodCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getClassCounter()); } @Test public void testIncrement() { CoverageNodeImpl parent = new CoverageNodeImpl(ElementType.GROUP, "sample"); ICoverageNode child = new CoverageNodeImpl(ElementType.GROUP, "sample") { { instructionCounter = CounterImpl.getInstance(1, 41); branchCounter = CounterImpl.getInstance(10, 15); lineCounter = CounterImpl.getInstance(5, 3); complexityCounter = CounterImpl.getInstance(4, 2); methodCounter = CounterImpl.getInstance(1, 21); classCounter = CounterImpl.getInstance(1, 11); } }; parent.increment(child); assertEquals(CounterImpl.getInstance(1, 41), parent.getCounter(INSTRUCTION)); assertEquals(CounterImpl.getInstance(1, 41), parent.getInstructionCounter()); assertEquals(CounterImpl.getInstance(10, 15), parent.getCounter(BRANCH)); assertEquals(CounterImpl.getInstance(10, 15), parent.getBranchCounter()); assertEquals(CounterImpl.getInstance(5, 3), parent.getCounter(LINE)); assertEquals(CounterImpl.getInstance(5, 3), parent.getLineCounter()); assertEquals(CounterImpl.getInstance(4, 2), parent.getCounter(COMPLEXITY)); assertEquals(CounterImpl.getInstance(4, 2), parent.getComplexityCounter()); assertEquals(CounterImpl.getInstance(1, 21), parent.getCounter(METHOD)); assertEquals(CounterImpl.getInstance(1, 21), parent.getMethodCounter()); assertEquals(CounterImpl.getInstance(1, 11), parent.getCounter(CLASS)); assertEquals(CounterImpl.getInstance(1, 11), parent.getClassCounter()); } @Test public void testIncrementCollection() { CoverageNodeImpl parent = new CoverageNodeImpl(ElementType.GROUP, "sample"); ICoverageNode child1 = new CoverageNodeImpl(ElementType.GROUP, "sample") { { branchCounter = CounterImpl.getInstance(5, 2); } }; ICoverageNode child2 = new CoverageNodeImpl(ElementType.GROUP, "sample") { { branchCounter = CounterImpl.getInstance(3, 3); } }; parent.increment(Arrays.asList(child1, child2)); assertEquals(CounterImpl.getInstance(8, 5), parent.getBranchCounter()); } @Test public void testGetPlainCopy() { ICoverageNode node = new CoverageNodeImpl(ElementType.CLASS, "Sample") { { classCounter = CounterImpl.getInstance(1, 1); methodCounter = CounterImpl.getInstance(2, 2); branchCounter = CounterImpl.getInstance(3, 3); instructionCounter = CounterImpl.getInstance(4, 4); lineCounter = CounterImpl.getInstance(5, 5); complexityCounter = CounterImpl.getInstance(6, 6); } }; ICoverageNode copy = node.getPlainCopy(); assertEquals(ElementType.CLASS, copy.getElementType()); assertEquals("Sample", copy.getName()); assertEquals(CounterImpl.getInstance(1, 1), copy.getClassCounter()); assertEquals(CounterImpl.getInstance(2, 2), copy.getMethodCounter()); assertEquals(CounterImpl.getInstance(3, 3), copy.getBranchCounter()); assertEquals(CounterImpl.getInstance(4, 4), copy.getInstructionCounter()); assertEquals(CounterImpl.getInstance(5, 5), copy.getLineCounter()); assertEquals(CounterImpl.getInstance(6, 6), copy.getComplexityCounter()); } @Test public void testToString() { CoverageNodeImpl node = new CoverageNodeImpl(ElementType.CLASS, "Test"); assertEquals("Test [CLASS]", node.toString()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/analysis/NodeComparatorTest.java000066400000000000000000000051351304217427400307340ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import static org.jacoco.core.analysis.ICoverageNode.ElementType.GROUP; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.jacoco.core.analysis.ICoverageNode.CounterEntity; import org.jacoco.core.internal.analysis.CounterImpl; import org.junit.Test; /** * Unit test for {@link NodeComparator}. */ public class NodeComparatorTest { @Test public void testSort() { ICoverageNode d1 = new MockNode(18); ICoverageNode d2 = new MockNode(21); ICoverageNode d3 = new MockNode(30); ICoverageNode d4 = new MockNode(60); ICoverageNode d5 = new MockNode(99); final List result = CounterComparator.TOTALITEMS.on( CounterEntity.INSTRUCTION).sort( Arrays.asList(d3, d5, d1, d4, d2)); assertEquals(Arrays.asList(d1, d2, d3, d4, d5), result); } @Test public void testSecond1() { ICoverageNode d1 = new MockLineData(5, 30); ICoverageNode d2 = new MockLineData(3, 80); final NodeComparator c1 = CounterComparator.TOTALITEMS .on(CounterEntity.INSTRUCTION); final NodeComparator c2 = CounterComparator.TOTALITEMS .on(CounterEntity.LINE); assertTrue(c1.second(c2).compare(d1, d2) > 0); } @Test public void testSecond2() { ICoverageNode d1 = new MockLineData(5, 30); ICoverageNode d2 = new MockLineData(5, 80); final NodeComparator c1 = CounterComparator.TOTALITEMS .on(CounterEntity.INSTRUCTION); final NodeComparator c2 = CounterComparator.TOTALITEMS .on(CounterEntity.LINE); assertTrue(c1.second(c2).compare(d1, d2) < 0); } private static final class MockNode extends CoverageNodeImpl { MockNode(int total) { super(GROUP, "mock"); instructionCounter = CounterImpl.getInstance(total, 0); } } private static final class MockLineData extends CoverageNodeImpl { MockLineData(int totalInstruction, int totalLine) { super(GROUP, "mock"); instructionCounter = CounterImpl.getInstance(totalInstruction, 0); lineCounter = CounterImpl.getInstance(totalLine, 0); } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/data/000077500000000000000000000000001304217427400233765ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/data/ExecutionDataReaderWriterTest.java000066400000000000000000000234551304217427400321670ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Random; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link ExecutionDataReader} and {@link ExecutionDataWriter}. * The tests don't care about the written binary format, they just verify * symmetry. */ public class ExecutionDataReaderWriterTest { protected ByteArrayOutputStream buffer; private ExecutionDataWriter writer; private ExecutionDataStore store; private SessionInfo sessionInfo; private Random random; @Before public void setup() throws IOException { buffer = new ByteArrayOutputStream(); writer = createWriter(buffer); store = new ExecutionDataStore(); random = new Random(5); } @Test public void testEmpty() throws IOException { final ExecutionDataReader reader = createReader(); reader.setSessionInfoVisitor(new ISessionInfoVisitor() { public void visitSessionInfo(final SessionInfo info) { fail("No data expected."); } }); reader.setExecutionDataVisitor(new IExecutionDataVisitor() { public void visitClassExecution(final ExecutionData data) { fail("No data expected."); } }); assertFalse(reader.read()); } @Test public void testFlush() throws IOException { final boolean[] flushCalled = new boolean[] { false }; final OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { } @Override public void flush() throws IOException { flushCalled[0] = true; } }; new ExecutionDataWriter(out).flush(); assertTrue(flushCalled[0]); } @Test public void testCustomBlocks() throws IOException { buffer.write(0x55); buffer.write(0x66); final ExecutionDataReader reader = new ExecutionDataReader( new ByteArrayInputStream(buffer.toByteArray())) { @Override protected boolean readBlock(byte blocktype) throws IOException { switch (blocktype) { case 0x55: return true; case 0x66: return false; } return super.readBlock(blocktype); } }; assertTrue(reader.read()); } @Test public void testGetFileHeader() { byte[] header = ExecutionDataWriter.getFileHeader(); assertEquals(5, header.length); assertEquals(0x01, 0xFF & header[0]); assertEquals(0xC0, 0xFF & header[1]); assertEquals(0xC0, 0xFF & header[2]); final char version = ExecutionDataWriter.FORMAT_VERSION; assertEquals(version >> 8, 0xFF & header[3]); assertEquals(version & 0xFF, 0xFF & header[4]); } @Test public void testMultipleHeaders() throws IOException { new ExecutionDataWriter(buffer); new ExecutionDataWriter(buffer); new ExecutionDataWriter(buffer); assertFalse(createReader().read()); } @Test(expected = IOException.class) public void testInvalidMagicNumber() throws IOException { buffer = new ByteArrayOutputStream(); buffer.write(ExecutionDataWriter.BLOCK_HEADER); buffer.write(0x12); buffer.write(0x34); createReader().read(); } @Test(expected = IncompatibleExecDataVersionException.class) public void testInvalidVersion() throws IOException { buffer = new ByteArrayOutputStream(); buffer.write(ExecutionDataWriter.BLOCK_HEADER); buffer.write(0xC0); buffer.write(0xC0); final char version = ExecutionDataWriter.FORMAT_VERSION - 1; buffer.write(version >> 8); buffer.write(version & 0xFF); createReader().read(); } @Test(expected = IOException.class) public void testMissingHeader() throws IOException { buffer.reset(); writer.visitClassExecution(new ExecutionData(Long.MIN_VALUE, "Sample", createData(8))); createReaderWithVisitors().read(); } @Test(expected = IOException.class) public void testUnknownBlock() throws IOException { buffer.write(0xff); createReader().read(); } @Test(expected = EOFException.class) public void testTruncatedFile() throws IOException { writer.visitClassExecution(new ExecutionData(Long.MIN_VALUE, "Sample", createData(8))); final byte[] content = buffer.toByteArray(); buffer.reset(); buffer.write(content, 0, content.length - 1); createReaderWithVisitors().read(); } @Test public void testEmptyFile() throws IOException { buffer.reset(); createReader().read(); } // === Session Info === @Test(expected = IOException.class) public void testNoSessionInfoVisitor() throws IOException { writer.visitSessionInfo(new SessionInfo("x", 0, 1)); createReader().read(); } @Test public void testSessionInfo() throws IOException { writer.visitSessionInfo(new SessionInfo("TestSession", 2837123124567891234L, 3444234223498879234L)); assertFalse(createReaderWithVisitors().read()); assertNotNull(sessionInfo); assertEquals("TestSession", sessionInfo.getId()); assertEquals(2837123124567891234L, sessionInfo.getStartTimeStamp()); assertEquals(3444234223498879234L, sessionInfo.getDumpTimeStamp()); } @Test(expected = RuntimeException.class) public void testSessionInfoIOException() throws IOException { final boolean[] broken = new boolean[1]; final ExecutionDataWriter writer = createWriter(new OutputStream() { @Override public void write(int b) throws IOException { if (broken[0]) { throw new IOException(); } } }); broken[0] = true; writer.visitSessionInfo(new SessionInfo("X", 0, 0)); } // === Execution Data === @Test(expected = IOException.class) public void testNoExecutionDataVisitor() throws IOException { writer.visitClassExecution(new ExecutionData(Long.MIN_VALUE, "Sample", createData(8))); createReader().read(); } @Test public void testMinClassId() throws IOException { final boolean[] data = createData(8); writer.visitClassExecution(new ExecutionData(Long.MIN_VALUE, "Sample", data)); assertFalse(createReaderWithVisitors().read()); assertArrayEquals(data, store.get(Long.MIN_VALUE).getProbes()); } @Test public void testMaxClassId() throws IOException { final boolean[] data = createData(8); writer.visitClassExecution(new ExecutionData(Long.MAX_VALUE, "Sample", data)); assertFalse(createReaderWithVisitors().read()); assertArrayEquals(data, store.get(Long.MAX_VALUE).getProbes()); } @Test public void testEmptyClass() throws IOException { final boolean[] data = createData(0); writer.visitClassExecution(new ExecutionData(3, "Sample", data)); assertFalse(createReaderWithVisitors().read()); assertTrue(store.getContents().isEmpty()); } @Test public void testNoHitClass() throws IOException { final boolean[] data = new boolean[] { false, false, false }; writer.visitClassExecution(new ExecutionData(3, "Sample", data)); assertFalse(createReaderWithVisitors().read()); assertTrue(store.getContents().isEmpty()); } @Test public void testOneClass() throws IOException { final boolean[] data = createData(15); writer.visitClassExecution(new ExecutionData(3, "Sample", data)); assertFalse(createReaderWithVisitors().read()); assertArrayEquals(data, store.get(3).getProbes()); } @Test public void testTwoClasses() throws IOException { final boolean[] data1 = createData(15); final boolean[] data2 = createData(185); writer.visitClassExecution(new ExecutionData(333, "Sample", data1)); writer.visitClassExecution(new ExecutionData(-45, "Sample", data2)); assertFalse(createReaderWithVisitors().read()); assertArrayEquals(data1, store.get(333).getProbes()); assertArrayEquals(data2, store.get(-45).getProbes()); } @Test public void testBigClass() throws IOException { final boolean[] data = createData(3599); writer.visitClassExecution(new ExecutionData(123, "Sample", data)); assertFalse(createReaderWithVisitors().read()); assertArrayEquals(data, store.get(123).getProbes()); } @Test(expected = RuntimeException.class) public void testExecutionDataIOException() throws IOException { final boolean[] broken = new boolean[1]; final ExecutionDataWriter writer = createWriter(new OutputStream() { @Override public void write(int b) throws IOException { if (broken[0]) { throw new IOException(); } } }); broken[0] = true; writer.visitClassExecution(new ExecutionData(3, "Sample", createData(1))); } private ExecutionDataReader createReaderWithVisitors() throws IOException { final ExecutionDataReader reader = createReader(); reader.setExecutionDataVisitor(store); reader.setSessionInfoVisitor(new ISessionInfoVisitor() { public void visitSessionInfo(SessionInfo info) { sessionInfo = info; } }); return reader; } private boolean[] createData(final int probeCount) { final boolean[] data = new boolean[probeCount]; for (int j = 0; j < data.length; j++) { data[j] = random.nextBoolean(); } return data; } private void assertArrayEquals(final boolean[] expected, final boolean[] actual) { assertTrue(Arrays.equals(expected, actual)); } protected ExecutionDataWriter createWriter(OutputStream out) throws IOException { return new ExecutionDataWriter(out); } protected ExecutionDataReader createReader() throws IOException { return new ExecutionDataReader(new ByteArrayInputStream( buffer.toByteArray())); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/data/ExecutionDataStoreTest.java000066400000000000000000000160301304217427400306530ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link ExecutionDataStore}. */ public class ExecutionDataStoreTest implements IExecutionDataVisitor { private ExecutionDataStore store; private Map dataOutput; @Before public void setup() { store = new ExecutionDataStore(); dataOutput = new HashMap(); } @Test public void testEmpty() { assertNull(store.get(123)); assertFalse(store.contains("org/jacoco/example/Foo")); store.accept(this); assertEquals(Collections.emptyMap(), dataOutput); } @Test public void testPut() { final boolean[] probes = new boolean[] { false, false, true }; store.put(new ExecutionData(1000, "Sample", probes)); final ExecutionData data = store.get(1000); assertSame(probes, data.getProbes()); assertTrue(store.contains("Sample")); store.accept(this); assertEquals(Collections.singletonMap(Long.valueOf(1000), data), dataOutput); } @Test public void testReentrantAccept() { final boolean[] probes = new boolean[] { false, false, true }; store.put(new ExecutionData(1000, "Sample0", probes)); store.put(new ExecutionData(1001, "Sample1", probes)); store.accept(new IExecutionDataVisitor() { public void visitClassExecution(ExecutionData data) { store.put(new ExecutionData(1002, "Sample2", probes)); ExecutionDataStoreTest.this.visitClassExecution(data); } }); assertEquals(2, dataOutput.size()); } @Test public void testGetContents() { final boolean[] probes = new boolean[] {}; final ExecutionData a = new ExecutionData(1000, "A", probes); store.put(a); final ExecutionData aa = new ExecutionData(1000, "A", probes); store.put(aa); final ExecutionData b = new ExecutionData(1001, "B", probes); store.put(b); final Set actual = new HashSet( store.getContents()); final Set expected = new HashSet( Arrays.asList(a, b)); assertEquals(expected, actual); } @Test public void testGetWithoutCreate() { final ExecutionData data = new ExecutionData(1000, "Sample", new boolean[] {}); store.put(data); assertSame(data, store.get(1000)); } @Test public void testGetWithCreate() { final Long id = Long.valueOf(1000); final ExecutionData data = store.get(id, "Sample", 3); assertEquals(1000, data.getId()); assertEquals("Sample", data.getName()); assertEquals(3, data.getProbes().length); assertFalse(data.getProbes()[0]); assertFalse(data.getProbes()[1]); assertFalse(data.getProbes()[2]); assertSame(data, store.get(id, "Sample", 3)); assertTrue(store.contains("Sample")); } @Test(expected = IllegalStateException.class) public void testGetNegative1() { final boolean[] data = new boolean[] { false, false, true }; store.put(new ExecutionData(1000, "Sample", data)); store.get(Long.valueOf(1000), "Other", 3); } @Test(expected = IllegalStateException.class) public void testGetNegative2() { final boolean[] data = new boolean[] { false, false, true }; store.put(new ExecutionData(1000, "Sample", data)); store.get(Long.valueOf(1000), "Sample", 4); } @Test(expected = IllegalStateException.class) public void testPutNegative() { final boolean[] data = new boolean[0]; store.put(new ExecutionData(1000, "Sample1", data)); store.put(new ExecutionData(1000, "Sample2", data)); } @Test public void testMerge() { final boolean[] data1 = new boolean[] { false, true, false, true }; store.visitClassExecution(new ExecutionData(1000, "Sample", data1)); final boolean[] data2 = new boolean[] { false, true, true, false }; store.visitClassExecution(new ExecutionData(1000, "Sample", data2)); final boolean[] result = store.get(1000).getProbes(); assertFalse(result[0]); assertTrue(result[1]); assertTrue(result[2]); assertTrue(result[3]); } @Test(expected = IllegalStateException.class) public void testMergeNegative() { final boolean[] data1 = new boolean[] { false, false }; store.visitClassExecution(new ExecutionData(1000, "Sample", data1)); final boolean[] data2 = new boolean[] { false, false, false }; store.visitClassExecution(new ExecutionData(1000, "Sample", data2)); } @Test public void testSubtract() { final boolean[] data1 = new boolean[] { false, true, false, true }; store.put(new ExecutionData(1000, "Sample", data1)); final boolean[] data2 = new boolean[] { false, false, true, true }; store.subtract(new ExecutionData(1000, "Sample", data2)); final boolean[] result = store.get(1000).getProbes(); assertFalse(result[0]); assertTrue(result[1]); assertFalse(result[2]); assertFalse(result[3]); } @Test public void testSubtractOtherId() { final boolean[] data1 = new boolean[] { false, true }; store.put(new ExecutionData(1000, "Sample1", data1)); final boolean[] data2 = new boolean[] { true, true }; store.subtract(new ExecutionData(2000, "Sample2", data2)); final boolean[] result = store.get(1000).getProbes(); assertFalse(result[0]); assertTrue(result[1]); assertNull(store.get(2000)); } @Test public void testSubtractStore() { final boolean[] data1 = new boolean[] { false, true, false, true }; store.put(new ExecutionData(1000, "Sample", data1)); final ExecutionDataStore store2 = new ExecutionDataStore(); final boolean[] data2 = new boolean[] { false, false, true, true }; store2.put(new ExecutionData(1000, "Sample", data2)); store.subtract(store2); final boolean[] result = store.get(1000).getProbes(); assertFalse(result[0]); assertTrue(result[1]); assertFalse(result[2]); assertFalse(result[3]); } @Test public void testReset() throws InstantiationException, IllegalAccessException { final boolean[] data1 = new boolean[] { true, true, false }; store.put(new ExecutionData(1000, "Sample", data1)); store.reset(); final boolean[] data2 = store.get(1000).getProbes(); assertNotNull(data2); assertFalse(data2[0]); assertFalse(data2[1]); assertFalse(data2[2]); } // === IExecutionDataOutput === public void visitClassExecution(final ExecutionData data) { dataOutput.put(Long.valueOf(data.getId()), data); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/data/ExecutionDataTest.java000066400000000000000000000105001304217427400276320ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Unit tests for {@link ExecutionData}. */ public class ExecutionDataTest { @Test public void testCreateEmpty() { final ExecutionData e = new ExecutionData(5, "Example", 3); assertEquals(5, e.getId()); assertEquals("Example", e.getName()); assertEquals(3, e.getProbes().length); assertFalse(e.getProbes()[0]); assertFalse(e.getProbes()[1]); assertFalse(e.getProbes()[2]); } @Test public void testGetters() { final boolean[] data = new boolean[0]; final ExecutionData e = new ExecutionData(5, "Example", data); assertEquals(5, e.getId()); assertEquals("Example", e.getName()); assertSame(data, e.getProbes()); } @Test public void testReset() { final ExecutionData e = new ExecutionData(5, "Example", new boolean[] { true, false, true }); e.reset(); assertFalse(e.getProbes()[0]); assertFalse(e.getProbes()[1]); assertFalse(e.getProbes()[2]); } @Test public void testHasHits() { final boolean[] probes = new boolean[] { false, false, false }; final ExecutionData e = new ExecutionData(5, "Example", probes); assertFalse(e.hasHits()); probes[1] = true; assertTrue(e.hasHits()); } @Test public void testHasHits_empty() { final boolean[] probes = new boolean[] {}; final ExecutionData e = new ExecutionData(5, "Example", probes); assertFalse(e.hasHits()); } @Test public void testMerge() { final ExecutionData a = new ExecutionData(5, "Example", new boolean[] { false, true, false, true }); final ExecutionData b = new ExecutionData(5, "Example", new boolean[] { false, false, true, true }); a.merge(b); // b is merged into a: assertFalse(a.getProbes()[0]); assertTrue(a.getProbes()[1]); assertTrue(a.getProbes()[2]); assertTrue(a.getProbes()[3]); // b must not be modified: assertFalse(b.getProbes()[0]); assertFalse(b.getProbes()[1]); assertTrue(b.getProbes()[2]); assertTrue(b.getProbes()[3]); } @Test public void testMergeSubtract() { final ExecutionData a = new ExecutionData(5, "Example", new boolean[] { false, true, false, true }); final ExecutionData b = new ExecutionData(5, "Example", new boolean[] { false, false, true, true }); a.merge(b, false); // b is subtracted from a: assertFalse(a.getProbes()[0]); assertTrue(a.getProbes()[1]); assertFalse(a.getProbes()[2]); assertFalse(a.getProbes()[3]); // b must not be modified: assertFalse(b.getProbes()[0]); assertFalse(b.getProbes()[1]); assertTrue(b.getProbes()[2]); assertTrue(b.getProbes()[3]); } @Test public void testAssertCompatibility() { final ExecutionData a = new ExecutionData(5, "Example", new boolean[] { true }); a.assertCompatibility(5, "Example", 1); } @Test(expected = IllegalStateException.class) public void testAssertCompatibilityNegative1() { final ExecutionData a = new ExecutionData(5, "Example", new boolean[] { true }); a.assertCompatibility(55, "Example", 1); } @Test(expected = IllegalStateException.class) public void testAssertCompatibilityNegative2() { final ExecutionData a = new ExecutionData(5, "Example", new boolean[] { true }); a.assertCompatibility(5, "Exxxample", 1); } @Test(expected = IllegalStateException.class) public void testAssertCompatibilityNegative3() { final ExecutionData a = new ExecutionData(5, "Example", new boolean[] { true }); a.assertCompatibility(5, "Example", 3); } @Test public void testToString() { final ExecutionData a = new ExecutionData(Long.MAX_VALUE, "Example", new boolean[] { true }); assertEquals("ExecutionData[name=Example, id=7fffffffffffffff]", a.toString()); } } IncompatibleExecDataVersionExceptionTest.java000066400000000000000000000027531304217427400342630ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/data/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link IncompatibleExecDataVersionExceptionTest}. */ public class IncompatibleExecDataVersionExceptionTest { private IncompatibleExecDataVersionException exception; @Before public void setup() { exception = new IncompatibleExecDataVersionException(0x1234); } @Test public void testGetMessage() { String expected = "Cannot read execution data version 0x1234. " + "This version of JaCoCo uses execution data version 0x" + Integer.toHexString(ExecutionDataWriter.FORMAT_VERSION) + "."; assertEquals(expected, exception.getMessage()); } @Test public void testGetActualVersion() { assertEquals(0x1234, exception.getActualVersion()); } @Test public void testGetExpectedVersion() { assertEquals(ExecutionDataWriter.FORMAT_VERSION, exception.getExpectedVersion()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/data/SessionInfoStoreTest.java000066400000000000000000000055321304217427400303620ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link SessionInfoStore}. */ public class SessionInfoStoreTest { private SessionInfoStore store; @Before public void setup() { store = new SessionInfoStore(); } @Test public void testEmpty() { assertEquals(Collections.emptyList(), store.getInfos()); assertTrue(store.isEmpty()); } @Test public void testIsEmpty() { store.visitSessionInfo(new SessionInfo("A", 123, 456)); assertFalse(store.isEmpty()); } @Test public void testGetInfos() { final SessionInfo a = new SessionInfo("A", 12345, 500000); store.visitSessionInfo(a); final SessionInfo b = new SessionInfo("B", 12345, 400000); store.visitSessionInfo(b); final SessionInfo c = new SessionInfo("C", 12345, 600000); store.visitSessionInfo(c); assertEquals(Arrays.asList(b, a, c), store.getInfos()); } @Test public void testGetMergedEmpty() { final SessionInfo info = store.getMerged("MERGE"); assertEquals("MERGE", info.getId()); assertEquals(0, info.getStartTimeStamp()); assertEquals(0, info.getDumpTimeStamp()); } @Test public void testGetMerged() { store.visitSessionInfo(new SessionInfo("A", 23456, 500000)); store.visitSessionInfo(new SessionInfo("B", 12345, 400000)); store.visitSessionInfo(new SessionInfo("C", 34567, 600000)); final SessionInfo info = store.getMerged("MERGE"); assertEquals("MERGE", info.getId()); assertEquals(12345, info.getStartTimeStamp()); assertEquals(600000, info.getDumpTimeStamp()); } @Test public void testAccept() { final SessionInfo a = new SessionInfo("A", 12345, 500000); store.visitSessionInfo(a); final SessionInfo b = new SessionInfo("B", 12345, 400000); store.visitSessionInfo(b); final SessionInfo c = new SessionInfo("C", 12345, 600000); store.visitSessionInfo(c); final List actual = new ArrayList(); store.accept(new ISessionInfoVisitor() { public void visitSessionInfo(SessionInfo info) { actual.add(info); } }); assertEquals(Arrays.asList(b, a, c), actual); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/data/SessionInfoTest.java000066400000000000000000000030671304217427400273460ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * Unit tests for {@link SessionInfo}. */ public class SessionInfoTest { @Test(expected = IllegalArgumentException.class) public void testNullId() { new SessionInfo(null, 1, 2); } @Test public void testGetters() { final SessionInfo info = new SessionInfo("id", 1000, 2000); assertEquals("id", info.getId()); assertEquals(1000, info.getStartTimeStamp()); assertEquals(2000, info.getDumpTimeStamp()); } @Test public void testCompare() { assertEquals(0, new SessionInfo("id", 1000, 2000).compareTo(new SessionInfo( "id", 1234, 2000))); assertEquals(-1, new SessionInfo("id", 3333, 1999).compareTo(new SessionInfo( "id", 1234, 2000))); assertEquals(+1, new SessionInfo("id", 1234, 2001).compareTo(new SessionInfo( "id", 2222, 2000))); } @Test public void testToString() { assertEquals("SessionInfo[id]", new SessionInfo("id", 1000, 2000).toString()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/instr/000077500000000000000000000000001304217427400236245ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/instr/InstrumenterTest.java000066400000000000000000000212401304217427400300250ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.instr; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Pack200; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.jacoco.core.analysis.AnalyzerTest; import org.jacoco.core.runtime.RuntimeData; import org.jacoco.core.runtime.SystemPropertiesRuntime; import org.jacoco.core.test.TargetLoader; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link Instrumenter}. */ public class InstrumenterTest { // no serialVersionUID to enforce calculation @SuppressWarnings("serial") public static class SerializationTarget implements Serializable { private final String text; private final int nr; public SerializationTarget(final String text, final int nr) { this.text = text; this.nr = nr; } @Override public String toString() { return text + nr; } } private SystemPropertiesRuntime runtime; private Instrumenter instrumenter; @Before public void setup() throws Exception { runtime = new SystemPropertiesRuntime(); instrumenter = new Instrumenter(runtime); runtime.startup(new RuntimeData()); } @After public void teardown() { runtime.shutdown(); } @Test public void testInstrumentClass() throws Exception { byte[] bytes = instrumenter.instrument( TargetLoader.getClassDataAsBytes(InstrumenterTest.class), "Test"); TargetLoader loader = new TargetLoader(); Class clazz = loader.add(InstrumenterTest.class, bytes); assertEquals("org.jacoco.core.instr.InstrumenterTest", clazz.getName()); } @Test public void testInstrumentBrokenClass1() throws IOException { final byte[] brokenclass = TargetLoader .getClassDataAsBytes(AnalyzerTest.class); brokenclass[10] = 0x23; try { instrumenter.instrument(brokenclass, "Broken"); fail(); } catch (IOException e) { assertEquals("Error while instrumenting class Broken.", e.getMessage()); } } @Test public void testInstrumentBrokenClass2() throws IOException { final byte[] brokenclass = TargetLoader .getClassDataAsBytes(AnalyzerTest.class); brokenclass[10] = 0x23; try { instrumenter.instrument(new ByteArrayInputStream(brokenclass), "Broken"); fail(); } catch (IOException e) { assertEquals("Error while instrumenting class Broken.", e.getMessage()); } } @Test public void testSerialization() throws Exception { // Create instrumented instance: byte[] bytes = instrumenter.instrument( TargetLoader.getClassData(SerializationTarget.class), "Test"); TargetLoader loader = new TargetLoader(); Object obj1 = loader.add(SerializationTarget.class, bytes) .getConstructor(String.class, Integer.TYPE) .newInstance("Hello", Integer.valueOf(42)); // Serialize instrumented instance: ByteArrayOutputStream buffer = new ByteArrayOutputStream(); new ObjectOutputStream(buffer).writeObject(obj1); // Deserialize with original class definition: Object obj2 = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())).readObject(); assertEquals("Hello42", obj2.toString()); } @Test public void testInstrumentAll_Class() throws IOException { InputStream in = TargetLoader.getClassData(getClass()); OutputStream out = new ByteArrayOutputStream(); int count = instrumenter.instrumentAll(in, out, "Test"); assertEquals(1, count); } @Test public void testInstrumentAll_Zip() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(buffer); zipout.putNextEntry(new ZipEntry("Test.class")); zipout.write(TargetLoader.getClassDataAsBytes(getClass())); zipout.finish(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int count = instrumenter.instrumentAll( new ByteArrayInputStream(buffer.toByteArray()), out, "Test"); assertEquals(1, count); ZipInputStream zipin = new ZipInputStream(new ByteArrayInputStream( out.toByteArray())); assertEquals("Test.class", zipin.getNextEntry().getName()); assertNull(zipin.getNextEntry()); } @Test public void testInstrumentAll_BrokenClassFileInZip() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(buffer); zipout.putNextEntry(new ZipEntry("Test.class")); final byte[] brokenclass = TargetLoader.getClassDataAsBytes(getClass()); brokenclass[10] = 0x23; zipout.write(brokenclass); zipout.finish(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { instrumenter.instrumentAll( new ByteArrayInputStream(buffer.toByteArray()), out, "test.zip"); fail(); } catch (IOException e) { assertEquals( "Error while instrumenting class test.zip@Test.class.", e.getMessage()); } } @Test public void testInstrumentAll_Pack200() throws IOException { ByteArrayOutputStream jarbuffer = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(jarbuffer); zipout.putNextEntry(new ZipEntry("Test.class")); zipout.write(TargetLoader.getClassDataAsBytes(getClass())); zipout.finish(); ByteArrayOutputStream pack200buffer = new ByteArrayOutputStream(); GZIPOutputStream gzipOutput = new GZIPOutputStream(pack200buffer); Pack200.newPacker().pack( new JarInputStream(new ByteArrayInputStream( jarbuffer.toByteArray())), gzipOutput); gzipOutput.finish(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int count = instrumenter.instrumentAll(new ByteArrayInputStream( pack200buffer.toByteArray()), out, "Test"); jarbuffer.reset(); Pack200.newUnpacker() .unpack(new GZIPInputStream(new ByteArrayInputStream( out.toByteArray())), new JarOutputStream(jarbuffer)); assertEquals(1, count); ZipInputStream zipin = new ZipInputStream(new ByteArrayInputStream( jarbuffer.toByteArray())); assertEquals("Test.class", zipin.getNextEntry().getName()); assertNull(zipin.getNextEntry()); } @Test public void testInstrumentAll_Other() throws IOException { InputStream in = new ByteArrayInputStream("text".getBytes()); ByteArrayOutputStream out = new ByteArrayOutputStream(); int count = instrumenter.instrumentAll(in, out, "Test"); assertEquals(0, count); assertEquals("text", new String(out.toByteArray())); } @Test public void testInstrumentAll_RemoveSignatures() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(buffer); zipout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); zipout.putNextEntry(new ZipEntry("META-INF/ALIAS.SF")); zipout.finish(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int count = instrumenter.instrumentAll( new ByteArrayInputStream(buffer.toByteArray()), out, "Test"); assertEquals(0, count); ZipInputStream zipin = new ZipInputStream(new ByteArrayInputStream( out.toByteArray())); assertEquals("META-INF/MANIFEST.MF", zipin.getNextEntry().getName()); assertNull(zipin.getNextEntry()); } @Test public void testInstrumentAll_KeepSignatures() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(buffer); zipout.putNextEntry(new ZipEntry("META-INF/ALIAS.SF")); zipout.finish(); ByteArrayOutputStream out = new ByteArrayOutputStream(); instrumenter.setRemoveSignatures(false); int count = instrumenter.instrumentAll( new ByteArrayInputStream(buffer.toByteArray()), out, "Test"); assertEquals(0, count); ZipInputStream zipin = new ZipInputStream(new ByteArrayInputStream( out.toByteArray())); assertEquals("META-INF/ALIAS.SF", zipin.getNextEntry().getName()); assertNull(zipin.getNextEntry()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/instr/MethodRecorder.java000066400000000000000000000032571304217427400274040ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.instr; import java.io.PrintWriter; import java.io.StringWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.util.Printer; import org.objectweb.asm.util.Textifier; import org.objectweb.asm.util.TraceMethodVisitor; /** * Recorder of method events for test verification. */ public class MethodRecorder { private final Printer printer; private final MethodVisitor visitor; public MethodRecorder() { printer = new Textifier(); visitor = new TraceMethodVisitor(printer); } public Printer getPrinter() { return printer; } public MethodVisitor getVisitor() { return visitor; } @Override public boolean equals(Object obj) { if (!(obj instanceof MethodRecorder)) { return false; } MethodRecorder that = (MethodRecorder) obj; return printer.getText().equals(that.printer.getText()); } @Override public int hashCode() { return printer.getText().hashCode(); } @Override public String toString() { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); printer.print(writer); writer.flush(); return buffer.toString(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/000077500000000000000000000000001304217427400243015ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/ContentTypeDetectorTest.java000066400000000000000000000136441304217427400317620ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.jar.JarInputStream; import java.util.jar.Pack200; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.jacoco.core.test.TargetLoader; import org.junit.Test; /** * Unit tests for {@link ContentTypeDetector}. */ public class ContentTypeDetectorTest { private byte[] data; private ContentTypeDetector detector; @Test public void testEmptyStream() throws IOException { initData(); assertEquals(ContentTypeDetector.UNKNOWN, detector.getType()); assertContent(); } @Test public void testClassFile() throws IOException { initData(TargetLoader .getClassDataAsBytes(ContentTypeDetectorTest.class)); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile11() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x03, 0x00, 0x2D); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile12() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x2E); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile13() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x2F); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile14() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x30); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile15() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x31); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile16() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x32); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile17() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x33); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile18() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x34); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testClassFile19() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x35); assertEquals(ContentTypeDetector.CLASSFILE, detector.getType()); assertContent(); } @Test public void testMachObjectFile() throws IOException { initData(0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00, 0x00, 0x02); assertEquals(ContentTypeDetector.UNKNOWN, detector.getType()); assertContent(); } @Test public void testZipFile() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(buffer); zip.putNextEntry(new ZipEntry("hello.txt")); zip.write("Hello Zip!".getBytes()); zip.close(); initData(buffer.toByteArray()); assertEquals(ContentTypeDetector.ZIPFILE, detector.getType()); assertContent(); } @Test public void testPack200File() throws IOException { final ByteArrayOutputStream zipbuffer = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(zipbuffer); zip.putNextEntry(new ZipEntry("hello.txt")); zip.write("Hello Zip!".getBytes()); zip.close(); final ByteArrayOutputStream pack200buffer = new ByteArrayOutputStream(); Pack200.newPacker().pack( new JarInputStream(new ByteArrayInputStream( zipbuffer.toByteArray())), pack200buffer); initData(pack200buffer.toByteArray()); assertEquals(ContentTypeDetector.PACK200FILE, detector.getType()); assertContent(); } @Test public void testGZipFile() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final OutputStream gz = new GZIPOutputStream(buffer); gz.write("Hello gz!".getBytes()); gz.close(); initData(buffer.toByteArray()); assertEquals(ContentTypeDetector.GZFILE, detector.getType()); assertContent(); } @Test public void testStreamWithoutMarkSupport() throws IOException { initData(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07); detector = new ContentTypeDetector(new ByteArrayInputStream(data) { @Override public void mark(int readlimit) { } @Override public void reset() { } @Override public boolean markSupported() { return false; } }); assertContent(); } private void initData(byte[] bytes) throws IOException { this.data = bytes; this.detector = new ContentTypeDetector(new ByteArrayInputStream(data)); } private void initData(final int... bytes) throws IOException { byte[] data = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { data[i] = (byte) bytes[i]; } initData(data); } private void assertContent() throws IOException { final InputStream actual = detector.getInputStream(); for (int b : data) { assertEquals(b, (byte) actual.read()); } assertEquals(-1, actual.read()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/Pack200StreamsTest.java000066400000000000000000000064201304217427400304450ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Pack200; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.jacoco.core.test.TargetLoader; import org.junit.Test; /** * Unit tests for {@link Pack200Streams}. */ public class Pack200StreamsTest { @Test public void testPack() throws IOException { ByteArrayOutputStream jarbuffer = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(jarbuffer); zipout.putNextEntry(new ZipEntry("Test.class")); zipout.write(TargetLoader.getClassDataAsBytes(getClass())); zipout.finish(); ByteArrayOutputStream pack200buffer = new ByteArrayOutputStream(); Pack200Streams.pack(jarbuffer.toByteArray(), new NoCloseOutputStream( pack200buffer)); jarbuffer.reset(); Pack200.newUnpacker().unpack( new ByteArrayInputStream(pack200buffer.toByteArray()), new JarOutputStream(jarbuffer)); ZipInputStream zipin = new ZipInputStream(new ByteArrayInputStream( jarbuffer.toByteArray())); assertEquals("Test.class", zipin.getNextEntry().getName()); assertNull(zipin.getNextEntry()); } @Test public void testUnpack() throws IOException { ByteArrayOutputStream jarbuffer = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(jarbuffer); zipout.putNextEntry(new ZipEntry("Test.class")); zipout.write(TargetLoader.getClassDataAsBytes(getClass())); zipout.finish(); ByteArrayOutputStream pack200buffer = new ByteArrayOutputStream(); Pack200.newPacker().pack( new JarInputStream(new ByteArrayInputStream( jarbuffer.toByteArray())), pack200buffer); InputStream result = Pack200Streams.unpack(new NoCloseInputStream( new ByteArrayInputStream(pack200buffer.toByteArray()))); ZipInputStream zipin = new ZipInputStream(result); assertEquals("Test.class", zipin.getNextEntry().getName()); assertNull(zipin.getNextEntry()); } static class NoCloseInputStream extends FilterInputStream { public NoCloseInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { fail(); } } static class NoCloseOutputStream extends FilterOutputStream { public NoCloseOutputStream(OutputStream out) { super(out); } @Override public void close() throws IOException { fail(); } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/000077500000000000000000000000001304217427400261245ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/BundleCoverageImplTest.java000066400000000000000000000106571304217427400333470ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.ICoverageNode; import org.jacoco.core.analysis.IPackageCoverage; import org.jacoco.core.analysis.ISourceFileCoverage; import org.junit.Test; /** * Unit tests for {@link BundleCoverageImpl}. */ public class BundleCoverageImplTest { @Test public void testProperties() { Collection classes = Collections.emptySet(); Collection sourcefiles = Collections.emptySet(); Collection packages = Collections .singleton((IPackageCoverage) new PackageCoverageImpl("p1", classes, sourcefiles)); BundleCoverageImpl bundle = new BundleCoverageImpl("testbundle", packages); assertEquals(ICoverageNode.ElementType.BUNDLE, bundle.getElementType()); assertEquals("testbundle", bundle.getName()); assertEquals(packages, bundle.getPackages()); } @Test public void testCounters() { Collection classes = Collections.emptySet(); Collection sourcefiles = Collections.emptySet(); final IPackageCoverage p1 = new PackageCoverageImpl("p1", classes, sourcefiles) { { classCounter = CounterImpl.getInstance(1, 0); methodCounter = CounterImpl.getInstance(2, 0); branchCounter = CounterImpl.getInstance(3, 0); instructionCounter = CounterImpl.getInstance(4, 0); lineCounter = CounterImpl.getInstance(5, 0); } }; final IPackageCoverage p2 = new PackageCoverageImpl("p1", classes, sourcefiles) { { classCounter = CounterImpl.getInstance(1, 0); methodCounter = CounterImpl.getInstance(2, 0); branchCounter = CounterImpl.getInstance(3, 0); instructionCounter = CounterImpl.getInstance(4, 0); lineCounter = CounterImpl.getInstance(5, 0); } }; BundleCoverageImpl bundle = new BundleCoverageImpl("testbundle", Arrays.asList(p1, p2)); assertEquals(CounterImpl.getInstance(2, 0), bundle.getClassCounter()); assertEquals(CounterImpl.getInstance(4, 0), bundle.getMethodCounter()); assertEquals(CounterImpl.getInstance(6, 0), bundle.getBranchCounter()); assertEquals(CounterImpl.getInstance(8, 0), bundle.getInstructionCounter()); assertEquals(CounterImpl.getInstance(10, 0), bundle.getLineCounter()); } @Test public void testGroupByPackage() { ClassCoverageImpl ca = new ClassCoverageImpl("p1/A", 1, false); ca.setSourceFileName("A.java"); ClassCoverageImpl cb = new ClassCoverageImpl("p2/B", 2, false); cb.setSourceFileName("B.java"); ISourceFileCoverage sb = new SourceFileCoverageImpl("B.java", "p2"); ISourceFileCoverage sc = new SourceFileCoverageImpl("C.java", "p3"); BundleCoverageImpl bundle = new BundleCoverageImpl("bundle", Arrays.asList((IClassCoverage) ca, (IClassCoverage) cb), Arrays.asList(sb, sc)); Collection packages = bundle.getPackages(); assertEquals(3, packages.size(), 0.0); IPackageCoverage p1 = findPackage("p1", packages); assertNotNull(p1); assertEquals(Collections.singletonList(ca), p1.getClasses()); assertTrue(p1.getSourceFiles().isEmpty()); IPackageCoverage p2 = findPackage("p2", packages); assertNotNull(p2); assertEquals(Collections.singletonList(cb), p2.getClasses()); assertEquals(Collections.singletonList(sb), p2.getSourceFiles()); IPackageCoverage p3 = findPackage("p3", packages); assertNotNull(p3); assertTrue(p3.getClasses().isEmpty()); assertEquals(Collections.singletonList(sc), p3.getSourceFiles()); } private IPackageCoverage findPackage(String name, Collection packages) { for (IPackageCoverage p : packages) { if (name.equals(p.getName())) { return p; } } return null; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/ClassAnalyzerTest.java000066400000000000000000000053351304217427400324100ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.jacoco.core.internal.flow.MethodProbesVisitor; import org.jacoco.core.internal.instr.InstrSupport; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Opcodes; /** * Unit tests for {@link ClassAnalyzer}. */ public class ClassAnalyzerTest { private ClassAnalyzer analyzer; private ClassCoverageImpl coverage; @Before public void setup() { coverage = new ClassCoverageImpl("Foo", 0x0000, false); analyzer = new ClassAnalyzer(coverage, null, new StringPool()); analyzer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Foo", null, "java/lang/Object", null); } @Test(expected = IllegalStateException.class) public void testAnalyzeInstrumentedClass1() { analyzer.visitField(InstrSupport.DATAFIELD_ACC, InstrSupport.DATAFIELD_NAME, InstrSupport.DATAFIELD_DESC, null, null); } @Test(expected = IllegalStateException.class) public void testAnalyzeInstrumentedClass2() { analyzer.visitMethod(InstrSupport.INITMETHOD_ACC, InstrSupport.INITMETHOD_NAME, InstrSupport.INITMETHOD_DESC, null, null); } @Test public void testMethodFilter_Empty() { final MethodProbesVisitor mv = analyzer.visitMethod(0, "foo", "()V", null, null); mv.visitEnd(); assertEquals(0, coverage.getMethods().size()); } @Test public void testMethodFilter_NonSynthetic() { final MethodProbesVisitor mv = analyzer.visitMethod(0, "foo", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.RETURN); mv.visitEnd(); assertEquals(1, coverage.getMethods().size()); } @Test public void testMethodFilter_Synthetic() { final MethodProbesVisitor mv = analyzer.visitMethod( Opcodes.ACC_SYNTHETIC, "foo", "()V", null, null); assertNull(mv); assertTrue(coverage.getMethods().isEmpty()); } @Test public void testMethodFilter_Lambda() { final MethodProbesVisitor mv = analyzer.visitMethod( Opcodes.ACC_SYNTHETIC, "lambda$1", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.RETURN); mv.visitEnd(); assertEquals(1, coverage.getMethods().size()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/ClassCoverageImplTest.java000066400000000000000000000073111304217427400331740ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Collections; import org.jacoco.core.analysis.ICoverageNode; import org.jacoco.core.analysis.ISourceNode; import org.junit.Before; import org.junit.Test; /** * Unit test for {@link ClassCoverageImpl}. */ public class ClassCoverageImplTest { private ClassCoverageImpl node; @Before public void setup() { node = new ClassCoverageImpl("Sample", 12345, false); } @Test public void testDefaults() { assertEquals(ICoverageNode.ElementType.CLASS, node.getElementType()); assertEquals("Sample", node.getName()); assertEquals(12345, node.getId()); assertFalse(node.isNoMatch()); assertEquals(Collections.emptyList(), node.getMethods()); } @Test public void testSignature() { node.setSignature("LSample;"); assertEquals("LSample;", node.getSignature()); } @Test public void testSuperName() { node.setSuperName("java/lang/Object"); assertEquals("java/lang/Object", node.getSuperName()); } @Test public void testInterfaces() { node.setInterfaces(new String[] { "A", "B" }); assertArrayEquals(new String[] { "A", "B" }, node.getInterfaceNames()); } @Test public void testSourceFileName() { node.setSourceFileName("Sample.java"); assertEquals("Sample.java", node.getSourceFileName()); } @Test public void testNoMatch() { ClassCoverageImpl node = new ClassCoverageImpl("Sample", 12345, true); assertTrue(node.isNoMatch()); } @Test public void testGetPackageName1() { ClassCoverageImpl node = new ClassCoverageImpl("ClassInDefaultPackage", 0, false); assertEquals("", node.getPackageName()); } @Test public void testGetPackageName2() { ClassCoverageImpl data = new ClassCoverageImpl( "org/jacoco/examples/Sample", 0, false); assertEquals("org/jacoco/examples", data.getPackageName()); } @Test public void testEmptyClass() { assertEquals(CounterImpl.COUNTER_0_0, node.getInstructionCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getBranchCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getMethodCounter()); assertEquals(CounterImpl.COUNTER_1_0, node.getClassCounter()); } @Test public void testAddMethodMissed() { node.addMethod(createMethod(false)); assertEquals(CounterImpl.COUNTER_1_0, node.getInstructionCounter()); assertEquals(CounterImpl.COUNTER_1_0, node.getMethodCounter()); assertEquals(CounterImpl.COUNTER_1_0, node.getClassCounter()); } @Test public void testAddMethodCovered() { node.addMethod(createMethod(true)); assertEquals(CounterImpl.COUNTER_0_1, node.getInstructionCounter()); assertEquals(CounterImpl.COUNTER_0_1, node.getMethodCounter()); assertEquals(CounterImpl.COUNTER_0_1, node.getClassCounter()); } private MethodCoverageImpl createMethod(boolean covered) { final MethodCoverageImpl m = new MethodCoverageImpl("sample", "()V", null); m.increment( covered ? CounterImpl.COUNTER_0_1 : CounterImpl.COUNTER_1_0, CounterImpl.COUNTER_0_0, ISourceNode.UNKNOWN_LINE); m.incrementMethodCounter(); return m; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/CounterImplTest.java000066400000000000000000000141561304217427400320770ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.analysis.ICounter.CounterValue; import org.junit.Test; /** * Unit tests for {@link CounterImpl}. */ public class CounterImplTest { @Test public void testGetInstance1() { ICounter c = CounterImpl.getInstance(0, 0); assertEquals(0, c.getTotalCount()); assertEquals(0.0, c.getValue(CounterValue.TOTALCOUNT), 0.0); assertEquals(0, c.getMissedCount()); assertEquals(0.0, c.getValue(CounterValue.MISSEDCOUNT), 0.0); assertEquals(0, c.getCoveredCount()); assertEquals(0.0, c.getValue(CounterValue.COVEREDCOUNT), 0.0); } @Test public void testGetInstance2() { ICounter c = CounterImpl.getInstance(33, 15); assertEquals(48, c.getTotalCount()); assertEquals(48.0, c.getValue(CounterValue.TOTALCOUNT), 0.0); assertEquals(33, c.getMissedCount()); assertEquals(33.0, c.getValue(CounterValue.MISSEDCOUNT), 0.0); assertEquals(15, c.getCoveredCount()); assertEquals(15.0, c.getValue(CounterValue.COVEREDCOUNT), 0.0); } @Test public void testGetInstance3() { ICounter c = CounterImpl.getInstance(15, 12); ICounter copy = CounterImpl.getInstance(c); assertEquals(27, copy.getTotalCount()); assertEquals(27.0, c.getValue(CounterValue.TOTALCOUNT), 0.0); assertEquals(15, copy.getMissedCount()); assertEquals(15.0, c.getValue(CounterValue.MISSEDCOUNT), 0.0); assertEquals(12, copy.getCoveredCount()); assertEquals(12.0, c.getValue(CounterValue.COVEREDCOUNT), 0.0); } @Test public void testFixInstance() { ICounter c1 = CounterImpl.getInstance(30, 30); ICounter c2 = CounterImpl.getInstance(30, 30); assertSame(c1, c2); } @Test public void testVarInstance() { ICounter c1 = CounterImpl.getInstance(31, 30); ICounter c2 = CounterImpl.getInstance(31, 30); assertNotSame(c1, c2); } @Test public void testIncrement1() { CounterImpl c = CounterImpl.getInstance(1, 1); c = c.increment(CounterImpl.getInstance(2, 1)); assertEquals(3, c.getMissedCount()); assertEquals(2, c.getCoveredCount()); } @Test public void testIncrement2() { CounterImpl c = CounterImpl.getInstance(31, 5); c = c.increment(CounterImpl.getInstance(7, 3)); assertEquals(38, c.getMissedCount()); assertEquals(8, c.getCoveredCount()); } @Test public void testGetCoveredRatio1() { ICounter c = CounterImpl.getInstance(30, 10); assertEquals(0.25, c.getCoveredRatio(), 0.0); assertEquals(0.25, c.getValue(CounterValue.COVEREDRATIO), 0.0); } @Test public void testGetCoveredRatio2() { ICounter c = CounterImpl.getInstance(20, 0); assertEquals(0.0, c.getCoveredRatio(), 0.0); assertEquals(0.0, c.getValue(CounterValue.COVEREDRATIO), 0.0); } @Test public void testGetCoveredRatio3() { ICounter c = CounterImpl.getInstance(0, 0); assertEquals(Double.NaN, c.getCoveredRatio(), 0.0); assertEquals(Double.NaN, c.getValue(CounterValue.COVEREDRATIO), 0.0); } @Test public void testGetMissedRatio1() { ICounter c = CounterImpl.getInstance(10, 30); assertEquals(0.25, c.getMissedRatio(), 0.0); assertEquals(0.25, c.getValue(CounterValue.MISSEDRATIO), 0.0); } @Test public void testGetMissedRatio2() { ICounter c = CounterImpl.getInstance(0, 20); assertEquals(0.0, c.getMissedRatio(), 0.0); assertEquals(0.0, c.getValue(CounterValue.MISSEDRATIO), 0.0); } @Test public void testGetMissedRatio3() { ICounter c = CounterImpl.getInstance(0, 0); assertEquals(Double.NaN, c.getMissedRatio(), 0.0); assertEquals(Double.NaN, c.getValue(CounterValue.MISSEDRATIO), 0.0); } @Test public void testGetMissedStatus1() { ICounter c = CounterImpl.getInstance(0, 0); assertEquals(ICounter.EMPTY, c.getStatus()); } @Test public void testGetMissedStatus2() { ICounter c = CounterImpl.getInstance(5, 0); assertEquals(ICounter.NOT_COVERED, c.getStatus()); } @Test public void testGetMissedStatus3() { ICounter c = CounterImpl.getInstance(0, 5); assertEquals(ICounter.FULLY_COVERED, c.getStatus()); } @Test public void testGetMissedStatus4() { ICounter c = CounterImpl.getInstance(2, 3); assertEquals(ICounter.PARTLY_COVERED, c.getStatus()); } @Test public void testEquals1() { ICounter c1 = CounterImpl.getInstance(300, 123); ICounter c2 = CounterImpl.getInstance(300, 123); assertEquals(c1, c2); } @Test public void testEquals2() { ICounter c1 = CounterImpl.getInstance(300, 123); ICounter c2 = CounterImpl.getInstance(400, 123); assertFalse(c1.equals(c2)); } @Test public void testEquals3() { ICounter c1 = CounterImpl.getInstance(300, 123); ICounter c2 = CounterImpl.getInstance(300, 124); assertFalse(c1.equals(c2)); } @Test public void testEquals4() { ICounter c = CounterImpl.getInstance(300, 123); assertFalse(c.equals(new Integer(123))); } @Test public void testHashCode1() { ICounter c1 = CounterImpl.getInstance(300, 123); ICounter c2 = CounterImpl.getInstance(300, 123); assertEquals(c1.hashCode(), c2.hashCode()); } @Test public void testHashCode2() { ICounter c1 = CounterImpl.getInstance(300, 123); ICounter c2 = CounterImpl.getInstance(400, 123); assertFalse(c1.hashCode() == c2.hashCode()); } @Test public void testHashCode3() { ICounter c1 = CounterImpl.getInstance(300, 123); ICounter c2 = CounterImpl.getInstance(300, 124); assertFalse(c1.hashCode() == c2.hashCode()); } @Test public void testToString() { ICounter c = CounterImpl.getInstance(300, 123); assertEquals("Counter[300/123]", c.toString()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/LineImplTest.java000066400000000000000000000122271304217427400313440ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.jacoco.core.analysis.ICounter; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link LineImplTest}. */ public class LineImplTest { private LineImpl line; @Before public void setup() { line = LineImpl.EMPTY; } @Test public void testEMPTY() { assertEquals(CounterImpl.COUNTER_0_0, line.getInstructionCounter()); assertEquals(CounterImpl.COUNTER_0_0, line.getBranchCounter()); assertEquals(ICounter.EMPTY, line.getStatus()); } @Test public void testIncrement1() { line = line.increment(CounterImpl.getInstance(1, 2), CounterImpl.getInstance(3, 4)); assertEquals(CounterImpl.getInstance(1, 2), line.getInstructionCounter()); assertEquals(CounterImpl.getInstance(3, 4), line.getBranchCounter()); } @Test public void testIncrement2() { line = line.increment(CounterImpl.getInstance(1, 2), CounterImpl.getInstance(3, 4000)); assertEquals(CounterImpl.getInstance(1, 2), line.getInstructionCounter()); assertEquals(CounterImpl.getInstance(3, 4000), line.getBranchCounter()); } @Test public void testIncrement3() { line = line.increment(CounterImpl.getInstance(1, 2), CounterImpl.getInstance(3000, 4000)); assertEquals(CounterImpl.getInstance(1, 2), line.getInstructionCounter()); assertEquals(CounterImpl.getInstance(3000, 4000), line.getBranchCounter()); } @Test public void testIncrement4() { line = line.increment(CounterImpl.getInstance(1, 2000), CounterImpl.getInstance(3000, 4000)); assertEquals(CounterImpl.getInstance(1, 2000), line.getInstructionCounter()); assertEquals(CounterImpl.getInstance(3000, 4000), line.getBranchCounter()); } @Test public void testIncrement5() { line = line.increment(CounterImpl.getInstance(1000, 2000), CounterImpl.getInstance(3000, 4000)); assertEquals(CounterImpl.getInstance(1000, 2000), line.getInstructionCounter()); assertEquals(CounterImpl.getInstance(3000, 4000), line.getBranchCounter()); } @Test public void testGetStatus1() { line = line.increment(CounterImpl.getInstance(1, 0), CounterImpl.getInstance(0, 0)); assertEquals(ICounter.NOT_COVERED, line.getStatus()); } @Test public void testGetStatus2() { line = line.increment(CounterImpl.getInstance(0, 0), CounterImpl.getInstance(1, 0)); assertEquals(ICounter.NOT_COVERED, line.getStatus()); } @Test public void testGetStatus3() { line = line.increment(CounterImpl.getInstance(0, 1), CounterImpl.getInstance(0, 0)); assertEquals(ICounter.FULLY_COVERED, line.getStatus()); } @Test public void testGetStatus4() { line = line.increment(CounterImpl.getInstance(0, 0), CounterImpl.getInstance(0, 1)); assertEquals(ICounter.FULLY_COVERED, line.getStatus()); } @Test public void testGetStatus5() { line = line.increment(CounterImpl.getInstance(1, 1), CounterImpl.getInstance(0, 0)); assertEquals(ICounter.PARTLY_COVERED, line.getStatus()); } @Test public void testGetStatus6() { line = line.increment(CounterImpl.getInstance(0, 1), CounterImpl.getInstance(1, 1)); assertEquals(ICounter.PARTLY_COVERED, line.getStatus()); } @Test public void testHashCode() { line = line.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 444)); LineImpl line2 = LineImpl.EMPTY; line2 = line2.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 444)); assertEquals(line.hashCode(), line2.hashCode()); } @Test public void testEquals1() { line = line.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 444)); LineImpl line2 = LineImpl.EMPTY; line2 = line2.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 444)); assertEquals(line, line2); } @Test public void testEquals2() { line = line.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 444)); assertFalse(line.equals(new Object())); } @Test public void testEquals3() { line = line.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 444)); LineImpl line2 = LineImpl.EMPTY; line2 = line2.increment(CounterImpl.getInstance(111, 2220), CounterImpl.getInstance(333, 444)); assertFalse(line.equals(line2)); } @Test public void testEquals4() { line = line.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 4440)); LineImpl line2 = LineImpl.EMPTY; line2 = line2.increment(CounterImpl.getInstance(111, 222), CounterImpl.getInstance(333, 444)); assertFalse(line.equals(line2)); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/MethodAnalyzerTest.java000066400000000000000000000343101304217427400325560ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import org.jacoco.core.analysis.ILine; import org.jacoco.core.analysis.IMethodCoverage; import org.jacoco.core.internal.flow.IProbeIdGenerator; import org.jacoco.core.internal.flow.LabelFlowAnalyzer; import org.jacoco.core.internal.flow.MethodProbesAdapter; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TryCatchBlockNode; /** * Unit tests for {@link MethodAnalyzer}. */ public class MethodAnalyzerTest implements IProbeIdGenerator { private int nextProbeId; private boolean[] probes; private MethodNode method; private IMethodCoverage result; @Before public void setup() { nextProbeId = 0; method = new MethodNode(); method.tryCatchBlocks = new ArrayList(); probes = new boolean[32]; } public int nextId() { return nextProbeId++; } // === Scenario: linear Sequence without branches === private void createLinearSequence() { method.visitLineNumber(1001, new Label()); method.visitInsn(Opcodes.NOP); method.visitLineNumber(1002, new Label()); method.visitInsn(Opcodes.RETURN); } @Test public void testLinearSequenceNotCovered1() { createLinearSequence(); runMethodAnalzer(); assertEquals(1, nextProbeId); assertLine(1001, 1, 0, 0, 0); assertLine(1002, 1, 0, 0, 0); } @Test public void testLinearSequenceNotCovered2() { createLinearSequence(); probes = null; runMethodAnalzer(); assertEquals(1, nextProbeId); assertLine(1001, 1, 0, 0, 0); assertLine(1002, 1, 0, 0, 0); } @Test public void testLinearSequenceCovered() { createLinearSequence(); probes[0] = true; runMethodAnalzer(); assertLine(1001, 0, 1, 0, 0); assertLine(1002, 0, 1, 0, 0); } // === Scenario: simple if branch === private void createIfBranch() { method.visitLineNumber(1001, new Label()); method.visitVarInsn(Opcodes.ILOAD, 1); Label l1 = new Label(); method.visitJumpInsn(Opcodes.IFEQ, l1); method.visitLineNumber(1002, new Label()); method.visitLdcInsn("a"); method.visitInsn(Opcodes.ARETURN); method.visitLabel(l1); method.visitLineNumber(1003, l1); method.visitLdcInsn("b"); method.visitInsn(Opcodes.ARETURN); } @Test public void testIfBranchNotCovered() { createIfBranch(); runMethodAnalzer(); assertEquals(2, nextProbeId); assertLine(1001, 2, 0, 2, 0); assertLine(1002, 2, 0, 0, 0); assertLine(1003, 2, 0, 0, 0); } @Test public void testIfBranchCovered1() { createIfBranch(); probes[0] = true; runMethodAnalzer(); assertLine(1001, 0, 2, 1, 1); assertLine(1002, 0, 2, 0, 0); assertLine(1003, 2, 0, 0, 0); } @Test public void testIfBranchCovered2() { createIfBranch(); probes[1] = true; runMethodAnalzer(); assertLine(1001, 0, 2, 1, 1); assertLine(1002, 2, 0, 0, 0); assertLine(1003, 0, 2, 0, 0); } @Test public void testIfBranchCovered3() { createIfBranch(); probes[0] = true; probes[1] = true; runMethodAnalzer(); assertLine(1001, 0, 2, 0, 2); assertLine(1002, 0, 2, 0, 0); assertLine(1003, 0, 2, 0, 0); } // === Scenario: branch which merges back === private void createIfBranchMerge() { method.visitLineNumber(1001, new Label()); method.visitVarInsn(Opcodes.ILOAD, 1); Label l1 = new Label(); method.visitJumpInsn(Opcodes.IFEQ, l1); method.visitLineNumber(1002, new Label()); method.visitInsn(Opcodes.NOP); method.visitLabel(l1); method.visitLineNumber(1003, l1); method.visitInsn(Opcodes.RETURN); } @Test public void testIfBranchMergeNotCovered() { createIfBranchMerge(); runMethodAnalzer(); assertEquals(3, nextProbeId); assertLine(1001, 2, 0, 2, 0); assertLine(1002, 1, 0, 0, 0); assertLine(1003, 1, 0, 0, 0); } @Test public void testIfBranchMergeCovered1() { createIfBranchMerge(); probes[0] = true; runMethodAnalzer(); assertLine(1001, 0, 2, 1, 1); assertLine(1002, 1, 0, 0, 0); assertLine(1003, 1, 0, 0, 0); } @Test public void testIfBranchMergeCovered2() { createIfBranchMerge(); probes[1] = true; runMethodAnalzer(); assertLine(1001, 0, 2, 1, 1); assertLine(1002, 0, 1, 0, 0); assertLine(1003, 1, 0, 0, 0); } @Test public void testIfBranchMergeCovered3() { createIfBranchMerge(); probes[0] = true; probes[1] = true; probes[2] = true; runMethodAnalzer(); assertLine(1001, 0, 2, 0, 2); assertLine(1002, 0, 1, 0, 0); assertLine(1003, 0, 1, 0, 0); } // === Scenario: branch which jump backwards === private void createJumpBackwards() { method.visitLineNumber(1001, new Label()); final Label l1 = new Label(); method.visitJumpInsn(Opcodes.GOTO, l1); final Label l2 = new Label(); method.visitLabel(l2); method.visitLineNumber(1002, l2); method.visitInsn(Opcodes.RETURN); method.visitLabel(l1); method.visitLineNumber(1003, l1); method.visitJumpInsn(Opcodes.GOTO, l2); } @Test public void testJumpBackwardsNotCovered() { createJumpBackwards(); runMethodAnalzer(); assertEquals(1, nextProbeId); assertLine(1001, 1, 0, 0, 0); assertLine(1002, 1, 0, 0, 0); assertLine(1003, 1, 0, 0, 0); } @Test public void testJumpBackwardsCovered() { createJumpBackwards(); probes[0] = true; runMethodAnalzer(); assertLine(1001, 0, 1, 0, 0); assertLine(1002, 0, 1, 0, 0); assertLine(1003, 0, 1, 0, 0); } // === Scenario: jump to first instruction === private void createJumpToFirst() { final Label l1 = new Label(); method.visitLabel(l1); method.visitLineNumber(1001, l1); method.visitVarInsn(Opcodes.ALOAD, 0); method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "Foo", "test", "()Z", false); method.visitJumpInsn(Opcodes.IFEQ, l1); final Label l2 = new Label(); method.visitLabel(l2); method.visitLineNumber(1002, l2); method.visitInsn(Opcodes.RETURN); } @Test public void testJumpToFirstNotCovered() { createJumpToFirst(); runMethodAnalzer(); assertEquals(2, nextProbeId); assertLine(1001, 3, 0, 2, 0); assertLine(1002, 1, 0, 0, 0); } @Test public void testJumpToFirstCovered1() { createJumpToFirst(); probes[0] = true; runMethodAnalzer(); assertEquals(2, nextProbeId); assertLine(1001, 0, 3, 1, 1); assertLine(1002, 1, 0, 0, 0); } @Test public void testJumpToFirstCovered2() { createJumpToFirst(); probes[0] = true; probes[1] = true; runMethodAnalzer(); assertEquals(2, nextProbeId); assertLine(1001, 0, 3, 0, 2); assertLine(1002, 0, 1, 0, 0); } // === Scenario: table switch === private void createTableSwitch() { method.visitLineNumber(1001, new Label()); method.visitVarInsn(Opcodes.ILOAD, 1); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); method.visitTableSwitchInsn(1, 3, l3, new Label[] { l1, l2, l1 }); method.visitLabel(l1); method.visitLineNumber(1002, l1); method.visitIntInsn(Opcodes.BIPUSH, 11); method.visitVarInsn(Opcodes.ISTORE, 2); method.visitLineNumber(1003, new Label()); Label l5 = new Label(); method.visitJumpInsn(Opcodes.GOTO, l5); method.visitLabel(l2); method.visitLineNumber(1004, l2); method.visitIntInsn(Opcodes.BIPUSH, 22); method.visitVarInsn(Opcodes.ISTORE, 2); method.visitLineNumber(1005, new Label()); method.visitJumpInsn(Opcodes.GOTO, l5); method.visitLabel(l3); method.visitLineNumber(1006, l3); method.visitInsn(Opcodes.ICONST_0); method.visitVarInsn(Opcodes.ISTORE, 2); method.visitLabel(l5); method.visitLineNumber(1007, l5); method.visitVarInsn(Opcodes.ILOAD, 2); method.visitInsn(Opcodes.IRETURN); } @Test public void testTableSwitchNotCovered() { createTableSwitch(); runMethodAnalzer(); assertEquals(4, nextProbeId); assertLine(1001, 2, 0, 3, 0); assertLine(1002, 2, 0, 0, 0); assertLine(1003, 1, 0, 0, 0); assertLine(1004, 2, 0, 0, 0); assertLine(1005, 1, 0, 0, 0); assertLine(1006, 2, 0, 0, 0); assertLine(1007, 2, 0, 0, 0); } @Test public void testTableSwitchCovered1() { createTableSwitch(); probes[0] = true; probes[3] = true; runMethodAnalzer(); assertEquals(4, nextProbeId); assertLine(1001, 0, 2, 2, 1); assertLine(1002, 0, 2, 0, 0); assertLine(1003, 0, 1, 0, 0); assertLine(1004, 2, 0, 0, 0); assertLine(1005, 1, 0, 0, 0); assertLine(1006, 2, 0, 0, 0); assertLine(1007, 0, 2, 0, 0); } @Test public void testTableSwitchCovered2() { createTableSwitch(); probes[2] = true; probes[3] = true; runMethodAnalzer(); assertEquals(4, nextProbeId); assertLine(1001, 0, 2, 2, 1); assertLine(1002, 2, 0, 0, 0); assertLine(1003, 1, 0, 0, 0); assertLine(1004, 2, 0, 0, 0); assertLine(1005, 1, 0, 0, 0); assertLine(1006, 0, 2, 0, 0); assertLine(1007, 0, 2, 0, 0); } @Test public void testTableSwitchCovered3() { createTableSwitch(); probes[0] = true; probes[1] = true; probes[2] = true; probes[3] = true; runMethodAnalzer(); assertEquals(4, nextProbeId); assertLine(1001, 0, 2, 0, 3); assertLine(1002, 0, 2, 0, 0); assertLine(1003, 0, 1, 0, 0); assertLine(1004, 0, 2, 0, 0); assertLine(1005, 0, 1, 0, 0); assertLine(1006, 0, 2, 0, 0); assertLine(1007, 0, 2, 0, 0); } // === Scenario: table switch with merge === private void createTableSwitchMerge() { method.visitLineNumber(1001, new Label()); method.visitInsn(Opcodes.ICONST_0); method.visitVarInsn(Opcodes.ISTORE, 2); method.visitLineNumber(1002, new Label()); method.visitVarInsn(Opcodes.ILOAD, 1); Label l2 = new Label(); Label l3 = new Label(); Label l4 = new Label(); method.visitTableSwitchInsn(1, 3, l4, new Label[] { l2, l3, l2 }); method.visitLabel(l2); method.visitLineNumber(1003, l2); method.visitIincInsn(2, 1); method.visitLabel(l3); method.visitLineNumber(1004, l3); method.visitIincInsn(2, 1); method.visitLabel(l4); method.visitLineNumber(1005, l4); method.visitVarInsn(Opcodes.ILOAD, 2); method.visitInsn(Opcodes.IRETURN); } @Test public void testTableSwitchMergeNotCovered() { createTableSwitchMerge(); runMethodAnalzer(); assertEquals(5, nextProbeId); assertLine(1001, 2, 0, 0, 0); assertLine(1002, 2, 0, 3, 0); assertLine(1003, 1, 0, 0, 0); assertLine(1004, 1, 0, 0, 0); assertLine(1005, 2, 0, 0, 0); } @Test public void testTableSwitchMergeNotCovered1() { createTableSwitchMerge(); probes[0] = true; probes[4] = true; runMethodAnalzer(); assertEquals(5, nextProbeId); assertLine(1001, 0, 2, 0, 0); assertLine(1002, 0, 2, 2, 1); assertLine(1003, 1, 0, 0, 0); assertLine(1004, 1, 0, 0, 0); assertLine(1005, 0, 2, 0, 0); } @Test public void testTableSwitchMergeNotCovered2() { createTableSwitchMerge(); probes[1] = true; probes[3] = true; probes[4] = true; runMethodAnalzer(); assertEquals(5, nextProbeId); assertLine(1001, 0, 2, 0, 0); assertLine(1002, 0, 2, 2, 1); assertLine(1003, 1, 0, 0, 0); assertLine(1004, 0, 1, 0, 0); assertLine(1005, 0, 2, 0, 0); } @Test public void testTableSwitchMergeNotCovered3() { createTableSwitchMerge(); probes[2] = true; probes[3] = true; probes[4] = true; runMethodAnalzer(); assertEquals(5, nextProbeId); assertLine(1001, 0, 2, 0, 0); assertLine(1002, 0, 2, 2, 1); assertLine(1003, 0, 1, 0, 0); assertLine(1004, 0, 1, 0, 0); assertLine(1005, 0, 2, 0, 0); } @Test public void testTableSwitchMergeNotCovered4() { createTableSwitchMerge(); probes[0] = true; probes[1] = true; probes[2] = true; probes[3] = true; probes[4] = true; runMethodAnalzer(); assertEquals(5, nextProbeId); assertLine(1001, 0, 2, 0, 0); assertLine(1002, 0, 2, 0, 3); assertLine(1003, 0, 1, 0, 0); assertLine(1004, 0, 1, 0, 0); assertLine(1005, 0, 2, 0, 0); } // === Scenario: try/catch block === private void createTryCatchBlock() { Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); Label l4 = new Label(); method.visitTryCatchBlock(l1, l2, l3, "java/lang/Exception"); method.visitLabel(l1); method.visitLineNumber(1001, l1); method.visitVarInsn(Opcodes.ALOAD, 0); method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Throwable", "printStackTrace", "()V", false); method.visitLabel(l2); method.visitJumpInsn(Opcodes.GOTO, l4); method.visitLabel(l3); method.visitLineNumber(1002, l3); method.visitVarInsn(Opcodes.ASTORE, 1); method.visitLabel(l4); method.visitLineNumber(1004, l4); method.visitInsn(Opcodes.RETURN); } @Test public void testTryCatchBlockNotCovered() { createTryCatchBlock(); runMethodAnalzer(); assertEquals(3, nextProbeId); assertEquals(CounterImpl.getInstance(5, 0), result.getInstructionCounter()); assertLine(1001, 3, 0, 0, 0); assertLine(1002, 1, 0, 0, 0); assertLine(1004, 1, 0, 0, 0); } @Test public void testTryCatchBlockFullyCovered() { createTryCatchBlock(); probes[0] = true; probes[1] = true; probes[2] = true; runMethodAnalzer(); assertEquals(3, nextProbeId); assertEquals(CounterImpl.getInstance(0, 5), result.getInstructionCounter()); assertLine(1001, 0, 3, 0, 0); assertLine(1002, 0, 1, 0, 0); assertLine(1004, 0, 1, 0, 0); } private void runMethodAnalzer() { LabelFlowAnalyzer.markLabels(method); final MethodAnalyzer analyzer = new MethodAnalyzer("doit", "()V", null, probes); final MethodProbesAdapter probesAdapter = new MethodProbesAdapter( analyzer, this); method.accept(probesAdapter); result = analyzer.getCoverage(); } private void assertLine(int nr, int insnMissed, int insnCovered, int branchesMissed, int branchesCovered) { final ILine line = result.getLine(nr); assertEquals("Instructions in line " + nr, CounterImpl.getInstance(insnMissed, insnCovered), line.getInstructionCounter()); assertEquals("Branches in line " + nr, CounterImpl.getInstance(branchesMissed, branchesCovered), line.getBranchCounter()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/MethodCoverageImplTest.java000066400000000000000000000114001304217427400333410ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import org.jacoco.core.analysis.ICoverageNode; import org.junit.Test; /** * Unit test for {@link MethodCoverageImpl}. */ public class MethodCoverageImplTest { @Test public void testProperties() { // Example: java.util.Collections.emptySet() MethodCoverageImpl node = new MethodCoverageImpl("emptySet", "()Ljava/util/Set;", "()Ljava/util/Set;"); assertEquals(ICoverageNode.ElementType.METHOD, node.getElementType()); assertEquals("emptySet", node.getName()); assertEquals("()Ljava/util/Set;", node.getDesc()); assertEquals("()Ljava/util/Set;", node.getSignature()); } @Test public void testEmptyMethod() { ICoverageNode node = new MethodCoverageImpl("sample", "()V", null); assertEquals(CounterImpl.COUNTER_0_0, node.getInstructionCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getBranchCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getLineCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getComplexityCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getMethodCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getClassCounter()); } @Test public void testIncrementMissedInstructions() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.getInstance(25, 0), CounterImpl.COUNTER_0_0, 3); node.incrementMethodCounter(); assertEquals(CounterImpl.COUNTER_1_0, node.getMethodCounter()); assertEquals(CounterImpl.COUNTER_1_0, node.getComplexityCounter()); } @Test public void testIncrementCoveredInstructions() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.getInstance(12, 13), CounterImpl.COUNTER_0_0, 3); node.incrementMethodCounter(); assertEquals(CounterImpl.COUNTER_0_1, node.getMethodCounter()); assertEquals(CounterImpl.COUNTER_0_1, node.getComplexityCounter()); } @Test public void testIncrementComplexity1() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.COUNTER_0_0, 3); assertEquals(CounterImpl.COUNTER_0_0, node.getComplexityCounter()); } @Test public void testIncrementComplexity2() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.getInstance(2, 0), 3); assertEquals(CounterImpl.getInstance(1, 0), node.getComplexityCounter()); } @Test public void testIncrementComplexity3() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.getInstance(1, 1), 3); assertEquals(CounterImpl.getInstance(1, 0), node.getComplexityCounter()); } @Test public void testIncrementComplexity4() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.getInstance(0, 2), 3); assertEquals(CounterImpl.getInstance(0, 1), node.getComplexityCounter()); } @Test public void testIncrementComplexity5() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.getInstance(3, 0), 3); assertEquals(CounterImpl.getInstance(2, 0), node.getComplexityCounter()); } @Test public void testIncrementComplexity6() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.getInstance(2, 1), 3); assertEquals(CounterImpl.getInstance(2, 0), node.getComplexityCounter()); } @Test public void testIncrementComplexity7() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.getInstance(1, 2), 3); assertEquals(CounterImpl.getInstance(1, 1), node.getComplexityCounter()); } @Test public void testIncrementComplexity8() { MethodCoverageImpl node = new MethodCoverageImpl("sample", "()V", null); node.increment(CounterImpl.COUNTER_0_0, CounterImpl.getInstance(0, 3), 3); assertEquals(CounterImpl.getInstance(0, 2), node.getComplexityCounter()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/PackageCoverageTest.java000066400000000000000000000077331304217427400326500ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import java.util.Collection; import java.util.Collections; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.ICoverageNode; import org.jacoco.core.analysis.ISourceFileCoverage; import org.junit.Test; /** * Unit test for {@link PackageCoverageImpl}. */ public class PackageCoverageTest { @Test public void testProperties() { Collection classes = Collections .singleton((IClassCoverage) new ClassCoverageImpl( "org/jacoco/test/Sample", 0, false)); Collection sourceFiles = Collections .singleton((ISourceFileCoverage) new SourceFileCoverageImpl( "Sample.java", "org/jacoco/test/Sample")); PackageCoverageImpl data = new PackageCoverageImpl("org/jacoco/test", classes, sourceFiles); assertEquals(ICoverageNode.ElementType.PACKAGE, data.getElementType()); assertEquals("org/jacoco/test", data.getName()); assertEquals(classes, data.getClasses()); assertEquals(sourceFiles, data.getSourceFiles()); } @Test public void testCountersWithSources() { // Classes with source reference will not considered for counters: final ClassCoverageImpl classnode = new ClassCoverageImpl( "org/jacoco/test/Sample", 0, false) { { classCounter = CounterImpl.getInstance(9, 0); methodCounter = CounterImpl.getInstance(9, 0); branchCounter = CounterImpl.getInstance(9, 0); instructionCounter = CounterImpl.getInstance(9, 0); } }; classnode.setSourceFileName("Sample.java"); // Only source files will be considered for counters: final ISourceFileCoverage sourceFile = new SourceFileCoverageImpl( "Sample.java", "org/jacoco/test/Sample") { { classCounter = CounterImpl.getInstance(1, 0); methodCounter = CounterImpl.getInstance(2, 0); branchCounter = CounterImpl.getInstance(3, 0); instructionCounter = CounterImpl.getInstance(4, 0); } }; PackageCoverageImpl data = new PackageCoverageImpl("org/jacoco/test", Collections.singleton((IClassCoverage) classnode), Collections.singleton(sourceFile)); assertEquals(CounterImpl.getInstance(1, 0), data.getClassCounter()); assertEquals(CounterImpl.getInstance(2, 0), data.getMethodCounter()); assertEquals(CounterImpl.getInstance(3, 0), data.getBranchCounter()); assertEquals(CounterImpl.getInstance(4, 0), data.getInstructionCounter()); } @Test public void testCountersWithoutSources() { // Classes without source reference will be considered for counters: final ClassCoverageImpl classnode = new ClassCoverageImpl( "org/jacoco/test/Sample", 0, false) { { classCounter = CounterImpl.getInstance(1, 0); methodCounter = CounterImpl.getInstance(2, 0); branchCounter = CounterImpl.getInstance(3, 0); instructionCounter = CounterImpl.getInstance(4, 0); } }; final Collection sourceFiles = Collections .emptySet(); PackageCoverageImpl data = new PackageCoverageImpl("org/jacoco/test", Collections.singleton((IClassCoverage) classnode), sourceFiles); assertEquals(CounterImpl.getInstance(1, 0), data.getClassCounter()); assertEquals(CounterImpl.getInstance(2, 0), data.getMethodCounter()); assertEquals(CounterImpl.getInstance(3, 0), data.getBranchCounter()); assertEquals(CounterImpl.getInstance(4, 0), data.getInstructionCounter()); assertEquals(CounterImpl.getInstance(0, 0), data.getLineCounter()); } } SourceFileCoverageImplTest.java000066400000000000000000000021341304217427400341060ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.jacoco.core.analysis.ICoverageNode.ElementType.SOURCEFILE; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * Unit test for {@link SourceFileCoverageImpl}. */ public class SourceFileCoverageImplTest { @Test public void testProperties() { SourceFileCoverageImpl data = new SourceFileCoverageImpl("Sample.java", "org/jacoco/examples"); assertEquals(SOURCEFILE, data.getElementType()); assertEquals("org/jacoco/examples", data.getPackageName()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/SourceNodeImplTest.java000066400000000000000000000144121304217427400325210ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import org.jacoco.core.analysis.ICoverageNode.ElementType; import org.jacoco.core.analysis.ISourceNode; import org.junit.Test; /** * Unit tests for {@link SourceNodeImpl}. */ public class SourceNodeImplTest { @Test public void testInit() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); assertEquals(ElementType.CLASS, node.getElementType()); assertEquals("Foo", node.getName()); assertEquals(ISourceNode.UNKNOWN_LINE, node.getFirstLine()); assertEquals(ISourceNode.UNKNOWN_LINE, node.getLastLine()); assertEquals(LineImpl.EMPTY, node.getLine(123)); } @Test public void testGetLine() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); node.ensureCapacity(10, 20); assertEquals(LineImpl.EMPTY, node.getLine(5)); assertEquals(LineImpl.EMPTY, node.getLine(15)); assertEquals(LineImpl.EMPTY, node.getLine(25)); } @Test public void testEnsureCapacityUnknown1() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); node.ensureCapacity(10, ISourceNode.UNKNOWN_LINE); assertEquals(LineImpl.EMPTY, node.getLine(10)); } @Test public void testEnsureCapacityUnknown2() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); node.ensureCapacity(ISourceNode.UNKNOWN_LINE, 10); assertEquals(LineImpl.EMPTY, node.getLine(10)); } @Test public void testIncrementLineUnknown() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); node.increment(CounterImpl.getInstance(1, 2), CounterImpl.getInstance(3, 4), ISourceNode.UNKNOWN_LINE); assertEquals(CounterImpl.getInstance(1, 2), node.getInstructionCounter()); assertEquals(CounterImpl.getInstance(3, 4), node.getBranchCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getLineCounter()); } @Test public void testIncrementLines() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); node.increment(CounterImpl.getInstance(1, 1), CounterImpl.COUNTER_0_0, 10); node.increment(CounterImpl.getInstance(2, 2), CounterImpl.COUNTER_0_0, 12); assertEquals(CounterImpl.getInstance(1, 1), node.getLine(10) .getInstructionCounter()); assertEquals(CounterImpl.COUNTER_0_0, node.getLine(11) .getInstructionCounter()); assertEquals(CounterImpl.getInstance(2, 2), node.getLine(12) .getInstructionCounter()); } @Test public void testIncrementLine1_1() { testIncrementLine(0, 0, 0, 0, 0, 0); } @Test public void testIncrementLine1_2() { testIncrementLine(0, 0, 5, 0, 1, 0); } @Test public void testIncrementLine1_3() { testIncrementLine(0, 0, 0, 5, 0, 1); } @Test public void testIncrementLine1_4() { testIncrementLine(0, 0, 5, 5, 0, 1); } @Test public void testIncrementLine2_1() { testIncrementLine(3, 0, 0, 0, 1, 0); } @Test public void testIncrementLine2_2() { testIncrementLine(3, 0, 5, 0, 1, 0); } @Test public void testIncrementLine2_3() { testIncrementLine(3, 0, 0, 5, 0, 1); } @Test public void testIncrementLine2_4() { testIncrementLine(3, 0, 5, 5, 0, 1); } @Test public void testIncrementLine3_1() { testIncrementLine(0, 3, 0, 0, 0, 1); } @Test public void testIncrementLine3_2() { testIncrementLine(0, 3, 5, 0, 0, 1); } @Test public void testIncrementLine3_3() { testIncrementLine(0, 3, 0, 5, 0, 1); } @Test public void testIncrementLine3_4() { testIncrementLine(0, 3, 5, 5, 0, 1); } @Test public void testIncrementLine4_1() { testIncrementLine(3, 3, 0, 0, 0, 1); } @Test public void testIncrementLine4_2() { testIncrementLine(3, 3, 5, 0, 0, 1); } @Test public void testIncrementLine4_3() { testIncrementLine(3, 3, 0, 5, 0, 1); } @Test public void testIncrementLine4_4() { testIncrementLine(3, 3, 5, 5, 0, 1); } private void testIncrementLine(int mi1, int ci1, int mi2, int ci2, int expectedMissedLines, int expectedCoveredLines) { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); node.increment(CounterImpl.getInstance(mi1, ci1), CounterImpl.COUNTER_0_0, 33); node.increment(CounterImpl.getInstance(mi2, ci2), CounterImpl.COUNTER_0_0, 33); assertEquals(CounterImpl.getInstance(expectedMissedLines, expectedCoveredLines), node.getLineCounter()); assertEquals(CounterImpl.getInstance(mi1 + mi2, ci1 + ci2), node .getLine(33).getInstructionCounter()); } @Test public void testIncrementChildNoLines() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); final SourceNodeImpl child = new SourceNodeImpl(ElementType.CLASS, "Foo") { { this.instructionCounter = CounterImpl.getInstance(1, 11); this.branchCounter = CounterImpl.getInstance(2, 22); this.methodCounter = CounterImpl.getInstance(3, 33); this.classCounter = CounterImpl.getInstance(4, 44); } }; node.increment(child); assertEquals(CounterImpl.getInstance(1, 11), node.getInstructionCounter()); assertEquals(CounterImpl.getInstance(2, 22), node.getBranchCounter()); assertEquals(CounterImpl.getInstance(3, 33), node.getMethodCounter()); assertEquals(CounterImpl.getInstance(4, 44), node.getClassCounter()); } @Test public void testIncrementChildWithLines() { final SourceNodeImpl node = new SourceNodeImpl(ElementType.CLASS, "Foo"); final SourceNodeImpl child = new SourceNodeImpl(ElementType.CLASS, "Foo"); child.increment(CounterImpl.getInstance(1, 11), CounterImpl.getInstance(3, 33), 5); node.increment(child); node.increment(child); assertEquals(CounterImpl.getInstance(2, 22), node.getInstructionCounter()); assertEquals(CounterImpl.getInstance(6, 66), node.getBranchCounter()); assertEquals(CounterImpl.getInstance(0, 1), node.getLineCounter()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/analysis/StringPoolTest.java000066400000000000000000000034631304217427400317350ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link StringPool}. */ public class StringPoolTest { private StringPool pool; @Before public void setup() { pool = new StringPool(); } @Test public void testGetStringNull() { assertNull(pool.get((String) null)); } @Test public void testGetString() { final String a = pool.get(new String("JaCoCo")); final String b = pool.get(new String("JaCoCo")); assertEquals("JaCoCo", a); assertEquals("JaCoCo", b); assertSame(a, b); } @Test public void testGetArrayNull() { assertNull(pool.get((String[]) null)); } @Test public void testGetEmptyArray() { final String[] arr1 = pool.get(new String[0]); final String[] arr2 = pool.get(new String[0]); assertEquals(0, arr1.length); assertSame(arr1, arr2); } @Test public void testGetArray() { final String[] arr1 = pool.get(new String[] { new String("JaCoCo") }); final String[] arr2 = pool.get(new String[] { new String("JaCoCo") }); assertEquals(1, arr1.length); assertEquals("JaCoCo", arr1[0]); assertSame(arr1[0], arr2[0]); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/data/000077500000000000000000000000001304217427400252125ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/data/CRC64Test.java000066400000000000000000000035171304217427400275040ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.data; import static org.junit.Assert.assertEquals; import java.io.UnsupportedEncodingException; import org.junit.Test; /** * Unit tests for {@link CRC64}. */ public class CRC64Test { @Test public void test0() { final long sum = CRC64.checksum(new byte[0]); assertEquals(0L, sum); } /** * Example taken from http://swissknife.sourceforge.net/docs/CRC64.html * * @throws UnsupportedEncodingException */ @Test public void test1() throws UnsupportedEncodingException { final long sum = CRC64.checksum("IHATEMATH".getBytes("ASCII")); assertEquals(0xE3DCADD69B01ADD1L, sum); } /** * Example generated with http://fsumfe.sourceforge.net/ * * @throws UnsupportedEncodingException */ @Test public void test2() { final long sum = CRC64.checksum(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }); assertEquals(0x5300000000000000L, sum); } /** * Example generated with http://fsumfe.sourceforge.net/ * * @throws UnsupportedEncodingException */ @Test public void test3() throws UnsupportedEncodingException { final long sum = CRC64.checksum("JACOCO_JACOCO_JACOCO_JACOCO" .getBytes("ASCII")); assertEquals(0xD8016B38AAD48308L, sum); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/data/CompactDataInputOutputTest.java000066400000000000000000000057631304217427400333510ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.data; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link CompactDataInput} and {@link CompactDataOutput}. The * tests don't care about the written binary format, they just verify symmetry. */ public class CompactDataInputOutputTest { private CompactDataOutput out; private CompactDataInput in; @Before public void setup() throws IOException { PipedOutputStream pipe = new PipedOutputStream(); out = new CompactDataOutput(pipe); in = new CompactDataInput(new PipedInputStream(pipe)); } @Test public void testVarInt0x00000000() throws IOException { testVarInt(0x00000000); } @Test public void testVarInt0x0000007F() throws IOException { testVarInt(0x0000007F); } @Test public void testVarInt0x00000080() throws IOException { testVarInt(0x00000080); } @Test public void testVarInt0x00000100() throws IOException { testVarInt(0x00000100); } @Test public void testVarInt0x12345678() throws IOException { testVarInt(0x12345678); } @Test public void testVarIntMinus1() throws IOException { testVarInt(-1); } @Test public void testVarIntMinValue() throws IOException { testVarInt(Integer.MIN_VALUE); } @Test public void testVarIntMaxValue() throws IOException { testVarInt(Integer.MAX_VALUE); } private void testVarInt(int value) throws IOException { out.writeVarInt(value); out.close(); assertEquals(Long.valueOf(value), Long.valueOf(in.readVarInt())); assertEquals(Integer.valueOf(-1), Integer.valueOf(in.read())); } @Test public void testPackedBooleanEmpty() throws IOException { testPackedBoolean(); } @Test public void testPackedBoolean3() throws IOException { testPackedBoolean(false, false, true); } @Test public void testPackedBoolean8() throws IOException { testPackedBoolean(true, false, true, false, false, true, false, true); } @Test public void testPackedBoolean9() throws IOException { testPackedBoolean(true, true, false, true, false, false, true, false, true); } private void testPackedBoolean(boolean... values) throws IOException { out.writeBooleanArray(values); out.close(); final boolean[] actual = in.readBooleanArray(); for (int i = 0; i < values.length; i++) { assertEquals("Index " + i, Boolean.valueOf(values[i]), Boolean.valueOf(actual[i])); } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/000077500000000000000000000000001304217427400252505ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/ClassProbesAdapterTest.java000066400000000000000000000131771304217427400325050ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * Unit tests for {@link ClassProbesAdapter}. */ public class ClassProbesAdapterTest { private static class MockMethodVisitor extends MethodProbesVisitor { boolean frame = false; @Override public void visitJumpInsnWithProbe(int opcode, Label label, int probeId, IFrame frame) { frame.accept(this); } @Override public void visitTableSwitchInsnWithProbes(int min, int max, Label dflt, Label[] labels, IFrame frame) { frame.accept(this); } @Override public void visitLookupSwitchInsnWithProbes(Label dflt, int[] keys, Label[] labels, IFrame frame) { frame.accept(this); } @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { frame = true; } } private static class MockClassVisitor extends ClassProbesVisitor { int count; @Override public MethodProbesVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return null; } @Override public void visitTotalProbeCount(int count) { this.count = count; } } @Test public void testProbeCounter() { final MockClassVisitor cv = new MockClassVisitor(); final ClassProbesAdapter adapter = new ClassProbesAdapter(cv, false); assertEquals(0, adapter.nextId()); assertEquals(1, adapter.nextId()); assertEquals(2, adapter.nextId()); adapter.visitEnd(); assertEquals(3, cv.count); } @Test public void testVisitClassMethods() { final MockClassVisitor cv = new MockClassVisitor() { @Override public MethodProbesVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new MockMethodVisitor(); } }; final ClassProbesAdapter adapter = new ClassProbesAdapter(cv, false); adapter.visit(Opcodes.V1_5, 0, "Foo", null, "java/lang/Object", null); writeMethod(adapter); writeMethod(adapter); writeMethod(adapter); assertEquals(0, cv.count); adapter.visitEnd(); assertEquals(3, cv.count); } @Test public void testVisitMethodNullMethodVisitor() { final MockClassVisitor cv = new MockClassVisitor(); final ClassProbesAdapter adapter = new ClassProbesAdapter(cv, false); writeMethod(adapter); // 1 probe writeMethodWithBranch(adapter); // 3 probes writeMethodWithTableSwitch(adapter); // 3 probes writeMethodWithLookupSwitch(adapter); // 3 probes adapter.visitEnd(); assertEquals(10, cv.count); } @Test public void testVisitWithFrames() { final MockMethodVisitor mv = new MockMethodVisitor(); final MockClassVisitor cv = new MockClassVisitor() { @Override public MethodProbesVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return mv; } }; final ClassProbesAdapter adapter = new ClassProbesAdapter(cv, true); writeMethodWithBranch(adapter); adapter.visitEnd(); assertTrue(mv.frame); } @Test public void testVisitWithoutFrames() { final MockMethodVisitor mv = new MockMethodVisitor(); final MockClassVisitor cv = new MockClassVisitor() { @Override public MethodProbesVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return mv; } }; final ClassProbesAdapter adapter = new ClassProbesAdapter(cv, false); writeMethodWithBranch(adapter); adapter.visitEnd(); assertFalse(mv.frame); } private void writeMethod(final ClassVisitor cv) { MethodVisitor mv = cv.visitMethod(0, "foo", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 1); mv.visitEnd(); } private void writeMethodWithBranch(final ClassVisitor cv) { MethodVisitor mv = cv.visitMethod(0, "foo", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.ICONST_0); Label l = new Label(); mv.visitJumpInsn(Opcodes.IFEQ, l); mv.visitInsn(Opcodes.NOP); mv.visitLabel(l); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } private void writeMethodWithTableSwitch(final ClassVisitor cv) { MethodVisitor mv = cv.visitMethod(0, "foo", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.ICONST_0); Label l1 = new Label(); Label l2 = new Label(); mv.visitTableSwitchInsn(0, 0, l1, new Label[] { l2 }); mv.visitLabel(l1); mv.visitInsn(Opcodes.NOP); mv.visitLabel(l2); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } private void writeMethodWithLookupSwitch(final ClassVisitor cv) { MethodVisitor mv = cv.visitMethod(0, "foo", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.ICONST_0); Label l1 = new Label(); Label l2 = new Label(); mv.visitLookupSwitchInsn(l1, new int[] { 0 }, new Label[] { l2 }); mv.visitLabel(l1); mv.visitInsn(Opcodes.NOP); mv.visitLabel(l2); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/FrameSnapshotTest.java000066400000000000000000000053251304217427400315320ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import static org.junit.Assert.assertEquals; import org.jacoco.core.instr.MethodRecorder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.commons.AnalyzerAdapter; /** * Unit tests for {@link FrameSnapshot}. */ public class FrameSnapshotTest { private AnalyzerAdapter analyzer; private IFrame frame; private MethodRecorder expected; private MethodVisitor expectedVisitor; @Before public void setup() { analyzer = new AnalyzerAdapter("Foo", 0, "doit", "()V", null); expected = new MethodRecorder(); expectedVisitor = expected.getVisitor(); } @After public void teardown() { MethodRecorder actual = new MethodRecorder(); frame.accept(actual.getVisitor()); assertEquals(expected, actual); } @Test public void testNullAnalyzer() { frame = FrameSnapshot.create(null, 0); } @Test public void testNoFrame() { analyzer.visitJumpInsn(Opcodes.GOTO, new Label()); frame = FrameSnapshot.create(analyzer, 0); } @Test public void testFrame() { analyzer.visitInsn(Opcodes.ICONST_0); frame = FrameSnapshot.create(analyzer, 0); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, arr("Foo"), 1, arr(Opcodes.INTEGER)); } @Test public void testReduce() { analyzer.visitInsn(Opcodes.ICONST_0); analyzer.visitInsn(Opcodes.LCONST_0); analyzer.visitInsn(Opcodes.ICONST_0); analyzer.visitInsn(Opcodes.DCONST_0); frame = FrameSnapshot.create(analyzer, 0); final Object[] stack = arr(Opcodes.INTEGER, Opcodes.LONG, Opcodes.INTEGER, Opcodes.DOUBLE); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, arr("Foo"), 4, stack); } @Test public void testPop() { analyzer.visitInsn(Opcodes.ICONST_0); analyzer.visitInsn(Opcodes.LCONST_0); analyzer.visitInsn(Opcodes.ICONST_0); analyzer.visitInsn(Opcodes.ICONST_0); frame = FrameSnapshot.create(analyzer, 2); final Object[] stack = arr(Opcodes.INTEGER, Opcodes.LONG); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, arr("Foo"), 2, stack); } private Object[] arr(Object... elements) { return elements; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/InstructionTest.java000066400000000000000000000045641304217427400313050ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link Instruction}. */ public class InstructionTest { private Instruction instruction; @Before public void setup() { instruction = new Instruction(123); } @Test public void testInit() { assertEquals(123, instruction.getLine()); assertEquals(0, instruction.getBranches()); assertEquals(0, instruction.getCoveredBranches()); } @Test public void testAddBranch() { instruction.addBranch(); assertEquals(1, instruction.getBranches()); instruction.addBranch(); assertEquals(2, instruction.getBranches()); instruction.addBranch(); assertEquals(3, instruction.getBranches()); assertEquals(0, instruction.getCoveredBranches()); } @Test public void testSetPredecessor() { final Instruction predecessor = new Instruction(122); instruction.setPredecessor(predecessor); assertEquals(1, predecessor.getBranches()); } @Test public void testSetCovered() { final Instruction predecessor = new Instruction(122); instruction.setPredecessor(predecessor); instruction.setCovered(); assertEquals(1, instruction.getCoveredBranches()); assertEquals(1, predecessor.getCoveredBranches()); instruction.setCovered(); assertEquals(2, instruction.getCoveredBranches()); assertEquals(1, predecessor.getCoveredBranches()); } @Test public void testSetCoveredOnLongSequence() { final Instruction first = new Instruction(0); Instruction next = first; for (int i = 0; i < 0x10000; i++) { final Instruction insn = new Instruction(i); insn.setPredecessor(next); next = insn; } // The implementation must not cause an StackOverflowError even on very // long sequences: next.setCovered(); assertEquals(1, first.getCoveredBranches()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/LabelFlowAnalyzerTest.java000066400000000000000000000241501304217427400323320ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.objectweb.asm.Opcodes.*; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; /** * Unit tests for {@link LabelFlowAnalyzer}. */ public class LabelFlowAnalyzerTest { private LabelFlowAnalyzer analyzer; private Label label; @Before public void setup() { analyzer = new LabelFlowAnalyzer(); label = new Label(); } @Test public void testInit() { assertFalse(analyzer.successor); assertTrue(analyzer.first); assertNull(analyzer.lineStart); } @Test public void testFlowScenario01() { assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario02() { analyzer.visitJumpInsn(GOTO, label); assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario03() { analyzer.visitInsn(RETURN); analyzer.visitLabel(label); assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario04() { analyzer.visitLabel(label); assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario05() { analyzer.visitLabel(label); analyzer.visitJumpInsn(GOTO, label); assertTrue(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario06() { analyzer.visitJumpInsn(IFEQ, label); analyzer.visitLabel(label); assertTrue(LabelInfo.isMultiTarget(label)); assertTrue(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario07() { analyzer.visitJumpInsn(IFEQ, label); analyzer.visitJumpInsn(GOTO, label); assertTrue(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario08() { analyzer.visitJumpInsn(IFEQ, label); analyzer.visitJumpInsn(IFGT, label); analyzer.visitLabel(label); assertTrue(LabelInfo.isMultiTarget(label)); assertTrue(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario09() { analyzer.visitInsn(Opcodes.NOP); analyzer.visitLabel(label); analyzer.visitLabel(label); assertFalse(LabelInfo.isMultiTarget(label)); assertTrue(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario10() { analyzer.visitTryCatchBlock(new Label(), new Label(), label, "java/lang/Exception"); analyzer.visitJumpInsn(GOTO, label); assertTrue(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario11() { // Even if the same label is referenced multiple times but from the same // source instruction this is only counted as one target. analyzer.visitLookupSwitchInsn(label, new int[] { 0, 1 }, new Label[] { label, label }); assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testFlowScenario12() { // Even if the same label is referenced multiple times but from the same // source instruction this is only counted as one target. analyzer.visitTableSwitchInsn(0, 1, label, new Label[] { label, label }); assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testInsn() { testInsn(NOP, true); testInsn(ACONST_NULL, true); testInsn(ICONST_M1, true); testInsn(ICONST_0, true); testInsn(ICONST_1, true); testInsn(ICONST_2, true); testInsn(ICONST_3, true); testInsn(ICONST_4, true); testInsn(ICONST_5, true); testInsn(LCONST_0, true); testInsn(LCONST_1, true); testInsn(FCONST_0, true); testInsn(FCONST_1, true); testInsn(FCONST_2, true); testInsn(DCONST_0, true); testInsn(DCONST_1, true); testInsn(IALOAD, true); testInsn(LALOAD, true); testInsn(FALOAD, true); testInsn(DALOAD, true); testInsn(AALOAD, true); testInsn(BALOAD, true); testInsn(CALOAD, true); testInsn(SALOAD, true); testInsn(IASTORE, true); testInsn(LASTORE, true); testInsn(FASTORE, true); testInsn(DASTORE, true); testInsn(AASTORE, true); testInsn(BASTORE, true); testInsn(CASTORE, true); testInsn(SASTORE, true); testInsn(POP, true); testInsn(POP2, true); testInsn(DUP, true); testInsn(DUP_X1, true); testInsn(DUP_X2, true); testInsn(DUP2, true); testInsn(DUP2_X1, true); testInsn(DUP2_X2, true); testInsn(SWAP, true); testInsn(IADD, true); testInsn(LADD, true); testInsn(FADD, true); testInsn(DADD, true); testInsn(ISUB, true); testInsn(LSUB, true); testInsn(FSUB, true); testInsn(DSUB, true); testInsn(IMUL, true); testInsn(LMUL, true); testInsn(FMUL, true); testInsn(DMUL, true); testInsn(IDIV, true); testInsn(LDIV, true); testInsn(FDIV, true); testInsn(DDIV, true); testInsn(IREM, true); testInsn(LREM, true); testInsn(FREM, true); testInsn(DREM, true); testInsn(INEG, true); testInsn(LNEG, true); testInsn(FNEG, true); testInsn(DNEG, true); testInsn(ISHL, true); testInsn(LSHL, true); testInsn(ISHR, true); testInsn(LSHR, true); testInsn(IUSHR, true); testInsn(LUSHR, true); testInsn(IAND, true); testInsn(LAND, true); testInsn(IOR, true); testInsn(LOR, true); testInsn(IXOR, true); testInsn(LXOR, true); testInsn(I2L, true); testInsn(I2F, true); testInsn(I2D, true); testInsn(L2I, true); testInsn(L2F, true); testInsn(L2D, true); testInsn(F2I, true); testInsn(F2L, true); testInsn(F2D, true); testInsn(D2I, true); testInsn(D2L, true); testInsn(D2F, true); testInsn(I2B, true); testInsn(I2C, true); testInsn(I2S, true); testInsn(LCMP, true); testInsn(FCMPL, true); testInsn(FCMPG, true); testInsn(DCMPL, true); testInsn(DCMPG, true); testInsn(IRETURN, false); testInsn(LRETURN, false); testInsn(FRETURN, false); testInsn(DRETURN, false); testInsn(ARETURN, false); testInsn(RETURN, false); testInsn(ARRAYLENGTH, true); testInsn(ATHROW, false); testInsn(MONITORENTER, true); testInsn(MONITOREXIT, true); } private void testInsn(int opcode, boolean expected) { // ensure the flags are actually set: analyzer.successor = !expected; analyzer.first = true; analyzer.visitInsn(opcode); assertTrue(expected == analyzer.successor); assertFalse(analyzer.first); } @Test(expected = AssertionError.class) public void testVisitInsnNegative() { analyzer.visitInsn(RET); } @Test public void testIntInsn() { analyzer.visitIntInsn(BIPUSH, 0); assertTrue(analyzer.successor); assertFalse(analyzer.first); } @Test public void testVarInsn() { analyzer.visitVarInsn(ILOAD, 0); assertTrue(analyzer.successor); assertFalse(analyzer.first); } @Test public void testTypeInsn() { analyzer.visitTypeInsn(NEW, "java/lang/String"); assertTrue(analyzer.successor); assertFalse(analyzer.first); } @Test public void testFieldInsn() { analyzer.successor = false; analyzer.visitFieldInsn(GETFIELD, "Foo", "name", "Ljava/lang/String;"); assertTrue(analyzer.successor); assertFalse(analyzer.first); } @Test public void testLineNumber() { analyzer.visitLineNumber(42, label); assertSame(label, analyzer.lineStart); } @Test public void testMethodInsn() { analyzer.visitLineNumber(42, label); analyzer.visitMethodInsn(INVOKEVIRTUAL, "Foo", "doit", "()V", false); assertTrue(analyzer.successor); assertFalse(analyzer.first); assertTrue(LabelInfo.isMethodInvocationLine(label)); } @Test public void testInvokeDynamicInsn() { analyzer.visitLineNumber(42, label); analyzer.visitInvokeDynamicInsn("foo", "()V", null); assertTrue(analyzer.successor); assertFalse(analyzer.first); assertTrue(LabelInfo.isMethodInvocationLine(label)); } @Test public void testJumpInsn() { testJumpInsn(IFEQ, true); testJumpInsn(IFNE, true); testJumpInsn(IFLT, true); testJumpInsn(IFGE, true); testJumpInsn(IFGT, true); testJumpInsn(IFLE, true); testJumpInsn(IF_ICMPEQ, true); testJumpInsn(IF_ICMPNE, true); testJumpInsn(IF_ICMPLT, true); testJumpInsn(IF_ICMPGE, true); testJumpInsn(IF_ICMPGT, true); testJumpInsn(IF_ICMPLE, true); testJumpInsn(IF_ACMPEQ, true); testJumpInsn(IF_ACMPNE, true); testJumpInsn(GOTO, false); testJumpInsn(IFNULL, true); testJumpInsn(IFNONNULL, true); } private void testJumpInsn(int opcode, boolean expected) { // ensure the flags are actually set: analyzer.successor = !expected; analyzer.first = true; analyzer.visitJumpInsn(opcode, label); assertTrue(expected == analyzer.successor); assertFalse(analyzer.first); } @Test(expected = AssertionError.class) public void testVisitJumpInsnNegative() { analyzer.visitJumpInsn(JSR, label); } @Test public void testLdcInsn() { analyzer.visitLdcInsn("Foo"); assertTrue(analyzer.successor); assertFalse(analyzer.first); } @Test public void testIincInsn() { analyzer.visitIincInsn(0, 1); assertTrue(analyzer.successor); assertFalse(analyzer.first); } @Test public void testTableSwitchInsn() { analyzer.visitTableSwitchInsn(0, 0, label, new Label[] { label }); assertFalse(analyzer.successor); assertFalse(analyzer.first); } @Test public void testLookupSwitchInsn() { analyzer.visitLookupSwitchInsn(label, new int[] { 0 }, new Label[] { label }); assertFalse(analyzer.successor); assertFalse(analyzer.first); } @Test public void testMultiANewArrayInsn() { analyzer.visitMultiANewArrayInsn("java/lang/String", 3); assertTrue(analyzer.successor); assertFalse(analyzer.first); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/LabelInfoTest.java000066400000000000000000000106611304217427400306120ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Label; /** * Unit tests for {@link LabelInfoTest}. */ public class LabelInfoTest { private Label label; @Before public void setup() { label = new Label(); } @Test public void testDefaults() { assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); assertFalse(LabelInfo.isMethodInvocationLine(label)); assertFalse(LabelInfo.isDone(label)); assertEquals(LabelInfo.NO_PROBE, LabelInfo.getProbeId(label)); assertNull(LabelInfo.getIntermediateLabel(label)); assertNull(LabelInfo.getInstruction(label)); } @Test public void testOtherInfoObject() { label.info = new Object(); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testSuccessor() { LabelInfo.setSuccessor(label); assertFalse(LabelInfo.isMultiTarget(label)); assertTrue(LabelInfo.isSuccessor(label)); } @Test public void testMultiTarget1() { LabelInfo.setTarget(label); assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); LabelInfo.setTarget(label); assertTrue(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); } @Test public void testMultiTarget2() { LabelInfo.setSuccessor(label); assertFalse(LabelInfo.isMultiTarget(label)); assertTrue(LabelInfo.isSuccessor(label)); LabelInfo.setTarget(label); assertTrue(LabelInfo.isMultiTarget(label)); assertTrue(LabelInfo.isSuccessor(label)); } @Test public void testMultiTarget3() { LabelInfo.setTarget(label); assertFalse(LabelInfo.isMultiTarget(label)); assertFalse(LabelInfo.isSuccessor(label)); LabelInfo.setSuccessor(label); assertTrue(LabelInfo.isMultiTarget(label)); assertTrue(LabelInfo.isSuccessor(label)); } @Test public void testMethodInvocationLine() { LabelInfo.setMethodInvocationLine(label); assertTrue(LabelInfo.isMethodInvocationLine(label)); } @Test public void testNeedsProbe() { testNeedsProbe(false, false, false, false); testNeedsProbe(true, false, false, false); testNeedsProbe(false, true, false, false); testNeedsProbe(true, true, false, false); testNeedsProbe(false, false, true, false); testNeedsProbe(true, false, true, true); testNeedsProbe(false, true, true, true); testNeedsProbe(true, true, true, true); } private void testNeedsProbe(boolean multitarget, boolean methodinvocationline, boolean successor, boolean expected) { if (multitarget) { LabelInfo.setTarget(label); LabelInfo.setTarget(label); } if (methodinvocationline) { LabelInfo.setMethodInvocationLine(label); } if (successor) { LabelInfo.setSuccessor(label); } assertTrue(expected == LabelInfo.needsProbe(label)); // Reset: label = new Label(); } @Test public void testSetResetDone1() { LabelInfo.setDone(label); assertTrue(LabelInfo.isDone(label)); LabelInfo.resetDone(label); assertFalse(LabelInfo.isDone(label)); } @Test public void testSetResetDone2() { LabelInfo.setDone(label); assertTrue(LabelInfo.isDone(label)); LabelInfo.resetDone(new Label[] { label, new Label() }); assertFalse(LabelInfo.isDone(label)); } @Test public void testSetProbeId() { LabelInfo.setProbeId(label, 123); assertEquals(123, LabelInfo.getProbeId(label)); } @Test public void testSetIntermediateLabel() { final Label i = new Label(); LabelInfo.setIntermediateLabel(label, i); assertSame(i, LabelInfo.getIntermediateLabel(label)); } @Test public void testSetInstruction() { final Instruction instruction = new Instruction(123); LabelInfo.setInstruction(label, instruction); assertSame(instruction, LabelInfo.getInstruction(label)); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/MethodProbesAdapterTest.java000066400000000000000000000243221304217427400326520ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.jacoco.core.instr.MethodRecorder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.commons.AnalyzerAdapter; import org.objectweb.asm.util.Printer; /** * Unit tests for {@link MethodProbesAdapter}. */ public class MethodProbesAdapterTest implements IProbeIdGenerator { private Label label; private int id; private MethodRecorder expected, actual; private MethodProbesVisitor expectedVisitor; private MethodVisitor adapter; private IFrame frame; private static class TraceAdapter extends MethodProbesVisitor { private final Printer printer; TraceAdapter(MethodRecorder recorder) { super(recorder.getVisitor()); printer = recorder.getPrinter(); } @Override public void visitProbe(int probeId) { rec("visitProbe", Integer.valueOf(probeId)); } @Override public void visitInsnWithProbe(int opcode, int probeId) { rec("visitInsnWithProbe", Integer.valueOf(opcode), Integer.valueOf(probeId)); } @Override public void visitJumpInsnWithProbe(int opcode, Label label, int probeId, IFrame frame) { rec("visitJumpInsnWithProbe", Integer.valueOf(opcode), label, Integer.valueOf(probeId)); frame.accept(this); } @Override public void visitTableSwitchInsnWithProbes(int min, int max, Label dflt, Label[] labels, IFrame frame) { rec("visitTableSwitchInsnWithProbes", Integer.valueOf(min), Integer.valueOf(max), dflt, labels); frame.accept(this); } @Override public void visitLookupSwitchInsnWithProbes(Label dflt, int[] keys, Label[] labels, IFrame frame) { rec("visitLookupSwitchInsnWithProbes", dflt, keys, labels); frame.accept(this); } private void rec(String name, Object... args) { printer.text.add(name + Arrays.asList(args)); } } @Before public void setup() { label = new Label(); id = 1000; expected = new MethodRecorder(); expectedVisitor = new TraceAdapter(expected); actual = new MethodRecorder(); MethodProbesVisitor actualVisitor = new TraceAdapter(actual); MethodProbesAdapter probesAdapter = new MethodProbesAdapter( actualVisitor, this); final AnalyzerAdapter analyzer = new AnalyzerAdapter("Foo", 0, "doit", "()V", probesAdapter); probesAdapter.setAnalyzer(analyzer); adapter = analyzer; frame = new IFrame() { public void accept(MethodVisitor mv) { } }; } @After public void verify() { assertEquals(expected, actual); } @Test public void testVisitProbe1() { LabelInfo.setTarget(label); LabelInfo.setSuccessor(label); adapter.visitLabel(label); expectedVisitor.visitProbe(1000); expectedVisitor.visitLabel(label); } @Test public void testVisitProbe2() { LabelInfo.setTarget(label); LabelInfo.setTarget(label); adapter.visitLabel(label); expectedVisitor.visitLabel(label); } @Test public void testVisitProbe3() { adapter.visitLabel(label); expectedVisitor.visitLabel(label); } @Test public void testVisitInsn1() { adapter.visitInsn(Opcodes.RETURN); expectedVisitor.visitInsnWithProbe(Opcodes.RETURN, 1000); } @Test public void testVisitInsn2() { adapter.visitInsn(Opcodes.ICONST_0); adapter.visitInsn(Opcodes.ICONST_0); adapter.visitInsn(Opcodes.IADD); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitInsn(Opcodes.IADD); } @Test public void testVisitJumpInsn1() { LabelInfo.setTarget(label); LabelInfo.setTarget(label); adapter.visitJumpInsn(Opcodes.GOTO, label); expectedVisitor .visitJumpInsnWithProbe(Opcodes.GOTO, label, 1000, frame); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, new Object[] { "Foo" }, 0, null); } @Test public void testVisitJumpInsn2() { LabelInfo.setTarget(label); LabelInfo.setTarget(label); adapter.visitInsn(Opcodes.ICONST_0); adapter.visitJumpInsn(Opcodes.IFLT, label); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor .visitJumpInsnWithProbe(Opcodes.IFLT, label, 1000, frame); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, new Object[] { "Foo" }, 0, null); } @Test public void testVisitJumpInsn3() { adapter.visitInsn(Opcodes.ICONST_0); adapter.visitJumpInsn(Opcodes.IFLT, label); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitJumpInsn(Opcodes.IFLT, label); } @Test public void testVisitJumpInsn4() { LabelInfo.setTarget(label); LabelInfo.setTarget(label); adapter.visitInsn(Opcodes.ICONST_0); adapter.visitInsn(Opcodes.ICONST_0); adapter.visitJumpInsn(Opcodes.IF_ICMPEQ, label); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitJumpInsnWithProbe(Opcodes.IF_ICMPEQ, label, 1000, frame); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, new Object[] { "Foo" }, 0, null); } @Test public void testVisitLookupSwitchInsn1() { LabelInfo.setTarget(label); LabelInfo.setTarget(label); final int[] keys = new int[] { 0, 1 }; final Label[] labels = new Label[] { label, label }; adapter.visitInsn(Opcodes.ICONST_0); adapter.visitLookupSwitchInsn(label, keys, labels); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitLookupSwitchInsnWithProbes(label, keys, labels, frame); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, new Object[] { "Foo" }, 0, null); assertEquals(1000, LabelInfo.getProbeId(label)); } @Test public void testVisitLookupSwitchInsn2() { Label label2 = new Label(); LabelInfo.setTarget(label2); LabelInfo.setTarget(label2); final int[] keys = new int[] { 0, 1 }; final Label[] labels = new Label[] { label2, label }; adapter.visitInsn(Opcodes.ICONST_0); adapter.visitLookupSwitchInsn(label, keys, labels); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitLookupSwitchInsnWithProbes(label, keys, labels, frame); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, new Object[] { "Foo" }, 0, null); assertEquals(LabelInfo.NO_PROBE, LabelInfo.getProbeId(label)); assertEquals(1000, LabelInfo.getProbeId(label2)); } @Test public void testVisitLookupSwitchInsn3() { final int[] keys = new int[] { 0, 1 }; final Label[] labels = new Label[] { label, label }; adapter.visitInsn(Opcodes.ICONST_0); adapter.visitLookupSwitchInsn(label, keys, labels); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitLookupSwitchInsn(label, keys, labels); } @Test public void testVisitTableSwitchInsn1() { LabelInfo.setTarget(label); LabelInfo.setTarget(label); final Label[] labels = new Label[] { label, label }; adapter.visitInsn(Opcodes.ICONST_0); adapter.visitTableSwitchInsn(0, 1, label, labels); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitTableSwitchInsnWithProbes(0, 1, label, labels, frame); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, new Object[] { "Foo" }, 0, null); assertEquals(1000, LabelInfo.getProbeId(label)); } @Test public void testVisitTableSwitchInsn2() { Label label2 = new Label(); LabelInfo.setTarget(label2); LabelInfo.setTarget(label2); final Label[] labels = new Label[] { label2, label }; adapter.visitInsn(Opcodes.ICONST_0); adapter.visitTableSwitchInsn(0, 1, label, labels); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitTableSwitchInsnWithProbes(0, 1, label, labels, frame); expectedVisitor.visitFrame(Opcodes.F_FULL, 1, new Object[] { "Foo" }, 0, null); assertEquals(LabelInfo.NO_PROBE, LabelInfo.getProbeId(label)); assertEquals(1000, LabelInfo.getProbeId(label2)); } @Test public void testVisitTableSwitchInsn3() { final Label[] labels = new Label[] { label, label }; adapter.visitInsn(Opcodes.ICONST_0); adapter.visitTableSwitchInsn(0, 1, label, labels); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitTableSwitchInsn(0, 1, label, labels); } @Test public void testVisitTryCatchBlockNoProbe() { Label start = new Label(); Label end = new Label(); Label handler = new Label(); adapter.visitTryCatchBlock(start, end, handler, "java/lang/Exception"); adapter.visitLabel(start); expectedVisitor.visitTryCatchBlock(start, end, handler, "java/lang/Exception"); expectedVisitor.visitLabel(start); } @Test public void testVisitTryCatchBlockWithProbe() { Label target = new Label(); LabelInfo.setSuccessor(target); LabelInfo.setTarget(target); Label end = new Label(); Label handler = new Label(); Label start = new Label(); adapter.visitTryCatchBlock(target, end, handler, "java/lang/Exception"); adapter.visitLabel(target); expectedVisitor.visitTryCatchBlock(start, end, handler, "java/lang/Exception"); expectedVisitor.visitLabel(start); expectedVisitor.visitProbe(1000); expectedVisitor.visitLabel(target); } @Test public void testVisitMultipleTryCatchBlocksWithProbe() { Label target = new Label(); LabelInfo.setSuccessor(target); LabelInfo.setTarget(target); Label end = new Label(); Label handler1 = new Label(); Label handler2 = new Label(); Label start = new Label(); adapter.visitTryCatchBlock(target, end, handler1, "java/lang/Exception"); adapter.visitTryCatchBlock(target, end, handler2, "java/io/IOException"); adapter.visitLabel(target); expectedVisitor.visitTryCatchBlock(start, end, handler1, "java/lang/Exception"); expectedVisitor.visitTryCatchBlock(start, end, handler2, "java/io/IOException"); expectedVisitor.visitLabel(start); expectedVisitor.visitProbe(1000); expectedVisitor.visitLabel(target); } // === IProbeIdGenerator === public int nextId() { return id++; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/flow/MethodSanitizerTest.java000066400000000000000000000074471304217427400321000ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import static org.junit.Assert.assertEquals; import org.jacoco.core.instr.MethodRecorder; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.MethodNode; /** * Unit tests for {@link MethodSanitizer}. */ public class MethodSanitizerTest { private MethodNode actual; private MethodNode expected; private MethodVisitor sanitizer; @Before public void setup() { actual = new MethodNode(0, "test", "()V", null, null); expected = new MethodNode(0, "test", "()V", null, null); sanitizer = new MethodSanitizer(actual, 0, "test", "()V", null, null); } @Test public void testLocalVariablePositive() { Label l1 = new Label(); Label l2 = new Label(); sanitizer.visitCode(); sanitizer.visitLabel(l1); sanitizer.visitInsn(Opcodes.RETURN); sanitizer.visitLabel(l2); sanitizer.visitLocalVariable("x", "I", null, l1, l2, 0); sanitizer.visitMaxs(0, 0); sanitizer.visitEnd(); Label m1 = new Label(); Label m2 = new Label(); expected.visitLabel(m1); expected.visitInsn(Opcodes.RETURN); expected.visitLabel(m2); expected.visitLocalVariable("x", "I", null, m1, m2, 0); expected.visitMaxs(0, 0); expected.visitEnd(); assertOutput(); } @Test public void testLocalVariableNegative1() { Label l1 = new Label(); Label l2 = new Label(); sanitizer.visitCode(); sanitizer.visitInsn(Opcodes.RETURN); sanitizer.visitLabel(l2); sanitizer.visitLocalVariable("x", "I", null, l1, l2, 0); sanitizer.visitMaxs(0, 0); sanitizer.visitEnd(); Label m2 = new Label(); expected.visitInsn(Opcodes.RETURN); expected.visitLabel(m2); expected.visitMaxs(0, 0); expected.visitEnd(); assertOutput(); } @Test public void testLocalVariableNegative2() { Label l1 = new Label(); Label l2 = new Label(); sanitizer.visitCode(); sanitizer.visitLabel(l1); sanitizer.visitInsn(Opcodes.RETURN); sanitizer.visitLocalVariable("x", "I", null, l1, l2, 0); sanitizer.visitMaxs(0, 0); sanitizer.visitEnd(); Label m1 = new Label(); expected.visitLabel(m1); expected.visitInsn(Opcodes.RETURN); expected.visitMaxs(0, 0); expected.visitEnd(); assertOutput(); } @Test public void testLineNumberPositive() { Label l1 = new Label(); sanitizer.visitCode(); sanitizer.visitLabel(l1); sanitizer.visitLineNumber(15, l1); sanitizer.visitInsn(Opcodes.RETURN); sanitizer.visitMaxs(0, 0); sanitizer.visitEnd(); Label m1 = new Label(); expected.visitLabel(m1); expected.visitLineNumber(15, m1); expected.visitInsn(Opcodes.RETURN); expected.visitMaxs(0, 0); expected.visitEnd(); assertOutput(); } @Test public void testLineNumberNegative() { Label l1 = new Label(); sanitizer.visitCode(); sanitizer.visitLineNumber(15, l1); sanitizer.visitInsn(Opcodes.RETURN); sanitizer.visitMaxs(0, 0); sanitizer.visitEnd(); expected.visitInsn(Opcodes.RETURN); expected.visitMaxs(0, 0); expected.visitEnd(); assertOutput(); } private void assertOutput() { assertEquals(dump(expected), dump(actual)); } private MethodRecorder dump(MethodNode node) { MethodRecorder rec = new MethodRecorder(); node.accept(rec.getVisitor()); return rec; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/000077500000000000000000000000001304217427400254405ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/ClassInstrumenterTest.java000066400000000000000000000041351304217427400326330ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertNull; import org.jacoco.core.JaCoCo; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; /** * Unit tests for {@link ClassInstrumenter}. */ public class ClassInstrumenterTest implements IProbeArrayStrategy { private ClassInstrumenter instrumenter; @Before public void setup() { instrumenter = new ClassInstrumenter(this, new ClassVisitor( JaCoCo.ASM_API_VERSION) { }); } @Test(expected = IllegalStateException.class) public void testInstrumentInstrumentedClass1() { instrumenter.visitField(InstrSupport.DATAFIELD_ACC, InstrSupport.DATAFIELD_NAME, InstrSupport.DATAFIELD_DESC, null, null); } @Test(expected = IllegalStateException.class) public void testInstrumentInstrumentedClass2() { instrumenter.visitMethod(InstrSupport.INITMETHOD_ACC, InstrSupport.INITMETHOD_NAME, InstrSupport.INITMETHOD_DESC, null, null); } @Test public void testNoMethodVisitor() { instrumenter = new ClassInstrumenter(this, new ClassVisitor( JaCoCo.ASM_API_VERSION) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return null; } }); assertNull(instrumenter.visitMethod(0, "foo", "()V", null, null)); } // === IProbeArrayStrategy === public int storeInstance(MethodVisitor mv, boolean clinit, int variable) { return 0; } public void addMembers(ClassVisitor cv, int probeCount) { } } DuplicateFrameEliminatorTest.java000066400000000000000000000101171304217427400337750ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertEquals; import org.jacoco.core.instr.MethodRecorder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LookupSwitchInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MultiANewArrayInsnNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; /** * Unit tests for {@link DuplicateFrameEliminator}. */ public class DuplicateFrameEliminatorTest { private MethodRecorder actual; private MethodRecorder expected; private MethodVisitor eliminator; @Before public void setup() { actual = new MethodRecorder(); expected = new MethodRecorder(); eliminator = new DuplicateFrameEliminator(actual.getVisitor()); } @After public void verify() { assertEquals(expected, actual); } @Test public void testDuplicateFrame() { frame(eliminator); frame(eliminator); frame(expected.getVisitor()); } @Test public void testInsn() { testInstructionBetweenFrames(new InsnNode(Opcodes.NOP)); } @Test public void testIntInsn() { testInstructionBetweenFrames(new IntInsnNode(Opcodes.BIPUSH, 123)); } @Test public void testVarInsn() { testInstructionBetweenFrames(new VarInsnNode(Opcodes.ILOAD, 0)); } @Test public void testTypeInsn() { testInstructionBetweenFrames(new TypeInsnNode(Opcodes.NEW, "java/lang/Object")); } @Test public void testFieldInsn() { testInstructionBetweenFrames(new FieldInsnNode(Opcodes.GETFIELD, "Foo", "f", "I")); } @Test public void testMethodInsn() { testInstructionBetweenFrames(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "Foo", "run", "()V", false)); } @Test public void testInvokeDynamicInsn() { testInstructionBetweenFrames(new InvokeDynamicInsnNode("foo", "()V", new Handle(0, null, null, null, false))); } @Test public void testJumpInsn() { testInstructionBetweenFrames(new JumpInsnNode(Opcodes.GOTO, new LabelNode())); } @Test public void testLdcInsn() { testInstructionBetweenFrames(new LdcInsnNode("JaCoCo")); } @Test public void testIincInsn() { testInstructionBetweenFrames(new IincInsnNode(3, 42)); } @Test public void testTableSwitchInsn() { testInstructionBetweenFrames(new TableSwitchInsnNode(0, 0, new LabelNode(), new LabelNode[0])); } @Test public void testLookupSwitchInsn() { testInstructionBetweenFrames(new LookupSwitchInsnNode(new LabelNode(), new int[0], new LabelNode[0])); } @Test public void testMultiANewArrayInsn() { testInstructionBetweenFrames(new MultiANewArrayInsnNode( "java/lang/String", 4)); } private void testInstructionBetweenFrames(AbstractInsnNode node) { frame(eliminator); node.accept(eliminator); frame(eliminator); frame(expected.getVisitor()); node.accept(expected.getVisitor()); frame(expected.getVisitor()); } private void frame(MethodVisitor mv) { mv.visitFrame(Opcodes.NEW, 1, new Object[] { Opcodes.INTEGER }, 0, new Object[0]); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/InstrSupportTest.java000066400000000000000000000061111304217427400316360ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.util.Printer; import org.objectweb.asm.util.Textifier; import org.objectweb.asm.util.TraceMethodVisitor; /** * Unit tests for {@link InstrSupport}. */ public class InstrSupportTest { private Printer printer; private TraceMethodVisitor trace; @Before public void setup() { printer = new Textifier(); trace = new TraceMethodVisitor(printer); } @Test public void testAssertNotIntrumentedPositive() { InstrSupport.assertNotInstrumented("run", "Foo"); } @Test(expected = IllegalStateException.class) public void testAssertNotIntrumentedField() { InstrSupport.assertNotInstrumented("$jacocoData", "Foo"); } @Test(expected = IllegalStateException.class) public void testAssertNotIntrumentedMethod() { InstrSupport.assertNotInstrumented("$jacocoInit", "Foo"); } @Test public void testPushIntM2147483648() { InstrSupport.push(trace, -2147483648); assertInstruction("LDC -2147483648"); } @Test public void testPushIntM32768() { InstrSupport.push(trace, -32768); assertInstruction("SIPUSH -32768"); } @Test public void testPushIntM128() { InstrSupport.push(trace, -128); assertInstruction("BIPUSH -128"); } @Test public void testPushIntM1() { InstrSupport.push(trace, -1); assertInstruction("ICONST_M1"); } @Test public void testPushInt0() { InstrSupport.push(trace, 0); assertInstruction("ICONST_0"); } @Test public void testPushInt1() { InstrSupport.push(trace, 1); assertInstruction("ICONST_1"); } @Test public void testPushInt2() { InstrSupport.push(trace, 2); assertInstruction("ICONST_2"); } @Test public void testPushInt3() { InstrSupport.push(trace, 3); assertInstruction("ICONST_3"); } @Test public void testPushInt4() { InstrSupport.push(trace, 4); assertInstruction("ICONST_4"); } @Test public void testPushInt5() { InstrSupport.push(trace, 5); assertInstruction("ICONST_5"); } @Test public void testPushInt127() { InstrSupport.push(trace, 127); assertInstruction("BIPUSH 127"); } @Test public void testPushInt32767() { InstrSupport.push(trace, 32767); assertInstruction("SIPUSH 32767"); } @Test public void testPushInt2147483647() { InstrSupport.push(trace, 2147483647); assertInstruction("LDC 2147483647"); } private void assertInstruction(String expected) { assertEquals(1, printer.getText().size()); assertEquals(expected, printer.getText().get(0).toString().trim()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/MethodInstrumenterTest.java000066400000000000000000000152701304217427400330100ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertEquals; import org.jacoco.core.instr.MethodRecorder; import org.jacoco.core.internal.flow.IFrame; import org.jacoco.core.internal.flow.LabelInfo; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * Unit tests for {@link MethodInstrumenter}. */ public class MethodInstrumenterTest { private MethodInstrumenter instrumenter; private MethodRecorder expected, actual; private MethodVisitor expectedVisitor; private IFrame frame; @Before public void setup() { actual = new MethodRecorder(); expected = new MethodRecorder(); expectedVisitor = expected.getVisitor(); final IProbeInserter probeInserter = new IProbeInserter() { public void insertProbe(int id) { actual.getVisitor().visitLdcInsn("Probe " + id); } }; instrumenter = new MethodInstrumenter(actual.getVisitor(), probeInserter); frame = new IFrame() { public void accept(MethodVisitor mv) { mv.visitFrame(Opcodes.F_FULL, 0, null, 0, null); } }; } void sampleReturn() { return; } @Test public void testVisitProbe() { instrumenter.visitProbe(33); expectedVisitor.visitLdcInsn("Probe 33"); assertEquals(expected, actual); } @Test public void testVisitInsnWithProbe() { instrumenter.visitInsnWithProbe(Opcodes.RETURN, 3); expectedVisitor.visitLdcInsn("Probe 3"); expectedVisitor.visitInsn(Opcodes.RETURN); assertEquals(expected, actual); } @Test public void testVisitJumpInsnWithProbe_GOTO() { final Label label = new Label(); instrumenter.visitJumpInsnWithProbe(Opcodes.GOTO, label, 3, frame); expectedVisitor.visitLdcInsn("Probe 3"); expectedVisitor.visitJumpInsn(Opcodes.GOTO, label); assertEquals(expected, actual); } @Test public void testVisitJumpInsnWithProbe_IFEQ() { testVisitJumpInsnWithProbe(Opcodes.IFEQ, Opcodes.IFNE); } @Test public void testVisitJumpInsnWithProbe_IFGE() { testVisitJumpInsnWithProbe(Opcodes.IFGE, Opcodes.IFLT); } @Test public void testVisitJumpInsnWithProbe_IFGT() { testVisitJumpInsnWithProbe(Opcodes.IFGT, Opcodes.IFLE); } @Test public void testVisitJumpInsnWithProbe_IFLE() { testVisitJumpInsnWithProbe(Opcodes.IFLE, Opcodes.IFGT); } @Test public void testVisitJumpInsnWithProbe_IFLT() { testVisitJumpInsnWithProbe(Opcodes.IFLT, Opcodes.IFGE); } @Test public void testVisitJumpInsnWithProbe_IFNE() { testVisitJumpInsnWithProbe(Opcodes.IFNE, Opcodes.IFEQ); } @Test public void testVisitJumpInsnWithProbe_IF_ACMPEQ() { testVisitJumpInsnWithProbe(Opcodes.IF_ACMPEQ, Opcodes.IF_ACMPNE); } @Test public void testVisitJumpInsnWithProbe_IF_ACMPNE() { testVisitJumpInsnWithProbe(Opcodes.IF_ACMPNE, Opcodes.IF_ACMPEQ); } @Test public void testVisitJumpInsnWithProbe_IF_ICMPEQ() { testVisitJumpInsnWithProbe(Opcodes.IF_ICMPEQ, Opcodes.IF_ICMPNE); } @Test public void testVisitJumpInsnWithProbe_IF_ICMPGE() { testVisitJumpInsnWithProbe(Opcodes.IF_ICMPGE, Opcodes.IF_ICMPLT); } @Test public void testVisitJumpInsnWithProbe_IF_ICMPGT() { testVisitJumpInsnWithProbe(Opcodes.IF_ICMPGT, Opcodes.IF_ICMPLE); } @Test public void testVisitJumpInsnWithProbe_IF_ICMPLE() { testVisitJumpInsnWithProbe(Opcodes.IF_ICMPLE, Opcodes.IF_ICMPGT); } @Test public void testVisitJumpInsnWithProbe_IF_ICMPLT() { testVisitJumpInsnWithProbe(Opcodes.IF_ICMPLT, Opcodes.IF_ICMPGE); } @Test public void testVisitJumpInsnWithProbe_IF_ICMPNE() { testVisitJumpInsnWithProbe(Opcodes.IF_ICMPNE, Opcodes.IF_ICMPEQ); } @Test public void testVisitJumpInsnWithProbe_IFNULL() { testVisitJumpInsnWithProbe(Opcodes.IFNULL, Opcodes.IFNONNULL); } @Test public void testVisitJumpInsnWithProbe_IFNONNULL() { testVisitJumpInsnWithProbe(Opcodes.IFNONNULL, Opcodes.IFNULL); } @Test(expected = IllegalArgumentException.class) public void testVisitJumpInsnWithProbe_InvalidOpcode() { testVisitJumpInsnWithProbe(Opcodes.NOP, Opcodes.NOP); } private void testVisitJumpInsnWithProbe(int opcodeOrig, int opcodeInstr) { final Label label = new Label(); instrumenter.visitJumpInsnWithProbe(opcodeOrig, label, 3, frame); final Label l2 = new Label(); expectedVisitor.visitJumpInsn(opcodeInstr, l2); expectedVisitor.visitLdcInsn("Probe 3"); expectedVisitor.visitJumpInsn(Opcodes.GOTO, label); expectedVisitor.visitLabel(l2); expectedVisitor.visitFrame(Opcodes.F_FULL, 0, null, 0, null); assertEquals(expected, actual); } @Test public void testVisitTableSwitchInsnWithProbes() { final Label L0 = new Label(); final Label L1 = new Label(); final Label L2 = new Label(); LabelInfo.setProbeId(L0, 0); LabelInfo.setProbeId(L1, 1); instrumenter.visitTableSwitchInsnWithProbes(3, 5, L0, new Label[] { L1, L1, L2 }, frame); expectedVisitor.visitTableSwitchInsn(3, 4, L0, new Label[] { L1, L1, L2 }); expectedVisitor.visitLabel(L0); expectedVisitor.visitFrame(Opcodes.F_FULL, 0, null, 0, null); expectedVisitor.visitLdcInsn("Probe 0"); expectedVisitor.visitJumpInsn(Opcodes.GOTO, new Label()); expectedVisitor.visitLabel(L1); expectedVisitor.visitFrame(Opcodes.F_FULL, 0, null, 0, null); expectedVisitor.visitLdcInsn("Probe 1"); expectedVisitor.visitJumpInsn(Opcodes.GOTO, new Label()); assertEquals(expected, actual); } @Test public void testVisitLookupSwitchInsnWithProbes() { final Label L0 = new Label(); final Label L1 = new Label(); final Label L2 = new Label(); LabelInfo.setProbeId(L0, 0); LabelInfo.setProbeId(L1, 1); instrumenter.visitLookupSwitchInsnWithProbes(L0, new int[] { 10, 20, 30 }, new Label[] { L1, L1, L2 }, frame); expectedVisitor.visitLookupSwitchInsn(L0, new int[] { 10, 20, 30 }, new Label[] { L1, L1, L2 }); expectedVisitor.visitLabel(L0); expectedVisitor.visitFrame(Opcodes.F_FULL, 0, null, 0, null); expectedVisitor.visitLdcInsn("Probe 0"); expectedVisitor.visitJumpInsn(Opcodes.GOTO, new Label()); expectedVisitor.visitLabel(L1); expectedVisitor.visitFrame(Opcodes.F_FULL, 0, null, 0, null); expectedVisitor.visitLdcInsn("Probe 1"); expectedVisitor.visitJumpInsn(Opcodes.GOTO, new Label()); assertEquals(expected, actual); } } ProbeArrayStrategyFactoryTest.java000066400000000000000000000260201304217427400342050ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.jacoco.core.runtime.IExecutionDataAccessorGenerator; import org.jacoco.core.runtime.OfflineInstrumentationAccessGenerator; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * Unit tests for {@link ProbeArrayStrategyFactory} and the * {@link IProbeArrayStrategy} implementations. The verifies the behaviour of * the returned {@link IProbeArrayStrategy} instances for different classes. */ public class ProbeArrayStrategyFactoryTest { private IExecutionDataAccessorGenerator generator; private ClassVisitorMock cv; @Before public void setup() { generator = new OfflineInstrumentationAccessGenerator(); cv = new ClassVisitorMock(); } @Test public void testClass1() { final IProbeArrayStrategy strategy = test(Opcodes.V1_1, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(false); } @Test public void testClass2() { final IProbeArrayStrategy strategy = test(Opcodes.V1_2, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(false); } @Test public void testClass3() { final IProbeArrayStrategy strategy = test(Opcodes.V1_3, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(false); } @Test public void testClass4() { final IProbeArrayStrategy strategy = test(Opcodes.V1_4, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(false); } @Test public void testClass5() { final IProbeArrayStrategy strategy = test(Opcodes.V1_5, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(false); } @Test public void testClass6() { final IProbeArrayStrategy strategy = test(Opcodes.V1_6, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(true); } @Test public void testClass7() { final IProbeArrayStrategy strategy = test(Opcodes.V1_7, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(true); } @Test public void testClass8() { final IProbeArrayStrategy strategy = test(Opcodes.V1_8, 0, false, true, true); assertEquals(ClassFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_ACC); assertInitMethod(true); strategy.storeInstance(cv.visitMethod(0, null, null, null, null), false, 0); } @Test public void testInterface7() { final IProbeArrayStrategy strategy = test(Opcodes.V1_7, Opcodes.ACC_INTERFACE, true, false, true); assertEquals(LocalProbeArrayStrategy.class, strategy.getClass()); assertNoDataField(); assertNoInitMethod(); } @Test public void testEmptyInterface7() { final IProbeArrayStrategy strategy = test(Opcodes.V1_7, Opcodes.ACC_INTERFACE, false, false, false); assertEquals(NoneProbeArrayStrategy.class, strategy.getClass()); assertNoDataField(); assertNoInitMethod(); } @Test(expected = UnsupportedOperationException.class) public void testEmptyInterface7StoreInstance() { IProbeArrayStrategy strategy = test(Opcodes.V1_7, Opcodes.ACC_INTERFACE, false, false, false); strategy.storeInstance(null, false, 0); } @Test public void testInterface8() { cv.isInterface = true; final IProbeArrayStrategy strategy = test(Opcodes.V1_8, Opcodes.ACC_INTERFACE, false, true, true); assertEquals(InterfaceFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_INTF_ACC); assertInitAndClinitMethods(); strategy.storeInstance(cv.visitMethod(0, null, null, null, null), false, 0); } @Test public void testEmptyInterface8() { final IProbeArrayStrategy strategy = test(Opcodes.V1_8, Opcodes.ACC_INTERFACE, false, false, false); assertEquals(NoneProbeArrayStrategy.class, strategy.getClass()); assertNoDataField(); assertNoInitMethod(); } @Test(expected = UnsupportedOperationException.class) public void testEmptyInterface8StoreInstance() { final IProbeArrayStrategy strategy = test(Opcodes.V1_8, Opcodes.ACC_INTERFACE, false, false, false); strategy.storeInstance(null, false, 0); } @Test public void testClinitAndAbstractMethodsInterface8() { final IProbeArrayStrategy strategy = test(Opcodes.V1_8, Opcodes.ACC_INTERFACE, true, false, true); assertEquals(LocalProbeArrayStrategy.class, strategy.getClass()); assertNoDataField(); assertNoInitMethod(); strategy.storeInstance(cv.visitMethod(0, null, null, null, null), false, 0); } @Test public void testClinitInterface8() { final IProbeArrayStrategy strategy = test(Opcodes.V1_8, Opcodes.ACC_INTERFACE, true, false, false); assertEquals(LocalProbeArrayStrategy.class, strategy.getClass()); assertNoDataField(); assertNoInitMethod(); } @Test public void testClinitAndMethodsInterface8() { cv.isInterface = true; final IProbeArrayStrategy strategy = test(Opcodes.V1_8, Opcodes.ACC_INTERFACE, true, true, true); assertEquals(InterfaceFieldProbeArrayStrategy.class, strategy.getClass()); assertDataField(InstrSupport.DATAFIELD_INTF_ACC); assertInitAndClinitMethods(); strategy.storeInstance(cv.visitMethod(0, "", null, null, null), true, 0); } private IProbeArrayStrategy test(int version, int access, boolean clinit, boolean method, boolean abstractMethod) { final ClassWriter writer = new ClassWriter(0); writer.visit(version, access, "Foo", "java/lang/Object", null, null); if (clinit) { final MethodVisitor mv = writer.visitMethod( Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } if (method) { final MethodVisitor mv = writer.visitMethod( Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "doit", "()V", null, null); mv.visitCode(); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } if (abstractMethod) { final MethodVisitor mv = writer.visitMethod(Opcodes.ACC_ABSTRACT, "foo", "()V", null, null); mv.visitEnd(); } writer.visitEnd(); final IProbeArrayStrategy strategy = ProbeArrayStrategyFactory .createFor(new ClassReader(writer.toByteArray()), generator); strategy.addMembers(cv, 123); return strategy; } private static class AddedMethod { private final int access; private final String name; private final String desc; private boolean frames; AddedMethod(int access, String name, String desc) { this.access = access; this.name = name; this.desc = desc; } void assertInitMethod(boolean frames) { assertEquals(InstrSupport.INITMETHOD_NAME, name); assertEquals(InstrSupport.INITMETHOD_DESC, desc); assertEquals(InstrSupport.INITMETHOD_ACC, access); assertEquals(Boolean.valueOf(frames), Boolean.valueOf(frames)); } void assertClinit() { assertEquals(InstrSupport.CLINIT_NAME, name); assertEquals(InstrSupport.CLINIT_DESC, desc); assertEquals(InstrSupport.CLINIT_ACC, access); assertEquals(Boolean.valueOf(false), Boolean.valueOf(frames)); } } private static class ClassVisitorMock extends ClassVisitor { private boolean isInterface; private int fieldAccess; private String fieldName; private final List methods = new ArrayList(); ClassVisitorMock() { super(Opcodes.ASM5); } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { assertNull(fieldName); fieldAccess = access; fieldName = name; return null; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { final AddedMethod m = new AddedMethod(access, name, desc); methods.add(m); return new MethodVisitor(Opcodes.ASM5) { @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { m.frames = true; } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { assertEquals(InstrSupport.DATAFIELD_NAME, name); assertEquals(InstrSupport.DATAFIELD_DESC, desc); if (opcode == Opcodes.GETSTATIC) { assertEquals(InstrSupport.INITMETHOD_NAME, methods.get(methods.size() - 1).name); } else if (opcode == Opcodes.PUTSTATIC) { if (isInterface) { assertEquals(InstrSupport.CLINIT_NAME, methods.get(methods.size() - 1).name); } else { assertEquals(InstrSupport.INITMETHOD_NAME, methods.get(methods.size() - 1).name); } } else { fail(); } } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if ("getProbes".equals(name)) { // method's owner is not interface: assertFalse(itf); return; } assertEquals(itf, isInterface); assertEquals(Opcodes.INVOKESTATIC, opcode); assertEquals("Foo", owner); assertEquals(InstrSupport.INITMETHOD_NAME, name); assertEquals(InstrSupport.INITMETHOD_DESC, desc); } }; } } void assertDataField(int access) { assertEquals(InstrSupport.DATAFIELD_NAME, cv.fieldName); assertEquals(access, cv.fieldAccess); } void assertNoDataField() { assertNull(cv.fieldName); } void assertInitMethod(boolean frames) { assertEquals(cv.methods.size(), 1); cv.methods.get(0).assertInitMethod(frames); } void assertInitAndClinitMethods() { assertEquals(2, cv.methods.size()); cv.methods.get(0).assertInitMethod(true); cv.methods.get(1).assertClinit(); } void assertNoInitMethod() { assertEquals(0, cv.methods.size()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/ProbeCounterTest.java000066400000000000000000000033261304217427400315560ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.Opcodes; /** * Unit tests for {@link ProbeCounter}. */ public class ProbeCounterTest { private ProbeCounter counter; @Before public void setup() { counter = new ProbeCounter(); } @Test public void testInitial() { assertFalse(counter.hasMethods()); assertEquals(0, counter.getCount()); } @Test public void testVisitTotalProbeCount() { counter.visitTotalProbeCount(42); assertEquals(42, counter.getCount()); } @Test public void testVisitClinitMethod() { assertNull(counter.visitMethod(0, "", null, null, null)); assertFalse(counter.hasMethods()); } @Test public void testVisitAbstractMethod() { counter.visitMethod(Opcodes.ACC_ABSTRACT, "foo", null, null, null); assertFalse(counter.hasMethods()); } @Test public void testVisitMethod() { assertNull(counter.visitMethod(0, "foo", null, null, null)); assertTrue(counter.hasMethods()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/ProbeInserterTest.java000066400000000000000000000210351304217427400317270ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertEquals; import org.jacoco.core.instr.MethodRecorder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * Unit tests for {@link ProbeInserter}. */ public class ProbeInserterTest { private MethodRecorder actual, expected; private MethodVisitor actualVisitor, expectedVisitor; private IProbeArrayStrategy arrayStrategy; @Before public void setup() { actual = new MethodRecorder(); actualVisitor = actual.getVisitor(); expected = new MethodRecorder(); expectedVisitor = expected.getVisitor(); arrayStrategy = new IProbeArrayStrategy() { public int storeInstance(MethodVisitor mv, boolean clinit, int variable) { mv.visitLdcInsn(clinit ? "clinit" : "init"); return 5; } public void addMembers(ClassVisitor delegate, int probeCount) { } }; } @After public void verify() { assertEquals(expected, actual); } @Test public void testVariableStatic() { ProbeInserter pi = new ProbeInserter(Opcodes.ACC_STATIC, "m", "()V", actualVisitor, arrayStrategy); pi.insertProbe(0); expectedVisitor.visitVarInsn(Opcodes.ALOAD, 0); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitInsn(Opcodes.ICONST_1); expectedVisitor.visitInsn(Opcodes.BASTORE); } @Test public void testVariableNonStatic() { ProbeInserter pi = new ProbeInserter(0, "m", "()V", actualVisitor, arrayStrategy); pi.insertProbe(0); expectedVisitor.visitVarInsn(Opcodes.ALOAD, 1); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitInsn(Opcodes.ICONST_1); expectedVisitor.visitInsn(Opcodes.BASTORE); } @Test public void testVariableNonStatic_IZObject() { ProbeInserter pi = new ProbeInserter(0, "m", "(IZLjava/lang/Object;)V", actualVisitor, arrayStrategy); pi.insertProbe(0); expectedVisitor.visitVarInsn(Opcodes.ALOAD, 4); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitInsn(Opcodes.ICONST_1); expectedVisitor.visitInsn(Opcodes.BASTORE); } @Test public void testVariableNonStatic_JD() { ProbeInserter pi = new ProbeInserter(0, "m", "(JD)V", actualVisitor, arrayStrategy); pi.insertProbe(0); expectedVisitor.visitVarInsn(Opcodes.ALOAD, 5); expectedVisitor.visitInsn(Opcodes.ICONST_0); expectedVisitor.visitInsn(Opcodes.ICONST_1); expectedVisitor.visitInsn(Opcodes.BASTORE); } @Test public void testVisitCode() { ProbeInserter pi = new ProbeInserter(0, "m", "()V", actualVisitor, arrayStrategy); pi.visitCode(); expectedVisitor.visitLdcInsn("init"); } @Test public void testVisitClinit() { ProbeInserter pi = new ProbeInserter(0, "", "()V", actualVisitor, arrayStrategy); pi.visitCode(); expectedVisitor.visitLdcInsn("clinit"); } @Test public void testVisitVarIns() { ProbeInserter pi = new ProbeInserter(0, "m", "(II)V", actualVisitor, arrayStrategy); pi.visitVarInsn(Opcodes.ALOAD, 0); pi.visitVarInsn(Opcodes.ILOAD, 1); pi.visitVarInsn(Opcodes.ILOAD, 2); pi.visitVarInsn(Opcodes.ISTORE, 3); pi.visitVarInsn(Opcodes.FSTORE, 4); // Argument variables stay at the same position: expectedVisitor.visitVarInsn(Opcodes.ALOAD, 0); expectedVisitor.visitVarInsn(Opcodes.ILOAD, 1); expectedVisitor.visitVarInsn(Opcodes.ILOAD, 2); // Local variables are shifted by one: expectedVisitor.visitVarInsn(Opcodes.ISTORE, 4); expectedVisitor.visitVarInsn(Opcodes.FSTORE, 5); } @Test public void testVisitIincInsn() { ProbeInserter pi = new ProbeInserter(0, "m", "(II)V", actualVisitor, arrayStrategy); pi.visitIincInsn(0, 100); pi.visitIincInsn(1, 101); pi.visitIincInsn(2, 102); pi.visitIincInsn(3, 103); pi.visitIincInsn(4, 104); // Argument variables stay at the same position: expectedVisitor.visitIincInsn(0, 100); expectedVisitor.visitIincInsn(1, 101); expectedVisitor.visitIincInsn(2, 102); // Local variables are shifted by one: expectedVisitor.visitIincInsn(4, 103); expectedVisitor.visitIincInsn(5, 104); } @Test public void testVisitLocalVariable() { ProbeInserter pi = new ProbeInserter(0, "m", "(II)V", actualVisitor, arrayStrategy); pi.visitLocalVariable(null, null, null, null, null, 0); pi.visitLocalVariable(null, null, null, null, null, 1); pi.visitLocalVariable(null, null, null, null, null, 2); pi.visitLocalVariable(null, null, null, null, null, 3); pi.visitLocalVariable(null, null, null, null, null, 4); // Argument variables stay at the same position: expectedVisitor.visitLocalVariable(null, null, null, null, null, 0); expectedVisitor.visitLocalVariable(null, null, null, null, null, 1); expectedVisitor.visitLocalVariable(null, null, null, null, null, 2); // Local variables are shifted by one: expectedVisitor.visitLocalVariable(null, null, null, null, null, 4); expectedVisitor.visitLocalVariable(null, null, null, null, null, 5); } @Test public void testVisitMaxs1() { ProbeInserter pi = new ProbeInserter(0, "m", "(II)V", actualVisitor, arrayStrategy); pi.visitCode(); pi.visitMaxs(0, 8); expectedVisitor.visitLdcInsn("init"); expectedVisitor.visitMaxs(5, 9); } @Test public void testVisitMaxs2() { ProbeInserter pi = new ProbeInserter(0, "m", "(II)V", actualVisitor, arrayStrategy); pi.visitCode(); pi.visitMaxs(10, 8); expectedVisitor.visitLdcInsn("init"); expectedVisitor.visitMaxs(13, 9); } @Test public void testVisitFrame() { ProbeInserter pi = new ProbeInserter(0, "m", "(J)V", actualVisitor, arrayStrategy); pi.visitFrame(Opcodes.F_NEW, 3, new Object[] { "Foo", Opcodes.LONG, "java/lang/String" }, 0, new Object[0]); expectedVisitor.visitFrame(Opcodes.F_NEW, 4, new Object[] { "Foo", Opcodes.LONG, "[Z", "java/lang/String" }, 0, new Object[0]); } @Test public void testVisitFrameNoLocals() { ProbeInserter pi = new ProbeInserter(Opcodes.ACC_STATIC, "m", "()V", actualVisitor, arrayStrategy); pi.visitFrame(Opcodes.F_NEW, 0, new Object[] {}, 0, new Object[0]); expectedVisitor.visitFrame(Opcodes.F_NEW, 1, new Object[] { "[Z" }, 0, new Object[0]); } @Test public void testVisitFrameProbeAt0() { ProbeInserter pi = new ProbeInserter(Opcodes.ACC_STATIC, "m", "()V", actualVisitor, arrayStrategy); pi.visitFrame(Opcodes.F_NEW, 2, new Object[] { Opcodes.DOUBLE, "Foo" }, 0, new Object[0]); expectedVisitor.visitFrame(Opcodes.F_NEW, 3, new Object[] { "[Z", Opcodes.DOUBLE, "Foo" }, 0, new Object[0]); } @Test public void testFillOneWord() { ProbeInserter pi = new ProbeInserter(Opcodes.ACC_STATIC, "m", "(I)V", actualVisitor, arrayStrategy); pi.visitFrame(Opcodes.F_NEW, 0, new Object[] {}, 0, new Object[] {}); // The locals in this frame are filled with TOP up to the probe variable expectedVisitor.visitFrame(Opcodes.F_NEW, 2, new Object[] { Opcodes.TOP, "[Z", }, 0, new Object[] {}); } @Test public void testFillTwoWord() { ProbeInserter pi = new ProbeInserter(Opcodes.ACC_STATIC, "m", "(J)V", actualVisitor, arrayStrategy); pi.visitFrame(Opcodes.F_NEW, 0, new Object[] {}, 0, new Object[] {}); // The locals in this frame are filled with TOP up to the probe variable expectedVisitor.visitFrame(Opcodes.F_NEW, 3, new Object[] { Opcodes.TOP, Opcodes.TOP, "[Z", }, 0, new Object[] {}); } @Test public void testFillPartly() { ProbeInserter pi = new ProbeInserter(Opcodes.ACC_STATIC, "m", "(DIJ)V", actualVisitor, arrayStrategy); pi.visitFrame(Opcodes.F_NEW, 1, new Object[] { Opcodes.DOUBLE }, 0, new Object[] {}); // The locals in this frame are filled with TOP up to the probe variable expectedVisitor.visitFrame(Opcodes.F_NEW, 5, new Object[] { Opcodes.DOUBLE, Opcodes.TOP, Opcodes.TOP, Opcodes.TOP, "[Z", }, 0, new Object[] {}); } @Test(expected = IllegalArgumentException.class) public void testVisitFrame_invalidType() { ProbeInserter pi = new ProbeInserter(0, "m", "()V", actualVisitor, arrayStrategy); pi.visitFrame(Opcodes.F_SAME, 0, null, 0, null); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/internal/instr/SignatureRemoverTest.java000066400000000000000000000067231304217427400324540ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.instr; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.jar.Manifest; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link SignatureRemover}. */ public class SignatureRemoverTest { private SignatureRemover remover; @Before public void setup() { remover = new SignatureRemover(); } @Test public void testRemoveNegative1() { assertFalse(remover.removeEntry("META-INF/ALIAS.MF")); } @Test public void testRemoveNegative2() { assertFalse(remover.removeEntry("META-INF/sub/ALIAS.SF")); } @Test public void testRemoveNegative3() { remover.setActive(false); assertFalse(remover.removeEntry("META-INF/SIG-ALIAS")); } @Test public void testRemovePositive1() { assertTrue(remover.removeEntry("META-INF/ALIAS.SF")); } @Test public void testRemovePositive2() { assertTrue(remover.removeEntry("META-INF/ALIAS.RSA")); } @Test public void testRemovePositive3() { assertTrue(remover.removeEntry("META-INF/ALIAS.DSA")); } @Test public void testRemovePositive4() { assertTrue(remover.removeEntry("META-INF/SIG-ALIAS")); } @Test public void testFilterNegative1() throws IOException { assertFalse(remover.filterEntry("MANIFEST.MF", null, null)); } @Test public void testFilterNegative2() throws IOException { remover.setActive(false); assertFalse(remover.filterEntry("META-INF/MANIFEST.MF", null, null)); } @Test public void testFilterPositive1() throws IOException { String original = "Manifest-Version: 1.0\r\n" + "Created-By: Apache Maven\r\n" // + "Bundle-SymbolicName: org.jacoco.core\r\n" // + "\r\n"// + "Name: org/jacoco/example/A.class\r\n" // + "SHA1-Digest: z1ly8OewPb9LOCpfNaIAhEgXZ5I=\r\n" // + "\r\n" // + "Name: org/jacoco/example/B.class\r\n" // + "SHA1-Digest: nfE4+Vmekj0pE5z0m0frpb10Gl0=\r\n" // + "OtherInfo: keep this\r\n" // + "\r\n" // + "Name: org/jacoco/example/C.class\r\n" // + "SHA1-Digest: xaNEXNWCrlTVcqPrXL0TwTcsvXU=\r\n"; InputStream in = new ByteArrayInputStream( original.getBytes("ISO-8859-1")); ByteArrayOutputStream out = new ByteArrayOutputStream(); assertTrue(remover.filterEntry("META-INF/MANIFEST.MF", in, out)); String expected = "Manifest-Version: 1.0\r\n" + "Created-By: Apache Maven\r\n" // + "Bundle-SymbolicName: org.jacoco.core\r\n" // + "\r\n"// + "Name: org/jacoco/example/B.class\r\n" // + "OtherInfo: keep this\r\n" // + "\r\n"; assertEquals( createManifest(expected.getBytes("ISO-8859-1")), createManifest(out.toByteArray())); } private static Manifest createManifest(final byte[] bytes) throws IOException { return new Manifest( new ByteArrayInputStream(bytes)); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/000077500000000000000000000000001304217427400241505ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/AgentOptionsTest.java000066400000000000000000000335611304217427400302750ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Properties; import org.junit.BeforeClass; import org.junit.Test; /** * Unit tests for {@link AgentOptions}. */ public class AgentOptionsTest { private static File defaultAgentJarFile; @BeforeClass public static void beforeClass() { defaultAgentJarFile = new File("jacocoagent.jar"); } @Test public void testDefaults() { AgentOptions options = new AgentOptions(); assertEquals(AgentOptions.DEFAULT_DESTFILE, options.getDestfile()); assertTrue(options.getAppend()); assertEquals("*", options.getIncludes()); assertEquals("", options.getExcludes()); assertEquals("sun.reflect.DelegatingClassLoader", options.getExclClassloader()); assertFalse(options.getInclBootstrapClasses()); assertFalse(options.getInclNoLocationClasses()); assertNull(options.getSessionId()); assertTrue(options.getDumpOnExit()); assertEquals(AgentOptions.OutputMode.file, options.getOutput()); assertEquals(AgentOptions.DEFAULT_ADDRESS, options.getAddress()); assertEquals(AgentOptions.DEFAULT_PORT, options.getPort()); assertNull(options.getClassDumpDir()); assertFalse(options.getJmx()); assertEquals("", options.toString()); } @Test public void testEmptyOptions() { AgentOptions options = new AgentOptions(""); assertEquals("", options.toString()); } @Test public void testNullOptions() { AgentOptions options = new AgentOptions((String) null); assertEquals("", options.toString()); } @Test public void testPropertiesOptions() { Properties properties = new Properties(); properties.put("destfile", "/target/test/test.exec"); properties.put("append", "false"); properties.put("includes", "org.*:com.*"); properties.put("excludes", "*Test"); properties.put("exclclassloader", "org.jacoco.test.TestLoader"); properties.put("inclbootstrapclasses", "true"); properties.put("inclnolocationclasses", "true"); properties.put("sessionid", "testsession"); properties.put("dumponexit", "false"); properties.put("output", "tcpserver"); properties.put("address", "remotehost"); properties.put("port", "1234"); properties.put("classdumpdir", "target/dump"); properties.put("jmx", "true"); AgentOptions options = new AgentOptions(properties); assertEquals("/target/test/test.exec", options.getDestfile()); assertFalse(options.getAppend()); assertEquals("org.*:com.*", options.getIncludes()); assertEquals("*Test", options.getExcludes()); assertEquals("org.jacoco.test.TestLoader", options.getExclClassloader()); assertTrue(options.getInclBootstrapClasses()); assertTrue(options.getInclNoLocationClasses()); assertEquals("testsession", options.getSessionId()); assertFalse(options.getDumpOnExit()); assertEquals(AgentOptions.OutputMode.tcpserver, options.getOutput()); assertEquals("remotehost", options.getAddress()); assertEquals(1234, options.getPort()); assertEquals("target/dump", options.getClassDumpDir()); assertTrue(options.getJmx()); } @Test public void testEmptyPropertiesOptions() { AgentOptions options = new AgentOptions(new Properties()); assertEquals("", options.toString()); } @Test public void testGetDestile() { AgentOptions options = new AgentOptions("destfile=/var/test.exec"); assertEquals("/var/test.exec", options.getDestfile()); } @Test public void testSetDestile() { AgentOptions options = new AgentOptions(); options.setDestfile("/var/test.exec"); assertEquals("/var/test.exec", options.getDestfile()); assertEquals("destfile=/var/test.exec", options.toString()); } @Test public void testGetAppendTrue() { AgentOptions options = new AgentOptions("append=true"); assertTrue(options.getAppend()); } @Test public void testGetAppendFalse() { AgentOptions options = new AgentOptions("append=false"); assertFalse(options.getAppend()); } @Test public void testSetAppendTrue() { AgentOptions options = new AgentOptions(); options.setAppend(true); assertTrue(options.getAppend()); assertEquals("append=true", options.toString()); } @Test public void testSetAppendFalse() { AgentOptions options = new AgentOptions(); options.setAppend(false); assertFalse(options.getAppend()); assertEquals("append=false", options.toString()); } @Test public void testGetExclClassloader() { AgentOptions options = new AgentOptions( "exclclassloader=org.jacoco.test.TestLoader"); assertEquals("org.jacoco.test.TestLoader", options.getExclClassloader()); } @Test public void testSetExclClassloader() { AgentOptions options = new AgentOptions(); options.setExclClassloader("org.jacoco.test.TestLoader"); assertEquals("org.jacoco.test.TestLoader", options.getExclClassloader()); assertEquals("exclclassloader=org.jacoco.test.TestLoader", options.toString()); } @Test public void testGetIncludes() { AgentOptions options = new AgentOptions("includes=org.*:com.*"); assertEquals("org.*:com.*", options.getIncludes()); } @Test public void testSetIncludes() { AgentOptions options = new AgentOptions(); options.setIncludes("org.jacoco.*"); assertEquals("org.jacoco.*", options.getIncludes()); assertEquals("includes=org.jacoco.*", options.toString()); } @Test public void testGetExcludes() { AgentOptions options = new AgentOptions("excludes=*Test"); assertEquals("*Test", options.getExcludes()); } @Test public void testSetExcludes() { AgentOptions options = new AgentOptions(); options.setExcludes("org.jacoco.test.*"); assertEquals("org.jacoco.test.*", options.getExcludes()); assertEquals("excludes=org.jacoco.test.*", options.toString()); } @Test public void testGetInclBootstrapClassesTrue() { AgentOptions options = new AgentOptions("inclbootstrapclasses=true"); assertTrue(options.getInclBootstrapClasses()); } @Test public void testGetInclBootstrapClassesFalse() { AgentOptions options = new AgentOptions("inclbootstrapclasses=false"); assertFalse(options.getInclBootstrapClasses()); } @Test public void testSetInclBootstrapClassesTrue() { AgentOptions options = new AgentOptions(); options.setInclBootstrapClasses(true); assertTrue(options.getInclBootstrapClasses()); assertEquals("inclbootstrapclasses=true", options.toString()); } @Test public void testSetInclBootstrapClassesFalse() { AgentOptions options = new AgentOptions(); options.setInclBootstrapClasses(false); assertFalse(options.getInclBootstrapClasses()); assertEquals("inclbootstrapclasses=false", options.toString()); } @Test public void testGetInclNoLocationClassesTrue() { AgentOptions options = new AgentOptions("inclnolocationclasses=true"); assertTrue(options.getInclNoLocationClasses()); } @Test public void testGetInclNoLocationClassesFalse() { AgentOptions options = new AgentOptions("inclnolocationclasses=false"); assertFalse(options.getInclNoLocationClasses()); } @Test public void testSetInclNoLocationClassesTrue() { AgentOptions options = new AgentOptions(); options.setInclNoLocationClasses(true); assertTrue(options.getInclNoLocationClasses()); assertEquals("inclnolocationclasses=true", options.toString()); } @Test public void testSetInclNoLocationClassesFalse() { AgentOptions options = new AgentOptions(); options.setInclNoLocationClasses(false); assertFalse(options.getInclNoLocationClasses()); assertEquals("inclnolocationclasses=false", options.toString()); } @Test public void testGetSessionId() { AgentOptions options = new AgentOptions("sessionid=testsession"); assertEquals("testsession", options.getSessionId()); } @Test public void testSetSessionId() { AgentOptions options = new AgentOptions(); options.setSessionId("testsession"); assertEquals("testsession", options.getSessionId()); assertEquals("sessionid=testsession", options.toString()); } @Test public void testGetDumpOnExit() { AgentOptions options = new AgentOptions("dumponexit=false"); assertFalse(options.getDumpOnExit()); } @Test public void testSetDumpOnExit() { AgentOptions options = new AgentOptions(); options.setDumpOnExit(false); assertFalse(options.getDumpOnExit()); } @Test public void testGetOutput() { AgentOptions options = new AgentOptions("output=tcpserver"); assertEquals(AgentOptions.OutputMode.tcpserver, options.getOutput()); } @Test public void testSetOutput1() { AgentOptions options = new AgentOptions(); options.setOutput("tcpclient"); assertEquals(AgentOptions.OutputMode.tcpclient, options.getOutput()); } @Test public void testSetOutput2() { AgentOptions options = new AgentOptions(); options.setOutput(AgentOptions.OutputMode.tcpclient); assertEquals(AgentOptions.OutputMode.tcpclient, options.getOutput()); } @Test(expected = IllegalArgumentException.class) public void testInvalidOutput1() { new AgentOptions("output=foo"); } @Test(expected = IllegalArgumentException.class) public void testInvalidOutput2() { AgentOptions options = new AgentOptions(); options.setOutput("foo"); } @Test public void testGetPort() { AgentOptions options = new AgentOptions("port=1234"); assertEquals(1234, options.getPort()); } @Test public void testSetPort() { AgentOptions options = new AgentOptions(); options.setPort(1234); assertEquals(1234, options.getPort()); } @Test(expected = IllegalArgumentException.class) public void testParseInvalidPort() { new AgentOptions("port=xxx"); } @Test(expected = IllegalArgumentException.class) public void testSetNegativePort() { AgentOptions options = new AgentOptions(); options.setPort(-1234); } @Test public void testGetAddress() { AgentOptions options = new AgentOptions("address=remotehost"); assertEquals("remotehost", options.getAddress()); } @Test public void testSetAddress() { AgentOptions options = new AgentOptions(); options.setAddress("remotehost"); assertEquals("remotehost", options.getAddress()); } @Test public void testToString() { AgentOptions options = new AgentOptions(); options.setDestfile("test.exec"); options.setAppend(false); assertEquals("destfile=test.exec,append=false", options.toString()); } @Test(expected = IllegalArgumentException.class) public void testInvalidOptionFormat() { new AgentOptions("destfile"); } @Test(expected = IllegalArgumentException.class) public void testInvalidOptionKey() { new AgentOptions("destfile=test.exec,Some-thing_1=true"); } @Test(expected = IllegalArgumentException.class) public void testInvalidPortOptionValue() { new AgentOptions("port=-1234"); } @Test public void testGetClassDumpDir() { AgentOptions options = new AgentOptions("classdumpdir=target/dump"); assertEquals("target/dump", options.getClassDumpDir()); } @Test public void testSetClassDumpDir() { AgentOptions options = new AgentOptions(); options.setClassDumpDir("target/dump"); assertEquals("target/dump", options.getClassDumpDir()); assertEquals("classdumpdir=target/dump", options.toString()); } @Test public void testGetJmx() { AgentOptions options = new AgentOptions("jmx=true"); assertTrue(options.getJmx()); } @Test public void testSetJmx() { AgentOptions options = new AgentOptions(); options.setJmx(true); assertTrue(options.getJmx()); } @Test public void testGetVMArgumentWithNoOptions() { AgentOptions options = new AgentOptions(); String vmArgument = options.getVMArgument(defaultAgentJarFile); assertEquals( String.format("-javaagent:%s=", defaultAgentJarFile.toString()), vmArgument); } @Test public void testGetVMArgumentWithOneOption() { AgentOptions options = new AgentOptions(); options.setAppend(true); String vmArgument = options.getVMArgument(defaultAgentJarFile); assertEquals( String.format("-javaagent:%s=append=true", defaultAgentJarFile.toString()), vmArgument); } @Test public void testGetVMArgumentWithOptions() { AgentOptions options = new AgentOptions(); options.setAppend(true); options.setDestfile("some test.exec"); String vmArgument = options.getVMArgument(defaultAgentJarFile); assertEquals(String.format( "-javaagent:%s=destfile=some test.exec,append=true", defaultAgentJarFile.toString()), vmArgument); } @Test public void testGetQuotedVMArgument() { AgentOptions options = new AgentOptions(); options.setSessionId("my session"); String vmArgument = options.getQuotedVMArgument(defaultAgentJarFile); assertEquals(String.format("\"-javaagent:%s=sessionid=my session\"", defaultAgentJarFile.toString()), vmArgument); } @Test public void testPrependVMArguments() { AgentOptions options = new AgentOptions(); String vmArgument = options.prependVMArguments("a b c", defaultAgentJarFile); assertEquals( String.format("-javaagent:%s= a b c", defaultAgentJarFile.toString()), vmArgument); } @Test public void testPrependVMArgumentsReplace() { AgentOptions options = new AgentOptions(); String vmArgument = options.prependVMArguments(String.format( "a b -javaagent:%s=append=false c", defaultAgentJarFile), defaultAgentJarFile); assertEquals( String.format("-javaagent:%s= a b c", defaultAgentJarFile.toString()), vmArgument); } @Test public void testOptionValueWithSpecialCharacters() { AgentOptions options = new AgentOptions( "destfile=build/jacoco/foo, bar-1_0.exec"); assertEquals("build/jacoco/foo, bar-1_0.exec", options.getDestfile()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/CommandLineSupportTest.java000066400000000000000000000056051304217427400314440ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; /** * Unit tests for {@link CommandLineSupport}. */ public class CommandLineSupportTest { @Test public void testQuote1() { assertEquals("aBc", CommandLineSupport.quote("aBc")); } @Test public void testQuote2() { assertEquals("\"a c\"", CommandLineSupport.quote("a c")); } @Test public void testQuote3() { assertEquals("\"a\\\"c\"", CommandLineSupport.quote("a\"c")); } @Test public void testQuote4() { assertEquals("\" xy \"", CommandLineSupport.quote(" xy ")); } @Test public void testQuote5() { assertEquals("a\\\\b", CommandLineSupport.quote("a\\b")); } @Test public void testQuoteList1() { assertEquals("", CommandLineSupport.quote(Arrays. asList())); } @Test public void testQuoteList2() { assertEquals("a", CommandLineSupport.quote(Arrays.asList("a"))); } @Test public void testQuoteList3() { assertEquals("a b c", CommandLineSupport.quote(Arrays.asList("a", "b", "c"))); } @Test public void testQuoteList4() { assertEquals("a \"b b\" c", CommandLineSupport.quote(Arrays.asList("a", "b b", "c"))); } @Test public void testSplit1() { assertEquals(Arrays.asList(), CommandLineSupport.split(null)); } @Test public void testSplit2() { assertEquals(Arrays.asList(), CommandLineSupport.split("")); } @Test public void testSplit3() { assertEquals(Arrays.asList("abc"), CommandLineSupport.split("abc")); } @Test public void testSplit4() { assertEquals(Arrays.asList("aa", "bbbb", "cccccc"), CommandLineSupport.split(" aa bbbb cccccc ")); } @Test public void testSplit5() { assertEquals(Arrays.asList("a a", "b b "), CommandLineSupport.split("\"a a\" \"b b \" ")); } @Test public void testSplit6() { assertEquals(Arrays.asList("a\"c"), CommandLineSupport.split("a\\\"c")); } @Test public void testSplit7() { assertEquals(Arrays.asList("a\\c"), CommandLineSupport.split("a\\c")); } @Test public void testSplit8() { assertEquals(Arrays.asList("a\\"), CommandLineSupport.split("a\\")); } @Test public void testSplit9() { assertEquals(Arrays.asList("a\\", "b"), CommandLineSupport.split("a\\ b")); } @Test public void testSplit10() { assertEquals(Arrays.asList("a\\b"), CommandLineSupport.split("a\\\\b")); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/LoggerRuntimeTest.java000066400000000000000000000014151304217427400304370ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; /** * Unit tests for {@link LoggerRuntime}. */ public class LoggerRuntimeTest extends RuntimeTestBase { @Override IRuntime createRuntime() { return new LoggerRuntime(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/ModifiedSystemClassRuntimeTest.java000066400000000000000000000101271304217427400331330ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import org.jacoco.core.test.TargetLoader; import org.junit.Test; /** * Unit tests for {@link ModifiedSystemClassRuntime}. */ public class ModifiedSystemClassRuntimeTest extends RuntimeTestBase { @Override IRuntime createRuntime() { return new ModifiedSystemClassRuntime( ModifiedSystemClassRuntimeTest.class, "accessField"); } @Test(expected = RuntimeException.class) public void testCreateForNegative() throws Exception { Instrumentation inst = newInstrumentationMock(); ModifiedSystemClassRuntime.createFor(inst, TARGET_CLASS_NAME); } /** This static member emulate the instrumented system class. */ public static Object accessField; private static final String TARGET_CLASS_NAME = "org/jacoco/core/runtime/ModifiedSystemClassRuntimeTest"; /** * Note that we use Proxy here to mock {@link Instrumentation}, because JDK * 9 adds new method "addModule", whose parameter depends on class * "java.lang.reflect.Module" introduced in JDK 9. */ private Instrumentation newInstrumentationMock() { return (Instrumentation) Proxy.newProxyInstance(getClass() .getClassLoader(), new Class[] { Instrumentation.class }, new MyInvocationHandler()); } private static class MyInvocationHandler implements InvocationHandler { boolean added = false; boolean removed = false; /** * {@link Instrumentation#addTransformer(ClassFileTransformer)} */ void addTransformer(ClassFileTransformer transformer) { assertFalse(added); added = true; try { // Our class should get instrumented: final byte[] data = TargetLoader .getClassDataAsBytes(ModifiedSystemClassRuntimeTest.class); verifyInstrumentedClass(TARGET_CLASS_NAME, transformer.transform((ClassLoader) null, TARGET_CLASS_NAME, null, null, data)); // Other classes will not be instrumented: assertNull(transformer.transform(getClass().getClassLoader(), "some/other/Class", null, null, new byte[0])); } catch (Exception e) { throw new RuntimeException(e); } } /** * {@link Instrumentation#removeTransformer(ClassFileTransformer)} */ Boolean removeTransformer() { assertTrue(added); assertFalse(removed); removed = true; return Boolean.TRUE; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args.length == 1) { if ("removeTransformer".equals(method.getName())) { return removeTransformer(); } else if ("addTransformer".equals(method.getName())) { addTransformer((ClassFileTransformer) args[0]); return null; } } fail(); return null; } } private static void verifyInstrumentedClass(String name, byte[] source) throws Exception { name = name.replace('/', '.'); final Class targetClass = new TargetLoader().add(name, source); // Check added field: final Field f = targetClass.getField("$jacocoAccess"); assertTrue(Modifier.isPublic(f.getModifiers())); assertTrue(Modifier.isStatic(f.getModifiers())); assertTrue(Modifier.isTransient(f.getModifiers())); assertEquals(Object.class, f.getType()); } } OfflineInstrumentationAccessGeneratorTest.java000066400000000000000000000111721304217427400352750ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.jacoco.core.JaCoCo; import org.jacoco.core.instr.MethodRecorder; import org.jacoco.core.internal.instr.InstrSupport; import org.jacoco.core.test.TargetLoader; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import org.objectweb.asm.commons.Method; /** * Unit tests for {@link OfflineInstrumentationAccessGenerator}. */ public class OfflineInstrumentationAccessGeneratorTest { private IExecutionDataAccessorGenerator generator; private static boolean[] probes; // runtime stub public static boolean[] getProbes(final long classid, final String classname, final int probecount) { return probes; } @BeforeClass public static void setupClass() { probes = new boolean[3]; } @Before public void setup() { String name = getClass().getName().replace('.', '/'); generator = new OfflineInstrumentationAccessGenerator(name); } @Test public void testRuntimeAccess() throws Exception { ITarget target = generateAndInstantiateClass(123); assertSame(probes, target.get()); } @Test public void testRuntimeClassName() throws Exception { generator = new OfflineInstrumentationAccessGenerator(); MethodRecorder actual = new MethodRecorder(); generator.generateDataAccessor(987654321, "foo/Bar", 17, actual.getVisitor()); MethodRecorder expected = new MethodRecorder(); expected.getVisitor().visitLdcInsn(Long.valueOf(987654321)); expected.getVisitor().visitLdcInsn("foo/Bar"); expected.getVisitor().visitIntInsn(Opcodes.BIPUSH, 17); String rtname = JaCoCo.RUNTIMEPACKAGE.replace('.', '/') + "/Offline"; expected.getVisitor().visitMethodInsn(Opcodes.INVOKESTATIC, rtname, "getProbes", "(JLjava/lang/String;I)[Z", false); assertEquals(expected, actual); } /** * Creates a new class with the given id, loads this class and instantiates * it. The constructor of the generated class will request the probe array * from the access generator under test. */ private ITarget generateAndInstantiateClass(int classid) throws InstantiationException, IllegalAccessException { final String className = "org/jacoco/test/targets/RuntimeTestTarget_" + classid; Type classType = Type.getObjectType(className); final ClassWriter writer = new ClassWriter(0); writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", new String[] { Type.getInternalName(ITarget.class) }); writer.visitField(InstrSupport.DATAFIELD_ACC, InstrSupport.DATAFIELD_NAME, InstrSupport.DATAFIELD_DESC, null, null); // Constructor GeneratorAdapter gen = new GeneratorAdapter(writer.visitMethod( Opcodes.ACC_PUBLIC, "", "()V", null, new String[0]), Opcodes.ACC_PUBLIC, "", "()V"); gen.visitCode(); gen.loadThis(); gen.invokeConstructor(Type.getType(Object.class), new Method("", "()V")); gen.loadThis(); final int size = generator.generateDataAccessor(classid, className, 2, gen); gen.putStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC)); gen.returnValue(); gen.visitMaxs(size + 1, 0); gen.visitEnd(); // get() gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "get", "()[Z", null, new String[0]), Opcodes.ACC_PUBLIC, "get", "()[Z"); gen.visitCode(); gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC)); gen.returnValue(); gen.visitMaxs(1, 0); gen.visitEnd(); writer.visitEnd(); final TargetLoader loader = new TargetLoader(); return (ITarget) loader.add(className.replace('/', '.'), writer.toByteArray()).newInstance(); } /** * With this interface access read coverage data of the generated class. */ public interface ITarget { /** * Returns a reference to the probe array. * * @return the probe array */ boolean[] get(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/RemoteControlReaderWriterTest.java000066400000000000000000000057351304217427400330010ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import org.jacoco.core.data.ExecutionDataReader; import org.jacoco.core.data.ExecutionDataReaderWriterTest; import org.jacoco.core.data.ExecutionDataWriter; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link ExecutionDataReader} and {@link ExecutionDataWriter}. * The tests don't care about the written binary format, they just verify * symmetry. */ public class RemoteControlReaderWriterTest extends ExecutionDataReaderWriterTest { private RemoteControlWriter writer; @Before @Override public void setup() throws IOException { super.setup(); writer = createWriter(buffer); } @Test(expected = IOException.class) public void testNoRemoteCommandVisitor() throws IOException { writer.visitDumpCommand(false, false); final RemoteControlReader reader = createReader(); reader.read(); } @Test public void testVisitDump1() throws IOException { testVisitDump(false, false); } @Test public void testVisitDump2() throws IOException { testVisitDump(false, true); } @Test public void testVisitDump3() throws IOException { testVisitDump(true, false); } @Test public void testVisitDump4() throws IOException { testVisitDump(true, true); } private void testVisitDump(boolean doDump, boolean doReset) throws IOException { writer.visitDumpCommand(doDump, doReset); final RemoteControlReader reader = createReader(); final StringBuilder calls = new StringBuilder(); reader.setRemoteCommandVisitor(new IRemoteCommandVisitor() { public void visitDumpCommand(boolean dump, boolean reset) { calls.append("cmd(" + dump + "," + reset + ")"); } }); assertFalse(reader.read()); assertEquals("cmd(" + doDump + "," + doReset + ")", calls.toString()); } @Test public void testSendCmdOk() throws IOException { writer.sendCmdOk(); final RemoteControlReader reader = createReader(); assertTrue(reader.read()); } @Override protected RemoteControlReader createReader() throws IOException { return new RemoteControlReader(new ByteArrayInputStream( buffer.toByteArray())); } @Override protected RemoteControlWriter createWriter(OutputStream out) throws IOException { return new RemoteControlWriter(out); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/RuntimeDataTest.java000066400000000000000000000132731304217427400300760ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.concurrent.Callable; import org.jacoco.core.test.TargetLoader; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Unit tests for {@link RuntimeData}. * */ public class RuntimeDataTest { private RuntimeData data; private TestStorage storage; @Before public void setup() { data = new RuntimeData(); storage = new TestStorage(); } @Test public void testGetSetSessionId() { assertNotNull(data.getSessionId()); data.setSessionId("test-id"); assertEquals("test-id", data.getSessionId()); } @Test public void testGetProbes() { Object[] args = new Object[] { Long.valueOf(123), "Foo", Integer.valueOf(3) }; data.equals(args); assertEquals(3, ((boolean[]) args[0]).length); data.collect(storage, storage, false); boolean[] data = (boolean[]) args[0]; assertEquals(3, data.length, 0.0); assertFalse(data[0]); assertFalse(data[1]); assertFalse(data[2]); assertSame(storage.getData(123).getProbes(), data); assertEquals("Foo", storage.getData(123).getName()); } @Test public void testCollectEmpty() { data.collect(storage, storage, false); storage.assertSize(0); } @Test public void testCollectWithReset() { data.setSessionId("testsession"); boolean[] probes = data.getExecutionData(Long.valueOf(123), "Foo", 1) .getProbes(); probes[0] = true; data.collect(storage, storage, true); assertFalse(probes[0]); assertEquals("testsession", storage.getSessionInfo().getId()); } @Test public void testCollectWithoutReset() { data.setSessionId("testsession"); boolean[] probes = data.getExecutionData(Long.valueOf(123), "Foo", 1) .getProbes(); probes[0] = true; data.collect(storage, storage, false); assertTrue(probes[0]); assertEquals("testsession", storage.getSessionInfo().getId()); } @Test public void testEquals() { assertTrue(data.equals(data)); } @Test public void testHashCode() { assertEquals(System.identityHashCode(data), data.hashCode()); } @Test public void testGenerateArgumentArray() throws Exception { final ClassWriter writer = new ClassWriter(0); writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Sample", null, "java/lang/Object", new String[] { Type.getInternalName(Callable.class) }); // Constructor MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, new String[0]); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); // call() mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "call", "()Ljava/lang/Object;", null, new String[0]); mv.visitCode(); RuntimeData.generateArgumentArray(1000, "Sample", 15, mv); mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(5, 1); mv.visitEnd(); writer.visitEnd(); final TargetLoader loader = new TargetLoader(); Callable callable = (Callable) loader.add("Sample", writer.toByteArray()).newInstance(); final Object[] args = (Object[]) callable.call(); assertEquals(3, args.length, 0.0); assertEquals(Long.valueOf(1000), args[0]); assertEquals("Sample", args[1]); assertEquals(Integer.valueOf(15), args[2]); } @Test public void testGenerateAccessCall() throws Exception { final boolean[] probes = data.getExecutionData(Long.valueOf(1234), "Sample", 5).getProbes(); final ClassWriter writer = new ClassWriter(0); writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Sample", null, "java/lang/Object", new String[] { Type.getInternalName(Callable.class) }); // Constructor MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "", "(Ljava/lang/Object;)V", null, new String[0]); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitFieldInsn(Opcodes.PUTFIELD, "Sample", "access", "Ljava/lang/Object;"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(2, 2); mv.visitEnd(); // call() mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "call", "()Ljava/lang/Object;", null, new String[0]); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitFieldInsn(Opcodes.GETFIELD, "Sample", "access", "Ljava/lang/Object;"); RuntimeData.generateAccessCall(1234, "Sample", 5, mv); mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(6, 1); mv.visitEnd(); writer.visitField(Opcodes.ACC_PRIVATE, "access", "Ljava/lang/Object;", null, null); writer.visitEnd(); final TargetLoader loader = new TargetLoader(); Callable callable = (Callable) loader .add("Sample", writer.toByteArray()) .getConstructor(Object.class).newInstance(data); assertSame(probes, callable.call()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/RuntimeTestBase.java000066400000000000000000000135401304217427400300740ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.jacoco.core.JaCoCo; import org.jacoco.core.internal.instr.InstrSupport; import org.jacoco.core.test.TargetLoader; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import org.objectweb.asm.commons.Method; /** * Abstract test base for {@link IRuntime} implementations. */ public abstract class RuntimeTestBase { private RuntimeData data; private IRuntime runtime; private TestStorage storage; abstract IRuntime createRuntime(); @Before public void setup() throws Exception { data = new RuntimeData(); runtime = createRuntime(); runtime.startup(data); storage = new TestStorage(); } @After public void shutdown() { runtime.shutdown(); } @Test public void testDataAccessor() throws InstantiationException, IllegalAccessException { ITarget t = generateAndInstantiateClass(1234); data.collect(storage, storage, false); storage.assertData(1234, t.get()); } @Test public void testNoLocalVariablesInDataAccessor() throws InstantiationException, IllegalAccessException { runtime.generateDataAccessor(1001, "Target", 5, new MethodVisitor( JaCoCo.ASM_API_VERSION) { @Override public void visitVarInsn(int opcode, int var) { fail("No usage of local variables allowed."); } }); } @Test public void testExecutionRecording() throws InstantiationException, IllegalAccessException { generateAndInstantiateClass(1001).a(); data.collect(storage, storage, false); storage.assertSize(1); final boolean[] data = storage.getData(1001).getProbes(); assertTrue(data[0]); assertFalse(data[1]); } @Test public void testLoadSameClassTwice() throws InstantiationException, IllegalAccessException { generateAndInstantiateClass(1001).a(); generateAndInstantiateClass(1001).b(); data.collect(storage, storage, false); storage.assertSize(1); final boolean[] data = storage.getData(1001).getProbes(); assertTrue(data[0]); assertTrue(data[1]); } /** * Creates a new class with the given id, loads this class and instantiates * it. The constructor of the generated class will request the probe array * from the runtime under test. */ private ITarget generateAndInstantiateClass(int classid) throws InstantiationException, IllegalAccessException { final String className = "org/jacoco/test/targets/RuntimeTestTarget_" + classid; Type classType = Type.getObjectType(className); final ClassWriter writer = new ClassWriter(0); writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", new String[] { Type.getInternalName(ITarget.class) }); writer.visitField(InstrSupport.DATAFIELD_ACC, InstrSupport.DATAFIELD_NAME, InstrSupport.DATAFIELD_DESC, null, null); // Constructor GeneratorAdapter gen = new GeneratorAdapter(writer.visitMethod( Opcodes.ACC_PUBLIC, "", "()V", null, new String[0]), Opcodes.ACC_PUBLIC, "", "()V"); gen.visitCode(); gen.loadThis(); gen.invokeConstructor(Type.getType(Object.class), new Method("", "()V")); gen.loadThis(); final int size = runtime.generateDataAccessor(classid, className, 2, gen); gen.putStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC)); gen.returnValue(); gen.visitMaxs(size + 1, 0); gen.visitEnd(); // get() gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "get", "()[Z", null, new String[0]), Opcodes.ACC_PUBLIC, "get", "()[Z"); gen.visitCode(); gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC)); gen.returnValue(); gen.visitMaxs(1, 0); gen.visitEnd(); // a() gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "a", "()V", null, new String[0]), Opcodes.ACC_PUBLIC, "a", "()V"); gen.visitCode(); gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC)); gen.push(0); gen.push(1); gen.arrayStore(Type.BOOLEAN_TYPE); gen.returnValue(); gen.visitMaxs(3, 0); gen.visitEnd(); // b() gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "b", "()V", null, new String[0]), Opcodes.ACC_PUBLIC, "b", "()V"); gen.visitCode(); gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC)); gen.push(1); gen.push(1); gen.arrayStore(Type.BOOLEAN_TYPE); gen.returnValue(); gen.visitMaxs(3, 0); gen.visitEnd(); writer.visitEnd(); final TargetLoader loader = new TargetLoader(); return (ITarget) loader.add(className.replace('/', '.'), writer.toByteArray()).newInstance(); } /** * With this interface we modify and read coverage data of the generated * class. */ public interface ITarget { /** * Returns a reference to the probe array. * * @return the probe array */ boolean[] get(); /** * The implementation will mark probe 0 as executed */ void a(); /** * The implementation will mark probe 1 as executed */ void b(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/SystemPropertiesRuntimeTest.java000066400000000000000000000014531304217427400325630ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; /** * Unit tests for {@link SystemPropertiesRuntime}. */ public class SystemPropertiesRuntimeTest extends RuntimeTestBase { @Override IRuntime createRuntime() { return new SystemPropertiesRuntime(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/TestStorage.java000066400000000000000000000032501304217427400272570ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.util.HashMap; import java.util.Map; import org.jacoco.core.data.ExecutionData; import org.jacoco.core.data.IExecutionDataVisitor; import org.jacoco.core.data.ISessionInfoVisitor; import org.jacoco.core.data.SessionInfo; class TestStorage implements IExecutionDataVisitor, ISessionInfoVisitor { private final Map data = new HashMap(); private SessionInfo info; public void assertSize(int size) { assertEquals(size, data.size(), 0.0); } public ExecutionData getData(long classId) { return data.get(Long.valueOf(classId)); } public SessionInfo getSessionInfo() { return info; } public void assertData(long classId, boolean[] expected) { assertSame(expected, getData(classId).getProbes()); } // === ICoverageDataVisitor === public void visitClassExecution(final ExecutionData ed) { data.put(Long.valueOf(ed.getId()), ed); } // === ISessionInfoVisitor === public void visitSessionInfo(SessionInfo info) { this.info = info; } }jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/URLStreamHandlerRuntimeTest.java000066400000000000000000000014531304217427400323360ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; /** * Unit tests for {@link URLStreamHandlerRuntime}. */ public class URLStreamHandlerRuntimeTest extends RuntimeTestBase { @Override IRuntime createRuntime() { return new URLStreamHandlerRuntime(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/runtime/WildcardMatcherTest.java000066400000000000000000000047061304217427400307170ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.runtime; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class WildcardMatcherTest { @Test public void testEmpty() { assertTrue(new WildcardMatcher("").matches("")); assertFalse(new WildcardMatcher("").matches("abc")); } @Test public void testExact() { assertTrue(new WildcardMatcher("abc/def.txt").matches("abc/def.txt")); } @Test public void testCaseSensitive() { assertFalse(new WildcardMatcher("abcdef").matches("abcDef")); assertFalse(new WildcardMatcher("ABCDEF").matches("AbCDEF")); } @Test public void testQuote() { assertFalse(new WildcardMatcher("rst.xyz").matches("rstAxyz")); assertTrue(new WildcardMatcher("(x)+").matches("(x)+")); } @Test public void testWildcards() { assertTrue(new WildcardMatcher("*").matches("")); assertTrue(new WildcardMatcher("*").matches("java/lang/Object")); assertTrue(new WildcardMatcher("*Test").matches("jacoco/MatcherTest")); assertTrue(new WildcardMatcher("Matcher*").matches("Matcher")); assertTrue(new WildcardMatcher("Matcher*").matches("MatcherTest")); assertTrue(new WildcardMatcher("a*b*a").matches("a-b-b-a")); assertFalse(new WildcardMatcher("a*b*a").matches("alaska")); assertTrue(new WildcardMatcher("Hello?orld").matches("HelloWorld")); assertFalse(new WildcardMatcher("Hello?orld").matches("HelloWWWorld")); assertTrue(new WildcardMatcher("?aco*").matches("jacoco")); } @Test public void testMultiExpression() { assertTrue(new WildcardMatcher("Hello:World").matches("World")); assertTrue(new WildcardMatcher("Hello:World").matches("World")); assertTrue(new WildcardMatcher("*Test:*Foo").matches("UnitTest")); } @Test public void testDollar() { assertTrue(new WildcardMatcher("*$*").matches("java/util/Map$Entry")); assertTrue(new WildcardMatcher("*$$$*") .matches("org/example/Enity$$$generated123")); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/000077500000000000000000000000001304217427400234445ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/InstrumentingLoader.java000066400000000000000000000050641304217427400303110ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test; import java.io.IOException; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.RuntimeData; import org.jacoco.core.runtime.SystemPropertiesRuntime; /** * Class loader which loads classes from another class loader and instruments * them. */ public final class InstrumentingLoader extends ClassLoader { private final IRuntime runtime; private final String scope; private final ClassLoader delegate; private final RuntimeData data; private final Instrumenter instrumenter; public InstrumentingLoader(IRuntime runtime, String scope, ClassLoader delegate) throws Exception { this.runtime = runtime; this.scope = scope; this.delegate = delegate; this.data = new RuntimeData(); runtime.startup(data); this.instrumenter = new Instrumenter(runtime); } public InstrumentingLoader(Class target) throws Exception { this(new SystemPropertiesRuntime(), target.getPackage().getName(), target.getClassLoader()); } @Override protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith(scope)) { final byte[] bytes; try { bytes = TargetLoader.getClassDataAsBytes(delegate, name); } catch (IOException e) { throw new ClassNotFoundException("Unable to load", e); } final byte[] instrumented; try { instrumented = instrumenter.instrument(bytes, name); } catch (IOException e) { throw new ClassNotFoundException("Unable to instrument", e); } final Class c = defineClass(name, instrumented, 0, instrumented.length); if (resolve) { resolveClass(c); } return c; } return super.loadClass(name, resolve); } public ExecutionDataStore collect() { final ExecutionDataStore store = new ExecutionDataStore(); data.collect(store, new SessionInfoStore(), false); runtime.shutdown(); return store; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/TargetLoader.java000066400000000000000000000051461304217427400266720ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; /** * Loads given classes from a byte arrays. */ public class TargetLoader extends ClassLoader { private final Map classes; public TargetLoader() { super(TargetLoader.class.getClassLoader()); this.classes = new HashMap(); } public Class add(final String name, final byte[] bytes) { this.classes.put(name, bytes); return load(name); } public Class add(final Class name, final byte[] bytes) { return add(name.getName(), bytes); } private Class load(final String sourcename) { try { return loadClass(sourcename); } catch (ClassNotFoundException e) { // must not happen throw new RuntimeException(e); } } public static InputStream getClassData(Class clazz) { return getClassData(clazz.getClassLoader(), clazz.getName()); } public static InputStream getClassData(ClassLoader loader, String name) { final String resource = name.replace('.', '/') + ".class"; return loader.getResourceAsStream(resource); } public static byte[] getClassDataAsBytes(ClassLoader loader, String name) throws IOException { return readBytes(getClassData(loader, name)); } public static byte[] getClassDataAsBytes(Class clazz) throws IOException { return readBytes(getClassData(clazz)); } private static byte[] readBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[0x100]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } in.close(); return out.toByteArray(); } @Override protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { final byte[] bytes = classes.get(name); if (bytes != null) { Class c = defineClass(name, bytes, 0, bytes.length); if (resolve) { resolveClass(c); } return c; } return super.loadClass(name, resolve); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/000077500000000000000000000000001304217427400244005ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/AnalysisTimeScenario.java000066400000000000000000000035071304217427400313360ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; import java.util.concurrent.Callable; import org.jacoco.core.analysis.Analyzer; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.ICoverageVisitor; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.test.TargetLoader; /** * Scenario to measure the time taken by the instrumentation process itself. */ public class AnalysisTimeScenario extends TimedScenario { private final Class target; private final int count; protected AnalysisTimeScenario(Class target, int count) { super(String.format("analysing %s classes", Integer.valueOf(count))); this.target = target; this.count = count; } @Override protected Callable getInstrumentedCallable() throws Exception { final byte[] bytes = TargetLoader.getClassDataAsBytes(target); final ExecutionDataStore executionData = new ExecutionDataStore(); ICoverageVisitor visitor = new ICoverageVisitor() { public void visitCoverage(IClassCoverage coverage) { } }; final Analyzer analyzer = new Analyzer(executionData, visitor); return new Callable() { public Void call() throws Exception { for (int i = 0; i < count; i++) { analyzer.analyzeClass(bytes, target.getName()); } return null; } }; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/ExecuteInstrumentedCodeScenario.java000066400000000000000000000036641304217427400335370ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; import java.util.concurrent.Callable; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.LoggerRuntime; import org.jacoco.core.runtime.RuntimeData; import org.jacoco.core.test.TargetLoader; import org.objectweb.asm.ClassReader; /** * This scenario runs a given scenario twice and reports the execution time: * Once on its original version, once in a instrumented version. */ public class ExecuteInstrumentedCodeScenario extends TimedScenario { private final Class> target; protected ExecuteInstrumentedCodeScenario(String description, Class> target) { super(description); this.target = target; } @Override @SuppressWarnings("unchecked") protected Callable getInstrumentedCallable() throws Exception { ClassReader reader = new ClassReader(TargetLoader.getClassData(target)); IRuntime runtime = new LoggerRuntime(); runtime.startup(new RuntimeData()); final Instrumenter instr = new Instrumenter(runtime); final byte[] instrumentedBuffer = instr.instrument(reader); final TargetLoader loader = new TargetLoader(); return (Callable) loader.add(target, instrumentedBuffer) .newInstance(); } @Override protected Callable getReferenceCallable() throws Exception { return target.newInstance(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/IPerfOutput.java000066400000000000000000000030371304217427400274740ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; /** * Interface to report performance figures to. */ public interface IPerfOutput { /** Indicator for no reference time given */ public static final long NO_REFERENCE = Long.MIN_VALUE; /** * Reports the result of a time measurement with a optional reference time * for comparison. * * @param description * textual description of the test case * @param duration * duration in nano seconds * @param reference * optional reference time in nano seconds */ void writeTimeResult(String description, long duration, long reference); /** * Reports the result of a byte size measurement with a optional reference * size for comparison. * * @param description * textual description of the test case * @param size * size in bytes * @param reference * optional reference size in bytes */ void writeByteResult(String description, long size, long reference); } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/IPerfScenario.java000066400000000000000000000015341304217427400277370ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; /** * Interface for a performance scenario. */ public interface IPerfScenario { /** * Runs the performance scenario and reports the result to the given * interface. * * @param output */ public void run(IPerfOutput output) throws Exception; } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/InstrumentationSizeSzenario.java000066400000000000000000000027061304217427400330210ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.LoggerRuntime; import org.jacoco.core.test.TargetLoader; import org.objectweb.asm.ClassReader; /** * Scenario to measure the overhead in terms of additional byte code size * through instrumentation. */ public class InstrumentationSizeSzenario implements IPerfScenario { private final Class target; public InstrumentationSizeSzenario(Class target) { this.target = target; } public void run(IPerfOutput output) throws Exception { final IRuntime runtime = new LoggerRuntime(); ClassReader reader = new ClassReader(TargetLoader.getClassData(target)); final Instrumenter instr = new Instrumenter(runtime); instr.instrument(reader); output.writeByteResult("instrumented class", instr.instrument(reader).length, reader.b.length); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/InstrumentationTimeScenario.java000066400000000000000000000030631304217427400327530ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; import java.util.concurrent.Callable; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.LoggerRuntime; import org.jacoco.core.test.TargetLoader; /** * Scenario to measure the time taken by the instrumentation process itself. */ public class InstrumentationTimeScenario extends TimedScenario { private final Class target; private final int count; protected InstrumentationTimeScenario(Class target, int count) { super(String.format("instrumenting %s classes", Integer.valueOf(count))); this.target = target; this.count = count; } @Override protected Callable getInstrumentedCallable() throws Exception { final byte[] bytes = TargetLoader.getClassDataAsBytes(target); final Instrumenter instr = new Instrumenter(new LoggerRuntime()); return new Callable() { public Void call() throws Exception { for (int i = 0; i < count; i++) { instr.instrument(bytes, "TestTarget"); } return null; } }; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/PerfOutputWriter.java000066400000000000000000000051031304217427400305540ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; import static java.lang.String.format; import java.io.PrintWriter; import org.jacoco.core.JaCoCo; /** * Formatted text output. */ public class PerfOutputWriter implements IPerfOutput { private final PrintWriter writer; public PerfOutputWriter(final PrintWriter writer) { this.writer = writer; writeHeader(); } private void writeHeader() { writer.printf("JaCoCo Performance Data%n%n"); writer.printf("JaCoCo Version: %s%n", JaCoCo.VERSION); writer.printf("JVM Vendor: %s%n", System.getProperty("java.vm.vendor")); writer.printf("JVM Version: %s%n%n", System.getProperty("java.vm.version")); writer.println("scenario instr ref overhead"); writer.println("----------------------------------------------------------"); } public void writeTimeResult(final String description, final long duration, final long reference) { final double dms = (double) duration / 1000000; if (reference == NO_REFERENCE) { writeResult(description, dms, "%.2f", "ms"); } else { final double rms = (double) reference / 1000000; writeResult(description, dms, rms, "%.2f", "ms"); } } public void writeByteResult(String description, long size, long reference) { if (size == 0) { return; } if (reference == NO_REFERENCE) { writeResult(description, size, "%.0f", "bytes"); } else { writeResult(description, size, reference, "%.0f", "bytes"); } } private void writeResult(final String description, final double subject, String fmt, String unit) { writer.printf("%-30s%8s %-6s%n", description, format(fmt, Double.valueOf(subject)), unit); } private void writeResult(final String description, final double subject, final double reference, String fmt, String unit) { double overhead = 100 * (subject - reference) / reference; writer.printf("%-30s%8s%8s %-6s%4.0f%%%n", description, format(fmt, Double.valueOf(subject)), format(fmt, Double.valueOf(reference)), unit, Double.valueOf(overhead)); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/PerformanceSuite.java000066400000000000000000000032721304217427400305220ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; import java.io.PrintWriter; import org.jacoco.core.test.perf.targets.Target01; import org.jacoco.core.test.perf.targets.Target02; import org.jacoco.core.test.perf.targets.Target03; /** * The main test suite. */ public class PerformanceSuite implements IPerfScenario { public void run(IPerfOutput output) throws Exception { new ExecuteInstrumentedCodeScenario("plain method calls", Target01.class).run(output); new ExecuteInstrumentedCodeScenario("loop only", Target02.class) .run(output); new ExecuteInstrumentedCodeScenario("game of life", Target03.class) .run(output); new InstrumentationSizeSzenario(Target03.class).run(output); new InstrumentationTimeScenario(Target03.class, 1000).run(output); new AnalysisTimeScenario(Target03.class, 1000).run(output); } public static void main(String[] args) throws Exception { final PrintWriter writer; if (args.length == 0) { writer = new PrintWriter(System.out, true); } else { writer = new PrintWriter(args[0]); } IPerfOutput output = new PerfOutputWriter(writer); new PerformanceSuite().run(output); writer.close(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/TimedScenario.java000066400000000000000000000040271304217427400277740ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf; import java.util.concurrent.Callable; /** * Base class for execution time test scenarios. */ public abstract class TimedScenario implements IPerfScenario { private static final int RUNS = 10; private final String description; protected TimedScenario(final String description) { this.description = description; } public void run(final IPerfOutput output) throws Exception { final long time = getMinimumTime(getInstrumentedCallable()); final Callable refRunnable = getReferenceCallable(); final long reftime; if (refRunnable == null) { reftime = IPerfOutput.NO_REFERENCE; } else { reftime = getMinimumTime(refRunnable); } output.writeTimeResult(description, time, reftime); } /** * Runs the given subject several times and returns the minimum execution * time. * * @param subject * @return minimum execution time in nano seconds * @throws Exception */ private long getMinimumTime(final Callable subject) throws Exception { long min = Long.MAX_VALUE; for (int i = 0; i < RUNS; i++) { final long t = getTime(subject); min = Math.min(min, t); } return min; } private long getTime(final Callable subject) throws Exception { long start = System.nanoTime(); subject.call(); return System.nanoTime() - start; } protected abstract Callable getInstrumentedCallable() throws Exception; protected Callable getReferenceCallable() throws Exception { return null; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/targets/000077500000000000000000000000001304217427400260515ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/targets/Target01.java000066400000000000000000000050321304217427400303030ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf.targets; import java.util.concurrent.Callable; /** * Plain method calls. */ public class Target01 implements Callable { @SuppressWarnings("unused") private int c; // 4 ^ 0 = 1 times public Void call() throws Exception { m1(); m1(); m1(); m1(); c++; // some side effect, otherwise the JIT will remove the method return null; } // 4 ^ 1 = 4 times public void m1() { m2(); m2(); m2(); m2(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 2 == 16 times public void m2() { m3(); m3(); m3(); m3(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 3 == 64 times public void m3() { m4(); m4(); m4(); m4(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 4 == 256 times public void m4() { m5(); m5(); m5(); m5(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 5 == 1,024 times public void m5() { m6(); m6(); m6(); m6(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 6 == 4,096 times public void m6() { m7(); m7(); m7(); m7(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 7 == 16,384 times public void m7() { m8(); m8(); m8(); m8(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 8 == 65,536 times public void m8() { m9(); m9(); m9(); m9(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 9 == 262,144 times public void m9() { m10(); m10(); m10(); m10(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 10 == 1,048,576 times public void m10() { m11(); m11(); m11(); m11(); c++; // some side effect, otherwise the JIT will remove the method } // 4 ^ 11 == 4,194,304 times public void m11() { c++; // some side effect, otherwise the JIT will remove the method } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/targets/Target02.java000066400000000000000000000015651304217427400303130ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf.targets; import java.util.concurrent.Callable; /** * Simple Loop. */ public class Target02 implements Callable { public Void call() throws Exception { @SuppressWarnings("unused") int count = 0; for (int i = 0; i < 10000000; i++) { count++; } return null; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/perf/targets/Target03.java000066400000000000000000000064151304217427400303130ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.perf.targets; import java.util.Random; import java.util.concurrent.Callable; /** * "Game of Life" implementation as a more reference scenario. Obviously the * implementation could be more elegant using several classes, but the test * runner targets one class only. Also one could think about more efficient * implementations which again is not the focus here. */ public class Target03 implements Callable { private final int width; private final int height; private boolean[][] field; public Target03(int width, int height) { this.width = width; this.height = height; this.field = createField(); } public Target03() { this(64, 64); } private boolean[][] createField() { boolean[][] f = new boolean[height][]; for (int i = 0; i < height; i++) { f[i] = new boolean[width]; } return f; } public void set(int x, int y, boolean flag) { field[wrap(x, width)][wrap(y, height)] = flag; } public boolean get(int x, int y) { return field[wrap(x, width)][wrap(y, height)]; } public void clear() { field = createField(); } public void randomFill(long seed, int count) { Random r = new Random(seed); for (int i = 0; i < count; i++) { set(r.nextInt(), r.nextInt(), true); } } public void tick() { boolean[][] next = createField(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { final int n = getNeighbors(x, y); if (get(x, y)) { next[x][y] = 2 <= n && n <= 3; } else { next[x][y] = n == 3; } } } field = next; } // Neighbor private int getNeighbors(int x, int y) { int count = 0; if (get(x - 1, y - 1)) { count++; } if (get(x + 0, y - 1)) { count++; } if (get(x + 1, y - 1)) { count++; } if (get(x + 1, y + 0)) { count++; } if (get(x + 1, y + 1)) { count++; } if (get(x + 0, y + 1)) { count++; } if (get(x - 1, y + 1)) { count++; } if (get(x - 1, y + 0)) { count++; } return count; } private int wrap(int value, int size) { int res = value % size; if (res < 0) { res += size; } return res; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { sb.append(get(x, y) ? 'O' : '.'); } sb.append('\n'); } return sb.toString(); } public Void call() throws Exception { clear(); randomFill(123, width * height / 2); for (int i = 0; i < 20; i++) { tick(); } return null; } // Demo public static void main(String[] args) { Target03 t = new Target03(10, 10); t.randomFill(123, 20); for (int i = 0; i < 10; i++) { System.out.println("Generation " + i + ":"); System.out.println(t); t.tick(); } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/000077500000000000000000000000001304217427400255765ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/AnnotationInitializerTest.java000066400000000000000000000030161304217427400336170ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.AnnotationInitializer; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Test of initializer in annotations. */ public class AnnotationInitializerTest extends ValidationTestBase { public AnnotationInitializerTest() { super(AnnotationInitializer.class); } @Override protected void run(Class targetClass) throws Exception { // Instrumentation should not add members, // otherwise sun.reflect.annotation.AnnotationInvocationHandler // can throw java.lang.annotation.AnnotationFormatError assertEquals(1, targetClass.getDeclaredFields().length); assertEquals(1, targetClass.getDeclaredMethods().length); // Force initialization targetClass.getField("CONST").get(null); } @Test public void testCoverageResult() { assertLine("const", ICounter.FULLY_COVERED); assertLine("value", ICounter.EMPTY); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/BadCycleClassTest.java000066400000000000000000000024641304217427400317430ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.BadCycleClass; import org.junit.Test; /** * Test of "bad cycles" with classes. */ public class BadCycleClassTest extends ValidationTestBase { public BadCycleClassTest() throws Exception { super(BadCycleClass.class); } @Test public void test() throws Exception { assertLine("childinit", ICounter.FULLY_COVERED); assertLine("childsomeMethod", ICounter.FULLY_COVERED); assertLine("childclinit", ICounter.FULLY_COVERED); // The cycle causes a constructor and instance method to be called // before the static initializer of a class: assertLogEvents("childinit", "childsomeMethod", "childclinit", "childinit"); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/BooleanExpressionsTest.java000066400000000000000000000053131304217427400331250ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target02; import org.junit.Test; /** * Tests of basic Java boolean expressions. */ public class BooleanExpressionsTest extends ValidationTestBase { public BooleanExpressionsTest() { super(Target02.class); } @Test public void testCoverageResult() { // 1. Boolean comparison result (one case) assertLine("booleancmp1", ICounter.PARTLY_COVERED, 1, 1); // 2. Boolean comparison result (both cases) assertLine("booleancmp2", ICounter.FULLY_COVERED, 0, 2); // 3. And assertLine("andFF", ICounter.FULLY_COVERED, 1, 1); assertLine("andFT", ICounter.FULLY_COVERED, 1, 1); assertLine("andTF", ICounter.FULLY_COVERED, 1, 1); assertLine("andTT", ICounter.FULLY_COVERED, 1, 1); // 4. Conditional And assertLine("conditionalandFF", ICounter.PARTLY_COVERED, 3, 1); assertLine("conditionalandFT", ICounter.PARTLY_COVERED, 3, 1); assertLine("conditionalandTF", ICounter.FULLY_COVERED, 2, 2); assertLine("conditionalandTT", ICounter.FULLY_COVERED, 2, 2); // 5. Or assertLine("orFF", ICounter.FULLY_COVERED, 1, 1); assertLine("orFT", ICounter.FULLY_COVERED, 1, 1); assertLine("orTF", ICounter.FULLY_COVERED, 1, 1); assertLine("orTT", ICounter.FULLY_COVERED, 1, 1); // 6. Conditional Or assertLine("conditionalorFF", ICounter.FULLY_COVERED, 2, 2); assertLine("conditionalorFT", ICounter.FULLY_COVERED, 2, 2); assertLine("conditionalorTF", ICounter.PARTLY_COVERED, 3, 1); assertLine("conditionalorTT", ICounter.PARTLY_COVERED, 3, 1); // 7. Exclusive Or assertLine("xorFF", ICounter.FULLY_COVERED, 1, 1); assertLine("xorFT", ICounter.FULLY_COVERED, 1, 1); assertLine("xorTF", ICounter.FULLY_COVERED, 1, 1); assertLine("xorTT", ICounter.FULLY_COVERED, 1, 1); // 8. Conditional Operator assertLine("condT", ICounter.PARTLY_COVERED, 1, 1); assertLine("condF", ICounter.PARTLY_COVERED, 1, 1); // 9. Not (one case) assertLine("notT", ICounter.PARTLY_COVERED, 1, 1); assertLine("notF", ICounter.PARTLY_COVERED, 1, 1); // 10. Not (both cases) assertLine("notTF", ICounter.FULLY_COVERED, 0, 2); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/ClassFileVersionsTest.java000066400000000000000000000100741304217427400327010ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import static org.junit.Assert.assertEquals; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_SUPER; import static org.objectweb.asm.Opcodes.ALOAD; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.RETURN; import static org.objectweb.asm.Opcodes.V1_1; import static org.objectweb.asm.Opcodes.V1_2; import static org.objectweb.asm.Opcodes.V1_3; import static org.objectweb.asm.Opcodes.V1_4; import static org.objectweb.asm.Opcodes.V1_5; import static org.objectweb.asm.Opcodes.V1_6; import static org.objectweb.asm.Opcodes.V1_7; import static org.objectweb.asm.Opcodes.V1_8; import java.io.IOException; import org.jacoco.core.JaCoCo; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.internal.Java9Support; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.SystemPropertiesRuntime; import org.junit.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; /** * Test class inserted stackmap frames for different class file versions. */ public class ClassFileVersionsTest { @Test public void test_1_1() throws IOException { testVersion(V1_1, false); } @Test public void test_1_2() throws IOException { testVersion(V1_2, false); } @Test public void test_1_3() throws IOException { testVersion(V1_3, false); } @Test public void test_1_4() throws IOException { testVersion(V1_4, false); } @Test public void test_1_5() throws IOException { testVersion(V1_5, false); } @Test public void test_1_6() throws IOException { testVersion(V1_6, true); } @Test public void test_1_7() throws IOException { testVersion(V1_7, true); } @Test public void test_1_8() throws IOException { testVersion(V1_8, true); } @Test public void test_1_9() throws IOException { testVersion(Java9Support.V1_9, true); } private void testVersion(int version, boolean frames) throws IOException { final byte[] original = createClass(version); IRuntime runtime = new SystemPropertiesRuntime(); Instrumenter instrumenter = new Instrumenter(runtime); byte[] instrumented = instrumenter.instrument(original, "TestTarget"); assertFrames(instrumented, frames); } private void assertFrames(byte[] source, boolean expected) { final boolean[] hasFrames = new boolean[] { false }; new ClassReader(Java9Support.downgradeIfRequired(source)).accept( new ClassVisitor(JaCoCo.ASM_API_VERSION) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new MethodVisitor(JaCoCo.ASM_API_VERSION) { @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { hasFrames[0] = true; } }; } }, 0); assertEquals(Boolean.valueOf(expected), Boolean.valueOf(hasFrames[0])); } private byte[] createClass(int version) { ClassWriter cw = new ClassWriter(0); MethodVisitor mv; cw.visit(version, ACC_PUBLIC + ACC_SUPER, "org/jacoco/test/Sample", null, "java/lang/Object", null); mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/ClassInitializerTest.java000066400000000000000000000025451304217427400325600ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target05; import org.junit.Test; /** * Tests of static initializer in classes. */ public class ClassInitializerTest extends ValidationTestBase { public ClassInitializerTest() { super(Target05.class); } @Test public void testCoverageResult() { assertLine("const1", ICounter.EMPTY); assertLine("const2", ICounter.EMPTY); assertLine("const3", ICounter.FULLY_COVERED); assertLine("const4", ICounter.FULLY_COVERED); assertLine("field1", ICounter.FULLY_COVERED); assertLine("field2", ICounter.FULLY_COVERED); assertLine("field3", ICounter.FULLY_COVERED); assertLine("field4", ICounter.FULLY_COVERED); assertLine("staticblock", ICounter.FULLY_COVERED); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/ControlStructuresTest.java000066400000000000000000000114161304217427400330300ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target01; import org.junit.Test; /** * Tests of basic Java control structures. */ public class ControlStructuresTest extends ValidationTestBase { public ControlStructuresTest() { super(Target01.class); } @Test public void testCoverageResult() { // 1. Direct unconditional execution assertLine("unconditional", ICounter.FULLY_COVERED); // 2. Missed if block assertLine("iffalse", ICounter.FULLY_COVERED, 1, 1); assertLine("missedif", ICounter.NOT_COVERED); assertLine("executedelse", ICounter.FULLY_COVERED); // 3. Executed if block assertLine("iftrue", ICounter.FULLY_COVERED, 1, 1); assertLine("executedif", ICounter.FULLY_COVERED); assertLine("missedelse", ICounter.NOT_COVERED); // 4. Missed while block // ECJ and javac produce different status here assertLine("whilefalse", 1, 1); assertLine("missedwhile", ICounter.NOT_COVERED); // 5. Always true while block assertLine("whiletrue", ICounter.FULLY_COVERED, 1, 1); // 6. Executed while block assertLine("whiletruefalse", ICounter.FULLY_COVERED, 0, 2); assertLine("executedwhile", ICounter.FULLY_COVERED); // 7. Executed do while block assertLine("executeddowhile", ICounter.FULLY_COVERED); // 8. Missed for block assertLine("missedforincrementer", ICounter.PARTLY_COVERED, 1, 1); assertLine("missedfor", ICounter.NOT_COVERED); // 9. Executed for block assertLine("executedforincrementer", ICounter.FULLY_COVERED, 0, 2); assertLine("executedfor", ICounter.FULLY_COVERED); // 10. Missed for each block assertLine("missedforeachincrementer", ICounter.PARTLY_COVERED, 1, 1); assertLine("missedforeach", ICounter.NOT_COVERED); // 11. Executed for each block assertLine("executedforeachincrementer", ICounter.FULLY_COVERED, 0, 2); assertLine("executedforeach", ICounter.FULLY_COVERED); // 12. Table switch with hit assertLine("tswitch1", ICounter.FULLY_COVERED, 3, 1); assertLine("tswitch1case1", ICounter.NOT_COVERED); assertLine("tswitch1case2", ICounter.FULLY_COVERED); assertLine("tswitch1case3", ICounter.NOT_COVERED); assertLine("tswitch1default", ICounter.NOT_COVERED); // 13. Continued table switch with hit assertLine("tswitch2", ICounter.FULLY_COVERED, 3, 1); assertLine("tswitch2case1", ICounter.NOT_COVERED); assertLine("tswitch2case2", ICounter.FULLY_COVERED); assertLine("tswitch2case3", ICounter.FULLY_COVERED); assertLine("tswitch2default", ICounter.FULLY_COVERED); // 14. Table switch without hit assertLine("tswitch2", ICounter.FULLY_COVERED, 3, 1); assertLine("tswitch3case1", ICounter.NOT_COVERED); assertLine("tswitch3case2", ICounter.NOT_COVERED); assertLine("tswitch3case3", ICounter.NOT_COVERED); assertLine("tswitch3default", ICounter.FULLY_COVERED); // 15. Lookup switch with hit assertLine("lswitch1", ICounter.FULLY_COVERED, 3, 1); assertLine("lswitch1case1", ICounter.NOT_COVERED); assertLine("lswitch1case2", ICounter.FULLY_COVERED); assertLine("lswitch1case3", ICounter.NOT_COVERED); assertLine("lswitch1default", ICounter.NOT_COVERED); // 16. Continued lookup switch with hit assertLine("lswitch2", ICounter.FULLY_COVERED, 3, 1); assertLine("lswitch2case1", ICounter.NOT_COVERED); assertLine("lswitch2case2", ICounter.FULLY_COVERED); assertLine("lswitch2case3", ICounter.FULLY_COVERED); assertLine("lswitch2default", ICounter.FULLY_COVERED); // 17. Lookup switch without hit assertLine("lswitch3", ICounter.FULLY_COVERED, 3, 1); assertLine("lswitch3case1", ICounter.NOT_COVERED); assertLine("lswitch3case2", ICounter.NOT_COVERED); assertLine("lswitch3case3", ICounter.NOT_COVERED); assertLine("lswitch3default", ICounter.FULLY_COVERED); // 18. Break statement assertLine("executedbreak", ICounter.FULLY_COVERED); assertLine("missedafterbreak", ICounter.NOT_COVERED); // 19. Continue statement assertLine("executedcontinue", ICounter.FULLY_COVERED); assertLine("missedaftercontinue", ICounter.NOT_COVERED); // 20. Return statement assertLine("return", ICounter.FULLY_COVERED); assertLine("afterreturn", ICounter.NOT_COVERED); // 21. Implicit return assertLine("implicitreturn", ICounter.FULLY_COVERED); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/CyclomaticComplexityTest.java000066400000000000000000000160551304217427400334550ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import static org.jacoco.core.test.validation.targets.Stubs.nop; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.Collection; import org.jacoco.core.analysis.Analyzer; import org.jacoco.core.analysis.CoverageBuilder; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.analysis.IMethodCoverage; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.internal.analysis.CounterImpl; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.RuntimeData; import org.jacoco.core.runtime.SystemPropertiesRuntime; import org.jacoco.core.test.TargetLoader; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Various tests for cyclomatic complexity of methods. */ public class CyclomaticComplexityTest { public interface Target { public void test(int arg); } private RuntimeData data; private IRuntime runtime; private byte[] bytes; private Target target; @Before public void setup() throws Exception { data = new RuntimeData(); runtime = new SystemPropertiesRuntime(); runtime.startup(data); } @After public void teardown() { runtime.shutdown(); } public static class Simple implements Target { public void test(int arg) { nop(); nop(); nop(); } } @Test public void testSimple1() throws Exception { instrument(Simple.class); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(1, 0), complexity); } @Test public void testSimple2() throws Exception { instrument(Simple.class); target.test(0); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(0, 1), complexity); } public static class If implements Target { public void test(int arg) { if (arg == 0) { nop(); } } } @Test public void testIf1() throws Exception { instrument(If.class); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(2, 0), complexity); } @Test public void testIf2() throws Exception { instrument(If.class); target.test(0); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(1, 1), complexity); } @Test public void testIf3() throws Exception { instrument(If.class); target.test(0); target.test(1); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(0, 2), complexity); } public static class TwoIf implements Target { public void test(int arg) { if (arg < 0) { nop(); } if (arg > 0) { nop(); } } } @Test public void testTwoIf1() throws Exception { instrument(TwoIf.class); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(3, 0), complexity); } @Test public void testTwoIf2() throws Exception { instrument(TwoIf.class); target.test(-1); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(2, 1), complexity); } @Test public void testTwoIf3() throws Exception { instrument(TwoIf.class); target.test(-1); target.test(0); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(1, 2), complexity); } @Test public void testTwoIf4() throws Exception { instrument(TwoIf.class); target.test(-1); target.test(+1); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(0, 3), complexity); } public static class NestedIf implements Target { public void test(int arg) { if (arg >= 0) { if (arg == 0) { nop(); } nop(); } } } @Test public void testNestedIf1() throws Exception { instrument(NestedIf.class); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(3, 0), complexity); } @Test public void testNestedIf2() throws Exception { instrument(NestedIf.class); target.test(-1); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(2, 1), complexity); } @Test public void testNestedIf3() throws Exception { instrument(NestedIf.class); target.test(-1); target.test(0); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(1, 2), complexity); } @Test public void testNestedIf4() throws Exception { instrument(NestedIf.class); target.test(-1); target.test(0); target.test(+1); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(0, 3), complexity); } public static class Switch implements Target { public void test(int arg) { switch (arg) { case 1: nop(); break; case 2: nop(); break; } } } @Test public void testSwitch1() throws Exception { instrument(Switch.class); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(3, 0), complexity); } @Test public void testSwitch2() throws Exception { instrument(Switch.class); target.test(0); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(2, 1), complexity); } @Test public void testSwitch3() throws Exception { instrument(Switch.class); target.test(0); target.test(1); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(1, 2), complexity); } @Test public void testSwitch4() throws Exception { instrument(Switch.class); target.test(0); target.test(1); target.test(2); final ICounter complexity = analyze(); assertEquals(CounterImpl.getInstance(0, 3), complexity); } private void instrument(final Class clazz) throws Exception { bytes = TargetLoader.getClassDataAsBytes(clazz); final byte[] instrumented = new Instrumenter(runtime).instrument(bytes, "TestTarget"); final TargetLoader loader = new TargetLoader(); target = (Target) loader.add(clazz, instrumented).newInstance(); } private ICounter analyze() throws IOException { final CoverageBuilder builder = new CoverageBuilder(); final ExecutionDataStore store = new ExecutionDataStore(); data.collect(store, new SessionInfoStore(), false); final Analyzer analyzer = new Analyzer(store, builder); analyzer.analyzeClass(bytes, "TestTarget"); final Collection classes = builder.getClasses(); assertEquals(1, classes.size(), 0.0); final IClassCoverage classCoverage = classes.iterator().next(); for (final IMethodCoverage m : classCoverage.getMethods()) { if (m.getName().equals("test")) { return m.getComplexityCounter(); } } throw new AssertionError("No test() method."); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/ExceptionsTest.java000066400000000000000000000103621304217427400314240ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target03; import org.junit.Test; /** * Tests of exception based control flow. */ public class ExceptionsTest extends ValidationTestBase { public ExceptionsTest() { super(Target03.class); } @Test public void testCoverageResult() { // 1. Implicit Exception // Currently no coverage at all, as we don't see when a block aborts // somewhere in the middle. assertLine("implicitException.before", ICounter.FULLY_COVERED); assertLine("implicitException.exception", ICounter.NOT_COVERED); assertLine("implicitException.after", ICounter.NOT_COVERED); // 2. Explicit Exception // Full coverage, as we recognize throw statements as block boundaries. assertLine("explicitException.before", ICounter.FULLY_COVERED); assertLine("explicitException.throw", ICounter.FULLY_COVERED); // 3. Try/Catch Block Without Exception Thrown assertLine("noExceptionTryCatch.beforeBlock", ICounter.FULLY_COVERED); assertLine("noExceptionTryCatch.tryBlock", ICounter.FULLY_COVERED); assertLine("noExceptionTryCatch.catchBlock", ICounter.NOT_COVERED); // 4. Try/Catch Block With Exception Thrown Implicitly // As always with implicit exceptions we don't see when a block aborts // somewhere in the middle. assertLine("implicitExceptionTryCatch.beforeBlock", ICounter.FULLY_COVERED); assertLine("implicitExceptionTryCatch.before", ICounter.FULLY_COVERED); assertLine("implicitExceptionTryCatch.exception", ICounter.NOT_COVERED); assertLine("implicitExceptionTryCatch.after", ICounter.NOT_COVERED); assertLine("implicitExceptionTryCatch.catchBlock", ICounter.FULLY_COVERED); // 5. Try/Catch Block With Exception Thrown Implicitly After Condition // As the try/catch block is entered at one branch of the condition // should be marked as executed assertLine("implicitExceptionTryCatchAfterCondition.condition", ICounter.FULLY_COVERED, 1, 1); assertLine("implicitExceptionTryCatchAfterCondition.exception", ICounter.NOT_COVERED); assertLine("implicitExceptionTryCatchAfterCondition.catchBlock", ICounter.FULLY_COVERED); // 6. Try/Catch Block With Exception Thrown Explicitly assertLine("explicitExceptionTryCatch.beforeBlock", ICounter.FULLY_COVERED); assertLine("explicitExceptionTryCatch.before", ICounter.FULLY_COVERED); assertLine("explicitExceptionTryCatch.throw", ICounter.FULLY_COVERED); assertLine("explicitExceptionTryCatch.catchBlock", ICounter.FULLY_COVERED); // 7. Finally Block Without Exception Thrown // Finally block is yellow as the exception path is missing. assertLine("noExceptionFinally.beforeBlock", ICounter.FULLY_COVERED); assertLine("noExceptionFinally.tryBlock", ICounter.FULLY_COVERED); assertLine("noExceptionFinally.finallyBlock", ICounter.PARTLY_COVERED); // 8. Finally Block With Implicit Exception // Finally block is yellow as the non-exception path is missing. assertLine("implicitExceptionFinally.beforeBlock", ICounter.FULLY_COVERED); assertLine("implicitExceptionFinally.before", ICounter.FULLY_COVERED); assertLine("implicitExceptionFinally.exception", ICounter.NOT_COVERED); assertLine("implicitExceptionFinally.after", ICounter.NOT_COVERED); assertLine("implicitExceptionFinally.finallyBlock", ICounter.PARTLY_COVERED); // 9. Finally Block With Exception Thrown Explicitly assertLine("explicitExceptionFinally.beforeBlock", ICounter.FULLY_COVERED); assertLine("explicitExceptionFinally.before", ICounter.FULLY_COVERED); assertLine("explicitExceptionFinally.throw", ICounter.FULLY_COVERED); assertLine("explicitExceptionFinally.finallyBlock", ICounter.FULLY_COVERED); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/ExplicitInitialFrameTest.java000066400000000000000000000020071304217427400333460ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target11; import org.junit.Test; /** * Test for a methods having a explicit initial frame. */ public class ExplicitInitialFrameTest extends ValidationTestBase { public ExplicitInitialFrameTest() { super(Target11.class); } @Test public void testCoverageResult() { assertLine("dowhilebody", ICounter.FULLY_COVERED); } } FieldInitializationInTwoConstructorsTest.java000066400000000000000000000022641304217427400365730ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target09; import org.junit.Test; /** * Test of field initialization in two constructors. */ public class FieldInitializationInTwoConstructorsTest extends ValidationTestBase { public FieldInitializationInTwoConstructorsTest() { super(Target09.class); } @Test public void testCoverageResult() { assertLine("field1", ICounter.PARTLY_COVERED); assertLine("field2", ICounter.PARTLY_COVERED); assertLine("constr1", ICounter.FULLY_COVERED); assertLine("constr2", ICounter.NOT_COVERED); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/FramesTest.java000066400000000000000000000123041304217427400305160ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import org.jacoco.core.JaCoCo; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.internal.Java9Support; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.SystemPropertiesRuntime; import org.jacoco.core.test.TargetLoader; import org.jacoco.core.test.validation.targets.Target01; import org.jacoco.core.test.validation.targets.Target02; import org.jacoco.core.test.validation.targets.Target03; import org.jacoco.core.test.validation.targets.Target04; import org.jacoco.core.test.validation.targets.Target05; import org.jacoco.core.test.validation.targets.Target06; import org.jacoco.core.test.validation.targets.Target07; import org.jacoco.core.test.validation.targets.Target08; import org.jacoco.core.test.validation.targets.Target09; import org.jacoco.core.test.validation.targets.Target10; import org.jacoco.core.test.validation.targets.Target11; import org.jacoco.core.test.validation.targets.Target12; import org.junit.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.util.TraceClassVisitor; /** * Tests whether stackmap frames are correctly adjusted. */ public class FramesTest { /** * Stack sizes calculated for instrumented classes might be sometimes bigger * than actually needed. This is an acceptable tradeoff in favor of keeping * track of the actual stack sizes. For test assertions we need to replace * max stack sizes with constant value. */ private static class MaxStackEliminator extends ClassVisitor { public MaxStackEliminator(ClassVisitor cv) { super(JaCoCo.ASM_API_VERSION, cv); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { final MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); return new MethodVisitor(JaCoCo.ASM_API_VERSION, mv) { @Override public void visitMaxs(int maxStack, int maxLocals) { super.visitMaxs(-1, maxLocals); } }; } } private void testFrames(Class target) throws IOException { testFrames(TargetLoader.getClassDataAsBytes(target)); } private void testFrames(byte[] source) throws IOException { IRuntime runtime = new SystemPropertiesRuntime(); Instrumenter instrumenter = new Instrumenter(runtime); source = calculateFrames(source); byte[] actual = instrumenter.instrument(source, "TestTarget"); byte[] expected = calculateFrames(actual); assertEquals(dump(expected), dump(actual)); } private byte[] calculateFrames(byte[] source) { ClassReader rc = new ClassReader( Java9Support.downgradeIfRequired(source)); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // Adjust Version to 1.6 to enable frames: rc.accept(new ClassVisitor(JaCoCo.ASM_API_VERSION, cw) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(Opcodes.V1_6, access, name, signature, superName, interfaces); } }, 0); return cw.toByteArray(); } private String dump(byte[] bytes) { final StringWriter buffer = new StringWriter(); final PrintWriter writer = new PrintWriter(buffer); new ClassReader(bytes).accept(new MaxStackEliminator( new TraceClassVisitor(writer)), ClassReader.EXPAND_FRAMES); return buffer.toString(); } @Test public void testTarget01() throws IOException { testFrames(Target01.class); } @Test public void testTarget02() throws IOException { testFrames(Target02.class); } @Test public void testTarget03() throws IOException { testFrames(Target03.class); } @Test public void testTarget04() throws IOException { testFrames(Target04.class); } @Test public void testTarget05() throws IOException { testFrames(Target05.class); } @Test public void testTarget06() throws IOException { testFrames(Target06.class); } @Test public void testTarget07() throws IOException { testFrames(Target07.class); } @Test public void testTarget08() throws IOException { testFrames(Target08.class); } @Test public void testTarget09() throws IOException { testFrames(Target09.class); } @Test public void testTarget10() throws IOException { testFrames(Target10.class); } @Test public void testTarget11() throws IOException { testFrames(Target11.class); } @Test public void testTarget12() throws IOException { testFrames(Target12.class); } } ImplicitDefaultConstructorTest.java000066400000000000000000000020041304217427400345430ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target06; import org.junit.Test; /** * Test of a implicit default constructor. */ public class ImplicitDefaultConstructorTest extends ValidationTestBase { public ImplicitDefaultConstructorTest() { super(Target06.class); } @Test public void testCoverageResult() { assertLine("classdef", ICounter.FULLY_COVERED); } } ImplicitFieldInitializationTest.java000066400000000000000000000022671304217427400346570ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target08; import org.junit.Test; /** * Test of a implicit field initialization. */ public class ImplicitFieldInitializationTest extends ValidationTestBase { public ImplicitFieldInitializationTest() { super(Target08.class); } @Test public void testCoverageResult() { assertLine("classdef", ICounter.FULLY_COVERED); assertLine("field1", ICounter.EMPTY); assertLine("field2", ICounter.FULLY_COVERED); assertLine("field3", ICounter.EMPTY); assertLine("field4", ICounter.FULLY_COVERED); } } InterfaceClassInitializerTest.java000066400000000000000000000024411304217427400343150ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target04; import org.junit.Test; /** * Tests of static initializer in interfaces. */ public class InterfaceClassInitializerTest extends ValidationTestBase { public InterfaceClassInitializerTest() { super(Target04.class); } @Override protected void run(final Class targetClass) throws Exception { // Force class initialization targetClass.getField("CONST1").get(null); } @Test public void testCoverageResult() { assertLine("const1", ICounter.EMPTY); assertLine("const2", ICounter.EMPTY); assertLine("const3", ICounter.FULLY_COVERED); assertLine("const4", ICounter.FULLY_COVERED); } } PrivateEmptyDefaultConstructorTest.java000066400000000000000000000020741304217427400354310ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target07; import org.junit.Test; /** * Test of a private empty default constructor. */ public class PrivateEmptyDefaultConstructorTest extends ValidationTestBase { public PrivateEmptyDefaultConstructorTest() { super(Target07.class); } @Test public void testCoverageResult() { assertLine("classdef", ICounter.EMPTY); assertLine("constructor", ICounter.NOT_COVERED); } } ProbesBeforeSuperConstructorTest.java000066400000000000000000000020261304217427400350640ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.test.validation.targets.Target10; import org.junit.Test; /** * Test of probes before the super constructor call. */ public class ProbesBeforeSuperConstructorTest extends ValidationTestBase { public ProbesBeforeSuperConstructorTest() { super(Target10.class); } @Test public void testCoverageResult() { assertLine("super", ICounter.PARTLY_COVERED, 3, 1); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/Source.java000066400000000000000000000064461304217427400277130ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Reads a single source file and allows access to it through special probe * comments in the following format //$line-tag$. */ public class Source { /** * Reads the source for the given type from the given source folder relative * to the working directory. * * @param srcFolder * source folder * @param type * type to load the source file for */ public static Source getSourceFor(final String srcFolder, final Class type) throws IOException { File folder = new File(srcFolder); File file = new File(folder, type.getName().replace('.', '/') + ".java"); return new Source(new FileReader(file)); } private static final Pattern TAG_PATTERN = Pattern .compile("\\$line-(.*)\\$"); private final List lines = new ArrayList(); private final Map tags = new HashMap(); /** * Reads a source file from the given reader. * * @param reader * @throws IOException */ public Source(final Reader reader) throws IOException { final BufferedReader buffer = new BufferedReader(reader); for (String l = buffer.readLine(); l != null; l = buffer.readLine()) { addLine(l); } buffer.close(); } private void addLine(final String l) { lines.add(l); final Matcher m = TAG_PATTERN.matcher(l); if (m.find()) { final String tag = m.group(1); if (tags.put(tag, Integer.valueOf(lines.size())) != null) { throw new IllegalArgumentException("Duplicate tag: " + tag); } } } /** * Returns all lines of the source file as a list. * * @return all lines of the source file */ public List getLines() { return Collections.unmodifiableList(lines); } /** * Returns the line with the given number * * @param nr * line number (first line is 1) * @return line content */ public String getLine(int nr) { return lines.get(nr - 1); } /** * Returns the line number with the given tag * * @param tag * tag from a //$line-tag$ marker * @return line number (first line is 1) * @throws NoSuchElementException * if there is no such tag */ public int getLineNumber(String tag) throws NoSuchElementException { final Integer nr = tags.get(tag); if (nr == null) { throw new NoSuchElementException("Unknown tag: " + tag); } return nr.intValue(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/SourceTest.java000066400000000000000000000052451304217427400305470ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.NoSuchElementException; import org.junit.Test; /** * Unit tests for {@link Source}. */ public class SourceTest { @Test public void testGetLines1() throws IOException { String src = "\na\nbb\n"; final Source s = new Source(new StringReader(src)); assertEquals(Arrays.asList("", "a", "bb"), s.getLines()); } @Test public void testGetLines2() throws IOException { String src = "aa\nbb\n;"; final Source s = new Source(new StringReader(src)); assertEquals(Arrays.asList("aa", "bb", ";"), s.getLines()); } @Test public void testGetLines3() throws IOException { String src = "xx\r\nyy"; final Source s = new Source(new StringReader(src)); assertEquals(Arrays.asList("xx", "yy"), s.getLines()); } @Test public void testGetLine() throws IOException { String src = "Hello\n\nWorld!"; final Source s = new Source(new StringReader(src)); assertEquals("Hello", s.getLine(1)); assertEquals("", s.getLine(2)); assertEquals("World!", s.getLine(3)); } @Test public void testGetLineNumber() throws IOException { String src = "a\nb$line-tag$\nc\nd\ne$line-tagx$\nf"; final Source s = new Source(new StringReader(src)); assertEquals(2, s.getLineNumber("tag"), 0.0); } @Test(expected = NoSuchElementException.class) public void testGetLineNumberNegative() throws IOException { String src = "a\nb$line-tag$\nc\nd\ne\nf"; final Source s = new Source(new StringReader(src)); s.getLineNumber("ag"); } @Test(expected = IllegalArgumentException.class) public void testDuplicateTag() throws IOException { String src = "a\nb$line-tag$\nc\nd\ne$line-tag$\nf"; new Source(new StringReader(src)); } @Test public void testGetSourceFor() throws IOException { final Source s = Source.getSourceFor("src", SourceTest.class); // Here we are. $line-testGetSourceFor$ final String l = s.getLine(s.getLineNumber("testGetSourceFor")); assertTrue(l, l.contains("Here we are.")); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/StructuredLockingTest.java000066400000000000000000000136471304217427400327670ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.internal.Java9Support; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.SystemPropertiesRuntime; import org.jacoco.core.test.TargetLoader; import org.jacoco.core.test.validation.targets.Target12; import org.junit.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TryCatchBlockNode; import org.objectweb.asm.tree.VarInsnNode; import org.objectweb.asm.tree.analysis.Analyzer; import org.objectweb.asm.tree.analysis.AnalyzerException; import org.objectweb.asm.tree.analysis.BasicInterpreter; import org.objectweb.asm.tree.analysis.BasicValue; import org.objectweb.asm.tree.analysis.Frame; import org.objectweb.asm.tree.analysis.Interpreter; /** * Tests that the invariants specified in chapter 2.11.10 of the JVM Spec do * also hold for instrumented classes. Note that only some runtimes like Android * ART do actually check these invariants. * * https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11.10 */ public class StructuredLockingTest { @Test public void testTarget12() throws Exception { testMonitorExit(Target12.class); } private void testMonitorExit(Class target) throws Exception { assertStructuredLocking(TargetLoader.getClassDataAsBytes(target)); } private void assertStructuredLocking(byte[] source) throws Exception { IRuntime runtime = new SystemPropertiesRuntime(); Instrumenter instrumenter = new Instrumenter(runtime); byte[] instrumented = instrumenter.instrument(source, "TestTarget"); ClassNode cn = new ClassNode(); new ClassReader(Java9Support.downgradeIfRequired(instrumented)) .accept(cn, 0); for (MethodNode mn : cn.methods) { assertStructuredLocking(cn.name, mn); } } private void assertStructuredLocking(String owner, MethodNode mn) throws Exception { Analyzer analyzer = new Analyzer( new BasicInterpreter()) { @Override protected Frame newFrame(int nLocals, int nStack) { return new LockFrame(nLocals, nStack); } @Override protected Frame newFrame(Frame src) { return new LockFrame(src); } }; Frame[] frames = analyzer.analyze(owner, mn); // Make sure no locks are left when method exits: for (int i = 0; i < frames.length; i++) { AbstractInsnNode insn = mn.instructions.get(i); switch (insn.getOpcode()) { case Opcodes.IRETURN: case Opcodes.LRETURN: case Opcodes.FRETURN: case Opcodes.DRETURN: case Opcodes.ARETURN: case Opcodes.RETURN: ((LockFrame) frames[i]).assertNoLock("Exit with lock"); break; case Opcodes.ATHROW: List handlers = analyzer.getHandlers(i); if (handlers == null || handlers.isEmpty()) { ((LockFrame) frames[i]).assertNoLock("Exit with lock"); } break; } } // Only instructions protected by a catch-all handler can hold locks: for (int i = 0; i < frames.length; i++) { AbstractInsnNode insn = mn.instructions.get(i); if (insn.getOpcode() > 0) { boolean catchAll = false; List handlers = analyzer.getHandlers(i); if (handlers != null) { for (TryCatchBlockNode node : handlers) { catchAll |= node.type == null; } } if (!catchAll) { ((LockFrame) frames[i]) .assertNoLock("No handlers for insn with lock"); } } } } /** * A Frame implementation that keeps track of the locking state. It is * assumed that the monitor objects are stored in local variables. */ private static class LockFrame extends Frame { Set locks; public LockFrame(final int nLocals, final int nStack) { super(nLocals, nStack); locks = new HashSet(); } public LockFrame(Frame src) { super(src); } @Override public Frame init(Frame src) { locks = new HashSet(((LockFrame) src).locks); return super.init(src); } @Override public void execute(AbstractInsnNode insn, Interpreter interpreter) throws AnalyzerException { super.execute(insn, interpreter); switch (insn.getOpcode()) { case Opcodes.MONITORENTER: // Lock is stored in a local variable: enter(((VarInsnNode) insn.getPrevious()).var); break; case Opcodes.MONITOREXIT: // Lock is stored in a local variable: exit(((VarInsnNode) insn.getPrevious()).var); break; } } void enter(int lock) { assertTrue("multiple ENTER for lock " + lock, locks.add(Integer.valueOf(lock))); } void exit(int lock) { assertTrue("invalid EXIT for lock " + lock, locks.remove(Integer.valueOf(lock))); } @Override public boolean merge(Frame frame, Interpreter interpreter) throws AnalyzerException { this.locks.addAll(((LockFrame) frame).locks); return super.merge(frame, interpreter); } void assertNoLock(String message) { assertEquals(message, Collections.emptySet(), locks); } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/ValidationTestBase.java000066400000000000000000000113031304217427400321640ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import org.jacoco.core.analysis.Analyzer; import org.jacoco.core.analysis.CoverageBuilder; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.analysis.ILine; import org.jacoco.core.analysis.ISourceFileCoverage; import org.jacoco.core.data.ExecutionData; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.internal.analysis.CounterImpl; import org.jacoco.core.test.InstrumentingLoader; import org.jacoco.core.test.TargetLoader; import org.jacoco.core.test.validation.targets.Stubs; import org.junit.Before; /** * Base class for validation tests. It executes the given class under code * coverage and provides the coverage results for validation. */ public abstract class ValidationTestBase { private static final String[] STATUS_NAME = new String[4]; { STATUS_NAME[ICounter.EMPTY] = "EMPTY"; STATUS_NAME[ICounter.NOT_COVERED] = "NOT_COVERED"; STATUS_NAME[ICounter.FULLY_COVERED] = "FULLY_COVERED"; STATUS_NAME[ICounter.PARTLY_COVERED] = "PARTLY_COVERED"; } private final String srcFolder; private final Class target; private ISourceFileCoverage sourceCoverage; private Source source; private InstrumentingLoader loader; protected ValidationTestBase(final String srcFolder, final Class target) { this.srcFolder = srcFolder; this.target = target; } protected ValidationTestBase(final Class target) { this("src", target); } @Before public void setup() throws Exception { final ExecutionDataStore store = execute(); analyze(store); source = Source.getSourceFor(srcFolder, target); } private ExecutionDataStore execute() throws Exception { loader = new InstrumentingLoader(target); run(loader.loadClass(target.getName())); return loader.collect(); } protected void run(final Class targetClass) throws Exception { targetClass.getMethod("main", String[].class).invoke(null, (Object) new String[0]); } private void analyze(final ExecutionDataStore store) throws IOException { final CoverageBuilder builder = new CoverageBuilder(); final Analyzer analyzer = new Analyzer(store, builder); for (ExecutionData data : store.getContents()) { analyze(analyzer, data); } String srcName = target.getName().replace('.', '/') + ".java"; for (ISourceFileCoverage file : builder.getSourceFiles()) { if (srcName.equals(file.getPackageName() + "/" + file.getName())) { sourceCoverage = file; return; } } fail("No source node found for " + srcName); } private void analyze(final Analyzer analyzer, final ExecutionData data) throws IOException { final byte[] bytes = TargetLoader.getClassDataAsBytes( target.getClassLoader(), data.getName()); analyzer.analyzeClass(bytes, data.getName()); } protected void assertLine(final String tag, final int status) { final int nr = source.getLineNumber(tag); final ILine line = sourceCoverage.getLine(nr); final String msg = String.format("Status in line %s: %s", Integer.valueOf(nr), source.getLine(nr)); final int insnStatus = line.getInstructionCounter().getStatus(); assertEquals(msg, STATUS_NAME[status], STATUS_NAME[insnStatus]); } protected void assertLine(final String tag, final int missedBranches, final int coveredBranches) { final int nr = source.getLineNumber(tag); final ILine line = sourceCoverage.getLine(nr); final String msg = String.format("Branches in line %s: %s", Integer.valueOf(nr), source.getLine(nr)); assertEquals(msg + " branches", CounterImpl.getInstance(missedBranches, coveredBranches), line.getBranchCounter()); } protected void assertLine(final String tag, final int status, final int missedBranches, final int coveredBranches) { assertLine(tag, status); assertLine(tag, missedBranches, coveredBranches); } protected void assertLogEvents(String... events) throws Exception { final Method getter = Class.forName(Stubs.class.getName(), false, loader).getMethod("getLogEvents"); assertEquals("Log events", Arrays.asList(events), getter.invoke(null)); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/000077500000000000000000000000001304217427400272475ustar00rootroot00000000000000AnnotationInitializer.java000066400000000000000000000014521304217427400343530ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; /** * This test target is an annotation with an initializer. */ public @interface AnnotationInitializer { Object CONST = new Object(); // $line-const$ int value() default 0; // $line-value$ } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/BadCycleClass.java000066400000000000000000000021071304217427400325460ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; public class BadCycleClass { public static class Base { static final Child b = new Child(); static { b.someMethod(); } } public static class Child extends Base { static { Stubs.logEvent("childclinit"); // $line-childclinit$ } public Child() { Stubs.logEvent("childinit"); // $line-childinit$ } void someMethod() { Stubs.logEvent("childsomeMethod"); // $line-childsomeMethod$ } } public static void main(String[] args) { new Child(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Stubs.java000066400000000000000000000051111304217427400312100ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import java.util.ArrayList; import java.util.List; /** * Collection of stub methods that are called from the coverage targets. * */ public class Stubs { /** * Exception stub. */ public static class StubException extends RuntimeException { static final long serialVersionUID = 0L; } /** * Superclass stub. */ public static class SuperClass { public SuperClass(boolean arg) { } } /** * Dummy method. */ public static void nop() { } /** * Dummy method. */ public static void nop(int i) { } /** * Dummy method. */ public static void nop(boolean b) { } /** * Dummy method. */ public static void nop(Object o) { } /** * @return always true */ public static boolean t() { return true; } /** * @return always false */ public static boolean f() { return false; } /** * @return always 1 */ public static int i1() { return 1; } /** * @return always 3 */ public static int i2() { return 2; } /** * @return always 3 */ public static int i3() { return 3; } /** * Always throws a {@link RuntimeException}. * * @throws StubException * always thrown */ public static void ex() throws StubException { throw new StubException(); } /** * Directly executes the given runnable. */ public static void exec(Runnable task) { task.run(); } /** * Never executes the given runnable. */ public static void noexec(Runnable task) { } /** * List of logged events. Using a static member here works as this class is * loaded in a new class loader for every test case. */ private static List events = new ArrayList(); /** * Records a event with the given id for later verification. */ public static void logEvent(String id) { events.add(id); } /** * Returns a list of all recorded events in the sequence of recording. */ public static List getLogEvents() { return events; } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target01.java000066400000000000000000000111071304217427400315010ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.f; import static org.jacoco.core.test.validation.targets.Stubs.i2; import static org.jacoco.core.test.validation.targets.Stubs.nop; import static org.jacoco.core.test.validation.targets.Stubs.t; import java.util.Collections; /** * This target exercises a set of common Java control structures. */ public class Target01 { public static void main(String[] args) { // 1. Unconditional execution nop(); // $line-unconditional$ // 2. Missed if block if (f()) { // $line-iffalse$ nop(); // $line-missedif$ } else { nop(); // $line-executedelse$ } // 3. Executed if block if (t()) { // $line-iftrue$ nop(); // $line-executedif$ } else { nop(); // $line-missedelse$ } // 4. Missed while block while (f()) { // $line-whilefalse$ nop(); // $line-missedwhile$ } // 5. Always executed while block while (t()) { // $line-whiletrue$ if (t()) { break; } } // 6. Executed while block int i = 0; while (i++ < 3) { // $line-whiletruefalse$ nop(); // $line-executedwhile$ } // 7. Executed do while block do { nop(); // $line-executeddowhile$ } while (f()); // 8. Missed for block for (nop(); f(); nop()) { // $line-missedforincrementer$ nop(); // $line-missedfor$ } // 9. Executed for block for (int j = 0; j < 1; j++) { // $line-executedforincrementer$ nop(); // $line-executedfor$ } // 10. Missed for each block for (Object o : Collections.emptyList()) { // $line-missedforeachincrementer$ nop(o); // $line-missedforeach$ } // 11. Executed for each block for (Object o : Collections.singleton(new Object())) { // $line-executedforeachincrementer$ nop(o); // $line-executedforeach$ } // 12. Table switch with hit switch (i2()) { // $line-tswitch1$ case 1: nop(); // $line-tswitch1case1$ break; case 2: nop(); // $line-tswitch1case2$ break; case 3: nop(); // $line-tswitch1case3$ break; default: nop(); // $line-tswitch1default$ break; } // 13. Continued table switch with hit switch (i2()) { // $line-tswitch2$ case 1: nop(); // $line-tswitch2case1$ case 2: nop(); // $line-tswitch2case2$ case 3: nop(); // $line-tswitch2case3$ default: nop(); // $line-tswitch2default$ } // 14. Table switch without hit switch (i2()) { // $line-tswitch3$ case 3: nop(); // $line-tswitch3case1$ break; case 4: nop(); // $line-tswitch3case2$ break; case 5: nop(); // $line-tswitch3case3$ break; default: nop(); // $line-tswitch3default$ break; } // 15. Lookup switch with hit switch (i2()) { // $line-lswitch1$ case -123: nop(); // $line-lswitch1case1$ break; case 2: nop(); // $line-lswitch1case2$ break; case 456: nop(); // $line-lswitch1case3$ break; default: nop(); // $line-lswitch1default$ break; } // 16. Continued lookup switch with hit switch (i2()) { // $line-lswitch2$ case -123: nop(); // $line-lswitch2case1$ case 2: nop(); // $line-lswitch2case2$ case 456: nop(); // $line-lswitch2case3$ default: nop(); // $line-lswitch2default$ } // 17. Lookup switch without hit switch (i2()) { // $line-lswitch3$ case -123: nop(); // $line-lswitch3case1$ break; case 456: nop(); // $line-lswitch3case2$ break; case 789: nop(); // $line-lswitch3case3$ break; default: nop(); // $line-lswitch3default$ break; } // 18. Break statement while (true) { if (t()) { break; // $line-executedbreak$ } nop(); // $line-missedafterbreak$ } // 19. Continue statement for (int j = 0; j < 1; j++) { if (t()) { continue; // $line-executedcontinue$ } nop(); // $line-missedaftercontinue$ } runReturn(); runImplicitReturn(); } private static void runReturn() { // 20. Return statement if (t()) { return; // $line-return$ } nop(); // $line-afterreturn$ } private static void runImplicitReturn() { // 21. Implicit return } // $line-implicitreturn$ } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target02.java000066400000000000000000000052621304217427400315070ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.f; import static org.jacoco.core.test.validation.targets.Stubs.i1; import static org.jacoco.core.test.validation.targets.Stubs.i2; import static org.jacoco.core.test.validation.targets.Stubs.nop; import static org.jacoco.core.test.validation.targets.Stubs.t; /** * This target exercises boolean expressions. */ public class Target02 { public static void main(String[] args) { // 1. Boolean comparison result (one case) nop(i2() > 3); // $line-booleancmp1$ // 2. Boolean comparison result (both cases) for (int i = 0; i < 2; i++) { nop(i < 1); // $line-booleancmp2$ } // 3. And if (f() & f()) { // $line-andFF$ nop(); } if (f() & t()) { // $line-andFT$ nop(); } if (t() & f()) { // $line-andTF$ nop(); } if (t() & t()) { // $line-andTT$ nop(); } // 4. Conditional And if (f() && f()) { // $line-conditionalandFF$ nop(); } if (f() && t()) { // $line-conditionalandFT$ nop(); } if (t() && f()) { // $line-conditionalandTF$ nop(); } if (t() && t()) { // $line-conditionalandTT$ nop(); } // 5. Or if (f() | f()) { // $line-orFF$ nop(); } if (f() | t()) { // $line-orFT$ nop(); } if (t() | f()) { // $line-orTF$ nop(); } if (t() | t()) { // $line-orTT$ nop(); } // 6. Conditional Or if (f() || f()) { // $line-conditionalorFF$ nop(); } if (f() || t()) { // $line-conditionalorFT$ nop(); } if (t() || f()) { // $line-conditionalorTF$ nop(); } if (t() || t()) { // $line-conditionalorTT$ nop(); } // 7. Exclusive Or if (f() ^ f()) { // $line-xorFF$ nop(); } if (f() ^ t()) { // $line-xorFT$ nop(); } if (t() ^ f()) { // $line-xorTF$ nop(); } if (t() ^ t()) { // $line-xorTT$ nop(); } // 8. Conditional Operator nop(t() ? i1() : i2()); // $line-condT$ nop(f() ? i1() : i2()); // $line-condF$ // 9. Not (one case) nop(!t()); // $line-notT$ nop(!f()); // $line-notF$ // 10. Not (both cases) for (boolean b : new boolean[] { true, false }) { nop(!b); // $line-notTF$ } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target03.java000066400000000000000000000101641304217427400315050ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.ex; import static org.jacoco.core.test.validation.targets.Stubs.f; import static org.jacoco.core.test.validation.targets.Stubs.nop; import org.jacoco.core.test.validation.targets.Stubs.StubException; /** * This target produces exception based control flow examples. */ public class Target03 { public static void main(String[] args) { try { implicitException(); } catch (StubException e) { } try { explicitException(); } catch (StubException e) { } noExceptionTryCatch(); implicitExceptionTryCatch(); implicitExceptionTryCatchAfterCondition(); explicitExceptionTryCatch(); noExceptionFinally(); try { explicitExceptionFinally(); } catch (StubException e) { } try { implicitExceptionFinally(); } catch (StubException e) { } } private static void implicitException() { nop(); // $line-implicitException.before$ ex(); // $line-implicitException.exception$ nop(); // $line-implicitException.after$ } private static void explicitException() { nop(); // $line-explicitException.before$ throw new StubException(); // $line-explicitException.throw$ } private static void noExceptionTryCatch() { nop(); // $line-noExceptionTryCatch.beforeBlock$ try { nop(); // $line-noExceptionTryCatch.tryBlock$ } catch (StubException e) { // $line-noExceptionTryCatch.catch$ nop(); // $line-noExceptionTryCatch.catchBlock$ } } private static void implicitExceptionTryCatch() { nop(); // $line-implicitExceptionTryCatch.beforeBlock$ try { nop(); // $line-implicitExceptionTryCatch.before$ ex(); // $line-implicitExceptionTryCatch.exception$ nop(); // $line-implicitExceptionTryCatch.after$ } catch (StubException e) { // $line-implicitExceptionTryCatch.catch$ nop(); // $line-implicitExceptionTryCatch.catchBlock$ } } private static void implicitExceptionTryCatchAfterCondition() { if (f()) { // $line-implicitExceptionTryCatchAfterCondition.condition$ return; } try { ex(); // $line-implicitExceptionTryCatchAfterCondition.exception$ } catch (StubException e) { nop(); // $line-implicitExceptionTryCatchAfterCondition.catchBlock$ } } private static void explicitExceptionTryCatch() { nop(); // $line-explicitExceptionTryCatch.beforeBlock$ try { nop(); // $line-explicitExceptionTryCatch.before$ throw new StubException(); // $line-explicitExceptionTryCatch.throw$ } catch (StubException e) { // $line-explicitExceptionTryCatch.catch$ nop(); // $line-explicitExceptionTryCatch.catchBlock$ } } private static void noExceptionFinally() { nop(); // $line-noExceptionFinally.beforeBlock$ try { nop(); // $line-noExceptionFinally.tryBlock$ } finally { // $line-noExceptionFinallyFinally$ nop(); // $line-noExceptionFinally.finallyBlock$ } } private static void implicitExceptionFinally() { nop(); // $line-implicitExceptionFinally.beforeBlock$ try { nop(); // $line-implicitExceptionFinally.before$ ex(); // $line-implicitExceptionFinally.exception$ nop(); // $line-implicitExceptionFinally.after$ } finally { // $line-implicitExceptionFinally.finally$ nop(); // $line-implicitExceptionFinally.finallyBlock$ } } private static void explicitExceptionFinally() { nop(); // $line-explicitExceptionFinally.beforeBlock$ try { nop(); // $line-explicitExceptionFinally.before$ throw new StubException(); // $line-explicitExceptionFinally.throw$ } finally { // $line-explicitExceptionFinally.finally$ nop(); // $line-explicitExceptionFinally.finallyBlock$ } } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target04.java000066400000000000000000000021171304217427400315050ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.i1; /** * This test target is an interface with a class initializer. */ public interface Target04 { // No code required to initialize these fields: static final int CONST1 = 12345; // $line-const1$ static final String CONST2 = "const"; // $line-const2$ // These fields are initialized within static final int CONST3 = i1(); // $line-const3$ static final Object CONST4 = new Object(); // $line-const4$ } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target05.java000066400000000000000000000027131304217427400315100ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.i1; /** * This test target is a class with a static initializer. */ public class Target05 { // $line-classdef$ // No code required to initialize these fields: public static final int CONST1 = 3; // $line-const1$ public static final String CONST2 = "Hello"; // $line-const2$ // These fields are initialized within public static final int CONST3 = i1(); // $line-const3$ public static final Object CONST4 = new Object(); // $line-const4$ public static int field1 = 3; // $line-field1$ public static String field2 = "Hello"; // $line-field2$ public static int field3 = i1(); // $line-field3$ public static Object field4 = new Object(); // $line-field4$ static { Stubs.nop(); // $line-staticblock$ } private Target05() { } public static void main(String[] args) { } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target06.java000066400000000000000000000014411304217427400315060ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; /** * This test target is a class with a implicit default constructor. */ public class Target06 { // $line-classdef$ public static void main(String[] args) { new Target06(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target07.java000066400000000000000000000014671304217427400315170ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; /** * This test target is a private empty default constructor. */ public class Target07 { // $line-classdef$ private Target07() { } // $line-constructor$ public static void main(String[] args) { } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target08.java000066400000000000000000000016621304217427400315150ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; /** * This test target has instance members with implicit initializers. */ public class Target08 { // $line-classdef$ Object field1; // $line-field1$ Object field2 = this; // $line-field2$ int field3; // $line-field3$ int field4 = 2000; // $line-field4$ public static void main(String[] args) { new Target08(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target09.java000066400000000000000000000017151304217427400315150ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; /** * This test target has instance members with initialization in two * constructors. */ public class Target09 { Object field1 = null; // $line-field1$ int field2 = 123; // $line-field2$ public Target09() { } // $line-constr1$ public Target09(String arg) { } // $line-constr2$ public static void main(String[] args) { new Target09(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target10.java000066400000000000000000000021201304217427400314740ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.f; import static org.jacoco.core.test.validation.targets.Stubs.t; import org.jacoco.core.test.validation.targets.Stubs.SuperClass; /** * This test target has a constructor containing control structures before the * superclass constructor is called. */ public class Target10 extends SuperClass { public Target10() { super(t() || f()); // $line-super$ } public static void main(String[] args) { new Target10(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target11.java000066400000000000000000000017351304217427400315100ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.f; import static org.jacoco.core.test.validation.targets.Stubs.nop; /** * This test target needs an explicit initial frame as the first instruction * already is a jump target. */ public class Target11 { public static void main(String[] args) { do { nop(); // $line-dowhilebody$ } while (f()); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/test/validation/targets/Target12.java000066400000000000000000000021721304217427400315050ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.test.validation.targets; import static org.jacoco.core.test.validation.targets.Stubs.nop; /** * This target uses synchronized blocks which compile to try/catch statements. */ public class Target12 { static void simple() { Object lock1 = new Object(); synchronized (lock1) { nop(); } } static void nested() { Object lock1 = new Object(); synchronized (lock1) { nop(); Object lock2 = new Object(); synchronized (lock2) { nop(); } nop(); } } public static void main(String[] args) { simple(); nested(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/tools/000077500000000000000000000000001304217427400236255ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/tools/ExecDumpClientTest.java000066400000000000000000000106171304217427400302060ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.tools; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jacoco.core.data.SessionInfo; import org.jacoco.core.runtime.IRemoteCommandVisitor; import org.jacoco.core.runtime.RemoteControlReader; import org.jacoco.core.runtime.RemoteControlWriter; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link ExecDumpClient}. */ public class ExecDumpClientTest { private ExecDumpClient client; private List callbacks; private boolean dumpRequested; private boolean resetRequested; private ServerSocket server; @Before public void setup() { callbacks = new ArrayList(); client = new ExecDumpClient() { @Override protected void onConnecting(InetAddress address, int port) { callbacks.add("onConnecting"); } @Override protected void onConnectionFailure(IOException exception) { callbacks.add("onConnectionFailure"); } }; } @After public void teardown() throws IOException { if (server != null) { server.close(); } } @Test public void testNoRetries() throws IOException { try { client.dump((String) null, getFreePort()); fail("ConnectException expected"); } catch (ConnectException e) { // expected } assertEquals(Arrays.asList("onConnecting"), callbacks); } @Test public void testWithRetries() throws IOException { client.setRetryCount(3); client.setRetryDelay(0); try { client.dump((String) null, getFreePort()); fail("ConnectException expected"); } catch (ConnectException e) { // expected } assertEquals(Arrays.asList( // Initial attempt "onConnecting", // 1. Retry "onConnectionFailure", "onConnecting", // 2. Retry "onConnectionFailure", "onConnecting", // 3. Retry "onConnectionFailure", "onConnecting") , callbacks); } @Test public void testDump() throws IOException { int port = createExecServer(); ExecFileLoader loader = client.dump((String) null, port); assertTrue(dumpRequested); assertFalse(resetRequested); List infos = loader.getSessionInfoStore().getInfos(); assertEquals(1, infos.size()); assertEquals("TestId", infos.get(0).getId()); } @Test public void testReset() throws IOException { int port = createExecServer(); client.setDump(false); client.setReset(true); client.dump((String) null, port); assertFalse(dumpRequested); assertTrue(resetRequested); } private int getFreePort() throws IOException { final ServerSocket server = new ServerSocket(0, 0, InetAddress.getByName(null)); final int port = server.getLocalPort(); server.close(); return port; } private int createExecServer() throws IOException { server = new ServerSocket(0, 0, InetAddress.getByName(null)); new Thread(new Runnable() { public void run() { try { handleConnection(server.accept()); } catch (IOException e) { // ignore } } }).start(); return server.getLocalPort(); } private void handleConnection(Socket socket) throws IOException { final RemoteControlWriter writer = new RemoteControlWriter( socket.getOutputStream()); final RemoteControlReader reader = new RemoteControlReader( socket.getInputStream()); reader.setRemoteCommandVisitor(new IRemoteCommandVisitor() { public void visitDumpCommand(boolean dump, boolean reset) throws IOException { dumpRequested = dump; resetRequested = reset; if (dump) { writer.visitSessionInfo(new SessionInfo("TestId", 100, 200)); } writer.sendCmdOk(); } }); reader.read(); } } jacoco-0.7.8/org.jacoco.core.test/src/org/jacoco/core/tools/ExecFileLoaderTest.java000066400000000000000000000111231304217427400301410ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.tools; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.jacoco.core.data.ExecutionData; import org.jacoco.core.data.ExecutionDataReader; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.ExecutionDataWriter; import org.jacoco.core.data.SessionInfo; import org.jacoco.core.data.SessionInfoStore; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Unit tests for {@link ExecFileLoader}. */ public class ExecFileLoaderTest { @Rule public final TemporaryFolder sourceFolder = new TemporaryFolder(); private ExecFileLoader loader; @Before public void setup() { loader = new ExecFileLoader(); } @Test public void testLoadFile() throws IOException { loader.load(createFile("a")); loader.load(createFile("bb")); assertLoaderContents("a", "bb"); } @Test public void testLoadInputStream() throws IOException { final FileInputStream in1 = new FileInputStream(createFile("a")); loader.load(in1); in1.close(); final FileInputStream in2 = new FileInputStream(createFile("bb")); loader.load(in2); in2.close(); assertLoaderContents("a", "bb"); } @Test(expected = IOException.class) public void testLoadBrokenContent() throws IOException { final File file = new File(sourceFolder.getRoot(), "broken.exec"); final FileWriter writer = new FileWriter(file); writer.write("Invalid Content"); writer.close(); loader.load(file); } @Test public void testSaveFile() throws IOException { final File file = new File(sourceFolder.getRoot(), "target.exec"); // Write invalid data to ensure the file is actually overwritten: final OutputStream out = new FileOutputStream(file); out.write("invalid".getBytes()); out.close(); loader.load(createFile("a")); loader.save(file, false); assertFileContents(file, "a"); } @Test public void testSaveFileAppend() throws IOException { final File file = createFile("a"); loader.load(createFile("bb")); loader.save(file, true); assertFileContents(file, "a", "bb"); } @Test public void testCreateSubfolders() throws IOException { final File file = new File(sourceFolder.getRoot(), "a/b/c/target.exec"); loader.load(createFile("a")); loader.save(file, true); assertFileContents(file, "a"); } private File createFile(String id) throws IOException { final File file = new File(sourceFolder.getRoot(), id + ".exec"); final FileOutputStream out = new FileOutputStream(file); final ExecutionDataWriter writer = new ExecutionDataWriter(out); final int value = id.length(); writer.visitClassExecution(new ExecutionData(value, id, new boolean[] { true })); writer.visitSessionInfo(new SessionInfo(id, value, value)); out.close(); return file; } private void assertLoaderContents(String... expected) { assertContents(loader.getExecutionDataStore(), loader.getSessionInfoStore(), expected); } private void assertFileContents(File file, String... expected) throws IOException { final InputStream in = new FileInputStream(file); final ExecutionDataStore execStore = new ExecutionDataStore(); final SessionInfoStore sessionStore = new SessionInfoStore(); final ExecutionDataReader reader = new ExecutionDataReader(in); reader.setExecutionDataVisitor(execStore); reader.setSessionInfoVisitor(sessionStore); reader.read(); assertContents(execStore, sessionStore, expected); } private void assertContents(ExecutionDataStore execStore, SessionInfoStore sessionStore, String... expected) { final List infos = sessionStore.getInfos(); assertEquals(expected.length, execStore.getContents().size()); assertEquals(expected.length, infos.size()); int idx = 0; for (String id : expected) { assertEquals(id, execStore.get(id.length()).getName()); assertEquals(id, infos.get(idx++).getId()); } } } jacoco-0.7.8/org.jacoco.core/000077500000000000000000000000001304217427400157435ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/.classpath000066400000000000000000000014151304217427400177270ustar00rootroot00000000000000 jacoco-0.7.8/org.jacoco.core/.gitignore000066400000000000000000000000151304217427400177270ustar00rootroot00000000000000/target /bin jacoco-0.7.8/org.jacoco.core/.project000066400000000000000000000010671304217427400174160ustar00rootroot00000000000000 org.jacoco.core org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.m2e.core.maven2Nature org.eclipse.jdt.core.javanature jacoco-0.7.8/org.jacoco.core/.settings/000077500000000000000000000000001304217427400176615ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/.settings/org.eclipse.core.resources.prefs000066400000000000000000000001121304217427400260660ustar00rootroot00000000000000eclipse.preferences.version=1 encoding/=UTF-8 encoding/src=UTF-8 jacoco-0.7.8/org.jacoco.core/.settings/org.eclipse.jdt.core.prefs000066400000000000000000000654061304217427400246560ustar00rootroot00000000000000#Sat Sep 05 17:45:34 CEST 2009 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=warning org.eclipse.jdt.core.compiler.problem.deprecation=warning org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=error org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=public org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingJavadocComments=warning org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=protected org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=no_tag org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=protected org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning org.eclipse.jdt.core.compiler.problem.unusedParameter=warning org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.5 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_assignment=0 org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 org.eclipse.jdt.core.formatter.blank_lines_after_package=1 org.eclipse.jdt.core.formatter.blank_lines_before_field=0 org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 org.eclipse.jdt.core.formatter.blank_lines_before_method=1 org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 org.eclipse.jdt.core.formatter.blank_lines_before_package=0 org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false org.eclipse.jdt.core.formatter.comment.format_block_comments=true org.eclipse.jdt.core.formatter.comment.format_header=false org.eclipse.jdt.core.formatter.comment.format_html=true org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true org.eclipse.jdt.core.formatter.comment.format_line_comments=true org.eclipse.jdt.core.formatter.comment.format_source_code=true org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true org.eclipse.jdt.core.formatter.comment.indent_root_tags=true org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert org.eclipse.jdt.core.formatter.comment.line_length=80 org.eclipse.jdt.core.formatter.compact_else_if=true org.eclipse.jdt.core.formatter.continuation_indentation=2 org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_empty_lines=false org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false org.eclipse.jdt.core.formatter.indentation.size=4 org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false org.eclipse.jdt.core.formatter.lineSplit=80 org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true org.eclipse.jdt.core.formatter.tabulation.char=tab org.eclipse.jdt.core.formatter.tabulation.size=4 org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true jacoco-0.7.8/org.jacoco.core/.settings/org.eclipse.jdt.ui.prefs000066400000000000000000000055111304217427400243320ustar00rootroot00000000000000#Thu Jul 02 08:43:37 CEST 2009 eclipse.preferences.version=1 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true formatter_profile=org.eclipse.jdt.ui.default.eclipse_profile formatter_settings_version=11 org.eclipse.jdt.ui.text.custom_code_templates= sp_cleanup.add_default_serial_version_id=true sp_cleanup.add_generated_serial_version_id=false sp_cleanup.add_missing_annotations=true sp_cleanup.add_missing_deprecated_annotations=true sp_cleanup.add_missing_methods=false sp_cleanup.add_missing_nls_tags=false sp_cleanup.add_missing_override_annotations=true sp_cleanup.add_serial_version_id=false sp_cleanup.always_use_blocks=true sp_cleanup.always_use_parentheses_in_expressions=false sp_cleanup.always_use_this_for_non_static_field_access=false sp_cleanup.always_use_this_for_non_static_method_access=false sp_cleanup.convert_to_enhanced_for_loop=false sp_cleanup.correct_indentation=false sp_cleanup.format_source_code=true sp_cleanup.format_source_code_changes_only=false sp_cleanup.make_local_variable_final=true sp_cleanup.make_parameters_final=true sp_cleanup.make_private_fields_final=true sp_cleanup.make_type_abstract_if_missing_method=false sp_cleanup.make_variable_declarations_final=true sp_cleanup.never_use_blocks=false sp_cleanup.never_use_parentheses_in_expressions=true sp_cleanup.on_save_use_additional_actions=true sp_cleanup.organize_imports=true sp_cleanup.qualify_static_field_accesses_with_declaring_class=false sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true sp_cleanup.qualify_static_member_accesses_with_declaring_class=false sp_cleanup.qualify_static_method_accesses_with_declaring_class=false sp_cleanup.remove_private_constructors=true sp_cleanup.remove_trailing_whitespaces=false sp_cleanup.remove_trailing_whitespaces_all=true sp_cleanup.remove_trailing_whitespaces_ignore_empty=false sp_cleanup.remove_unnecessary_casts=true sp_cleanup.remove_unnecessary_nls_tags=false sp_cleanup.remove_unused_imports=false sp_cleanup.remove_unused_local_variables=false sp_cleanup.remove_unused_private_fields=true sp_cleanup.remove_unused_private_members=false sp_cleanup.remove_unused_private_methods=true sp_cleanup.remove_unused_private_types=true sp_cleanup.sort_members=false sp_cleanup.sort_members_all=false sp_cleanup.use_blocks=true sp_cleanup.use_blocks_only_for_return_and_throw=false sp_cleanup.use_parentheses_in_expressions=false sp_cleanup.use_this_for_non_static_field_access=false sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true sp_cleanup.use_this_for_non_static_method_access=false sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true jacoco-0.7.8/org.jacoco.core/META-INF/000077500000000000000000000000001304217427400171035ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/META-INF/MANIFEST.MF000066400000000000000000000013321304217427400205340ustar00rootroot00000000000000Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JaCoCo Core Bundle-SymbolicName: org.jacoco.core Bundle-Version: 0.7.8.201612092310 Bundle-Vendor: Mountainminds GmbH & Co. KG Bundle-RequiredExecutionEnvironment: J2SE-1.5 Export-Package: org.jacoco.core;version="0.7.8", org.jacoco.core.analysis;version="0.7.8", org.jacoco.core.data;version="0.7.8", org.jacoco.core.instr;version="0.7.8", org.jacoco.core.internal.analysis;version="0.7.8";x-internal=true, org.jacoco.core.runtime;version="0.7.8", org.jacoco.core.tools;version="0.7.8" Import-Package: org.objectweb.asm;version="[5.1.0,5.2.0)", org.objectweb.asm.tree;version="[5.1.0,5.2.0)", org.objectweb.asm.commons;version="[5.1.0,5.2.0)" jacoco-0.7.8/org.jacoco.core/about.html000066400000000000000000000014761304217427400177530ustar00rootroot00000000000000 About

About This Content

@build.date@

License

All Content in this plug-in is made available by Mountainminds GmbH & Co. KG, Munich. Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" will mean the Content.

jacoco-0.7.8/org.jacoco.core/pom.xml000066400000000000000000000022731304217427400172640ustar00rootroot00000000000000 4.0.0 org.jacoco org.jacoco.build 0.7.8 ../org.jacoco.build org.jacoco.core JaCoCo :: Core JaCoCo Core org.ow2.asm asm-debug-all src jacoco-0.7.8/org.jacoco.core/src/000077500000000000000000000000001304217427400165325ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/000077500000000000000000000000001304217427400173215ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/000077500000000000000000000000001304217427400205575ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/000077500000000000000000000000001304217427400215075ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/JaCoCo.java000066400000000000000000000025321304217427400234520ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core; import java.util.ResourceBundle; import org.objectweb.asm.Opcodes; /** * Static Meta information about JaCoCo. */ public final class JaCoCo { /** Qualified build version of the JaCoCo core library. */ public static final String VERSION; /** Absolute URL of the current JaCoCo home page */ public static final String HOMEURL; /** Name of the runtime package of this build */ public static final String RUNTIMEPACKAGE; /** ASM API version */ public static final int ASM_API_VERSION = Opcodes.ASM5; static { final ResourceBundle bundle = ResourceBundle .getBundle("org.jacoco.core.jacoco"); VERSION = bundle.getString("VERSION"); HOMEURL = bundle.getString("HOMEURL"); RUNTIMEPACKAGE = bundle.getString("RUNTIMEPACKAGE"); } private JaCoCo() { } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/000077500000000000000000000000001304217427400233325ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/Analyzer.java000066400000000000000000000216551304217427400257730ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.StringTokenizer; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.jacoco.core.data.ExecutionData; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.internal.ContentTypeDetector; import org.jacoco.core.internal.Java9Support; import org.jacoco.core.internal.Pack200Streams; import org.jacoco.core.internal.analysis.ClassAnalyzer; import org.jacoco.core.internal.analysis.ClassCoverageImpl; import org.jacoco.core.internal.analysis.StringPool; import org.jacoco.core.internal.data.CRC64; import org.jacoco.core.internal.flow.ClassProbesAdapter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; /** * An {@link Analyzer} instance processes a set of Java class files and * calculates coverage data for them. For each class file the result is reported * to a given {@link ICoverageVisitor} instance. In addition the * {@link Analyzer} requires a {@link ExecutionDataStore} instance that holds * the execution data for the classes to analyze. The {@link Analyzer} offers * several methods to analyze classes from a variety of sources. */ public class Analyzer { private final ExecutionDataStore executionData; private final ICoverageVisitor coverageVisitor; private final StringPool stringPool; /** * Creates a new analyzer reporting to the given output. * * @param executionData * execution data * @param coverageVisitor * the output instance that will coverage data for every analyzed * class */ public Analyzer(final ExecutionDataStore executionData, final ICoverageVisitor coverageVisitor) { this.executionData = executionData; this.coverageVisitor = coverageVisitor; this.stringPool = new StringPool(); } /** * Creates an ASM class visitor for analysis. * * @param classid * id of the class calculated with {@link CRC64} * @param className * VM name of the class * @return ASM visitor to write class definition to */ private ClassVisitor createAnalyzingVisitor(final long classid, final String className) { final ExecutionData data = executionData.get(classid); final boolean[] probes; final boolean noMatch; if (data == null) { probes = null; noMatch = executionData.contains(className); } else { probes = data.getProbes(); noMatch = false; } final ClassCoverageImpl coverage = new ClassCoverageImpl(className, classid, noMatch); final ClassAnalyzer analyzer = new ClassAnalyzer(coverage, probes, stringPool) { @Override public void visitEnd() { super.visitEnd(); coverageVisitor.visitCoverage(coverage); } }; return new ClassProbesAdapter(analyzer, false); } /** * Analyzes the class given as a ASM reader. * * @param reader * reader with class definitions */ public void analyzeClass(final ClassReader reader) { final ClassVisitor visitor = createAnalyzingVisitor( CRC64.checksum(reader.b), reader.getClassName()); reader.accept(visitor, 0); } /** * Analyzes the class definition from a given in-memory buffer. * * @param buffer * class definitions * @param location * a location description used for exception messages * @throws IOException * if the class can't be analyzed */ public void analyzeClass(final byte[] buffer, final String location) throws IOException { try { analyzeClass( new ClassReader(Java9Support.downgradeIfRequired(buffer))); } catch (final RuntimeException cause) { throw analyzerError(location, cause); } } /** * Analyzes the class definition from a given input stream. * * @param input * stream to read class definition from * @param location * a location description used for exception messages * @throws IOException * if the stream can't be read or the class can't be analyzed */ public void analyzeClass(final InputStream input, final String location) throws IOException { try { analyzeClass(Java9Support.readFully(input), location); } catch (final RuntimeException e) { throw analyzerError(location, e); } } private IOException analyzerError(final String location, final Exception cause) { final IOException ex = new IOException(String.format( "Error while analyzing %s.", location)); ex.initCause(cause); return ex; } /** * Analyzes all classes found in the given input stream. The input stream * may either represent a single class file, a ZIP archive, a Pack200 * archive or a gzip stream that is searched recursively for class files. * All other content types are ignored. * * @param input * input data * @param location * a location description used for exception messages * @return number of class files found * @throws IOException * if the stream can't be read or a class can't be analyzed */ public int analyzeAll(final InputStream input, final String location) throws IOException { final ContentTypeDetector detector; try { detector = new ContentTypeDetector(input); } catch (IOException e) { throw analyzerError(location, e); } switch (detector.getType()) { case ContentTypeDetector.CLASSFILE: analyzeClass(detector.getInputStream(), location); return 1; case ContentTypeDetector.ZIPFILE: return analyzeZip(detector.getInputStream(), location); case ContentTypeDetector.GZFILE: return analyzeGzip(detector.getInputStream(), location); case ContentTypeDetector.PACK200FILE: return analyzePack200(detector.getInputStream(), location); default: return 0; } } /** * Analyzes all class files contained in the given file or folder. Class * files as well as ZIP files are considered. Folders are searched * recursively. * * @param file * file or folder to look for class files * @return number of class files found * @throws IOException * if the file can't be read or a class can't be analyzed */ public int analyzeAll(final File file) throws IOException { int count = 0; if (file.isDirectory()) { for (final File f : file.listFiles()) { count += analyzeAll(f); } } else { final InputStream in = new FileInputStream(file); try { count += analyzeAll(in, file.getPath()); } finally { in.close(); } } return count; } /** * Analyzes all classes from the given class path. Directories containing * class files as well as archive files are considered. * * @param path * path definition * @param basedir * optional base directory, if null the current * working directory is used as the base for relative path * entries * @return number of class files found * @throws IOException * if a file can't be read or a class can't be analyzed */ public int analyzeAll(final String path, final File basedir) throws IOException { int count = 0; final StringTokenizer st = new StringTokenizer(path, File.pathSeparator); while (st.hasMoreTokens()) { count += analyzeAll(new File(basedir, st.nextToken())); } return count; } private int analyzeZip(final InputStream input, final String location) throws IOException { final ZipInputStream zip = new ZipInputStream(input); ZipEntry entry; int count = 0; while ((entry = nextEntry(zip, location)) != null) { count += analyzeAll(zip, location + "@" + entry.getName()); } return count; } private ZipEntry nextEntry(ZipInputStream input, String location) throws IOException { try { return input.getNextEntry(); } catch (IOException e) { throw analyzerError(location, e); } } private int analyzeGzip(final InputStream input, final String location) throws IOException { GZIPInputStream gzipInputStream; try { gzipInputStream = new GZIPInputStream(input); } catch (IOException e) { throw analyzerError(location, e); } return analyzeAll(gzipInputStream, location); } private int analyzePack200(final InputStream input, final String location) throws IOException { InputStream unpackedInput; try { unpackedInput = Pack200Streams.unpack(input); } catch (IOException e) { throw analyzerError(location, e); } return analyzeAll(unpackedInput, location); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/CounterComparator.java000066400000000000000000000054631304217427400276540ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.io.Serializable; import java.util.Comparator; import org.jacoco.core.analysis.ICounter.CounterValue; import org.jacoco.core.analysis.ICoverageNode.CounterEntity; /** * Collection of comparators to compare {@link ICounter} objects by different * criteria. */ public class CounterComparator implements Comparator, Serializable { private static final long serialVersionUID = -3777463066252746748L; /** * Compares the absolute number of total items. */ public static final CounterComparator TOTALITEMS = new CounterComparator( CounterValue.TOTALCOUNT); /** * Compares the absolute number of covered items. */ public static final CounterComparator COVEREDITEMS = new CounterComparator( CounterValue.COVEREDCOUNT); /** * Compares the absolute number of missed items. */ public static final CounterComparator MISSEDITEMS = new CounterComparator( CounterValue.MISSEDCOUNT); /** * Compares the ratio of covered items. */ public static final CounterComparator COVEREDRATIO = new CounterComparator( CounterValue.COVEREDRATIO); /** * Compares the ratio of missed items. */ public static final CounterComparator MISSEDRATIO = new CounterComparator( CounterValue.MISSEDRATIO); private final CounterValue value; private final boolean reverse; private CounterComparator(final CounterValue value) { this(value, false); } private CounterComparator(final CounterValue value, final boolean reverse) { this.value = value; this.reverse = reverse; } public int compare(final ICounter c1, final ICounter c2) { final int cmp = Double.compare(c1.getValue(value), c2.getValue(value)); return reverse ? -cmp : cmp; } /** * Creates a new version of this comparator that sorts in reverse order. * * @return reverse comparator */ public CounterComparator reverse() { return new CounterComparator(value, !reverse); } /** * Creates a new comparator for {@link ICoverageNode} counters of the given * entity based on this counter sorting criteria. * * @param entity * counter entity to sort on * @return comparator for {@link ICoverageNode} elements */ public NodeComparator on(final CounterEntity entity) { return new NodeComparator(this, entity); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/CoverageBuilder.java000066400000000000000000000100771304217427400272440ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.jacoco.core.internal.analysis.BundleCoverageImpl; import org.jacoco.core.internal.analysis.SourceFileCoverageImpl; /** * Builder for hierarchical {@link ICoverageNode} structures from single * {@link IClassCoverage} nodes. The nodes are feed into the builder through its * {@link ICoverageVisitor} interface. Afterwards the aggregated data can be * obtained with {@link #getClasses()}, {@link #getSourceFiles()} or * {@link #getBundle(String)} in the following hierarchy: * *
 * {@link IBundleCoverage}
 * +-- {@link IPackageCoverage}*
 *     +-- {@link IClassCoverage}*
 *     +-- {@link ISourceFileCoverage}*
 * 
*/ public class CoverageBuilder implements ICoverageVisitor { private final Map classes; private final Map sourcefiles; /** * Create a new builder. * */ public CoverageBuilder() { this.classes = new HashMap(); this.sourcefiles = new HashMap(); } /** * Returns all class nodes currently contained in this builder. * * @return all class nodes */ public Collection getClasses() { return Collections.unmodifiableCollection(classes.values()); } /** * Returns all source file nodes currently contained in this builder. * * @return all source file nodes */ public Collection getSourceFiles() { return Collections.unmodifiableCollection(sourcefiles.values()); } /** * Creates a bundle from all nodes currently contained in this bundle. * * @param name * Name of the bundle * @return bundle containing all classes and source files */ public IBundleCoverage getBundle(final String name) { return new BundleCoverageImpl(name, classes.values(), sourcefiles.values()); } /** * Returns all classes for which execution data does not match. * * @see IClassCoverage#isNoMatch() * @return collection of classes with non-matching execution data */ public Collection getNoMatchClasses() { final Collection result = new ArrayList(); for (final IClassCoverage c : classes.values()) { if (c.isNoMatch()) { result.add(c); } } return result; } // === IStructureVisitor === public void visitCoverage(final IClassCoverage coverage) { // Only consider classes that actually contain code: if (coverage.getInstructionCounter().getTotalCount() > 0) { final String name = coverage.getName(); final IClassCoverage dup = classes.put(name, coverage); if (dup != null) { if (dup.getId() != coverage.getId()) { throw new IllegalStateException( "Can't add different class with same name: " + name); } } else { final String source = coverage.getSourceFileName(); if (source != null) { final SourceFileCoverageImpl sourceFile = getSourceFile( source, coverage.getPackageName()); sourceFile.increment(coverage); } } } } private SourceFileCoverageImpl getSourceFile(final String filename, final String packagename) { final String key = packagename + '/' + filename; SourceFileCoverageImpl sourcefile = (SourceFileCoverageImpl) sourcefiles .get(key); if (sourcefile == null) { sourcefile = new SourceFileCoverageImpl(filename, packagename); sourcefiles.put(key, sourcefile); } return sourcefile; } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/CoverageNodeImpl.java000066400000000000000000000106671304217427400273720ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.util.Collection; import org.jacoco.core.internal.analysis.CounterImpl; /** * Base implementation for coverage data nodes. */ public class CoverageNodeImpl implements ICoverageNode { private final ElementType elementType; private final String name; /** Counter for branches. */ protected CounterImpl branchCounter; /** Counter for instructions. */ protected CounterImpl instructionCounter; /** Counter for lines */ protected CounterImpl lineCounter; /** Counter for complexity. */ protected CounterImpl complexityCounter; /** Counter for methods. */ protected CounterImpl methodCounter; /** Counter for classes. */ protected CounterImpl classCounter; /** * Creates a new coverage data node. * * @param elementType * type of the element represented by this instance * @param name * name of this node */ public CoverageNodeImpl(final ElementType elementType, final String name) { this.elementType = elementType; this.name = name; this.branchCounter = CounterImpl.COUNTER_0_0; this.instructionCounter = CounterImpl.COUNTER_0_0; this.complexityCounter = CounterImpl.COUNTER_0_0; this.methodCounter = CounterImpl.COUNTER_0_0; this.classCounter = CounterImpl.COUNTER_0_0; this.lineCounter = CounterImpl.COUNTER_0_0; } /** * Increments the counters by the values given by another element. * * @param child * counters to add */ public void increment(final ICoverageNode child) { instructionCounter = instructionCounter.increment(child .getInstructionCounter()); branchCounter = branchCounter.increment(child.getBranchCounter()); lineCounter = lineCounter.increment(child.getLineCounter()); complexityCounter = complexityCounter.increment(child .getComplexityCounter()); methodCounter = methodCounter.increment(child.getMethodCounter()); classCounter = classCounter.increment(child.getClassCounter()); } /** * Increments the counters by the values given by the collection of * elements. * * @param children * list of nodes, which counters will be added to this node */ public void increment(final Collection children) { for (final ICoverageNode child : children) { increment(child); } } // === ICoverageDataNode === public ElementType getElementType() { return elementType; } public String getName() { return name; } public ICounter getInstructionCounter() { return instructionCounter; } public ICounter getBranchCounter() { return branchCounter; } public ICounter getLineCounter() { return lineCounter; } public ICounter getComplexityCounter() { return complexityCounter; } public ICounter getMethodCounter() { return methodCounter; } public ICounter getClassCounter() { return classCounter; } public ICounter getCounter(final CounterEntity entity) { switch (entity) { case INSTRUCTION: return getInstructionCounter(); case BRANCH: return getBranchCounter(); case LINE: return getLineCounter(); case COMPLEXITY: return getComplexityCounter(); case METHOD: return getMethodCounter(); case CLASS: return getClassCounter(); } throw new AssertionError(entity); } public ICoverageNode getPlainCopy() { final CoverageNodeImpl copy = new CoverageNodeImpl(elementType, name); copy.instructionCounter = CounterImpl.getInstance(instructionCounter); copy.branchCounter = CounterImpl.getInstance(branchCounter); copy.lineCounter = CounterImpl.getInstance(lineCounter); copy.complexityCounter = CounterImpl.getInstance(complexityCounter); copy.methodCounter = CounterImpl.getInstance(methodCounter); copy.classCounter = CounterImpl.getInstance(classCounter); return copy; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(name).append(" [").append(elementType).append("]"); return sb.toString(); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/IBundleCoverage.java000066400000000000000000000016561304217427400272030ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.util.Collection; /** * Coverage data of a bundle. A bundle groups a collection of packages. * * @see IPackageCoverage */ public interface IBundleCoverage extends ICoverageNode { /** * Returns all packages contained in this bundle. * * @return all packages */ public Collection getPackages(); }jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/IClassCoverage.java000066400000000000000000000045131304217427400270320ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.util.Collection; /** * Coverage data of a single class containing methods. The name of this node is * the fully qualified class name in VM notation (slash separated). * * @see IMethodCoverage */ public interface IClassCoverage extends ISourceNode { /** * Returns the identifier for this class which is the CRC64 signature of the * class definition. * * @return class identifier */ public long getId(); /** * Returns if the the analyzed class does match the execution data provided. * More precisely if execution data is available for a class with the same * qualified name but with a different class id. * * @return true if this class does not match to the provided * execution data. */ public boolean isNoMatch(); /** * Returns the VM signature of the class. * * @return VM signature of the class (may be null) */ public String getSignature(); /** * Returns the VM name of the superclass. * * @return VM name of the super class (may be null, i.e. * java/lang/Object) */ public String getSuperName(); /** * Returns the VM names of implemented/extended interfaces. * * @return VM names of implemented/extended interfaces */ public String[] getInterfaceNames(); /** * Returns the VM name of the package this class belongs to. * * @return VM name of the package */ public String getPackageName(); /** * Returns the optional name of the corresponding source file. * * @return name of the corresponding source file */ public String getSourceFileName(); /** * Returns the methods included in this class. * * @return methods of this class */ public Collection getMethods(); }jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/ICounter.java000066400000000000000000000053611304217427400257320ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; /** * A counter holds the missed and the covered number of particular items like * classes, methods, branches or instructions. */ public interface ICounter { /** * Different values provided by a counter. */ public enum CounterValue { /** Total number of items */ TOTALCOUNT, /** Number of missed items */ MISSEDCOUNT, /** Number of covered items */ COVEREDCOUNT, /** Ratio of missed to total items */ MISSEDRATIO, /** Ratio of covered to total items */ COVEREDRATIO } /** * Status flag for no items (value is 0x00). */ public static final int EMPTY = 0x00; /** * Status flag when all items are not covered (value is 0x01). */ public static final int NOT_COVERED = 0x01; /** * Status flag when all items are covered (value is 0x02). */ public static final int FULLY_COVERED = 0x02; /** * Status flag when items are partly covered (value is 0x03). */ public static final int PARTLY_COVERED = NOT_COVERED | FULLY_COVERED; /** * Returns the counter value of the given type. * * @param value * value type to return * @return counter value */ public double getValue(CounterValue value); /** * Returns the total count of items. * * @return total count of items */ public int getTotalCount(); /** * Returns the count of covered items. * * @return count of covered items */ public int getCoveredCount(); /** * Returns the count of missed items. * * @return count of missed items */ public int getMissedCount(); /** * Calculates the ratio of covered to total count items. If total count * items is 0 this method returns NaN. * * @return ratio of covered to total count items */ public double getCoveredRatio(); /** * Calculates the ratio of missed to total count items. If total count items * is 0 this method returns NaN. * * @return ratio of missed to total count items */ public double getMissedRatio(); /** * Returns the coverage status of this counter. * * @see ICounter#EMPTY * @see ICounter#NOT_COVERED * @see ICounter#PARTLY_COVERED * @see ICounter#FULLY_COVERED * * @return status of this line */ public int getStatus(); } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/ICoverageNode.java000066400000000000000000000057231304217427400266560ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; /** * Interface for hierarchical coverage data nodes with different coverage * counters. */ public interface ICoverageNode { /** * Type of a Java element represented by a {@link ICoverageNode} instance. */ public enum ElementType { /** Method */ METHOD, /** Class */ CLASS, /** Source File */ SOURCEFILE, /** Java Package */ PACKAGE, /** Bundle of Packages */ BUNDLE, /** Logical Group of Bundles */ GROUP, } /** * Different counter types supported by JaCoCo. */ public enum CounterEntity { /** Counter for instructions */ INSTRUCTION, /** Counter for branches */ BRANCH, /** Counter for source lines */ LINE, /** Counter for cyclomatic complexity */ COMPLEXITY, /** Counter for methods */ METHOD, /** Counter for classes */ CLASS } /** * Returns the type of element represented by this node. * * @return type of this node */ public abstract ElementType getElementType(); /** * Returns the name of this node. * * @return name of this node */ public String getName(); /** * Returns the counter for byte code instructions. * * @return counter for instructions */ public abstract ICounter getInstructionCounter(); /** * Returns the counter for branches. * * @return counter for branches */ public ICounter getBranchCounter(); /** * Returns the counter for lines. * * @return counter for lines */ public ICounter getLineCounter(); /** * Returns the counter for cyclomatic complexity. * * @return counter for complexity */ public ICounter getComplexityCounter(); /** * Returns the counter for methods. * * @return counter for methods */ public ICounter getMethodCounter(); /** * Returns the counter for classes. * * @return counter for classes */ public ICounter getClassCounter(); /** * Generic access to the the counters. * * @param entity * entity we're we want to have the counter for * @return counter for the given entity */ public ICounter getCounter(CounterEntity entity); /** * Creates a plain copy of this node. While {@link ICoverageNode} * implementations may contain heavy data structures, the copy returned by * this method is reduced to the counters only. This helps to save memory * while processing huge structures. * * @return copy with counters only */ public ICoverageNode getPlainCopy(); }jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/ICoverageVisitor.java000066400000000000000000000016431304217427400274250ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; /** * Interface for coverage data output as a stream of {@link IClassCoverage} * instances. */ public interface ICoverageVisitor { /** * For analyzed class coverage data is emitted to this method. * * @param coverage * coverage data for a class */ public void visitCoverage(IClassCoverage coverage); } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/ILine.java000066400000000000000000000024411304217427400251760ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; /** * The instruction and branch coverage of a single source line is described by * this interface. */ public interface ILine { /** * Returns the instruction counter for this line. * * @return instruction counter */ public ICounter getInstructionCounter(); /** * Returns the branches counter for this line. * * @return branches counter */ public ICounter getBranchCounter(); /** * Returns the coverage status of this line, calculated from the * instructions counter and branch counter. * * @see ICounter#EMPTY * @see ICounter#NOT_COVERED * @see ICounter#PARTLY_COVERED * @see ICounter#FULLY_COVERED * * @return status of this line */ public int getStatus(); } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/IMethodCoverage.java000066400000000000000000000017721304217427400272110ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; /** * Coverage data of a single method. The name of this node is the local method * name. */ public interface IMethodCoverage extends ISourceNode { /** * Returns the descriptor of the method. * * @return descriptor */ public String getDesc(); /** * Returns the generic signature of the method if defined. * * @return generic signature or null */ public String getSignature(); }jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/IPackageCoverage.java000066400000000000000000000023411304217427400273150ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.util.Collection; /** * Coverage data of a Java package containing classes and source files. The name * of this node is the package name in VM notation (slash separated). The name * of the default package is the empty string. * * @see IClassCoverage * @see ISourceFileCoverage */ public interface IPackageCoverage extends ICoverageNode { /** * Returns all classes contained in this package. * * @return all classes */ public Collection getClasses(); /** * Returns all source files in this package. * * @return all source files */ public Collection getSourceFiles(); }jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/ISourceFileCoverage.java000066400000000000000000000016231304217427400300240ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; /** * Coverage data of a single source file. The name of this node is the local * name of the source file. */ public interface ISourceFileCoverage extends ISourceNode { /** * Returns the VM name of the package the source file belongs to. * * @return package name */ public String getPackageName(); }jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/ISourceNode.java000066400000000000000000000027451304217427400263640ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; /** * Interface for coverage nodes that have individual source lines like methods, * classes and source files. */ public interface ISourceNode extends ICoverageNode { /** Place holder for unknown lines (no debug information) */ public static int UNKNOWN_LINE = -1; /** * The number of the first line coverage information is available for. If no * line is contained, the method returns -1. * * @return number of the first line or {@link #UNKNOWN_LINE} */ public int getFirstLine(); /** * The number of the last line coverage information is available for. If no * line is contained, the method returns -1. * * @return number of the last line or {@link #UNKNOWN_LINE} */ public int getLastLine(); /** * Returns the line information for given line. * * @param nr * line number of interest * @return line information */ public ILine getLine(int nr); } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/NodeComparator.java000066400000000000000000000051671304217427400271230ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.analysis; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.jacoco.core.analysis.ICoverageNode.CounterEntity; /** * Comparator to compare {@link ICoverageNode} objects by different counter * criteria. * * @see CounterComparator#on(ICoverageNode.CounterEntity) */ public class NodeComparator implements Comparator, Serializable { private static final long serialVersionUID = 8550521643608826519L; private final Comparator counterComparator; private final CounterEntity entity; NodeComparator(final Comparator counterComparator, final CounterEntity entity) { this.counterComparator = counterComparator; this.entity = entity; } /** * Creates a new composite comparator with a second search criterion. * * @param second * second criterion comparator * * @return composite comparator */ public NodeComparator second(final Comparator second) { final Comparator first = this; return new NodeComparator(null, null) { private static final long serialVersionUID = -5515272752138802838L; @Override public int compare(final ICoverageNode o1, final ICoverageNode o2) { final int result = first.compare(o1, o2); return result == 0 ? second.compare(o1, o2) : result; } }; } /** * Returns a sorted copy of the given collection of {@link ICoverageNode} * elements. * * @param * actual type of the elements * @param summaries * collection to create a copy of * @return sorted copy */ public List sort(final Collection summaries) { final List result = new ArrayList(summaries); Collections.sort(result, this); return result; } public int compare(final ICoverageNode n1, final ICoverageNode n2) { final ICounter c1 = n1.getCounter(entity); final ICounter c2 = n2.getCounter(entity); return counterComparator.compare(c1, c2); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/analysis/package-info.java000066400000000000000000000033101304217427400265160ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ /** *

* Coverage calculation and analysis. The coverage information is calculated * with an {@link org.jacoco.core.analysis.Analyzer} instance from class files * (target) and * {@linkplain org.jacoco.core.data.IExecutionDataVisitor execution data} * (actual). *

* *

* The {@link org.jacoco.core.analysis.CoverageBuilder} creates a hierarchy of * {@link org.jacoco.core.analysis.ICoverageNode} instances with the following * {@link org.jacoco.core.analysis.ICoverageNode.ElementType types}: *

* *
 * +-- {@linkplain org.jacoco.core.analysis.ICoverageNode.ElementType#GROUP Group} (optional)
 *     +-- {@linkplain org.jacoco.core.analysis.ICoverageNode.ElementType#BUNDLE Bundle}
 *         +-- {@linkplain org.jacoco.core.analysis.ICoverageNode.ElementType#PACKAGE Package}
 *             +-- {@linkplain org.jacoco.core.analysis.ICoverageNode.ElementType#SOURCEFILE Source File}
 *                 +-- {@linkplain org.jacoco.core.analysis.ICoverageNode.ElementType#CLASS Class}
 *                     +-- {@linkplain org.jacoco.core.analysis.ICoverageNode.ElementType#METHOD Method}
 * 
*/ package org.jacoco.core.analysis;jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/000077500000000000000000000000001304217427400224205ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/ExecutionData.java000066400000000000000000000123021304217427400260160ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static java.lang.String.format; import java.util.Arrays; /** * Execution data for a single Java class. While instances are immutable care * has to be taken about the probe data array of type boolean[] * which can be modified. */ public final class ExecutionData { private final long id; private final String name; private final boolean[] probes; /** * Creates a new {@link ExecutionData} object with the given probe data. * * @param id * class identifier * @param name * VM name * @param probes * probe data */ public ExecutionData(final long id, final String name, final boolean[] probes) { this.id = id; this.name = name; this.probes = probes; } /** * Creates a new {@link ExecutionData} object with the given probe data * length. All probes are set to false. * * @param id * class identifier * @param name * VM name * @param probeCount * probe count */ public ExecutionData(final long id, final String name, final int probeCount) { this.id = id; this.name = name; this.probes = new boolean[probeCount]; } /** * Return the unique identifier for this class. The identifier is the CRC64 * checksum of the raw class file definition. * * @return class identifier */ public long getId() { return id; } /** * The VM name of the class. * * @return VM name */ public String getName() { return name; } /** * Returns the execution data probes. A value of true indicates * that the corresponding probe was executed. * * @return probe data */ public boolean[] getProbes() { return probes; } /** * Sets all probes to false. */ public void reset() { Arrays.fill(probes, false); } /** * Checks whether any probe has been hit. * * @return true, if at least one probe has been hit */ public boolean hasHits() { for (final boolean p : probes) { if (p) { return true; } } return false; } /** * Merges the given execution data into the probe data of this object. I.e. * a probe entry in this object is marked as executed (true) if * this probe or the corresponding other probe was executed. So the result * is * *
	 * A or B
	 * 
* * The probe array of the other object is not modified. * * @param other * execution data to merge */ public void merge(final ExecutionData other) { merge(other, true); } /** * Merges the given execution data into the probe data of this object. A * probe in this object is set to the value of flag if the * corresponding other probe was executed. For flag==true this * corresponds to * *
	 * A or B
	 * 
* * For flag==true this can be considered as a subtraction * *
	 * A and not B
	 * 
* * The probe array of the other object is not modified. * * @param other * execution data to merge * @param flag * merge mode */ public void merge(final ExecutionData other, final boolean flag) { assertCompatibility(other.getId(), other.getName(), other.getProbes().length); final boolean[] otherData = other.getProbes(); for (int i = 0; i < probes.length; i++) { if (otherData[i]) { probes[i] = flag; } } } /** * Asserts that this execution data object is compatible with the given * parameters. The purpose of this check is to detect a very unlikely class * id collision. * * @param id * other class id, must be the same * @param name * other name, must be equal to this name * @param probecount * probe data length, must be the same as for this data * @throws IllegalStateException * if the given parameters do not match this instance */ public void assertCompatibility(final long id, final String name, final int probecount) throws IllegalStateException { if (this.id != id) { throw new IllegalStateException(format( "Different ids (%016x and %016x).", Long.valueOf(this.id), Long.valueOf(id))); } if (!this.name.equals(name)) { throw new IllegalStateException(format( "Different class names %s and %s for id %016x.", this.name, name, Long.valueOf(id))); } if (this.probes.length != probecount) { throw new IllegalStateException(format( "Incompatible execution data for class %s with id %016x.", name, Long.valueOf(id))); } } @Override public String toString() { return String.format("ExecutionData[name=%s, id=%016x]", name, Long.valueOf(id)); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/ExecutionDataReader.java000066400000000000000000000111431304217427400271430ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static java.lang.String.format; import java.io.IOException; import java.io.InputStream; import org.jacoco.core.internal.data.CompactDataInput; /** * Deserialization of execution data from binary streams. */ public class ExecutionDataReader { /** Underlying data input */ protected final CompactDataInput in; private ISessionInfoVisitor sessionInfoVisitor = null; private IExecutionDataVisitor executionDataVisitor = null; private boolean firstBlock = true; /** * Creates a new reader based on the given input stream input. Depending on * the nature of the underlying stream input should be buffered as most data * is read in single bytes. * * @param input * input stream to read execution data from */ public ExecutionDataReader(final InputStream input) { this.in = new CompactDataInput(input); } /** * Sets an listener for session information. * * @param visitor * visitor to retrieve session info events */ public void setSessionInfoVisitor(final ISessionInfoVisitor visitor) { this.sessionInfoVisitor = visitor; } /** * Sets an listener for execution data. * * @param visitor * visitor to retrieve execution data events */ public void setExecutionDataVisitor(final IExecutionDataVisitor visitor) { this.executionDataVisitor = visitor; } /** * Reads all data and reports it to the corresponding visitors. The stream * is read until its end or a command confirmation has been sent. * * @return true if additional data can be expected after a * command has been executed. false if the end of the * stream has been reached. * @throws IOException * might be thrown by the underlying input stream * @throws IncompatibleExecDataVersionException * incompatible data version from different JaCoCo release */ public boolean read() throws IOException, IncompatibleExecDataVersionException { byte type; do { int i = in.read(); if (i == -1) { return false; // EOF } type = (byte) i; if (firstBlock && type != ExecutionDataWriter.BLOCK_HEADER) { throw new IOException("Invalid execution data file."); } firstBlock = false; } while (readBlock(type)); return true; } /** * Reads a block of data identified by the given id. Subclasses may * overwrite this method to support additional block types. * * @param blocktype * block type * @return true if there are more blocks to read * @throws IOException * might be thrown by the underlying input stream */ protected boolean readBlock(final byte blocktype) throws IOException { switch (blocktype) { case ExecutionDataWriter.BLOCK_HEADER: readHeader(); return true; case ExecutionDataWriter.BLOCK_SESSIONINFO: readSessionInfo(); return true; case ExecutionDataWriter.BLOCK_EXECUTIONDATA: readExecutionData(); return true; default: throw new IOException(format("Unknown block type %x.", Byte.valueOf(blocktype))); } } private void readHeader() throws IOException { if (in.readChar() != ExecutionDataWriter.MAGIC_NUMBER) { throw new IOException("Invalid execution data file."); } final char version = in.readChar(); if (version != ExecutionDataWriter.FORMAT_VERSION) { throw new IncompatibleExecDataVersionException(version); } } private void readSessionInfo() throws IOException { if (sessionInfoVisitor == null) { throw new IOException("No session info visitor."); } final String id = in.readUTF(); final long start = in.readLong(); final long dump = in.readLong(); sessionInfoVisitor.visitSessionInfo(new SessionInfo(id, start, dump)); } private void readExecutionData() throws IOException { if (executionDataVisitor == null) { throw new IOException("No execution data visitor."); } final long id = in.readLong(); final String name = in.readUTF(); final boolean[] probes = in.readBooleanArray(); executionDataVisitor.visitClassExecution(new ExecutionData(id, name, probes)); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/ExecutionDataStore.java000066400000000000000000000126451304217427400270450ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * In-memory data store for execution data. The data can be added through its * {@link IExecutionDataVisitor} interface. If execution data is provided * multiple times for the same class the data is merged, i.e. a probe is marked * as executed if it is reported as executed at least once. This allows to merge * coverage date from multiple runs. A instance of this class is not thread * safe. */ public final class ExecutionDataStore implements IExecutionDataVisitor { private final Map entries = new HashMap(); private final Set names = new HashSet(); /** * Adds the given {@link ExecutionData} object into the store. If there is * already execution data with this same class id, this structure is merged * with the given one. * * @param data * execution data to add or merge * @throws IllegalStateException * if the given {@link ExecutionData} object is not compatible * to a corresponding one, that is already contained * @see ExecutionData#assertCompatibility(long, String, int) */ public void put(final ExecutionData data) throws IllegalStateException { final Long id = Long.valueOf(data.getId()); final ExecutionData entry = entries.get(id); if (entry == null) { entries.put(id, data); names.add(data.getName()); } else { entry.merge(data); } } /** * Subtracts the probes in the given {@link ExecutionData} object from the * store. I.e. for all set probes in the given data object the corresponding * probes in this store will be unset. If there is no execution data with id * of the given data object this operation will have no effect. * * @param data * execution data to subtract * @throws IllegalStateException * if the given {@link ExecutionData} object is not compatible * to a corresponding one, that is already contained * @see ExecutionData#assertCompatibility(long, String, int) */ public void subtract(final ExecutionData data) throws IllegalStateException { final Long id = Long.valueOf(data.getId()); final ExecutionData entry = entries.get(id); if (entry != null) { entry.merge(data, false); } } /** * Subtracts all probes in the given execution data store from this store. * * @param store * execution data store to subtract * @see #subtract(ExecutionData) */ public void subtract(final ExecutionDataStore store) { for (final ExecutionData data : store.getContents()) { subtract(data); } } /** * Returns the {@link ExecutionData} entry with the given id if it exists in * this store. * * @param id * class id * @return execution data or null */ public ExecutionData get(final long id) { return entries.get(Long.valueOf(id)); } /** * Checks whether execution data for classes with the given name are * contained in the store. * * @param name * VM name * @return true if at least one class with the name is * contained. */ public boolean contains(final String name) { return names.contains(name); } /** * Returns the coverage data for the class with the given identifier. If * there is no data available under the given id a new entry is created. * * @param id * class identifier * @param name * VM name of the class * @param probecount * probe data length * @return execution data */ public ExecutionData get(final Long id, final String name, final int probecount) { ExecutionData entry = entries.get(id); if (entry == null) { entry = new ExecutionData(id.longValue(), name, probecount); entries.put(id, entry); names.add(name); } else { entry.assertCompatibility(id.longValue(), name, probecount); } return entry; } /** * Resets all execution data probes, i.e. marks them as not executed. The * execution data objects itself are not removed. */ public void reset() { for (final ExecutionData executionData : this.entries.values()) { executionData.reset(); } } /** * Returns a collection that represents current contents of the store. * * @return current contents */ public Collection getContents() { return new ArrayList(entries.values()); } /** * Writes the content of the store to the given visitor interface. * * @param visitor * interface to write content to */ public void accept(final IExecutionDataVisitor visitor) { for (final ExecutionData data : getContents()) { visitor.visitClassExecution(data); } } // === IExecutionDataVisitor === public void visitClassExecution(final ExecutionData data) { put(data); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/ExecutionDataWriter.java000066400000000000000000000071731304217427400272250ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.jacoco.core.internal.data.CompactDataOutput; /** * Serialization of execution data into binary streams. */ public class ExecutionDataWriter implements ISessionInfoVisitor, IExecutionDataVisitor { /** File format version, will be incremented for each incompatible change. */ public static final char FORMAT_VERSION = 0x1007; /** Magic number in header for file format identification. */ public static final char MAGIC_NUMBER = 0xC0C0; /** Block identifier for file headers. */ public static final byte BLOCK_HEADER = 0x01; /** Block identifier for session information. */ public static final byte BLOCK_SESSIONINFO = 0x10; /** Block identifier for execution data of a single class. */ public static final byte BLOCK_EXECUTIONDATA = 0x11; /** Underlying data output */ protected final CompactDataOutput out; /** * Creates a new writer based on the given output stream. Depending on the * nature of the underlying stream output should be buffered as most data is * written in single bytes. * * @param output * binary stream to write execution data to * @throws IOException * if the header can't be written */ public ExecutionDataWriter(final OutputStream output) throws IOException { this.out = new CompactDataOutput(output); writeHeader(); } /** * Writes an file header to identify the stream and its protocol version. * * @throws IOException * if the header can't be written */ private void writeHeader() throws IOException { out.writeByte(BLOCK_HEADER); out.writeChar(MAGIC_NUMBER); out.writeChar(FORMAT_VERSION); } /** * Flushes the underlying stream. * * @throws IOException * if the underlying stream can't be flushed */ public void flush() throws IOException { out.flush(); } public void visitSessionInfo(final SessionInfo info) { try { out.writeByte(BLOCK_SESSIONINFO); out.writeUTF(info.getId()); out.writeLong(info.getStartTimeStamp()); out.writeLong(info.getDumpTimeStamp()); } catch (final IOException e) { throw new RuntimeException(e); } } public void visitClassExecution(final ExecutionData data) { if (data.hasHits()) { try { out.writeByte(BLOCK_EXECUTIONDATA); out.writeLong(data.getId()); out.writeUTF(data.getName()); out.writeBooleanArray(data.getProbes()); } catch (final IOException e) { throw new RuntimeException(e); } } } /** * Returns the first bytes of a file that represents a valid execution data * file. In any case every execution data file starts with the three bytes * 0x01 0xC0 0xC0. * * @return first bytes of a execution data file */ public static final byte[] getFileHeader() { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { new ExecutionDataWriter(buffer); } catch (final IOException e) { // Must not happen with ByteArrayOutputStream throw new AssertionError(e); } return buffer.toByteArray(); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/IExecutionDataVisitor.java000066400000000000000000000017341304217427400275160ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; /** * Interface for data output of collected execution data. This interface is * meant to be implemented by parties that want to retrieve data from the * coverage runtime. */ public interface IExecutionDataVisitor { /** * Provides execution data for a class. * * @param data * execution data for a class */ public void visitClassExecution(ExecutionData data); } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/ISessionInfoVisitor.java000066400000000000000000000021051304217427400272110ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; /** * Interface for data output of collected session information. This interface is * meant to be implemented by parties that want to retrieve data from the * coverage runtime. */ public interface ISessionInfoVisitor { /** * Provides session information for the subsequent execution data calls. In * case of merged sessions this method might be called multiple times. * * @param info * session information */ public void visitSessionInfo(final SessionInfo info); } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/IncompatibleExecDataVersionException.java000066400000000000000000000034171304217427400325220ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann, somechris - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import java.io.IOException; /** * Signals that execution data in an incompatible version was tried to read. */ public class IncompatibleExecDataVersionException extends IOException { private static final long serialVersionUID = 1L; private final int actualVersion; /** * Creates a new exception to flag version mismatches in execution data. * * @param actualVersion * version found in the exec data */ public IncompatibleExecDataVersionException(final int actualVersion) { super(String.format("Cannot read execution data version 0x%x. " + "This version of JaCoCo uses execution data version 0x%x.", Integer.valueOf(actualVersion), Integer.valueOf(ExecutionDataWriter.FORMAT_VERSION))); this.actualVersion = actualVersion; } /** * Gets the version expected in the execution data which can be read by this * version of JaCoCo. * * @return expected version in execution data */ public int getExpectedVersion() { return ExecutionDataWriter.FORMAT_VERSION; } /** * Gets the actual version found in the execution data. * * @return actual version in execution data */ public int getActualVersion() { return actualVersion; } }jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/SessionInfo.java000066400000000000000000000041311304217427400255210ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; /** * Data object describing a session which was the source of execution data. * {@link SessionInfo} instances can be sorted by dump date through the * {@link Comparable} interface. */ public class SessionInfo implements Comparable { private final String id; private final long start; private final long dump; /** * Create a immutable session info with the given data. * * @param id * arbitrary session identifier, must not be null * @param start * the epoc based time stamp when execution data recording has * been started * @param dump * the epoc based time stamp when execution data was collected */ public SessionInfo(final String id, final long start, final long dump) { if (id == null) { throw new IllegalArgumentException(); } this.id = id; this.start = start; this.dump = dump; } /** * @return identifier for this session */ public String getId() { return id; } /** * @return the epoc based time stamp when execution data recording has been * started */ public long getStartTimeStamp() { return start; } /** * @return the epoc based time stamp when execution data was collected */ public long getDumpTimeStamp() { return dump; } public int compareTo(final SessionInfo other) { if (this.dump < other.dump) { return -1; } if (this.dump > other.dump) { return +1; } return 0; } @Override public String toString() { return "SessionInfo[" + id + "]"; } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/SessionInfoStore.java000066400000000000000000000054741304217427400265510ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.data; import static java.lang.Math.max; import static java.lang.Math.min; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Container to collect and merge session {@link SessionInfo} objects. A * instance of this class is not thread safe. */ public class SessionInfoStore implements ISessionInfoVisitor { private final List infos = new ArrayList(); /** * Tests whether the store is empty. * * @return true if the store is empty */ public boolean isEmpty() { return infos.isEmpty(); } /** * Returns all {@link SessionInfo} objects currently contained in the store. * The info objects are ordered by its natural ordering (i.e. by the dump * time stamp). * * @return list of stored {@link SessionInfo} objects */ public List getInfos() { final List copy = new ArrayList(infos); Collections.sort(copy); return copy; } /** * Returns a new session info with the given id that contains a merged * version from all contained version. The start timestamp is the minimum of * all contained sessions, the dump timestamp the maximum of all contained * sessions. If no session is currently contained both timestamps are set to * 0. * * @param id * identifier for the merged session info * @return new {@link SessionInfo} object * */ public SessionInfo getMerged(final String id) { if (infos.isEmpty()) { return new SessionInfo(id, 0, 0); } long start = Long.MAX_VALUE; long dump = Long.MIN_VALUE; for (final SessionInfo i : infos) { start = min(start, i.getStartTimeStamp()); dump = max(dump, i.getDumpTimeStamp()); } return new SessionInfo(id, start, dump); } /** * Writes all contained {@link SessionInfo} objects into the given visitor. * The info objects are emitted in chronological order by dump timestamp. * * @param visitor * visitor to emit {@link SessionInfo} objects to */ public void accept(final ISessionInfoVisitor visitor) { for (final SessionInfo i : getInfos()) { visitor.visitSessionInfo(i); } } // === ISessionInfoVisitor === public void visitSessionInfo(final SessionInfo info) { infos.add(info); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/data/package-info.java000066400000000000000000000012501304217427400256050ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ /** * Representation and persistence of execution data and session information. */ package org.jacoco.core.data;jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/instr/000077500000000000000000000000001304217427400226465ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/instr/Instrumenter.java000066400000000000000000000201651304217427400262140ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.instr; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.jacoco.core.internal.ContentTypeDetector; import org.jacoco.core.internal.Java9Support; import org.jacoco.core.internal.Pack200Streams; import org.jacoco.core.internal.flow.ClassProbesAdapter; import org.jacoco.core.internal.instr.ClassInstrumenter; import org.jacoco.core.internal.instr.IProbeArrayStrategy; import org.jacoco.core.internal.instr.ProbeArrayStrategyFactory; import org.jacoco.core.internal.instr.SignatureRemover; import org.jacoco.core.runtime.IExecutionDataAccessorGenerator; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; /** * Several APIs to instrument Java class definitions for coverage tracing. */ public class Instrumenter { private final IExecutionDataAccessorGenerator accessorGenerator; private final SignatureRemover signatureRemover; /** * Creates a new instance based on the given runtime. * * @param runtime * runtime used by the instrumented classes */ public Instrumenter(final IExecutionDataAccessorGenerator runtime) { this.accessorGenerator = runtime; this.signatureRemover = new SignatureRemover(); } /** * Determines whether signatures should be removed from JAR files. This is * typically necessary as instrumentation modifies the class files and * therefore invalidates existing JAR signatures. Default is * true. * * @param flag * true if signatures should be removed */ public void setRemoveSignatures(final boolean flag) { signatureRemover.setActive(flag); } /** * Creates a instrumented version of the given class if possible. * * @param reader * definition of the class as ASM reader * @return instrumented definition * */ public byte[] instrument(final ClassReader reader) { final ClassWriter writer = new ClassWriter(reader, 0); final IProbeArrayStrategy strategy = ProbeArrayStrategyFactory .createFor(reader, accessorGenerator); final ClassVisitor visitor = new ClassProbesAdapter( new ClassInstrumenter(strategy, writer), true); reader.accept(visitor, ClassReader.EXPAND_FRAMES); return writer.toByteArray(); } /** * Creates a instrumented version of the given class if possible. * * @param buffer * definition of the class * @param name * a name used for exception messages * @return instrumented definition * @throws IOException * if the class can't be analyzed */ public byte[] instrument(final byte[] buffer, final String name) throws IOException { try { if (Java9Support.isPatchRequired(buffer)) { final byte[] result = instrument( new ClassReader(Java9Support.downgrade(buffer))); Java9Support.upgrade(result); return result; } else { return instrument(new ClassReader(buffer)); } } catch (final RuntimeException e) { throw instrumentError(name, e); } } /** * Creates a instrumented version of the given class if possible. * * @param input * stream to read class definition from * @param name * a name used for exception messages * @return instrumented definition * @throws IOException * if reading data from the stream fails or the class can't be * instrumented */ public byte[] instrument(final InputStream input, final String name) throws IOException { try { return instrument(Java9Support.readFully(input), name); } catch (final RuntimeException e) { throw instrumentError(name, e); } } /** * Creates a instrumented version of the given class file. * * @param input * stream to read class definition from * @param output * stream to write the instrumented version of the class to * @param name * a name used for exception messages * @throws IOException * if reading data from the stream fails or the class can't be * instrumented */ public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { try { output.write(instrument(Java9Support.readFully(input), name)); } catch (final RuntimeException e) { throw instrumentError(name, e); } } private IOException instrumentError(final String name, final RuntimeException cause) { final IOException ex = new IOException(String.format( "Error while instrumenting class %s.", name)); ex.initCause(cause); return ex; } /** * Creates a instrumented version of the given resource depending on its * type. Class files and the content of archive files are instrumented. All * other files are copied without modification. * * @param input * stream to contents from * @param output * stream to write the instrumented version of the contents * @param name * a name used for exception messages * @return number of instrumented classes * @throws IOException * if reading data from the stream fails or a class can't be * instrumented */ public int instrumentAll(final InputStream input, final OutputStream output, final String name) throws IOException { final ContentTypeDetector detector = new ContentTypeDetector(input); switch (detector.getType()) { case ContentTypeDetector.CLASSFILE: instrument(detector.getInputStream(), output, name); return 1; case ContentTypeDetector.ZIPFILE: return instrumentZip(detector.getInputStream(), output, name); case ContentTypeDetector.GZFILE: return instrumentGzip(detector.getInputStream(), output, name); case ContentTypeDetector.PACK200FILE: return instrumentPack200(detector.getInputStream(), output, name); default: copy(detector.getInputStream(), output); return 0; } } private int instrumentZip(final InputStream input, final OutputStream output, final String name) throws IOException { final ZipInputStream zipin = new ZipInputStream(input); final ZipOutputStream zipout = new ZipOutputStream(output); ZipEntry entry; int count = 0; while ((entry = zipin.getNextEntry()) != null) { final String entryName = entry.getName(); if (signatureRemover.removeEntry(entryName)) { continue; } zipout.putNextEntry(new ZipEntry(entryName)); if (!signatureRemover.filterEntry(entryName, zipin, zipout)) { count += instrumentAll(zipin, zipout, name + "@" + entryName); } zipout.closeEntry(); } zipout.finish(); return count; } private int instrumentGzip(final InputStream input, final OutputStream output, final String name) throws IOException { final GZIPOutputStream gzout = new GZIPOutputStream(output); final int count = instrumentAll(new GZIPInputStream(input), gzout, name); gzout.finish(); return count; } private int instrumentPack200(final InputStream input, final OutputStream output, final String name) throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final int count = instrumentAll(Pack200Streams.unpack(input), buffer, name); Pack200Streams.pack(buffer.toByteArray(), output); return count; } private void copy(final InputStream input, final OutputStream output) throws IOException { final byte[] buffer = new byte[1024]; int len; while ((len = input.read(buffer)) != -1) { output.write(buffer, 0, len); } } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/instr/package-info.java000066400000000000000000000013701304217427400260360ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ /** *

* Instrumentation of Java class files for code coverage. The main entry point * is the class {@link org.jacoco.core.instr.Instrumenter}. *

*/ package org.jacoco.core.instr;jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/000077500000000000000000000000001304217427400233235ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/ContentTypeDetector.java000066400000000000000000000060041304217427400301340ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import org.objectweb.asm.Opcodes; /** * Detector for content types of binary streams based on a magic headers. */ public class ContentTypeDetector { /** Unknown file type */ public static final int UNKNOWN = -1; /** File type Java class */ public static final int CLASSFILE = 0xcafebabe; /** File type ZIP archive */ public static final int ZIPFILE = 0x504b0304; /** File type GZIP compressed Data */ public static final int GZFILE = 0x1f8b0000; /** File type Pack200 archive */ public static final int PACK200FILE = 0xcafed00d; private static final int BUFFER_SIZE = 8; private final InputStream in; private final int type; /** * Creates a new detector based on the given input. To process the complete * original input afterwards use the stream returned by * {@link #getInputStream()}. * * @param in * input to read the header from * @throws IOException * if the stream can't be read */ public ContentTypeDetector(final InputStream in) throws IOException { if (in.markSupported()) { this.in = in; } else { this.in = new BufferedInputStream(in, BUFFER_SIZE); } this.in.mark(BUFFER_SIZE); this.type = determineType(this.in); this.in.reset(); } private static int determineType(final InputStream in) throws IOException { final int header = readInt(in); switch (header) { case ZIPFILE: return ZIPFILE; case PACK200FILE: return PACK200FILE; case CLASSFILE: // also verify version to distinguish from Mach Object files: switch (readInt(in)) { case Opcodes.V1_1: case Opcodes.V1_2: case Opcodes.V1_3: case Opcodes.V1_4: case Opcodes.V1_5: case Opcodes.V1_6: case Opcodes.V1_7: case Opcodes.V1_8: case Java9Support.V1_9: return CLASSFILE; } } if ((header & 0xffff0000) == GZFILE) { return GZFILE; } return UNKNOWN; } private static int readInt(final InputStream in) throws IOException { return in.read() << 24 | in.read() << 16 | in.read() << 8 | in.read(); } /** * Returns an input stream instance to read the complete content (including * the header) of the underlying stream. * * @return input stream containing the complete content */ public InputStream getInputStream() { return in; } /** * Returns the detected file type. * * @return file type */ public int getType() { return type; } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/Java9Support.java000066400000000000000000000060241304217427400265370ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Evgeny Mandrikov - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.objectweb.asm.Opcodes; /** * Patching for Java 9 classes, so that ASM can read them. */ public final class Java9Support { /** * Version of the Java 9 class file format. */ public static final int V1_9 = Opcodes.V1_8 + 1; private Java9Support() { } /** * Reads all bytes from an input stream into a byte array. * * @param is * the input stream to read from * @return a byte array containing all the bytes from the stream * @throws IOException * if an I/O error occurs */ public static byte[] readFully(final InputStream is) throws IOException { if (is == null) { throw new IllegalArgumentException(); } final byte[] buf = new byte[1024]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); while (true) { int r = is.read(buf); if (r == -1) { break; } out.write(buf, 0, r); } return out.toByteArray(); } private static void putShort(byte[] b, int index, int s) { b[index] = (byte) (s >>> 8); b[index + 1] = (byte) s; } private static short readShort(byte[] b, int index) { return (short) (((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF)); } /** * Determines whether class definition contains {@link #V1_9} version. * * @param buffer * definition of the class * @return true if class definition contains Java 9 version */ public static boolean isPatchRequired(byte[] buffer) { return readShort(buffer, 6) == V1_9; } /** * Returns new definition of class with version {@link Opcodes#V1_8}, * if it has version {@link #V1_9}. * * @param buffer * definition of the class * @return new definition of the class */ public static byte[] downgradeIfRequired(byte[] buffer) { return isPatchRequired(buffer) ? downgrade(buffer) : buffer; } /** * Replaces version in the definition of class on {@link Opcodes#V1_8}. * * @param b * definition of the class * @return new definition of the class */ public static byte[] downgrade(byte[] b) { byte[] result = new byte[b.length]; System.arraycopy(b, 0, result, 0, b.length); putShort(result, 6, Opcodes.V1_8); return result; } /** * Replaces version in the definition of class on {@link #V1_9}. * * @param b * definition of the class */ public static void upgrade(byte[] b) { putShort(b, 6, V1_9); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/Pack200Streams.java000066400000000000000000000046621304217427400266350ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Pack200; /** * Internal wrapper for the weird Pack200 Java API to allow usage with streams. */ public final class Pack200Streams { /** * Unpack a stream in Pack200 format into a stream in JAR/ZIP format. * * @param input * stream in Pack200 format * @return stream in JAR/ZIP format * @throws IOException * in case of errors with the streams */ public static InputStream unpack(final InputStream input) throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final JarOutputStream jar = new JarOutputStream(buffer); Pack200.newUnpacker().unpack(new NoCloseInput(input), jar); jar.finish(); return new ByteArrayInputStream(buffer.toByteArray()); } /** * Packs a buffer in JAR/ZIP format into a stream in Pack200 format. * * @param source * source in JAR/ZIP format * @param output * stream in Pack200 format * @throws IOException * in case of errors with the streams */ public static void pack(final byte[] source, final OutputStream output) throws IOException { final JarInputStream jar = new JarInputStream(new ByteArrayInputStream( source)); Pack200.newPacker().pack(jar, output); } private static class NoCloseInput extends FilterInputStream { protected NoCloseInput(final InputStream in) { super(in); } @Override public void close() throws IOException { // do not close the underlying stream } } private Pack200Streams() { } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/analysis/000077500000000000000000000000001304217427400251465ustar00rootroot00000000000000jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/analysis/BundleCoverageImpl.java000066400000000000000000000073211304217427400315230ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.jacoco.core.analysis.CoverageNodeImpl; import org.jacoco.core.analysis.IBundleCoverage; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.IPackageCoverage; import org.jacoco.core.analysis.ISourceFileCoverage; /** * Implementation of {@link IBundleCoverage}. */ public class BundleCoverageImpl extends CoverageNodeImpl implements IBundleCoverage { private final Collection packages; /** * Creates a new instance of a bundle with the given name. * * @param name * name of this bundle * @param packages * collection of all packages contained in this bundle */ public BundleCoverageImpl(final String name, final Collection packages) { super(ElementType.BUNDLE, name); this.packages = packages; increment(packages); } /** * Creates a new instance of a bundle with the given name. The packages are * calculated from the given classes and source files. * * @param name * name of this bundle * @param classes * all classes in this bundle * @param sourcefiles * all source files in this bundle */ public BundleCoverageImpl(final String name, final Collection classes, final Collection sourcefiles) { this(name, groupByPackage(classes, sourcefiles)); } private static Collection groupByPackage( final Collection classes, final Collection sourcefiles) { final Map> classesByPackage = new HashMap>(); for (final IClassCoverage c : classes) { addByName(classesByPackage, c.getPackageName(), c); } final Map> sourceFilesByPackage = new HashMap>(); for (final ISourceFileCoverage s : sourcefiles) { addByName(sourceFilesByPackage, s.getPackageName(), s); } final Set packageNames = new HashSet(); packageNames.addAll(classesByPackage.keySet()); packageNames.addAll(sourceFilesByPackage.keySet()); final Collection result = new ArrayList(); for (final String name : packageNames) { Collection c = classesByPackage.get(name); if (c == null) { c = Collections.emptyList(); } Collection s = sourceFilesByPackage.get(name); if (s == null) { s = Collections.emptyList(); } result.add(new PackageCoverageImpl(name, c, s)); } return result; } private static void addByName(final Map> map, final String name, final T value) { Collection list = map.get(name); if (list == null) { list = new ArrayList(); map.put(name, list); } list.add(value); } // === IBundleCoverage implementation === public Collection getPackages() { return packages; } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/analysis/ClassAnalyzer.java000066400000000000000000000065171304217427400305750ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import org.jacoco.core.analysis.IMethodCoverage; import org.jacoco.core.internal.flow.ClassProbesVisitor; import org.jacoco.core.internal.flow.MethodProbesVisitor; import org.jacoco.core.internal.instr.InstrSupport; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Opcodes; /** * Analyzes the structure of a class. */ public class ClassAnalyzer extends ClassProbesVisitor { private final ClassCoverageImpl coverage; private final boolean[] probes; private final StringPool stringPool; /** * Creates a new analyzer that builds coverage data for a class. * * @param coverage * coverage node for the analyzed class data * @param probes * execution data for this class or null * @param stringPool * shared pool to minimize the number of {@link String} instances */ public ClassAnalyzer(final ClassCoverageImpl coverage, final boolean[] probes, final StringPool stringPool) { this.coverage = coverage; this.probes = probes; this.stringPool = stringPool; } @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { coverage.setSignature(stringPool.get(signature)); coverage.setSuperName(stringPool.get(superName)); coverage.setInterfaces(stringPool.get(interfaces)); } @Override public void visitSource(final String source, final String debug) { coverage.setSourceFileName(stringPool.get(source)); } @Override public MethodProbesVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { InstrSupport.assertNotInstrumented(name, coverage.getName()); if (isMethodFiltered(access, name)) { return null; } return new MethodAnalyzer(stringPool.get(name), stringPool.get(desc), stringPool.get(signature), probes) { @Override public void visitEnd() { super.visitEnd(); final IMethodCoverage methodCoverage = getCoverage(); if (methodCoverage.getInstructionCounter().getTotalCount() > 0) { // Only consider methods that actually contain code coverage.addMethod(methodCoverage); } } }; } // TODO: Use filter hook in future private boolean isMethodFiltered(final int access, final String name) { return (access & Opcodes.ACC_SYNTHETIC) != 0 && !name.startsWith("lambda$"); } @Override public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { InstrSupport.assertNotInstrumented(name, coverage.getName()); return super.visitField(access, name, desc, signature, value); } @Override public void visitTotalProbeCount(final int count) { // nothing to do } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/analysis/ClassCoverageImpl.java000066400000000000000000000071331304217427400313600ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import java.util.ArrayList; import java.util.Collection; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.IMethodCoverage; /** * Implementation of {@link IClassCoverage}. */ public class ClassCoverageImpl extends SourceNodeImpl implements IClassCoverage { private final long id; private final boolean noMatch; private final Collection methods; private String signature; private String superName; private String[] interfaces; private String sourceFileName; /** * Creates a class coverage data object with the given parameters. * * @param name * VM name of the class * @param id * class identifier * @param noMatch * true, if class id does not match with execution * data */ public ClassCoverageImpl(final String name, final long id, final boolean noMatch) { super(ElementType.CLASS, name); this.id = id; this.noMatch = noMatch; this.methods = new ArrayList(); this.classCounter = CounterImpl.COUNTER_1_0; } /** * Add a method to this class. * * @param method * method data to add */ public void addMethod(final IMethodCoverage method) { this.methods.add(method); increment(method); // As class is considered as covered when at least one method is // covered: if (methodCounter.getCoveredCount() > 0) { this.classCounter = CounterImpl.COUNTER_0_1; } } /** * Sets the VM signature of the class. * * @param signature * VM signature of the class (may be null) */ public void setSignature(final String signature) { this.signature = signature; } /** * Sets the VM name of the superclass. * * @param superName * VM name of the super class (may be null, i.e. * java/lang/Object) */ public void setSuperName(final String superName) { this.superName = superName; } /** * Sets the VM names of implemented/extended interfaces. * * @param interfaces * VM names of implemented/extended interfaces */ public void setInterfaces(final String[] interfaces) { this.interfaces = interfaces; } /** * Sets the name of the corresponding source file for this class. * * @param sourceFileName * name of the source file */ public void setSourceFileName(final String sourceFileName) { this.sourceFileName = sourceFileName; } // === IClassCoverage implementation === public long getId() { return id; } public boolean isNoMatch() { return noMatch; } public String getSignature() { return signature; } public String getSuperName() { return superName; } public String[] getInterfaceNames() { return interfaces; } public String getPackageName() { final int pos = getName().lastIndexOf('/'); return pos == -1 ? "" : getName().substring(0, pos); } public String getSourceFileName() { return sourceFileName; } public Collection getMethods() { return methods; } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/analysis/CounterImpl.java000066400000000000000000000132241304217427400302540ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import org.jacoco.core.analysis.ICounter; /** * {@link ICounter} implementations. Implementing a factory pattern allows to * share counter instances. */ public abstract class CounterImpl implements ICounter { /** Max counter value for which singletons are created */ private static final int SINGLETON_LIMIT = 30; private static final CounterImpl[][] SINGLETONS = new CounterImpl[SINGLETON_LIMIT + 1][]; static { for (int i = 0; i <= SINGLETON_LIMIT; i++) { SINGLETONS[i] = new CounterImpl[SINGLETON_LIMIT + 1]; for (int j = 0; j <= SINGLETON_LIMIT; j++) { SINGLETONS[i][j] = new Fix(i, j); } } } /** Constant for Counter with 0/0 values. */ public static final CounterImpl COUNTER_0_0 = SINGLETONS[0][0]; /** Constant for Counter with 1/0 values. */ public static final CounterImpl COUNTER_1_0 = SINGLETONS[1][0]; /** Constant for Counter with 0/1 values. */ public static final CounterImpl COUNTER_0_1 = SINGLETONS[0][1]; /** * Mutable version of the counter. */ private static class Var extends CounterImpl { public Var(final int missed, final int covered) { super(missed, covered); } @Override public CounterImpl increment(final int missed, final int covered) { this.missed += missed; this.covered += covered; return this; } } /** * Immutable version of the counter. */ private static class Fix extends CounterImpl { public Fix(final int missed, final int covered) { super(missed, covered); } @Override public CounterImpl increment(final int missed, final int covered) { return getInstance(this.missed + missed, this.covered + covered); } } /** * Factory method to retrieve a counter with the given number of items. * * @param missed * number of missed items * @param covered * number of covered items * @return counter instance */ public static CounterImpl getInstance(final int missed, final int covered) { if (missed <= SINGLETON_LIMIT && covered <= SINGLETON_LIMIT) { return SINGLETONS[missed][covered]; } else { return new Var(missed, covered); } } /** * Factory method to retrieve a clone of the given counter. * * @param counter * counter to copy * @return counter instance */ public static CounterImpl getInstance(final ICounter counter) { return getInstance(counter.getMissedCount(), counter.getCoveredCount()); } /** number of missed items */ protected int missed; /** number of covered items */ protected int covered; /** * Creates a new instance with the given numbers. * * @param missed * number of missed items * @param covered * number of covered items */ protected CounterImpl(final int missed, final int covered) { this.missed = missed; this.covered = covered; } /** * Returns a counter with values incremented by the numbers of the given * counter. It is up to the implementation whether this counter instance is * modified or a new instance is returned. * * @param counter * number of additional total and covered items * @return counter instance with incremented values */ public CounterImpl increment(final ICounter counter) { return increment(counter.getMissedCount(), counter.getCoveredCount()); } /** * Returns a counter with values incremented by the given numbers. It is up * to the implementation whether this counter instance is modified or a new * instance is returned. * * @param missed * number of missed items * @param covered * number of covered items * @return counter instance with incremented values */ public abstract CounterImpl increment(int missed, int covered); // === ICounter implementation === public double getValue(final CounterValue value) { switch (value) { case TOTALCOUNT: return getTotalCount(); case MISSEDCOUNT: return getMissedCount(); case COVEREDCOUNT: return getCoveredCount(); case MISSEDRATIO: return getMissedRatio(); case COVEREDRATIO: return getCoveredRatio(); default: throw new AssertionError(value); } } public int getTotalCount() { return missed + covered; } public int getCoveredCount() { return covered; } public int getMissedCount() { return missed; } public double getCoveredRatio() { return (double) covered / (missed + covered); } public double getMissedRatio() { return (double) missed / (missed + covered); } public int getStatus() { int status = covered > 0 ? FULLY_COVERED : EMPTY; if (missed > 0) { status |= NOT_COVERED; } return status; } @Override public boolean equals(final Object obj) { if (obj instanceof ICounter) { final ICounter that = (ICounter) obj; return this.missed == that.getMissedCount() && this.covered == that.getCoveredCount(); } else { return false; } } @Override public int hashCode() { return missed ^ covered * 17; } @Override public String toString() { final StringBuilder b = new StringBuilder("Counter["); //$NON-NLS-1$ b.append(getMissedCount()); b.append('/').append(getCoveredCount()); b.append(']'); return b.toString(); } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/analysis/LineImpl.java000066400000000000000000000103441304217427400275240ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.analysis.ILine; /** * Implementation of {@link ILine}. */ public abstract class LineImpl implements ILine { /** Max instruction counter value for which singletons are created */ private static final int SINGLETON_INS_LIMIT = 8; /** Max branch counter value for which singletons are created */ private static final int SINGLETON_BRA_LIMIT = 4; private static final LineImpl[][][][] SINGLETONS = new LineImpl[SINGLETON_INS_LIMIT + 1][][][]; static { for (int i = 0; i <= SINGLETON_INS_LIMIT; i++) { SINGLETONS[i] = new LineImpl[SINGLETON_INS_LIMIT + 1][][]; for (int j = 0; j <= SINGLETON_INS_LIMIT; j++) { SINGLETONS[i][j] = new LineImpl[SINGLETON_BRA_LIMIT + 1][]; for (int k = 0; k <= SINGLETON_BRA_LIMIT; k++) { SINGLETONS[i][j][k] = new LineImpl[SINGLETON_BRA_LIMIT + 1]; for (int l = 0; l <= SINGLETON_BRA_LIMIT; l++) { SINGLETONS[i][j][k][l] = new Fix(i, j, k, l); } } } } } /** * Empty line without instructions or branches. */ public static final LineImpl EMPTY = SINGLETONS[0][0][0][0]; private static LineImpl getInstance(final CounterImpl instructions, final CounterImpl branches) { final int im = instructions.getMissedCount(); final int ic = instructions.getCoveredCount(); final int bm = branches.getMissedCount(); final int bc = branches.getCoveredCount(); if (im <= SINGLETON_INS_LIMIT && ic <= SINGLETON_INS_LIMIT && bm <= SINGLETON_BRA_LIMIT && bc <= SINGLETON_BRA_LIMIT) { return SINGLETONS[im][ic][bm][bc]; } return new Var(instructions, branches); } /** * Mutable version. */ private static final class Var extends LineImpl { Var(final CounterImpl instructions, final CounterImpl branches) { super(instructions, branches); } @Override public LineImpl increment(final ICounter instructions, final ICounter branches) { this.instructions = this.instructions.increment(instructions); this.branches = this.branches.increment(branches); return this; } } /** * Immutable version. */ private static final class Fix extends LineImpl { public Fix(final int im, final int ic, final int bm, final int bc) { super(CounterImpl.getInstance(im, ic), CounterImpl.getInstance(bm, bc)); } @Override public LineImpl increment(final ICounter instructions, final ICounter branches) { return getInstance(this.instructions.increment(instructions), this.branches.increment(branches)); } } /** instruction counter */ protected CounterImpl instructions; /** branch counter */ protected CounterImpl branches; private LineImpl(final CounterImpl instructions, final CounterImpl branches) { this.instructions = instructions; this.branches = branches; } /** * Adds the given counters to this line. * * @param instructions * instructions to add * @param branches * branches to add * @return instance with new counter values */ public abstract LineImpl increment(final ICounter instructions, final ICounter branches); // === ILine implementation === public int getStatus() { return instructions.getStatus() | branches.getStatus(); } public ICounter getInstructionCounter() { return instructions; } public ICounter getBranchCounter() { return branches; } @Override public int hashCode() { return 23 * instructions.hashCode() ^ branches.hashCode(); } @Override public boolean equals(final Object obj) { if (obj instanceof ILine) { final ILine that = (ILine) obj; return this.instructions.equals(that.getInstructionCounter()) && this.branches.equals(that.getBranchCounter()); } return false; } } jacoco-0.7.8/org.jacoco.core/src/org/jacoco/core/internal/analysis/MethodAnalyzer.java000066400000000000000000000174421304217427400307470ustar00rootroot00000000000000/******************************************************************************* * Copyright (c) 2009, 2016 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.analysis; import java.util.ArrayList; import java.util.List; import org.jacoco.core.analysis.ICounter; import org.jacoco.core.analysis.IMethodCoverage; import org.jacoco.core.analysis.ISourceNode; import org.jacoco.core.internal.flow.IFrame; import org.jacoco.core.internal.flow.Instruction; import org.jacoco.core.internal.flow.LabelInfo; import org.jacoco.core.internal.flow.MethodProbesVisitor; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; /** * A {@link MethodProbesVisitor} that analyzes which statements and branches of * a method have been executed based on given probe data. */ public class MethodAnalyzer extends MethodProbesVisitor { private final boolean[] probes; private final MethodCoverageImpl coverage; private int currentLine = ISourceNode.UNKNOWN_LINE; private int firstLine = ISourceNode.UNKNOWN_LINE; private int lastLine = ISourceNode.UNKNOWN_LINE; // Due to ASM issue #315745 there can be more than one label per instruction private final List