cobertura-1.9.4.1+dfsg.orig/ 0000755 0001750 0001750 00000000000 11345540725 015474 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/src-2/ 0000755 0001750 0001750 00000000000 11343534517 016422 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/src-2/someotherpackage/ 0000755 0001750 0001750 00000000000 11345540725 021743 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/src-2/someotherpackage/SomeOtherClass.java 0000644 0001750 0001750 00000003076 11343534517 025507 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Jeremy Thomerson
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package someotherpackage;
/**
* This class is only for testing that stuff from multiple source
* directories works properly.
*
* @author Jeremy Thomerson
*/
public class SomeOtherClass {
private int counter;
public SomeOtherClass() {
// no-op
}
public int incrementCounter() {
return ++counter;
}
public int decrementCounter() {
return --counter;
}
public int getCounter() {
return counter;
}
/**
* Don't call this method. It is one that is supposed to not be called
* by the unit tests so that we can verify that everything is being
* recorded properly.
*/
public void neverCallThisMethod() {
throw new UnsupportedOperationException("You weren't supposed to call this method.");
}
}
cobertura-1.9.4.1+dfsg.orig/cobertura-merge.sh 0000644 0001750 0001750 00000000323 11343534512 021104 0 ustar twerner twerner java -cp `dirname $0`/cobertura.jar:`dirname $0`/lib/asm-3.0.jar:`dirname $0`/lib/asm-tree-3.0.jar:`dirname $0`/lib/log4j-1.2.9.jar:`dirname $0`/lib/jakarta-oro-2.0.8.jar net.sourceforge.cobertura.merge.Main $*
cobertura-1.9.4.1+dfsg.orig/cobertura-check.bat 0000644 0001750 0001750 00000001143 11343534513 021220 0 ustar twerner twerner @echo off
REM
REM Grab the directory where this script resides, for use later
REM
set COBERTURA_HOME=%~dp0
REM
REM Read all parameters into a single variable using an ugly loop
REM
set CMD_LINE_ARGS=%1
if ""%1""=="""" goto doneStart
shift
:getArgs
if ""%1""=="""" goto doneStart
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto getArgs
:doneStart
java -cp "%COBERTURA_HOME%cobertura.jar;%COBERTURA_HOME%lib\asm-3.0.jar;%COBERTURA_HOME%lib\asm-tree-3.0.jar;%COBERTURA_HOME%lib\log4j-1.2.9.jar;%COBERTURA_HOME%lib\jakarta-oro-2.0.8.jar" net.sourceforge.cobertura.check.Main %CMD_LINE_ARGS%
cobertura-1.9.4.1+dfsg.orig/cobertura-merge.bat 0000644 0001750 0001750 00000001143 11343534521 021241 0 ustar twerner twerner @echo off
REM
REM Grab the directory where this script resides, for use later
REM
set COBERTURA_HOME=%~dp0
REM
REM Read all parameters into a single variable using an ugly loop
REM
set CMD_LINE_ARGS=%1
if ""%1""=="""" goto doneStart
shift
:getArgs
if ""%1""=="""" goto doneStart
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto getArgs
:doneStart
java -cp "%COBERTURA_HOME%cobertura.jar;%COBERTURA_HOME%lib\asm-3.0.jar;%COBERTURA_HOME%lib\asm-tree-3.0.jar;%COBERTURA_HOME%lib\log4j-1.2.9.jar;%COBERTURA_HOME%lib\jakarta-oro-2.0.8.jar" net.sourceforge.cobertura.merge.Main %CMD_LINE_ARGS%
cobertura-1.9.4.1+dfsg.orig/lib/ 0000755 0001750 0001750 00000000000 11345540725 016242 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/ 0000755 0001750 0001750 00000000000 11345540725 016453 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/ 0000755 0001750 0001750 00000000000 11343534512 017234 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/ 0000755 0001750 0001750 00000000000 11343534512 021557 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/ 0000755 0001750 0001750 00000000000 11343534520 023544 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/ 0000755 0001750 0001750 00000000000 11345540725 025563 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/html/ 0000755 0001750 0001750 00000000000 11345540725 026527 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/html/JavaToHtmlTest.java 0000644 0001750 0001750 00000005071 11343534514 032243 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting.html;
import junit.framework.TestCase;
public class JavaToHtmlTest extends TestCase
{
public static void testSyntaxHighlight()
{
JavaToHtml javaToHtml = new JavaToHtml();
assertEquals(
"package net.sourceforge.cobertura.reporting.html;",
javaToHtml
.process("package net.sourceforge.cobertura.reporting.html;"));
assertEquals(
"import junit.framework.TestCase;",
javaToHtml.process("import junit.framework.TestCase;"));
assertEquals(
"public class javaToHtmlTest extends TestCase {",
javaToHtml
.process("public class javaToHtmlTest extends TestCase {"));
assertEquals(
"public static void testSyntaxHighlight() {",
javaToHtml
.process("public static void testSyntaxHighlight() {"));
assertEquals(
"System.out.println(javaToHtml.process(\"\"));",
javaToHtml
.process("System.out.println(javaToHtml.process(\"\"));"));
assertEquals("}", javaToHtml.process("}"));
assertEquals(" ", javaToHtml.process(" "));
assertEquals(" ", javaToHtml.process(" "));
assertEquals(
"System.out.println('Q');",
javaToHtml.process("System.out.println('Q');"));
assertEquals(
".charAt(currentIndex - 1) == '\\\\')));",
javaToHtml.process(".charAt(currentIndex - 1) == '\\\\')));"));
assertEquals("'\\n'", javaToHtml
.process("'\\n'"));
}
} cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/html/files/ 0000755 0001750 0001750 00000000000 11345540725 027631 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/html/files/CopyFilesTest.java 0000644 0001750 0001750 00000005270 11343534521 033230 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting.html.files;
import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
public class CopyFilesTest extends TestCase
{
private final static String basedir = (System.getProperty("basedir") != null)
? System.getProperty("basedir")
: "./";
private final static File tmpDir = new File(basedir, "/build/test/tmp");
public void setUp()
{
tmpDir.mkdirs();
}
private final static void removeDir(File dir)
{
File files[] = dir.listFiles();
for (int i = 0; i < files.length; i++)
{
if (files[i].isDirectory())
removeDir(files[i]);
else
files[i].delete();
}
dir.delete();
}
public void tearDown()
{
removeDir(tmpDir);
}
public static void testCopy() throws IOException
{
CopyFiles.copy(tmpDir);
assertTrue(new File(tmpDir, "help.html").isFile());
assertTrue(new File(tmpDir, "index.html").isFile());
File cssDir = new File(tmpDir, "css");
assertTrue(cssDir.isDirectory());
assertTrue(new File(cssDir, "help.css").isFile());
assertTrue(new File(cssDir, "main.css").isFile());
assertTrue(new File(cssDir, "sortabletable.css").isFile());
assertTrue(new File(cssDir, "source-viewer.css").isFile());
assertTrue(new File(cssDir, "tooltip.css").isFile());
File imagesDir = new File(tmpDir, "images");
assertTrue(imagesDir.isDirectory());
assertTrue(new File(imagesDir, "blank.png").isFile());
assertTrue(new File(imagesDir, "downsimple.png").isFile());
assertTrue(new File(imagesDir, "upsimple.png").isFile());
File jsDir = new File(tmpDir, "js");
assertTrue(jsDir.isDirectory());
assertTrue(new File(jsDir, "customsorttypes.js").isFile());
assertTrue(new File(jsDir, "popup.js").isFile());
assertTrue(new File(jsDir, "sortabletable.js").isFile());
assertTrue(new File(jsDir, "stringbuilder.js").isFile());
}
} ././@LongLink 0000000 0000000 0000000 00000000145 00000000000 011565 L ustar root root cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/JUnitXMLParserErrorHandler.java cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/JUnitXMLParserErrorHandler.java0000644 0001750 0001750 00000003607 11343534513 033527 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
* Copyright (C) 2005 Grzegorz Lukasik
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting;
import junit.framework.Assert;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
/**
* This is a very simple SAX XML parser ErrorHandler. If
* you are parsing an XML document using a DocumentBuilder,
* and you set the DocumentBuilder's ErrorHandler to an
* instance of this class, and the XML document contains
* any suspect XML, then this class will throw a JUnit
* assertion failure.
*/
public class JUnitXMLParserErrorHandler implements ErrorHandler
{
private void createErrorMessage(SAXParseException exception)
{
Assert.fail("Line number: " + exception.getLineNumber()
+ " column: " + exception.getColumnNumber()
+ "\n"
+ exception.toString());
}
public void error(SAXParseException exception)
{
createErrorMessage(exception);
}
public void fatalError(SAXParseException exception)
{
createErrorMessage(exception);
}
public void warning(SAXParseException exception)
{
createErrorMessage(exception);
}
} ././@LongLink 0000000 0000000 0000000 00000000147 00000000000 011567 L ustar root root cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/JUnitXMLParserEntityResolver.java cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/JUnitXMLParserEntityResolver.ja0000644 0001750 0001750 00000005410 11343534515 033603 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* This is a very simple XML EntityResolver. If
* you are parsing an XML document using a DocumentBuilder,
* and you set the DocumentBuilder's EntityResolver to an
* instance of this class, then we never attempt to resolve
* XML documents on the Internet. Instead we use a local
* copy of the DTD.
*
*
*
* This is done so that the XMLReportTest.java JUnit test will
* not fail when the test is run on a non-networked machine,
* or when webpages must be accessed through a proxy server.
*
*/
public class JUnitXMLParserEntityResolver extends DefaultHandler
{
private final File DTD_DIRECTORY;
public JUnitXMLParserEntityResolver(File dtdDirectory)
{
this.DTD_DIRECTORY = dtdDirectory;
}
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException
{
System.out.println("systemId=" + systemId);
String systemIdBasename = systemId.substring(systemId.lastIndexOf('/'));
File localDtd = new File(this.DTD_DIRECTORY, systemIdBasename);
try
{
return new InputSource(new FileInputStream(localDtd));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open local DTD file "
+ localDtd.getAbsolutePath() + ", using " + systemId
+ " instead.");
}
InputSource source = null;
try {
super.resolveEntity(publicId, systemId);
} catch (Exception exception) {
// apparently 1.5 throws an IOException here, but we can't catch it specifically if
// we're not on 1.5 (docs on both kind of say that they throw it)
// actual code on 1.4.2 has it remmed out so that it only throws SAXException
throw new SAXException(exception);
}
return source;
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/ComplexityCalculatorTest.java 0000644 0001750 0001750 00000015664 11343534521 033444 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Grzegorz Lukasik
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting;
import net.sourceforge.cobertura.coveragedata.ClassData;
import net.sourceforge.cobertura.coveragedata.PackageData;
import net.sourceforge.cobertura.coveragedata.ProjectData;
import net.sourceforge.cobertura.coveragedata.SourceFileData;
import net.sourceforge.cobertura.util.FileFinder;
import net.sourceforge.cobertura.util.FileFixture;
import junit.framework.TestCase;
public class ComplexityCalculatorTest extends TestCase {
private FileFixture fileFixture;
private FileFinder fileFinder;
private ComplexityCalculator complexity;
public void testGetCCNForSourceFile() {
/*
* Sample1.java has a @Deprecated annotation to make sure the complexity works with annotations.
*/
double ccn1 = complexity.getCCNForSourceFile( new SourceFileData("com/example/Sample1.java"));
assertTrue( ccn1!=0.0);
double ccn2 = complexity.getCCNForSourceFile( new SourceFileData("com/example/Sample2.java"));
assertTrue( ccn2!=0.0);
assertTrue( ccn1!=ccn2);
ccn1 = complexity.getCCNForSourceFile( new SourceFileData("com/example/Sample5.java"));
assertTrue( ccn1!=0.0);
ccn2 = complexity.getCCNForSourceFile( new SourceFileData("com/example/Sample6.java"));
assertTrue( ccn2!=0.0);
assertTrue( ccn1!=ccn2);
double ccn0 = complexity.getCCNForSourceFile( new SourceFileData("com/example/Sample8.java"));
assertTrue( ccn0==0.0);
ccn0 = complexity.getCCNForSourceFile( new SourceFileData("Foo.java"));
assertTrue( ccn0==0.0);
}
public void testGetCCNForClass() {
double ccn1 = complexity.getCCNForClass( new ClassData("com.example.Sample3"));
assertTrue( ccn1!=0.0);
double ccn2 = complexity.getCCNForClass( new ClassData("com.example.Sample4"));
assertTrue( ccn2!=0.0);
assertTrue( ccn1!=ccn2);
ccn1 = complexity.getCCNForClass( new ClassData("com.example.Sample5"));
assertTrue( ccn1!=0.0);
ccn2 = complexity.getCCNForClass( new ClassData("com.example.Sample6"));
assertTrue( ccn2!=0.0);
assertTrue( ccn1!=ccn2);
double ccn0 = complexity.getCCNForClass( new ClassData("com.example.Sample8"));
assertEquals( 0.0, ccn0, 0.0);
ccn0 = complexity.getCCNForClass( new ClassData("Foo"));
assertEquals( 0.0, ccn0, 0.0);
}
public void testGetCCNForPackage() {
PackageData pd = new PackageData("com.example");
pd.addClassData( new ClassData("com.example.Sample3"));
double ccn1 = complexity.getCCNForPackage( pd);
assertTrue( ccn1!=0.0);
ComplexityCalculator complexity2 = new ComplexityCalculator( fileFinder);
pd.addClassData( new ClassData("com.example.Sample4"));
double ccn2 = complexity2.getCCNForPackage( pd);
double ccn3 = complexity2.getCCNForPackage( pd);
assertTrue( ccn2!=0.0);
assertTrue( ccn1!=ccn2);
assertEquals( ccn2, ccn3, 0e-9);
PackageData empty = new PackageData( "com.example2");
ComplexityCalculator complexity3 = new ComplexityCalculator( fileFinder);
assertEquals( 0.0, complexity3.getCCNForPackage( empty), 0.0);
}
public void testGetCCNForProject() {
ProjectData project = new ProjectData();
project.addClassData( new ClassData("com.example.Sample5"));
double ccn1 = complexity.getCCNForProject( project);
assertTrue( ccn1!=0.0);
ComplexityCalculator complexity2 = new ComplexityCalculator( fileFinder);
project.addClassData( new ClassData("com.example.Sample4"));
double ccn2 = complexity2.getCCNForProject( project);
assertTrue( ccn2!=0.0);
assertTrue( ccn1!=ccn2);
ComplexityCalculator complexity3 = new ComplexityCalculator( fileFinder);
project.addClassData( new ClassData("com.example.Sample8"));
double ccn3 = complexity3.getCCNForProject( project);
assertEquals( ccn2, ccn3, 0e-9);
ComplexityCalculator complexity4 = new ComplexityCalculator( fileFinder);
double ccn0 = complexity4.getCCNForProject( new ProjectData());
assertEquals( 0.0, ccn0, 0.0);
}
public void testGetCCNForSourceFile_null() {
try {
complexity.getCCNForSourceFile(null);
fail( "NullPointerException expected");
} catch( NullPointerException ex) {}
}
public void testGetCCNForPackage_null() {
try {
complexity.getCCNForPackage(null);
fail( "NullPointerException expected");
} catch( NullPointerException ex) {}
}
public void testGetCCNForProject_null() {
try {
complexity.getCCNForProject(null);
fail( "NullPointerException expected");
} catch( NullPointerException ex) {}
}
public void testConstructor_null() {
try {
new ComplexityCalculator(null);
fail( "NullPointerException expected");
} catch( NullPointerException ex) {}
}
protected void setUp() throws Exception {
super.setUp();
fileFixture = new FileFixture();
fileFixture.setUp();
fileFinder = new FileFinder();
fileFinder.addSourceDirectory(fileFixture.sourceDirectory(FileFixture.SOURCE_DIRECTORY_IDENTIFIER[0]).toString());
fileFinder.addSourceDirectory(fileFixture.sourceDirectory(FileFixture.SOURCE_DIRECTORY_IDENTIFIER[1]).toString());
fileFinder.addSourceFile( fileFixture.sourceDirectory(FileFixture.SOURCE_DIRECTORY_IDENTIFIER[2]).toString(), "com/example\\Sample5.java");
fileFinder.addSourceFile( fileFixture.sourceDirectory(FileFixture.SOURCE_DIRECTORY_IDENTIFIER[2]).toString(), "com/example/Sample6.java");
fileFinder.addSourceFile( fileFixture.sourceDirectory(FileFixture.SOURCE_DIRECTORY_IDENTIFIER[3]).toString(), "com/example/Sample7.java");
// Do not add com/example/Sample8.java
// fileFinder.addSourceFile( fileFixture.sourceDirectory(FileFixture.SOURCE_DIRECTORY_IDENTIFIER[3]).toString(), "com/example/Sample8.java");
complexity = new ComplexityCalculator( fileFinder);
}
protected void tearDown() throws Exception {
super.tearDown();
fileFixture.tearDown();
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/JUnitXMLHelper.java 0000644 0001750 0001750 00000004363 11343534520 031200 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2006 Mark Doliner
* Copyright (C) 2006 John Lewis
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class JUnitXMLHelper
{
private final static String BASEDIR = (System.getProperty("basedir") != null) ? System
.getProperty("basedir") : ".";
/**
* This reads the given file into an XML Document.
* @param file A valid file on the file system.
* @param validate Whether to validate the XML or not.
* @return An XML document representing the given XML file.
* @throws FileNotFoundException If the file does not exist.
* @throws IOException If the file could not be open/read.
* @throws JDOMException If the file is not well-formed XML, or
* if validation is enabled and the document is not
* valid.
*/
public static Document readXmlFile(File file, boolean validate) throws FileNotFoundException,
IOException, JDOMException
{
System.out.println("Reading " + file.getAbsolutePath());
// First create an XML document parser
SAXBuilder saxBuilder = new SAXBuilder();
saxBuilder.setValidation(validate);
saxBuilder.setEntityResolver(new JUnitXMLParserEntityResolver(
new File(BASEDIR, "/etc/dtds")));
saxBuilder.setErrorHandler(new JUnitXMLParserErrorHandler());
return saxBuilder.build(file);
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/xml/ 0000755 0001750 0001750 00000000000 11345540725 026363 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/xml/XMLReportTest.java 0000644 0001750 0001750 00000005035 11343534520 031717 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.reporting.xml;
import java.io.File;
import junit.framework.TestCase;
import net.sourceforge.cobertura.coveragedata.ClassData;
import net.sourceforge.cobertura.coveragedata.ProjectData;
import net.sourceforge.cobertura.reporting.ComplexityCalculator;
import net.sourceforge.cobertura.reporting.JUnitXMLHelper;
import net.sourceforge.cobertura.util.FileFinder;
public class XMLReportTest extends TestCase
{
private final static String BASEDIR = (System.getProperty("basedir") != null) ? System
.getProperty("basedir") : ".";
private final static String PATH_TO_TEST_OUTPUT = BASEDIR + "/build/test/XMLReportTest";
private File tmpDir;
public void setUp()
{
tmpDir = new File(PATH_TO_TEST_OUTPUT);
tmpDir.mkdirs();
}
public void tearDown()
{
tmpDir = new File(PATH_TO_TEST_OUTPUT);
File files[] = tmpDir.listFiles();
for (int i = 0; i < files.length; i++)
files[i].delete();
tmpDir.delete();
}
public void testXMLReportWithNonSourceLines() throws Exception
{
ProjectData projectData = new ProjectData();
// Adding line to the project data that hasn't been yet marked as source line
ClassData cd = projectData.getOrCreateClassData(XMLReport.class.getName());
cd.touch(7777,1);
File reportDir = File.createTempFile("XMLReportTest", "");
reportDir.delete();
reportDir.mkdir();
FileFinder fileFinder = new FileFinder();
ComplexityCalculator complexity = new ComplexityCalculator(fileFinder);
new XMLReport(projectData, reportDir, fileFinder, complexity);
File coverageFile = new File(reportDir, "coverage.xml");
JUnitXMLHelper.readXmlFile(coverageFile, true);
coverageFile.delete();
reportDir.delete();
}
}
././@LongLink 0000000 0000000 0000000 00000000146 00000000000 011566 L ustar root root cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/ComplexityCalculator2Test.groovy cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/reporting/ComplexityCalculator2Test.groov0000644 0001750 0001750 00000013655 11343534513 033740 0 ustar twerner twerner /*
* The Apache Software License, Version 1.1
*
* Copyright (C) 2000-2002 The Apache Software Foundation. All rights
* reserved.
* Copyright (C) 2008 John Lewis
*
* 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Ant" and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* .
*/
package net.sourceforge.cobertura.reporting
import junit.framework.TestCase
import net.sourceforge.cobertura.test.util.TestUtil
import net.sourceforge.cobertura.util.FileFinder
import net.sourceforge.cobertura.coveragedata.SourceFileData
import net.sourceforge.cobertura.reporting.ComplexityCalculator
public class ComplexityCalculator2Test extends TestCase {
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
void setUp() throws Exception {
}
public void testSearchJarsForSourceInJar() {
TestUtil.withTempDir { tempDir ->
def zipFile = TestUtil.createSourceArchive(tempDir)
//create a ComplexityCalculator that will use the archive
def fileFinder = new FileFinder();
fileFinder.addSourceDirectory(zipFile.parentFile.absolutePath);
def complexity = new ComplexityCalculator( fileFinder)
double ccn1 = complexity.getCCNForSourceFile( new SourceFileData(TestUtil.SIMPLE_SOURCE_PATHNAME));
assertTrue( ccn1==1.0);
}
}
public void testAnnotatedSource() {
/*
* Test for bug #2818738.
*/
TestUtil.withTempDir { tempDir ->
def filename = "TBSException.java"
def sourceFile = new File(tempDir, filename)
sourceFile.write('''
public class TBSException extends Exception {
public TBSException (ErrorHandler handler, Exception wrap) {
super(wrap);
@SuppressWarnings("unchecked")
final Iterator iter = handler.getExceptions().iterator(); // LINE 27
for (; iter.hasNext();)
{
Exception exception = iter.next();
this.errors.add(exception.getMessage());
}
}
}
''')
//create a ComplexityCalculator that will use the archive
def fileFinder = new FileFinder();
fileFinder.addSourceDirectory(tempDir.absolutePath);
def complexity = new ComplexityCalculator( fileFinder)
double ccn1 = complexity.getCCNForSourceFile( new SourceFileData(filename));
assertNotNull(ccn1)
assertEquals( 2.0, ccn1 as Double, 0.01);
}
}
/**
* This test highlights an issue with Javancss.
*
* http://jira.codehaus.org/browse/JAVANCSS-37
*
*/
public void testGenericsProblem() {
TestUtil.withTempDir { tempDir ->
def filename = "UserAudit.java"
def sourceFile = new File(tempDir, filename)
sourceFile.write('''
import java.util.ArrayList;
import java.util.List;
public class UserAudit extends UserAuditParent {
void postCopyOnDestination(String str) throws InstantiationException, IllegalAccessException {
List listToReset = new ArrayList();
List auditProducts;
auditProducts = this.copyListFromParent(AllowedMMProductAudit.class, getMmAuthorisedProducts_());
}
List getMmAuthorisedProducts_() {
return null;
}
}
''')
//create a ComplexityCalculator that will use the archive
def fileFinder = new FileFinder();
fileFinder.addSourceDirectory(tempDir.absolutePath);
def complexity = new ComplexityCalculator( fileFinder)
double ccn1 = complexity.getCCNForSourceFile( new SourceFileData(filename));
assertNotNull(ccn1)
assertEquals( "Javancss issue has been fixed: http://jira.codehaus.org/browse/JAVANCSS-37. Now fix this test.", 0.0/*should be 2.0?*/, ccn1 as Double, 0.01);
}
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/ant/ 0000755 0001750 0001750 00000000000 11345540725 024334 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/ant/Util.java 0000644 0001750 0001750 00000004524 11343534513 026115 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2006 John Lewis
* Copyright (C) 2006 Mark Doliner
*
* Note: This file is dual licensed under the GPL and the Apache
* Source License 1.1 (so that it can be used from both the main
* Cobertura classes and the ant tasks).
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.ant;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
class Util
{
static File createTemporaryTextFile(String prefix) throws IOException
{
File outputFile;
outputFile = File.createTempFile(prefix, ".txt");
outputFile.deleteOnExit();
return outputFile;
}
/**
* Returns the text of a file as a string.
*
* @param file The file to read.
* @return A string containing the text of the file
*/
static String getText(File file) throws FileNotFoundException, IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
ps.println(line);
}
ps.close();
}
finally
{
ps.close();
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
System.err.println("IOException when closing file " + file.getAbsolutePath());
e.printStackTrace();
}
}
}
return baos.toString();
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/ant/FunctionalConditionCoverageTest.java 0000644 0001750 0001750 00000036667 11343534514 033503 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2006 John Lewis
* Copyright (C) 2006 Mark Doliner
*
* Note: This file is dual licensed under the GPL and the Apache
* Source License 1.1 (so that it can be used from both the main
* Cobertura classes and the ant tasks).
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.ant;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import net.sourceforge.cobertura.reporting.JUnitXMLHelper;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Path.PathElement;
import org.jdom.Attribute;
import org.jdom.DataConversionException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
import test.condition.ConditionCalls;
/**
* These tests generally exec ant to run a test.xml file. A different target is used for
* each test. The text.xml file sets up a test, instruments, runs junit, and generates a
* coverage xml report. Then the xml report is parsed and checked.
*
* @author jwlewi
*/
public class FunctionalConditionCoverageTest extends TestCase
{
private final static File BASEDIR = new File((System.getProperty("basedir") != null) ? System
.getProperty("basedir") : ".", "examples/functionalconditiontest");
private final static String CONDITION_MISSING_TRUE = "50%";
private final static String CONDITION_MISSING_FALSE = "50%";
private final static Map testInfoMap = new HashMap();
static
{
ConditionTestInfo[] expectedConditions;
TestInfo info;
/*
* Load expected information into testInfoMap for each method.
*/
expectedConditions = new ConditionTestInfo[1];
expectedConditions[0] = new ConditionTestInfo("0", "jump", CONDITION_MISSING_FALSE);
info = new TestInfo(ConditionCalls.CALL_CONDITION_LINE_NUMBER, "50% (1/2)", expectedConditions);
info.setIgnoreLineNumber(ConditionCalls.CALL_IGNORE_LINE_NUMBER);
testInfoMap.put("call", info);
expectedConditions = new ConditionTestInfo[1];
expectedConditions[0] = new ConditionTestInfo("0", "switch", "33%");
info = new TestInfo(ConditionCalls.LOOKUP_SWITCH_LINE_NUMBER, "33% (1/3)", expectedConditions);
testInfoMap.put("callLookupSwitch", info);
expectedConditions = new ConditionTestInfo[1];
expectedConditions[0] = new ConditionTestInfo("0", "switch", "10%");
info = new TestInfo(ConditionCalls.TABLE_SWITCH_LINE_NUMBER, "10% (1/10)", expectedConditions);
testInfoMap.put("callTableSwitch", info);
expectedConditions = new ConditionTestInfo[3];
expectedConditions[0] = new ConditionTestInfo("0", "jump", CONDITION_MISSING_TRUE);
expectedConditions[1] = new ConditionTestInfo("1", "jump", "0%");
expectedConditions[2] = new ConditionTestInfo("2", "jump", CONDITION_MISSING_FALSE);
info = new TestInfo(ConditionCalls.MULTI_CONDITION_LINE_NUMBER, "33% (2/6)", expectedConditions);
testInfoMap.put("callMultiCondition", info);
expectedConditions = new ConditionTestInfo[3];
expectedConditions[0] = new ConditionTestInfo("0", "jump", CONDITION_MISSING_FALSE);
expectedConditions[1] = new ConditionTestInfo("1", "jump", CONDITION_MISSING_FALSE);
expectedConditions[2] = new ConditionTestInfo("2", "jump", "0%");
info = new TestInfo(ConditionCalls.MULTI_CONDITION2_LINE_NUMBER, "33% (2/6)", expectedConditions);
testInfoMap.put("callMultiCondition2", info);
};
private static class TestInfo
{
int conditionNumber;
String expectedLineConditionCoverage;
ConditionTestInfo[] expectedConditions;
Integer ignoreLineNumber;
TestInfo(int conditionNumber, String expectedLineConditionCoverage, ConditionTestInfo[] expectedConditions)
{
this.conditionNumber = conditionNumber;
this.expectedLineConditionCoverage = expectedLineConditionCoverage;
this.expectedConditions = expectedConditions;
}
public void setIgnoreLineNumber(int number) {
ignoreLineNumber = new Integer(number);
}
}
private static class ConditionTestInfo
{
String number;
String type;
String coverage;
ConditionTestInfo(String number, String type, String coverage)
{
this.number = number;
this.type = type;
this.coverage = coverage;
}
}
public static void testConditionCoverage() throws Exception
{
runTestAntScript("condition-coverage", "test-condition-coverage");
verify("condition-coverage");
}
private static void verify(String testName) throws Exception
{
verifyXml(testName);
verifyHtml(testName);
}
private static void verifyXml(String testName) throws Exception
{
// Get a list of all classes listed in the XML report
List classesList = getClassElements();
assertTrue("Test " + testName + ": Did not find any classes listed in the XML report.",
classesList.size() > 0);
boolean conditionCallsClassFound = false;
for (Iterator iter = classesList.iterator(); iter.hasNext();)
{
Element classElement = (Element)iter.next();
String className = classElement.getAttributeValue("name");
if (className.equals("test.condition.ConditionCalls"))
{
conditionCallsClassFound = true;
}
else
fail("Test "
+ testName
+ ": Found a class with the name '"
+ className
+ "' in the XML report, but was only expecting 'test.condition.ConditionCalls'.");
verifyClass(testName, classElement);
}
assertTrue("Test " + testName + ": Did not find class 'test.condition.ConditionCalls' in the XML report.",
conditionCallsClassFound);
}
/**
* Use XPath to get all <class> elements in the
* cobertura.xml file under the given directory.
* @return A list of JDOM Elements.
*/
private static List getClassElements() throws IOException, JDOMException
{
File xmlFile = new File(BASEDIR, "reports/cobertura-xml/coverage.xml");
Document document = JUnitXMLHelper.readXmlFile(xmlFile, true);
XPath xpath = XPath.newInstance("/coverage/packages/package/classes/class");
List classesList = xpath.selectNodes(document);
return classesList;
}
/**
* Verify that the class's condition information is correct.
*/
private static void verifyClass(String testName, Element classElement)
{
// Get a list of methods
Element methodsElement = classElement.getChild("methods");
List methodList = methodsElement.getChildren("method");
assertTrue("Test " + testName + ": Did not find any methods listed in the class "
+ classElement.getAttributeValue("name"), methodList.size() > 0);
List methodsFound = new ArrayList();
for (Iterator iter = methodList.iterator(); iter.hasNext();)
{
Element methodElement = (Element)iter.next();
String methodName = methodElement.getAttributeValue("name");
TestInfo info = (TestInfo) testInfoMap.get(methodName);
if (info != null)
{
if (methodsFound.contains(methodName))
{
fail("Test " + testName
+ ": Found more than one instance of the method " + methodName + " in the class "
+ classElement.getAttributeValue("name"));
}
methodsFound.add(methodName);
verifyMethod(info, testName, classElement, methodElement);
}
else if (methodName.equals("") ||
methodName.equals("") ||
methodName.startsWith("util") ||
methodName.equals("class$"))
{
// These methods are ok--ignore them.
}
else
{
fail("Test " + testName + ": Found method " + methodName + " in the class "
+ classElement.getAttributeValue("name")
+ ", but was only expecting either 'call' or 'dontCall'.");
}
}
/*
* now make sure all methods in testInfoMap were found and verified
*/
for (Iterator iter = testInfoMap.keySet().iterator(); iter.hasNext();) {
String methodName = (String) iter.next();
assertTrue("Test " + testName + ": Did not find method " + methodName + " in the class "
+ classElement.getAttributeValue("name"), methodsFound.contains(methodName));
}
}
private static void verifyMethod(TestInfo info, String testName, Element classElement, Element methodElement) {
Element linesElement = methodElement.getChild("lines");
List lineList = linesElement.getChildren("line");
String methodName = methodElement.getAttributeValue("name");
assertTrue("Test " + testName + ", class " + classElement.getAttributeValue("name")
+ ": Did not find any lines in the method "
+ methodName, lineList.size() > 0);
boolean foundCondition = false;
for (Iterator iter = lineList.iterator(); iter.hasNext();)
{
Element lineElement = (Element)iter.next();
int number;
try {
number = lineElement.getAttribute("number").getIntValue();
if ((info.ignoreLineNumber != null) && (info.ignoreLineNumber.intValue() == number))
{
fail("Expected line " + info.ignoreLineNumber + " to be ignored.");
}
} catch (DataConversionException e) {
throw new RuntimeException(e.toString());
}
if (number == info.conditionNumber) {
foundCondition = true;
verifyLineConditionInfo(lineElement, info.conditionNumber,
info.expectedLineConditionCoverage, info.expectedConditions);
}
}
assertTrue("Expected condition element for line " + info.conditionNumber + " of " + methodName, foundCondition);
}
private static void verifyLineConditionInfo(Element lineElement, int conditionLineNumber,
String expectedLineConditionCoverage, ConditionTestInfo[] expectedConditions)
{
String errorMessage = "Line " + conditionLineNumber;
boolean branch = false;
try {
branch = lineElement.getAttribute("branch").getBooleanValue();
} catch (DataConversionException e) {
fail(errorMessage + " has missing or wrong branch attribute");
}
assertTrue(errorMessage + "Branch attribute should be true", branch);
String lineCoverageStr = getRequiredAttribute(lineElement, "condition-coverage", errorMessage).getValue();
assertEquals(errorMessage + " has incorrect condition-coverage", expectedLineConditionCoverage, lineCoverageStr);
List conditionList = lineElement.getChildren("conditions");
assertTrue(errorMessage + " should have one and only one conditions element.", conditionList.size() == 1);
conditionList = ((Element) conditionList.get(0)).getChildren("condition");
assertEquals(errorMessage + " has incorrect number of condition elements.", expectedConditions.length, conditionList.size());
errorMessage = "Condition for " + conditionLineNumber;
int i = 0;
for (Iterator iter = conditionList.iterator(); iter.hasNext(); i++) {
Element element = (Element) iter.next();
verifyCondition(element, errorMessage, expectedConditions[i]);
}
}
private static void verifyCondition(Element conditionElement, String errorMessage, ConditionTestInfo info)
{
String numberStr = getRequiredAttribute(conditionElement, "number", errorMessage).getValue();
assertEquals(errorMessage + " has incorrect number", info.number, numberStr);
String typeStr = getRequiredAttribute(conditionElement, "type", errorMessage).getValue();
assertEquals(errorMessage + " has incorrect type", info.type, typeStr);
String coverageStr = getRequiredAttribute(conditionElement, "coverage", errorMessage).getValue();
assertEquals(errorMessage + " has incorrect coverage", info.coverage, coverageStr);
}
private static Attribute getRequiredAttribute(Element element, String attribute, String errorMessage) {
Attribute attr = element.getAttribute(attribute);
assertNotNull(errorMessage + " has missing " + attribute + " attribute.", attr);
return attr;
}
private static void verifyHtml(String testName) throws Exception
{
File htmlReportDir = new File(BASEDIR, "reports/cobertura-html");
// Get all files from report directory
String htmlFiles[] = htmlReportDir.list(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".html");
}
});
Arrays.sort(htmlFiles);
assertTrue(htmlFiles.length >= 5);
// Assert that all required files are there
String[] requiredFiles = { "index.html", "help.html", "frame-packages.html",
"frame-summary.html", "frame-sourcefiles.html" };
for (int i = 0; i < requiredFiles.length; i++)
{
if (!containsFile(htmlFiles, requiredFiles[i]))
{
fail("Test " + testName + ": File " + requiredFiles[i]
+ " not found among report files");
}
}
// Validate selected files
String previousPrefix = "NONE";
for (int i = 0; i < htmlFiles.length; i++)
{
// Validate file if has prefix different than previous one, or is required file
if (containsFile(requiredFiles, htmlFiles[i])
|| !htmlFiles[i].startsWith(previousPrefix))
{
JUnitXMLHelper.readXmlFile(new File(htmlReportDir, htmlFiles[i]), true);
}
if (htmlFiles[i].length() > 7)
{
previousPrefix = htmlFiles[i].substring(0, 7);
}
else
{
previousPrefix = htmlFiles[i];
}
}
}
private static boolean containsFile(String[] files, String fileName)
{
for (int i = 0; i < files.length; i++)
{
if (files[i].equals(fileName))
return true;
}
return false;
}
/**
* Use the ant 'java' task to run the test.xml
* file and the specified target.
*/
private static void runTestAntScript(String testName, String target) throws IOException
{
Java task = new Java();
task.setTaskName("java");
task.setProject(new Project());
task.init();
// Call ant launcher. Requires ant-lancher.jar.
task.setClassname("org.apache.tools.ant.launch.Launcher");
task.setFork(true);
AntUtil.transferCoberturaDataFileProperty(task);
task.createArg().setValue("-f");
task.createArg().setValue(BASEDIR + "/build.xml");
task.createArg().setValue(target);
task.setFailonerror(true);
// Set output to go to a temp file
File outputFile = Util.createTemporaryTextFile("cobertura-test");
task.setOutput(outputFile);
// Set the classpath to the same classpath as this JVM
Path classpath = task.createClasspath();
PathElement pathElement = classpath.createPathElement();
pathElement.setPath(System.getProperty("java.class.path"));
try
{
task.execute();
}
finally
{
if (outputFile.exists())
{
// Put the contents of the output file in the exception
System.out.println("\n\n\nOutput from Ant for " + testName
+ " test:\n----------------------------------------\n"
+ Util.getText(outputFile) + "----------------------------------------");
outputFile.delete();
}
}
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/ant/FunctionalTest.java 0000644 0001750 0001750 00000031561 11343534522 030143 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2008 John Lewis
* Copyright (C) 2006 Mark Doliner
*
* Note: This file is dual licensed under the GPL and the Apache
* Source License 1.1 (so that it can be used from both the main
* Cobertura classes and the ant tasks).
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.ant;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import net.sourceforge.cobertura.reporting.JUnitXMLHelper;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Path.PathElement;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
/**
* These tests generally exec ant to run a test.xml file. A different target is used for
* each test. The text.xml file sets up a test, instruments, runs junit, and generates a
* coverage xml report. Then the xml report is parsed and checked.
*
* @author jwlewi
*/
public class FunctionalTest extends TestCase
{
private static int forkedJVMDebugPort = 0;
private final static File BASEDIR = new File((System.getProperty("basedir") != null) ? System
.getProperty("basedir") : ".", "examples/functionaltest1");
public static void testInstrumentUsingDirSet() throws Exception
{
runTestAntScript("dirset", "test-dirset");
verify("dirset");
}
public static void testInstrumentUsingIncludesAndExcludes() throws Exception
{
runTestAntScript("includes-and-excludes", "test-includes-and-excludes");
verify("includes-and-excludes");
}
public static void testInstrumentUsingClassPath() throws Exception
{
runTestAntScript("classpath", "test-classpath");
verify("classpath");
}
public static void testInstrumentUsingWar() throws Exception
{
runTestAntScript("classpath", "test-war");
verify("war");
}
private static void verify(String testName) throws Exception
{
verifyXml(testName);
verifyHtml(testName);
}
private static void verifyXml(String testName) throws Exception
{
Document document = getSummaryXmlReportDocument();
verifyOverallComplexity(document);
document = getXmlReportDocument();
verifyOverallComplexity(document);
// Get a list of all classes listed in the XML report
List classesList = getClassElements(document);
assertTrue("Test " + testName + ": Did not find any classes listed in the XML report.",
classesList.size() > 0);
// text.xml only instruments the two "A" classes, so make
// sure those are the only classes listed in the XML report.
boolean firstPackageFound = false;
boolean secondPackageFound = false;
for (Iterator iter = classesList.iterator(); iter.hasNext();)
{
boolean verify = true;
Element classElement = (Element)iter.next();
String className = classElement.getAttributeValue("name");
if (className.equals("test.first.A"))
{
firstPackageFound = true;
}
else if (className.equals("test.second.A"))
{
secondPackageFound = true;
}
else if (className.equals("test.first.RemoteInterface")
|| (className.equals("test.first.RemoteListener"))
|| (className.equals("test.first.RemoteListener_Stub")))
{
//just ignore - it is ok
verify = false;
}
else
fail("Test "
+ testName
+ ": Found a class with the name '"
+ className
+ "' in the XML report, but was only expecting either 'test.first.A' or 'test.second.A'.");
if (verify)
{
verifyClass(className, testName, classElement);
}
}
assertTrue("Test " + testName + ": Did not find class 'test.first.A' in the XML report.",
firstPackageFound);
assertTrue("Test " + testName + ": Did not find class 'test.second.A' in the XML report.",
secondPackageFound);
}
private static void verifyOverallComplexity(Document document)
{
String complexity = document.getRootElement().getAttributeValue("complexity");
assertEquals("Invalid overall complexity ", "1.0", complexity);
}
private static Document getXmlReportDocument() throws IOException, JDOMException
{
File xmlFile = new File(BASEDIR, "reports/cobertura-xml/coverage.xml");
Document document = JUnitXMLHelper.readXmlFile(xmlFile, true);
return document;
}
private static Document getSummaryXmlReportDocument() throws IOException, JDOMException
{
File xmlFile = new File(BASEDIR, "reports/cobertura-xml/coverage-summary.xml");
Document document = JUnitXMLHelper.readXmlFile(xmlFile, true);
return document;
}
/**
* Use XPath to get all <class> elements in the
* cobertura.xml file under the given directory.
* @return A list of JDOM Elements.
*/
private static List getClassElements(Document document) throws IOException, JDOMException
{
XPath xpath = XPath.newInstance("/coverage/packages/package/classes/class");
List classesList = xpath.selectNodes(document);
return classesList;
}
/**
* Verify that the class's expected methods are found. Look for
* a method called "call" which should have a hit count of 1.
* The method called "dontCall" should have a hit count of 0.
* @param testName
*/
private static void verifyClass(String className, String testName, Element classElement)
{
verifyComplexity(className, classElement);
// Get a list of methods
Element methodsElement = classElement.getChild("methods");
List methodList = methodsElement.getChildren("method");
assertTrue("Test " + testName + ": Did not find any methods listed in the class "
+ classElement.getAttributeValue("name"), methodList.size() > 0);
boolean callMethodFound = false;
boolean dontCallMethodFound = false;
for (Iterator iter = methodList.iterator(); iter.hasNext();)
{
Element methodElement = (Element)iter.next();
String methodName = methodElement.getAttributeValue("name");
if (methodName.equals("call"))
{
if (callMethodFound)
{
fail("Test " + testName
+ ": Found more than one instance of the method 'call' in the class "
+ classElement.getAttributeValue("name"));
}
callMethodFound = true;
verifyMethod(testName, classElement, methodElement, 1);
}
else if (methodName.equals("dontCall"))
{
if (dontCallMethodFound)
{
fail("Test "
+ testName
+ ": Found more than one instance of the method 'dontCall' in the class "
+ classElement.getAttributeValue("name"));
}
dontCallMethodFound = true;
verifyMethod(testName, classElement, methodElement, 0);
}
else if (methodName.equals("") || methodName.equals("someMethod"))
{
// These methods are ok--ignore them.
}
else
{
fail("Test " + testName + ": Found method " + methodName + " in the class "
+ classElement.getAttributeValue("name")
+ ", but was only expecting either 'call' or 'dontCall'.");
}
}
assertTrue("Test " + testName + ": Did not find method 'call' in the class "
+ classElement.getAttributeValue("name"), callMethodFound);
assertTrue("Test " + testName + ": Did not find method 'dontCall' in the class "
+ classElement.getAttributeValue("name"), dontCallMethodFound);
}
private static void verifyComplexity(String className, Element classElement)
{
String complexity = classElement.getAttributeValue("complexity");
assertEquals("Invalid complexity with class " + className, "1.0", complexity);
}
/**
* Look at all lines in a method and make sure they have hit counts that
* match the expectedHits.
*/
private static void verifyMethod(String testName, Element classElement, Element methodElement,
int expectedHits)
{
Element linesElement = methodElement.getChild("lines");
List lineList = linesElement.getChildren("line");
assertTrue("Test " + testName + ", class " + classElement.getAttributeValue("name")
+ ": Did not find any lines in the method "
+ methodElement.getAttributeValue("name"), lineList.size() > 0);
for (Iterator iter = lineList.iterator(); iter.hasNext();)
{
Element lineElement = (Element)iter.next();
String hitsString = lineElement.getAttributeValue("hits");
int hits = Integer.parseInt(hitsString);
assertEquals("Test " + testName + ", class " + classElement.getAttributeValue("name")
+ ": Found incorrect hit count for the method "
+ methodElement.getAttributeValue("name"), expectedHits, hits);
}
}
private static void verifyHtml(String testName) throws Exception
{
File htmlReportDir = new File(BASEDIR, "reports/cobertura-html");
// Get all files from report directory
String htmlFiles[] = htmlReportDir.list(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".html");
}
});
Arrays.sort(htmlFiles);
assertTrue(htmlFiles.length >= 5);
// Assert that all required files are there
String[] requiredFiles = { "index.html", "help.html", "frame-packages.html",
"frame-summary.html", "frame-sourcefiles.html" , "test.first.A.html"};
for (int i = 0; i < requiredFiles.length; i++)
{
if (!containsFile(htmlFiles, requiredFiles[i]))
{
fail("Test " + testName + ": File " + requiredFiles[i]
+ " not found among report files");
}
}
// Validate selected files
String previousPrefix = "NONE";
for (int i = 0; i < htmlFiles.length; i++)
{
// Validate file if has prefix different than previous one, or is required file
if (containsFile(requiredFiles, htmlFiles[i])
|| !htmlFiles[i].startsWith(previousPrefix))
{
JUnitXMLHelper.readXmlFile(new File(htmlReportDir, htmlFiles[i]), true);
}
if (htmlFiles[i].length() > 7)
{
previousPrefix = htmlFiles[i].substring(0, 7);
}
else
{
previousPrefix = htmlFiles[i];
}
}
BufferedReader reader = new BufferedReader(new FileReader(new File(htmlReportDir, "test.first.A.html")));
String line;
boolean foundSomeMethod = false;
while ((line = reader.readLine()) != null) {
if (line.matches(".*someMethod.*")) {
foundSomeMethod = true;
}
}
assertTrue("someMethod not found in test.first.A.html", foundSomeMethod);
}
private static boolean containsFile(String[] files, String fileName)
{
for (int i = 0; i < files.length; i++)
{
if (files[i].equals(fileName))
return true;
}
return false;
}
/**
* Use the ant 'java' task to run the test.xml
* file and the specified target.
*/
private static void runTestAntScript(String testName, String target) throws IOException
{
Java task = new Java();
task.setTaskName("java");
task.setProject(new Project());
task.init();
// Call ant launcher. Requires ant-lancher.jar.
task.setClassname("org.apache.tools.ant.launch.Launcher");
task.setFork(true);
AntUtil.transferCoberturaDataFileProperty(task);
if (forkedJVMDebugPort > 0)
{
task.createJvmarg().setValue("-Xdebug");
task.createJvmarg().setValue("-Xrunjdwp:transport=dt_socket,address=" + forkedJVMDebugPort + ",server=y,suspend=y");
}
task.createArg().setValue("-f");
task.createArg().setValue(BASEDIR + "/build.xml");
task.createArg().setValue(target);
task.setFailonerror(true);
// Set output to go to a temp file
File outputFile = Util.createTemporaryTextFile("cobertura-test");
task.setOutput(outputFile);
// Set the classpath to the same classpath as this JVM
Path classpath = task.createClasspath();
PathElement pathElement = classpath.createPathElement();
pathElement.setPath(System.getProperty("java.class.path"));
try
{
task.execute();
}
finally
{
if (outputFile.exists())
{
// Put the contents of the output file in the exception
System.out.println("\n\n\nOutput from Ant for " + testName
+ " test:\n----------------------------------------\n"
+ Util.getText(outputFile) + "----------------------------------------");
outputFile.delete();
}
}
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/test/ 0000755 0001750 0001750 00000000000 11343534516 024530 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/test/util/ 0000755 0001750 0001750 00000000000 11345540725 025506 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/test/util/TestUtil.groovy 0000644 0001750 0001750 00000020574 11343534516 030541 0 ustar twerner twerner /*
* The Apache Software License, Version 1.1
*
* Copyright (C) 2000-2002 The Apache Software Foundation. All rights
* reserved.
* Copyright (C) 2009 John Lewis
*
* 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Ant" and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* .
*/
package net.sourceforge.cobertura.test.util
import junit.framework.Assert
public class TestUtil {
public static final antBuilder = new AntBuilder()
private static File coberturaClassDir
public static final String SOURCE_TEXT = '''
package a.mypackage;
public class SimpleSource {
public void aSimpleMethod() {
}
}
'''
public static final String SIMPLE_SOURCE_PATHNAME = 'a/mypackage/SimpleSource.java'
/**
* Usage TestUtil.withTempDir { tempDir -> doSomethingWith(tempDir) }
*
* Create a directory under the system's temporary directory, and automatically
* delete it before returning from withTempDir.
*
*/
public static withTempDir(Closure worker) {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File tempSubdir = new File(tempDir, "cobertura_test" + System.currentTimeMillis());
Throwable savedThrowable = null
try {
tempSubdir.mkdirs()
//now call the closure passing it the subdir
worker(tempSubdir)
} catch (Throwable t) {
savedThrowable = t
} finally {
try {
antBuilder.delete(dir:tempSubdir, failonerror:false)
} catch (Throwable t) {
if (savedThrowable) {
//something went wrong with the delete, but the savedThrowable is more important
t.printStackTrace(System.err)
throw savedThrowable
} else {
throw t
}
}
if (savedThrowable) {
throw savedThrowable
}
}
}
public static createSourceArchive(dir)
{
/*
* Create a simple source file in the temporary directory
*/
def sourceDir = new File(dir, "src")
def sourceFile = new File(sourceDir, SIMPLE_SOURCE_PATHNAME)
sourceFile.parentFile.mkdirs()
sourceFile.write(SOURCE_TEXT)
//create a source zip file with the simple source file
def zipDir = new File(dir, "zip")
zipDir.mkdirs()
def zipFile = new File(zipDir, "source.zip")
antBuilder.zip(destfile:zipFile, basedir:sourceDir)
//now delete the source file to make sure we use the zip file
Assert.assertTrue(sourceFile.delete())
return zipFile
}
public static synchronized getCoberturaClassDir() {
if (coberturaClassDir == null)
{
coberturaClassDir = new File("build/test/cobertura_classes")
coberturaClassDir.mkdirs()
antBuilder.javac(srcdir:'src', destdir:coberturaClassDir, debug:true, target:"1.5") {
classpath {
fileset(dir:'lib') {
include(name:'**/*.jar')
}
}
}
}
return coberturaClassDir
}
private static waitForLiveServer(webContainerHostname, webContainerPort, timeoutMin) {
InetSocketAddress address = new InetSocketAddress(webContainerHostname, webContainerPort);
antBuilder.echo(message:"Waiting $timeoutMin min for web server...")
long beginTime = System.currentTimeMillis();
long endTime = System.currentTimeMillis() + (timeoutMin * 60 * 1000);
boolean portOpened = false;
while ((!portOpened) && (System.currentTimeMillis() < endTime)) {
portOpened = trySocket(address);
if (portOpened) {
antBuilder.echo("Web server has opened the port in " + (System.currentTimeMillis() - beginTime)/1000.0/60.0 + " min.");
} else {
try {
Thread.sleep(2000); //2 sec
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (!portOpened) {
throw new RuntimeException("Timed out waiting for webapp server to initialize");
}
}
/**
* Checks to see if a socket is opened.
*/
public static boolean trySocket(InetSocketAddress address) {
boolean success = false;
Socket socket = null
try
{
socket = new Socket()
socket.connect(address);
success = true;
}
catch (ConnectException e) {
//this is expected
}
catch (Throwable e) {
e.printStackTrace();
}
finally {
if (socket)
{
socket.close();
}
}
return success;
}
public static getXMLReportDOM(xmlReport)
{
def parser = new XmlParser()
parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false)
parser.parse(xmlReport)
}
public static isMethodHit(dom, methodName)
{
def methods = dom.packages.'package'.classes.'class'.methods.method
def getMethod = methods.grep { it.'@name' == methodName }
def hitsPerLine = getMethod.lines.line.'@hits'[0]
return (hitsPerLine.any { it.toInteger() >= 1 })
}
public static getHitCount(dom, className, methodName)
{
def classes = dom.packages.'package'.classes.'class'
def clazz = classes.grep { it.'@name' == className }[0]
if (clazz == null)
{
return 0
}
def methods = clazz.methods.method
def method = methods.grep { it.'@name' == methodName }[0]
if (method == null)
{
return 0
}
def firstLine = method.lines.line[0]
if (firstLine == null)
{
return 0
}
def hitCount = firstLine.'@hits'
return hitCount.toInteger()
}
public static getLineCounts(dom, className, methodName)
{
def classes = dom.packages.'package'.classes.'class'
def clazz = classes.grep { it.'@name' == className }[0]
if (clazz == null)
{
return 0
}
def methods = clazz.methods.method
def method = methods.grep { it.'@name' == methodName }[0]
if (method == null)
{
return 0
}
def lines = method.lines.line.collect {[number:it.'@number', hits:it.'@hits'.toInteger()]}
return lines
}
public static getCoberturaAntBuilder(cobertura)
{
def ret = new AntBuilder()
ret.taskdef(resource:"tasks.properties") {
classpath {
pathelement(location:cobertura)
fileset(dir:'lib') {
include(name:"**/*.jar")
}
}
}
ret.taskdef(name:'groovyc', classname:'org.codehaus.groovy.ant.Groovyc') {
classpath {
fileset(dir:'antLibrary/common/groovy') {
include(name:'*.groovy')
}
}
}
return ret
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/test/util/WebappServer.groovy 0000644 0001750 0001750 00000026450 11343534521 031364 0 ustar twerner twerner /*
* The Apache Software License, Version 1.1
*
* Copyright (C) 2000-2002 The Apache Software Foundation. All rights
* reserved.
* Copyright (C) 2009 John Lewis
*
* 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Ant" and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* .
*/
package net.sourceforge.cobertura.test.util
import static org.junit.Assert.*
public class WebappServer
{
static final SIMPLE_SERVLET_CLASSNAME = "com.acme.servlet.SimpleServlet"
static final SIMPLE_SERVLET_TEXT = '''
package com.acme.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.IOException;
public class SimpleServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
out.println("Hi");
}
finally
{
if (out != null)
{
out.close();
}
}
}
}
'''
static final SIMPLE_SERVLET_WEB_XML_TEXT = '''
SimpleServlet
com.acme.servlet.SimpleServlet
SimpleServlet
/SimpleServlet
'''
private static final ant = TestUtil.antBuilder
private static final LOCALHOST = "127.0.0.1"
def dir = "."
def msecNeededToStop = 10000
def coberturaAnt
def modifyMainCoberturaDataFile
boolean tomcat
/**
* Copies a web server installation into dir and deploys a webapp to it.
*
*/
public deployApp(map)
{
modifyMainCoberturaDataFile = map.modifyMainCoberturaDataFile
def extractedDir = new File(dir, "extracted")
def webInfDir = new File(extractedDir, "WEB-INF")
def classesDir = new File(webInfDir, "classes")
def webInfFile = writeWebInfFile(webInfDir, map.webInfText)
compileSourceFiles(map.srcDir, classesDir)
copyJettyFiles(dir)
def war = makeWarFile(map.appName, webInfFile, classesDir)
ant.delete(dir:extractedDir)
def coberturaJar = createCoberturaJar()
coberturaAnt = TestUtil.getCoberturaAntBuilder(TestUtil.getCoberturaClassDir())
if (map.instrumentRegEx)
{
instrumentWar(war, map.instrumentRegEx)
}
if (map.instrumentCobertura)
{
instrumentCoberturaJar(coberturaJar)
}
if (map.deployCoberturaFlush)
{
deployCoberturaFlush(map.instrumentCobertura)
}
}
private writeWebInfFile(webInfDir, text)
{
webInfDir.mkdirs()
def webInfFile = new File(webInfDir, "web.xml")
webInfFile.write(text)
return webInfFile
}
private compileSourceFiles(srcDir, classesDir)
{
ant.mkdir(dir:classesDir)
ant.javac(srcdir:srcDir, destdir:classesDir, debug:'true', target:'1.5') {
classpath {
fileset(dir:"jetty") {
include(name:"**/*.jar")
}
}
}
}
private copyJettyFiles(todir)
{
ant.copy(todir:todir) {
fileset(dir:"jetty")
}
}
private makeWarFile(appName, webInfFile, classesDir)
{
def webappsDir = new File(dir, "webapps")
def war = new File(webappsDir, "${appName}.war")
ant.war(destfile:war, webxml:webInfFile) {
classes(dir:classesDir)
}
return war
}
private deployCoberturaFlush(instrumentCobertura)
{
def webappsDir = new File(dir, "webapps")
def war = new File(webappsDir, "coberturaFlush.war")
/*
* Here we want to make the coberturaFlush war similar to the way
* the production build does it. So, use the same file.
*/
GroovyScriptEngine gse = new GroovyScriptEngine(".")
Binding binding = new Binding()
binding.setVariable("ant", ant)
gse.run("buildUtil.groovy", binding)
//now call the buildWar closure
binding.getVariable("buildWar")(war)
if (instrumentCobertura)
{
instrumentWar(war, "net.sourceforge.cobertura.*")
}
}
private instrumentWar(war, instrumentRegEx)
{
coberturaAnt.'cobertura-instrument'(datafile:"${dir}/cobertura.ser") {
includeClasses(regex:instrumentRegEx)
excludeClasses(regex:'.*Test.*')
fileset(dir:war.getParent()) {
include(name:'*.war')
}
}
}
private instrumentCoberturaJar(coberturaJar)
{
coberturaAnt.'cobertura-instrument'(datafile:"${dir}/cobertura.ser") {
includeClasses(regex:"net.sourceforge.cobertura.*")
excludeClasses(regex:'.*Test.*')
fileset(dir:coberturaJar.getParent()) {
include(name:coberturaJar.name)
}
}
}
/**
* Starts the web server and calls the closure. The web server will be stopped
* when the closure exits (successfully or not).
*
*/
public withRunningServer(closure)
{
def freePorts = findFreePorts()
startWebServer(freePorts)
def data = null
try
{
data = [
xmlReport:new File("${dir}/coverage.xml"),
hostname:LOCALHOST,
webappPort:freePorts.webapp,
coberturaAnt:coberturaAnt]
data.datafile = getDatafileToUse()
/*
* add a closure that can be called to flush the cobertura data
*/
data.flushCobertura = {
def webappResponse = (new java.net.URL("http://${data.hostname}:${data.webappPort}/coberturaFlush/flushCobertura")).text
assertEquals("Response of coberturaFlush unexpected", "", webappResponse.trim())
}
TestUtil.waitForLiveServer(data.hostname, data.webappPort, 1) //1 min timeout
closure.call(data)
}
finally
{
stopWebServer(freePorts.stop)
}
/*
* Wait a bit for the server to stop completely
*/
Thread.sleep(msecNeededToStop)
coberturaAnt.'cobertura-report'(datafile:data.datafile, format:'xml', destdir:data.xmlReport.getParent())
def dom = TestUtil.getXMLReportDOM(data.xmlReport)
data.dom = dom
return data
}
private getDatafileToUse()
{
def datafile = new File("${dir}/cobertura.ser")
if (modifyMainCoberturaDataFile)
{
/*
* modify the cobertura.ser file created by the instrumentation target
* of the main build.xml file. That way, the counts
* will end up in the overall coverage report
*/
def tempfile = new File("build/cobertura.ser")
if (tempfile.exists())
{
datafile = tempfile
}
else
{
/*
* It looks like the main build.xml's instrument target has not been run.
* So, a coverage report is not being generated.
*/
}
}
return datafile
}
/**
* Find two port numbers that can be used to start a webapp server (one port for
* http connections; one port for a stop command).
*/
private findFreePorts()
{
def freePorts = [webapp:null, stop:null]
def webappSocket = null
def stopSocket = null
try
{
webappSocket = new ServerSocket(0, 1, null)
stopSocket = new ServerSocket(0, 1, null)
freePorts.webapp = webappSocket.getLocalPort()
freePorts.stop = stopSocket.getLocalPort()
}
finally
{
closeSocket(webappSocket)
closeSocket(stopSocket)
}
return freePorts
}
private closeSocket(socket)
{
try
{
if (socket) {
socket.close()
}
}
catch (Throwable t)
{
t.printStackTrace(System.err)
}
}
private startWebServer(freePorts)
{
ant.echo(message:"Starting Jetty webapp server on ${freePorts.webapp}")
ant.java(jar:"${dir}/start.jar", dir:dir, fork:true, spawn:true) {
sysproperty(key:'jetty.port', value:freePorts.webapp)
sysproperty(key:'STOP.PORT', value:freePorts.stop)
sysproperty(key:'STOP.KEY', value:'cobertura')
// fool Cobertura into thinking it is running in Tomcat
if (tomcat) {
sysproperty(key:'catalina.home', value:dir.absolutePath)
}
if (modifyMainCoberturaDataFile)
{
sysproperty(key:'net.sourceforge.cobertura.datafile', value:getDatafileToUse().getAbsolutePath())
}
}
}
private stopWebServer(stopPort)
{
ant.java(jar:"${dir}/start.jar", dir:dir, fork:true) {
arg(value:'--stop')
sysproperty(key:'STOP.PORT', value:stopPort)
sysproperty(key:'STOP.KEY', value:'cobertura')
}
}
private createCoberturaJar()
{
def coberturaJar = new File(dir, "lib/cobertura.jar")
def coberturaClassDir = TestUtil.getCoberturaClassDir()
ant.zip(destfile:coberturaJar) {
fileset(dir:coberturaClassDir)
}
return coberturaJar
}
public static writeSimpleServletSource(srcDir)
{
def servletSourceFile = new File(srcDir, "com/acme/servlet/SimpleServlet.java")
servletSourceFile.parentFile.mkdirs()
servletSourceFile.write(SIMPLE_SERVLET_TEXT)
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/ 0000755 0001750 0001750 00000000000 11345540725 026177 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/ClassDataTest.java 0000644 0001750 0001750 00000020727 11343534522 031545 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2003 jcoverage ltd.
* Copyright (C) 2005 Mark Doliner
* Copyright (C) 2006 Jiri Mares
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import java.util.Collection;
import junit.framework.TestCase;
public class ClassDataTest extends TestCase
{
private final ClassData a = new ClassData("com.example.HelloWorld");
private final ClassData b = new ClassData("com.example.HelloWorld");
private final ClassData c = new ClassData("com.example.HelloWorld");
private final ClassData defPckg = new ClassData("DefaultPackageClass");
public void setUp()
{
a.setSourceFileName("com/example/HelloWorld.java");
b.setSourceFileName("com/example/HelloWorld.java");
c.setSourceFileName("com/example/HelloWorld.java");
defPckg.setSourceFileName("DefaultPackageClass.java");
for (int i = 1; i <= 5; i++)
b.addLine(i, "test", "(I)B");
for (int i = 1; i <= 5; i++)
c.addLine(i, "test", "(I)B");
for (int i = 1; i <= 5; i++)
defPckg.addLine(i, "test", "(I)B");
b.touch(1,1);
b.touch(2,1);
}
public void testBranch()
{
// Setting an invalid line as a branch should not make the line valid
assertFalse(a.hasBranch(2));
a.addLineJump(2, 0);
assertFalse(a.hasBranch(2));
assertFalse(b.hasBranch(2));
b.addLineJump(2, 0);
assertTrue(b.hasBranch(2));
assertTrue(b.hasBranch(2));
b.addLineJump(2, 1);
assertTrue(b.hasBranch(2));
assertFalse(b.hasBranch(4));
b.addLineSwitch(4, 0, 1, 9);
assertTrue(b.hasBranch(4));
Collection branches = b.getBranches();
assertEquals(2, branches.size());
assertEquals(14, b.getNumberOfValidBranches());
assertTrue(branches.contains(new Integer(2)));
assertTrue(branches.contains(new Integer(4)));
//assertTrue(branches.contains(new LineData(2, "test", "(I)B")));
//assertTrue(branches.contains(new LineData(4, "test", "(I)B")));
}
public void testBranchCoverage()
{
assertEquals(0, a.getNumberOfValidBranches());
assertEquals(0, b.getNumberOfValidBranches());
assertEquals(1.00d, a.getBranchCoverageRate(), 0d);
assertEquals(1.00d, b.getBranchCoverageRate(), 0d);
assertEquals(1.00d, a.getBranchCoverageRate("test(I)B"), 0d);
assertEquals(1.00d, b.getBranchCoverageRate("test(I)B"), 0d);
c.addLineJump(1, 0);
c.addLineJump(2, 0);
c.addLineSwitch(3, 0, 1, 3);
c.addLineSwitch(4, 0, 1, 3);
assertEquals(12, c.getNumberOfValidBranches());
assertEquals(0, c.getNumberOfCoveredBranches());
assertEquals(0.00d, c.getBranchCoverageRate(), 0d);
assertEquals(0.00d, c.getBranchCoverageRate("test(I)B"), 0d);
c.touchJump(1, 0, true,1);
c.touchJump(1, 0, false,1);
c.touchJump(2, 0, true,1);
c.touchJump(2, 0, false,1);
assertEquals(12, c.getNumberOfValidBranches());
assertEquals(4, c.getNumberOfCoveredBranches());
assertEquals(0.33d, c.getBranchCoverageRate(), 0.01d);
assertEquals(0.33d, c.getBranchCoverageRate("test(I)B"), 0.01d);
c.touchSwitch(3, 0, 0,1);
c.touchSwitch(3, 0, 1,1);
c.touchSwitch(4, 0, 2,1);
c.touchSwitch(4, 0, -1,1);
assertEquals(12, c.getNumberOfValidBranches());
assertEquals(8, c.getNumberOfCoveredBranches());
assertEquals(0.66d, c.getBranchCoverageRate(), 0.01d);
assertEquals(0.66d, c.getBranchCoverageRate("test(I)B"), 0.01d);
}
public void testConstructor()
{
try
{
new ClassData(null);
fail("Expected an IllegalArgumentException but did not receive one!");
}
catch (IllegalArgumentException e)
{
// Good!
}
assertEquals("HelloWorld", a.getBaseName());
assertEquals("com.example", a.getPackageName());
assertEquals("com.example.HelloWorld", a.getName());
assertEquals("DefaultPackageClass", defPckg.getBaseName());
assertEquals("", defPckg.getPackageName());
assertEquals("DefaultPackageClass", defPckg.getName());
}
public void testEquals()
{
assertFalse(a.equals(null));
assertFalse(a.equals(new Integer(4)));
assertFalse(a.equals(new PackageData("com.example")));
assertTrue(a.equals(a));
assertFalse(a.equals(b));
assertFalse(a.equals(c));
assertFalse(a.equals(defPckg));
assertFalse(b.equals(a));
assertTrue(b.equals(b));
assertFalse(b.equals(c));
assertFalse(b.equals(defPckg));
assertFalse(c.equals(a));
assertFalse(c.equals(b));
assertTrue(c.equals(c));
assertFalse(c.equals(defPckg));
assertFalse(defPckg.equals(a));
assertFalse(defPckg.equals(b));
assertFalse(defPckg.equals(c));
assertTrue(defPckg.equals(defPckg));
c.touch(1,1);
c.touch(2,1);
assertTrue(b.equals(c));
}
public void testLineCoverage()
{
assertEquals(0, a.getNumberOfCoveredLines());
assertEquals(0, a.getNumberOfValidLines());
assertEquals(2, b.getNumberOfCoveredLines());
assertEquals(5, b.getNumberOfValidLines());
assertEquals(0, c.getNumberOfCoveredLines());
assertEquals(5, c.getNumberOfValidLines());
assertEquals(1d, a.getLineCoverageRate(), 0d);
assertEquals(0.4d, b.getLineCoverageRate(), 0d);
assertEquals(0d, c.getLineCoverageRate(), 0d);
assertEquals(1d, a.getLineCoverageRate("test(I)B"), 0d);
assertEquals(0.4d, b.getLineCoverageRate("test(I)B"), 0d);
assertEquals(0d, c.getLineCoverageRate("test(I)B"), 0d);
assertEquals(1d, a.getLineCoverageRate("notReal(I)B"), 0d);
assertEquals(1d, b.getLineCoverageRate("notReal(I)B"), 0d);
assertEquals(1d, c.getLineCoverageRate("notReal(I)B"), 0d);
}
public void testRemoveLine()
{
assertEquals(0, a.getNumberOfValidBranches());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(0, a.getNumberOfValidLines());
a.removeLine(3);
assertEquals(0, a.getNumberOfValidBranches());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(0, a.getNumberOfValidLines());
assertEquals(0, b.getNumberOfValidBranches());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(5, b.getNumberOfValidLines());
b.removeLine(3);
assertEquals(0, b.getNumberOfValidBranches());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(4, b.getNumberOfValidLines());
c.addLineJump(2, 0);
c.addLineSwitch(3, 0, 1, 2);
c.addLineJump(3, 0);
c.addLineJump(4, 0);
assertEquals(9, c.getNumberOfValidBranches());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(5, c.getNumberOfValidLines());
c.removeLine(3);
assertEquals(4, c.getNumberOfValidBranches());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(4, c.getNumberOfValidLines());
}
public void testSourceFileName()
{
a.setSourceFileName(null);
assertEquals("com/example/HelloWorld.java", a.getSourceFileName());
a.setSourceFileName("HelloWorld.java");
assertEquals("com/example/HelloWorld.java", a.getSourceFileName());
ClassData d = new ClassData("org.jaxen.expr.IdentitySet$IdentityWrapp");
assertEquals("org/jaxen/expr/IdentitySet.java", d.getSourceFileName());
ClassData e = new ClassData("org.jaxen.expr.NodeComparator$1");
assertEquals("org/jaxen/expr/NodeComparator.java", e.getSourceFileName());
assertEquals( "DefaultPackageClass.java", defPckg.getSourceFileName());
ClassData f = new ClassData("$strangeClass");
assertEquals( "$strangeClass.java", f.getSourceFileName());
}
public void testTouch()
{
int line = 3;
assertFalse(a.isValidSourceLineNumber(line));
a.touch(line,1);
assertTrue(a.isValidSourceLineNumber(line));
assertTrue(b.isValidSourceLineNumber(line));
assertEquals(0, b.getLineCoverage(line).getHits());
b.touch(line,1);
assertTrue(b.isValidSourceLineNumber(line));
assertEquals(1, b.getLineCoverage(line).getHits());
b.touch(line,1);
assertEquals(2, b.getLineCoverage(line).getHits());
assertTrue(b.isValidSourceLineNumber(line));
}
} ././@LongLink 0000000 0000000 0000000 00000000151 00000000000 011562 L ustar root root cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/CoverageDataFileHandlerTest.java cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/CoverageDataFileHandlerTest.0000644 0001750 0001750 00000005161 11343534514 033463 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import java.io.File;
import junit.framework.TestCase;
public class CoverageDataFileHandlerTest extends TestCase
{
private final static String basedir = (System.getProperty("basedir") != null)
? System.getProperty("basedir")
: ".";
private final static String pathToTestOutput = basedir
+ "/build/test/CoverageDataFileHandlerTest";
private final ProjectData a = new ProjectData();
private File tmpDir = new File(pathToTestOutput);
public void setUp()
{
// Create some coverage data
ClassData classData;
assertEquals(0, a.getNumberOfClasses());
assertEquals(0, a.getNumberOfChildren());
classData = new ClassData("HelloWorld");
classData.setSourceFileName("com/example/HelloWorld.java");
for (int i = 0; i < 10; i++)
classData.addLine(i, "test", "(I)B");
a.addClassData(classData);
assertEquals(1, a.getNumberOfClasses());
assertEquals(1, a.getNumberOfChildren());
classData = new ClassData("HelloWorldHelper");
classData.setSourceFileName("com/example/HelloWorldHelper.java");
for (int i = 0; i < 14; i++)
classData.addLine(i, "test", "(I)B");
a.addClassData(classData);
assertEquals(2, a.getNumberOfClasses());
assertEquals(1, a.getNumberOfChildren());
// Create the directory for our serialized coverage data
tmpDir.mkdirs();
}
public void tearDown()
{
tmpDir = new File(pathToTestOutput);
File files[] = tmpDir.listFiles();
for (int i = 0; i < files.length; i++)
files[i].delete();
tmpDir.delete();
}
public void testSaveAndRestore()
{
File dataFile = new File(tmpDir, "cobertura.ser");
CoverageDataFileHandler.saveCoverageData(a, dataFile);
ProjectData b;
b = CoverageDataFileHandler.loadCoverageData(dataFile);
assertEquals(a, b);
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/ProjectDataTest.java 0000644 0001750 0001750 00000013211 11343534515 032076 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
* Copyright (C) 2010 Charlie Squires
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import java.util.Iterator;
import java.util.SortedSet;
import junit.framework.TestCase;
public class ProjectDataTest extends TestCase
{
private ProjectData coverageData;
public void setUp()
{
coverageData = new ProjectData();
}
public void testAddClass()
{
ClassData classData;
assertEquals(0, coverageData.getNumberOfChildren());
assertEquals(0, coverageData.getClasses().size());
assertEquals(null, coverageData.getClassData("gobbleDeeGoop"));
classData = new ClassData("com.example.HelloWorld");
classData.setSourceFileName("com/example/HelloWorld.java");
for (int i = 0; i < 10; i++)
classData.addLine(i, "test", "(I)B");
coverageData.addClassData(classData);
assertEquals(1, coverageData.getNumberOfChildren());
assertEquals(1, coverageData.getClasses().size());
assertEquals(classData, coverageData.getClassData(classData.getName()));
classData = new ClassData("com.example.HelloWorldHelper");
classData.setSourceFileName("com/example/HelloWorldHelper.java");
for (int i = 0; i < 14; i++)
classData.addLine(i, "test", "(I)B");
coverageData.addClassData(classData);
assertEquals(1, coverageData.getNumberOfChildren());
assertEquals(2, coverageData.getClasses().size());
assertEquals(classData, coverageData.getClassData(classData.getName()));
// See what happens when we try to add the same class twice
classData = new ClassData("com.example.HelloWorld");
classData.setSourceFileName("com/example/HelloWorld.java");
for (int i = 0; i < 19; i++)
classData.addLine(i, "test", "(I)B");
try
{
coverageData.addClassData(classData);
// removed by Jeremy Thomerson when changing PackageData
// fail("Expected an IllegalArgumentException but did not receive one!");
}
catch (IllegalArgumentException e)
{
// Good!
}
assertEquals(1, coverageData.getNumberOfChildren());
assertEquals(2, coverageData.getClasses().size());
}
public void testEquals()
{
ProjectData a = new ProjectData();
ProjectData b = new ProjectData();
ProjectData c = new ProjectData();
ClassData classData1 = new ClassData("com.example.HelloWorld1");
ClassData classData2 = new ClassData("com.example.HelloWorld2");
ClassData classData3 = new ClassData("com.example.HelloWorld3");
ClassData classData4 = new ClassData("com.example.HelloWorld4");
classData1.setSourceFileName("com/example/HelloWorld1.java");
classData2.setSourceFileName("com/example/HelloWorld2.java");
classData3.setSourceFileName("com/example/HelloWorld3.java");
classData4.setSourceFileName("com/example/HelloWorld4.java");
a.addClassData(classData1);
a.addClassData(classData2);
a.addClassData(classData3);
b.addClassData(classData1);
b.addClassData(classData2);
c.addClassData(classData1);
c.addClassData(classData2);
c.addClassData(classData4);
assertFalse(a.equals(null));
assertFalse(a.equals(classData1));
assertTrue(a.equals(a));
assertFalse(a.equals(b));
assertFalse(a.equals(c));
assertFalse(b.equals(a));
assertTrue(b.equals(b));
assertFalse(b.equals(c));
assertFalse(c.equals(a));
assertFalse(c.equals(b));
assertTrue(c.equals(c));
b.addClassData(classData3);
assertTrue(a.equals(b));
assertTrue(b.equals(a));
assertFalse(a.equals(c));
assertFalse(c.equals(a));
}
public void testHashCode()
{
ProjectData a = new ProjectData();
ProjectData b = new ProjectData();
ClassData classData1 = new ClassData("com.example.HelloWorld1");
ClassData classData2 = new ClassData("com.example.HelloWorld2");
ClassData classData3 = new ClassData("com.example.HelloWorld3");
classData1.setSourceFileName("com/example/HelloWorld1.java");
classData2.setSourceFileName("com/example/HelloWorld2.java");
classData3.setSourceFileName("com/example/HelloWorld3.java");
a.addClassData(classData1);
a.addClassData(classData2);
a.addClassData(classData3);
b.addClassData(classData1);
b.addClassData(classData2);
assertEquals(a.hashCode(), a.hashCode());
assertEquals(b.hashCode(), b.hashCode());
b.addClassData(classData3);
assertEquals(a.hashCode(), b.hashCode());
}
public void testGetSubPackages()
{
coverageData.addClassData(new ClassData("com.example.HelloWorld"));
coverageData.addClassData(new ClassData("com.example.test.HelloWorldTest"));
coverageData.addClassData(new ClassData("com.examplesomething.HelloWorld"));
SortedSet subPackagesSet = coverageData.getSubPackages("com.example");
assertEquals(2, subPackagesSet.size());
Iterator subPackages = subPackagesSet.iterator();
assertEquals("com.example", ((PackageData)subPackages.next()).getName());
assertEquals("com.example.test", ((PackageData)subPackages.next()).getName());
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/TouchCollectorTest.java 0000644 0001750 0001750 00000006065 11343534522 032636 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2010 John Lewis
*
* Note: This file is dual licensed under the GPL and the Apache
* Source License (so that it can be used from both the main
* Cobertura classes and the ant tasks).
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
public class TouchCollectorTest extends TestCase
{
private static void touchIteratively(int num)
{
for (int i=0; i<2000; i++)
{
/*
* The following yield is needed to make sure the other thread gets
* some CPU. Otherwise, this thread will get too much of a jump ahead
* of the other thread.
*/
Thread.yield();
TouchCollector.touch(Integer.toString(i),1);
}
}
private void runTestWithTwoThreads() throws Throwable
{
final AtomicReference possibleThrowable = new AtomicReference();
ThreadGroup threadGroup = new ThreadGroup("TestThreadGroup") {
public void uncaughtException(Thread thread, Throwable t)
{
/*
* Save the Throwable for later use and interrupt this thread so it exits
*/
possibleThrowable.set(t);
thread.interrupt();
}
};
/*
* Create two threads using the above thread group
*/
Thread thread1 = new Thread(threadGroup, "1") {
public void run()
{
touchIteratively(0);
}
};
Thread thread2 = new Thread(threadGroup, "2") {
public void run()
{
touchIteratively(1);
}
};
thread1.start();
thread2.start();
/*
* Wait for the threads to exit
*/
if (thread1.isAlive()) thread1.join();
if (thread2.isAlive()) thread2.join();
Throwable t = possibleThrowable.get();
if (t != null)
{
throw t;
}
TouchCollector.applyTouchesOnProjectData(new ProjectData());
}
/**
* Tests the thread safety of the TouchCollector. Since TouchCollector has all
* static methods, it is difficult to get this test to fail everytime if
* there is a thread problem.
*
* At the time this test was written, TouchCollector had a problem, but
* this test needed to be run a few times before seeing a failure. The
* majority of times it would fail though.
*/
public void testMultiThreaded() throws Throwable
{
runTestWithTwoThreads();
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/SwitchDataTest.java 0000644 0001750 0001750 00000014201 11343534513 031727 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2006 Jiri Mares
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
public class SwitchDataTest extends TestCase
{
private final SwitchData a = new SwitchData(0, new int[] { 0, 1, 2, 3 });
private final SwitchData b = new SwitchData(1, 1, 9);
public void testEquals()
{
assertFalse(a.equals(null));
assertFalse(a.equals(Integer.valueOf(4)));
assertTrue(a.equals(a));
assertFalse(a.equals(b));
SwitchData aPrime = new SwitchData(0, new int[] { 0, 1, 2, 3 });
assertTrue(a.equals(aPrime));
}
public void testHashCode()
{
assertEquals(a.hashCode(), a.hashCode());
SwitchData aPrime = new SwitchData(0, new int[] { 0, 1, 2, 3 });
assertEquals(a.hashCode(), aPrime.hashCode());
}
public void testGetSwitchNumber()
{
assertEquals(0, a.getSwitchNumber());
assertEquals(1, b.getSwitchNumber());
}
public void testGetNumbers()
{
assertEquals(0, a.getBranchCoverageRate(), 0);
assertEquals(5, a.getNumberOfValidBranches(), 0);
assertEquals(0, a.getNumberOfCoveredBranches(), 0);
for (int i = 0; i < 5; i++)
{
a.touchBranch(1,1);
assertEquals(0.2, a.getBranchCoverageRate(), 0);
assertEquals(5, a.getNumberOfValidBranches(), 0);
assertEquals(1, a.getNumberOfCoveredBranches(), 0);
}
a.touchBranch(-1,1);
assertEquals(0.4, a.getBranchCoverageRate(), 0);
assertEquals(5, a.getNumberOfValidBranches(), 0);
assertEquals(2, a.getNumberOfCoveredBranches(), 0);
a.touchBranch(0,1);
assertEquals(0.6, a.getBranchCoverageRate(), 0);
assertEquals(5, a.getNumberOfValidBranches(), 0);
assertEquals(3, a.getNumberOfCoveredBranches(), 0);
a.touchBranch(2,1);
assertEquals(0.8, a.getBranchCoverageRate(), 0);
assertEquals(5, a.getNumberOfValidBranches(), 0);
assertEquals(4, a.getNumberOfCoveredBranches(), 0);
a.touchBranch(3,1);
assertEquals(1, a.getBranchCoverageRate(), 0);
assertEquals(5, a.getNumberOfValidBranches(), 0);
assertEquals(5, a.getNumberOfCoveredBranches(), 0);
}
public void testTouch()
{
assertEquals(0, a.getHits(0));
for (int i = 0; i < 400; i++)
a.touchBranch(0,1);
assertEquals(400, a.getHits(0));
assertEquals(0, a.getHits(1));
for (int i = 0; i < 4500; i++)
a.touchBranch(1,1);
assertEquals(4500, a.getHits(1));
assertEquals(0, a.getHits(2));
for (int i = 0; i < 300; i++)
a.touchBranch(2,1);
assertEquals(300, a.getHits(2));
assertEquals(0, a.getHits(3));
for (int i = 0; i < 800; i++)
a.touchBranch(3,1);
assertEquals(800, a.getHits(3));
assertEquals(0, a.getDefaultHits());
for (int i = 0; i < 200; i++)
a.touchBranch(-1,1);
assertEquals(200, a.getDefaultHits());
}
public void testMerge()
{
a.touchBranch(0,1);
a.touchBranch(0,1);
a.touchBranch(2,1);
a.touchBranch(-1,1);
SwitchData x = new SwitchData(0);
x.touchBranch(3,1);
x.touchBranch(3,1);
a.merge(x);
assertEquals(2, a.getHits(0));
assertEquals(0, a.getHits(1));
assertEquals(1, a.getHits(2));
assertEquals(2, a.getHits(3));
assertEquals(1, a.getDefaultHits());
x = new SwitchData(0);
x.touchBranch(5,1);
x.touchBranch(-1,1);
a.merge(x);
assertEquals(2, a.getHits(0));
assertEquals(0, a.getHits(1));
assertEquals(1, a.getHits(2));
assertEquals(2, a.getHits(3));
assertEquals(0, a.getHits(4));
assertEquals(1, a.getHits(5));
assertEquals(2, a.getDefaultHits());
}
private static void touchIteratively(SwitchData data, int num)
{
/*
* When this test fails, it usually does so well before 2000 iterations. If it
* gets past 2000, it will usually pass, so there is not much need in going much
* past 2000.
*/
for (int i=0; i<2000; i++)
{
/*
* The following yield is needed to make sure the other thread gets
* some CPU. Otherwise, this thread will get too much of a jump ahead
* of the other thread.
*/
Thread.yield();
data.touchBranch(i,1);
}
}
private void runTestWithTwoThreads() throws Throwable
{
final SwitchData data = new SwitchData(2);
final AtomicReference possibleThrowable = new AtomicReference();
ThreadGroup threadGroup = new ThreadGroup("TestThreadGroup") {
public void uncaughtException(Thread thread, Throwable t)
{
/*
* Save the Throwable for later use and interrupt this thread so it exits
*/
possibleThrowable.set(t);
thread.interrupt();
}
};
/*
* Create two threads using the above thread group
*/
Thread thread1 = new Thread(threadGroup, "1") {
public void run()
{
touchIteratively(data, 0);
}
};
Thread thread2 = new Thread(threadGroup, "2") {
public void run()
{
touchIteratively(data, 1);
}
};
thread1.start();
thread2.start();
/*
* Wait for the threads to exit
*/
if (thread1.isAlive()) thread1.join();
if (thread2.isAlive()) thread2.join();
Throwable t = possibleThrowable.get();
if (t != null)
{
throw t;
}
}
public void testMultiThreaded() throws Throwable
{
/*
* This test will often pass with only one iteration.
* It passes once in a while with 4. It never passes
* with 10 (I hope).
*/
for (int i=0; i<10; i++)
{
runTestWithTwoThreads();
}
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/LineDataTest.java 0000644 0001750 0001750 00000021746 11343534513 031371 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
* Copyright (C) 2006 Jiri Mares
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;
public class LineDataTest extends TestCase
{
private final LineData a = new LineData(10, "test1", "(I)B");
private final LineData b = new LineData(11, "test1", "(I)B");
private final LineData c = new LineData(12, "test2", "(I)B");
private final LineData d = new LineData(13, "test2", "(I)B");
private final LineData e = new LineData(14);
private final LineData f = new LineData(15);
public void testEquals()
{
assertFalse(a.equals(null));
assertFalse(a.equals(new Integer(4)));
assertTrue(a.equals(a));
assertFalse(a.equals(b));
assertFalse(a.equals(c));
assertFalse(a.equals(d));
assertFalse(a.equals(e));
assertFalse(a.equals(f));
LineData aPrime = new LineData(10, "test1", "(I)B");
assertTrue(a.equals(aPrime));
}
public void testHashCode()
{
assertEquals(a.hashCode(), a.hashCode());
LineData aPrime = new LineData(10, "test1", "(I)B");
assertEquals(a.hashCode(), aPrime.hashCode());
}
public void testGetLineNumber()
{
assertEquals(10, a.getLineNumber());
assertEquals(11, b.getLineNumber());
assertEquals(12, c.getLineNumber());
assertEquals(13, d.getLineNumber());
assertEquals(14, e.getLineNumber());
assertEquals(15, f.getLineNumber());
}
public void testGetNumbers()
{
assertEquals(1, a.getBranchCoverageRate(), 0);
assertEquals(0, a.getLineCoverageRate(), 0);
assertEquals(0, a.getNumberOfCoveredLines());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(0, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfValidLines());
a.addJump(0);
a.addJump(1);
assertEquals(0, a.getBranchCoverageRate(), 0);
assertEquals(0, a.getLineCoverageRate(), 0);
assertEquals(0, a.getNumberOfCoveredLines());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(4, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfValidLines());
for (int i = 0; i < 5; i++)
{
a.touch(1);
assertEquals(0, a.getBranchCoverageRate(), 0);
assertEquals(1, a.getLineCoverageRate(), 0);
assertEquals(1, a.getNumberOfCoveredLines());
assertEquals(0, a.getNumberOfCoveredBranches());
assertEquals(4, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfValidLines());
}
a.touchJump(0, true,1);
assertEquals(0.25, a.getBranchCoverageRate(), 0);
assertEquals(1, a.getLineCoverageRate(), 0);
assertEquals(1, a.getNumberOfCoveredLines());
assertEquals(1, a.getNumberOfCoveredBranches());
assertEquals(4, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfValidLines());
a.touchJump(1, false,1);
assertEquals(0.5, a.getBranchCoverageRate(), 0);
assertEquals(1, a.getLineCoverageRate(), 0);
assertEquals(1, a.getNumberOfCoveredLines());
assertEquals(2, a.getNumberOfCoveredBranches());
assertEquals(4, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfValidLines());
a.touchJump(1, true,1);
assertEquals(0.75, a.getBranchCoverageRate(), 0);
assertEquals(1, a.getLineCoverageRate(), 0);
assertEquals(1, a.getNumberOfCoveredLines());
assertEquals(3, a.getNumberOfCoveredBranches());
assertEquals(4, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfValidLines());
a.touchJump(0, false,1);
assertEquals(1, a.getBranchCoverageRate(), 0);
assertEquals(1, a.getLineCoverageRate(), 0);
assertEquals(1, a.getNumberOfCoveredLines());
assertEquals(4, a.getNumberOfCoveredBranches());
assertEquals(4, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfValidLines());
}
public void testSetConditional()
{
assertFalse(c.hasBranch());
c.addJump(0);
assertTrue(c.hasBranch());
c.addJump(1);
assertTrue(c.hasBranch());
}
public void testSetMethodNameAndDescriptor()
{
e.setMethodNameAndDescriptor("test3", "(I)B");
assertEquals("test3", e.getMethodName());
assertEquals("(I)B", e.getMethodDescriptor());
f.setMethodNameAndDescriptor("test4", "(I)B");
assertEquals("test4", f.getMethodName());
assertEquals("(I)B", f.getMethodDescriptor());
}
public void testTouch()
{
assertEquals(0, a.getHits());
for (int i = 0; i < 400; i++)
a.touch(2);
assertEquals(800, a.getHits());
}
private static void getSwitchDataIteratively(LineData data)
{
/*
* When this test fails, it usually does so well before 2000 iterations. If it
* gets past 2000, it will usually pass, so there is not much need in going much
* past 2000.
*/
for (int i=0; i<2000; i++)
{
/*
* The following yield is needed to make sure the other thread gets
* some CPU. Otherwise, this thread will get too much of a jump ahead
* of the other thread.
*/
Thread.yield();
data.getSwitchData(i, new SwitchData(1));
}
}
private void runGetSwitchDataTestWithTwoThreads() throws Throwable
{
final LineData data = new LineData(2);
final AtomicReference possibleThrowable = new AtomicReference();
ThreadGroup threadGroup = new ThreadGroup("TestThreadGroup") {
public void uncaughtException(Thread thread, Throwable t)
{
/*
* Save the Throwable for later use and interrupt this thread so it exits
*/
possibleThrowable.set(t);
thread.interrupt();
}
};
/*
* Create two threads using the above thread group
*/
Thread thread1 = new Thread(threadGroup, "1") {
public void run()
{
getSwitchDataIteratively(data);
}
};
Thread thread2 = new Thread(threadGroup, "2") {
public void run()
{
getSwitchDataIteratively(data);
}
};
thread1.start();
thread2.start();
/*
* Wait for the threads to exit
*/
if (thread1.isAlive()) thread1.join();
if (thread2.isAlive()) thread2.join();
Throwable t = possibleThrowable.get();
if (t != null)
{
throw t;
}
}
public void testMultiThreadedGetSwitchData() throws Throwable
{
/*
* This test will often pass with only one iteration.
* It passes once in a while with 10. It never passes
* with 100 (I hope).
*/
for (int i=0; i<100; i++)
{
runGetSwitchDataTestWithTwoThreads();
}
}
private static void getJumpDataIteratively(LineData data)
{
/*
* When this test fails, it usually does so well before 2000 iterations. If it
* gets past 2000, it will usually pass, so there is not much need in going much
* past 2000.
*/
for (int i=0; i<2000; i++)
{
/*
* The following yield is needed to make sure the other thread gets
* some CPU. Otherwise, this thread will get too much of a jump ahead
* of the other thread.
*/
Thread.yield();
data.getJumpData(i);
}
}
private void runGetJumpDataTestWithTwoThreads() throws Throwable
{
final LineData data = new LineData(2);
final AtomicReference possibleThrowable = new AtomicReference();
ThreadGroup threadGroup = new ThreadGroup("TestThreadGroup") {
public void uncaughtException(Thread thread, Throwable t)
{
/*
* Save the Throwable for later use and interrupt this thread so it exits
*/
possibleThrowable.set(t);
thread.interrupt();
}
};
/*
* Create two threads using the above thread group
*/
Thread thread1 = new Thread(threadGroup, "1") {
public void run()
{
getJumpDataIteratively(data);
}
};
Thread thread2 = new Thread(threadGroup, "2") {
public void run()
{
getJumpDataIteratively(data);
}
};
thread1.start();
thread2.start();
/*
* Wait for the threads to exit
*/
if (thread1.isAlive()) thread1.join();
if (thread2.isAlive()) thread2.join();
Throwable t = possibleThrowable.get();
if (t != null)
{
throw t;
}
}
public void testMultiThreadedGetJumpData() throws Throwable
{
/*
* This test will often pass with only one iteration.
* It passes once in a while with 10. It never passes
* with 100 (I hope).
*/
for (int i=0; i<100; i++)
{
runGetJumpDataTestWithTwoThreads();
}
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/PackageDataTest.java 0000644 0001750 0001750 00000014724 11343534515 032035 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Mark Doliner
* Copyright (C) 2006 Jiri Mares
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import junit.framework.TestCase;
public class PackageDataTest extends TestCase
{
private PackageData packageData;
public void setUp()
{
packageData = new PackageData("com.example");
assertEquals("com.example", packageData.getName());
}
public void testAddClass()
{
ClassData classData;
assertEquals(0, packageData.getNumberOfChildren());
classData = new ClassData("com.example.HelloWorld");
classData.setSourceFileName("com/example/HelloWorld.java");
for (int i = 0; i < 10; i++)
classData.addLine(i, "test", "(I)B");
packageData.addClassData(classData);
assertEquals(1, packageData.getNumberOfChildren());
assertTrue(packageData.contains(classData.getBaseName()));
classData = new ClassData("com.example.HelloWorldHelper");
classData.setSourceFileName("com/example/HelloWorldHelper.java");
for (int i = 0; i < 14; i++)
classData.addLine(i, "test", "(I)B");
packageData.addClassData(classData);
assertEquals(2, packageData.getNumberOfChildren());
assertTrue(packageData.contains(classData.getBaseName()));
// See what happens when we try to add the same class twice
classData = new ClassData("com.example.HelloWorld");
classData.setSourceFileName("com/example/HelloWorld.java");
for (int i = 0; i < 19; i++)
classData.addLine(i, "test", "(I)B");
try
{
packageData.addClassData(classData);
// removed by Jeremy Thomerson when changing PackageData
// fail("Expected an IllegalArgumentException but did not receive one!");
}
catch (IllegalArgumentException e)
{
// Good!
}
assertEquals(2, packageData.getNumberOfChildren());
}
public void testBranchCoverage()
{
assertEquals(0, packageData.getNumberOfCoveredBranches());
assertEquals(0, packageData.getNumberOfValidBranches());
assertEquals(1.00d, packageData.getBranchCoverageRate(), 0d);
ClassData classData = new ClassData("com.example.HelloWorld");
classData.setSourceFileName("com/example/HelloWorld.java");
for (int i = 0; i < 10; i++)
classData.addLine(i, "test", "(I)B");
packageData.addClassData(classData);
assertEquals(0, packageData.getNumberOfCoveredBranches());
assertEquals(0, packageData.getNumberOfValidBranches());
assertEquals(1.00d, packageData.getBranchCoverageRate(), 0d);
classData.addLineJump(1, 0);
classData.addLineSwitch(1, 1, new int[] {1,5});
classData.addLineJump(2, 0);
classData.addLineSwitch(3, 0, 1, 3);
assertEquals(0, packageData.getNumberOfCoveredBranches());
assertEquals(12, packageData.getNumberOfValidBranches());
assertEquals(0.00d, packageData.getBranchCoverageRate(), 0d);
classData.touch(1,1);
classData.touchJump(1, 0, true,1);
classData.touch(1,1);
classData.touchJump(1, 0, false,1);
classData.touchSwitch(1, 1, 0,1);
classData.touch(2,1);
classData.touchJump(2, 0, false,1);
assertEquals(4, packageData.getNumberOfCoveredBranches());
assertEquals(12, packageData.getNumberOfValidBranches());
assertEquals(0.33d, packageData.getBranchCoverageRate(), 0.01d);
}
public void testConstructor()
{
try
{
new PackageData(null);
fail("Expected an IllegalArgumentException but did not receive one!");
}
catch (IllegalArgumentException e)
{
// Good!
}
}
public void testEquals()
{
PackageData a = new PackageData("com.example");
PackageData b = new PackageData("com.example");
PackageData c = new PackageData("com.example");
ClassData classData1 = new ClassData("com.example.HelloWorld1");
ClassData classData2 = new ClassData("com.example.HelloWorld2");
ClassData classData3 = new ClassData("com.example.HelloWorld3");
ClassData classData4 = new ClassData("com.example.HelloWorld4");
classData1.setSourceFileName("com/example/HelloWorld1.java");
classData2.setSourceFileName("com/example/HelloWorld2.java");
classData3.setSourceFileName("com/example/HelloWorld3.java");
classData4.setSourceFileName("com/example/HelloWorld4.java");
a.addClassData(classData1);
a.addClassData(classData2);
a.addClassData(classData3);
b.addClassData(classData1);
b.addClassData(classData2);
c.addClassData(classData1);
c.addClassData(classData2);
c.addClassData(classData4);
assertFalse(a.equals(null));
assertFalse(a.equals(classData1));
assertTrue(a.equals(a));
assertFalse(a.equals(b));
assertFalse(a.equals(c));
assertFalse(b.equals(a));
assertTrue(b.equals(b));
assertFalse(b.equals(c));
assertFalse(c.equals(a));
assertFalse(c.equals(b));
assertTrue(c.equals(c));
b.addClassData(classData3);
assertTrue(a.equals(b));
assertTrue(b.equals(a));
assertFalse(a.equals(c));
assertFalse(c.equals(a));
}
public void testHashCode()
{
PackageData a = new PackageData("com.example");
PackageData b = new PackageData("com.example");
ClassData classData1 = new ClassData("com.example.HelloWorld1");
ClassData classData2 = new ClassData("com.example.HelloWorld2");
ClassData classData3 = new ClassData("com.example.HelloWorld3");
classData1.setSourceFileName("com/example/HelloWorld1.java");
classData2.setSourceFileName("com/example/HelloWorld2.java");
classData3.setSourceFileName("com/example/HelloWorld3.java");
a.addClassData(classData1);
a.addClassData(classData2);
a.addClassData(classData3);
b.addClassData(classData1);
b.addClassData(classData2);
assertEquals(a.hashCode(), a.hashCode());
assertEquals(b.hashCode(), b.hashCode());
b.addClassData(classData3);
assertEquals(a.hashCode(), b.hashCode());
assertEquals(b.hashCode(), b.hashCode());
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/JumpDataTest.java 0000644 0001750 0001750 00000004737 11343534522 031416 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2006 Jiri Mares
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata;
import junit.framework.TestCase;
public class JumpDataTest extends TestCase
{
private final JumpData a = new JumpData(0);
private final JumpData b = new JumpData(1);
public void testEquals()
{
assertFalse(a.equals(null));
assertFalse(a.equals(new Integer(4)));
assertTrue(a.equals(a));
assertFalse(a.equals(b));
JumpData aPrime = new JumpData(0);
assertTrue(a.equals(aPrime));
}
public void testHashCode()
{
assertEquals(a.hashCode(), a.hashCode());
JumpData aPrime = new JumpData(0);
assertEquals(a.hashCode(), aPrime.hashCode());
}
public void testGetBranchNumber()
{
assertEquals(0, a.getConditionNumber());
assertEquals(1, b.getConditionNumber());
}
public void testGetNumbers()
{
assertEquals(0, a.getBranchCoverageRate(), 0);
assertEquals(2, a.getNumberOfValidBranches());
assertEquals(0, a.getNumberOfCoveredBranches());
for (int i = 0; i < 5; i++)
{
a.touchBranch(true,1);
assertEquals(0.5, a.getBranchCoverageRate(), 0);
assertEquals(2, a.getNumberOfValidBranches());
assertEquals(1, a.getNumberOfCoveredBranches());
}
a.touchBranch(false,1);
assertEquals(1, a.getBranchCoverageRate(), 0);
assertEquals(2, a.getNumberOfValidBranches());
assertEquals(2, a.getNumberOfCoveredBranches());
}
public void testTouchBranch()
{
assertEquals(0, a.getTrueHits());
for (int i = 0; i < 400; i++)
a.touchBranch(true,1);
assertEquals(400, a.getTrueHits());
assertEquals(0, a.getFalseHits());
for (int i = 0; i < 200; i++)
a.touchBranch(false,1);
assertEquals(200, a.getFalseHits());
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/countermaps/ 0000755 0001750 0001750 00000000000 11345540725 030537 5 ustar twerner twerner ././@LongLink 0000000 0000000 0000000 00000000156 00000000000 011567 L ustar root root cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/countermaps/AtomicCounterMapTest.java cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/coveragedata/countermaps/AtomicCounterMap0000644 0001750 0001750 00000005501 11343534516 033674 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2010 Piotr Tabor
*
* Note: This file is dual licensed under the GPL and the Apache
* Source License (so that it can be used from both the main
* Cobertura classes and the ant tasks).
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.coveragedata.countermaps;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
public class AtomicCounterMapTest {
@Test
public void incrementTest(){
AtomicCounterMap map=new AtomicCounterMap();
for(int i=0; i<1000; i++){
for(int j=i; j>=0; j-- ){
map.incrementValue(j);
}
}
Map res=map.getFinalStateAndCleanIt();
Assert.assertEquals(1000, res.size());
for(Map.Entry ii:res.entrySet()){
Assert.assertEquals(1000,ii.getKey()+ii.getValue());
}
Assert.assertEquals(0, map.getFinalStateAndCleanIt().size());
for(int i=0; i<100; i++){
for(int j=i; j>=0; j-- ){
map.incrementValue(j,2);
map.incrementValue(j,-1);
}
}
res=map.getFinalStateAndCleanIt();
Assert.assertEquals(100, res.size());
for(Map.Entry ii:res.entrySet()){
Assert.assertEquals(100,ii.getKey()+ii.getValue());
}
}
//1.347;1.288;1.729;1.287 - counters.putIfAbsent(key, new AtomicInteger(inc)); return ...
//1.982;1.965;1.965
//1.935;1.944,1.937 - no return
//1.923;1.960;1.325;1.951 - final
@Test
public void performanceTestInit(){
AtomicCounterMap map=new AtomicCounterMap();
for(int i=0; i<1000000; i++){
map.incrementValue(i);
}
}
//1.349;1,760;1.363;1.780
//0.718;0.678;0,681 AtomicInteger v=counters.get(key);if(v!=null){return v.incrementAndGet();}else{v=counters.putIfAbsent(key, new AtomicInteger(1));return (v!=null)?v.incrementAndGet():1;}
//0.679,0.689,0.681 - no return
//0.675;0.680,0.710,0.679 - final
@Test
public void performanceTestOverride(){
AtomicCounterMap map=new AtomicCounterMap();
for(int i=0; i<10000000; i++){
map.incrementValue(1);
}
}
}
cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/util/ 0000755 0001750 0001750 00000000000 11345540725 024527 5 ustar twerner twerner cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/util/StringUtilTest.java 0000644 0001750 0001750 00000003503 11343534520 030331 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 Jeremy Thomerson
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.util;
import junit.framework.TestCase;
/**
* @author Jeremy Thomerson
*/
public class StringUtilTest extends TestCase
{
public void testReplace()
{
String result;
result = StringUtil.replaceAll(
"cobertura is a very, very cool coverage tool", "very",
"really");
assertEquals("cobertura is a really, really cool coverage tool",
result);
result = StringUtil.replaceAll("V", "<", "<");
result = StringUtil.replaceAll(result, ">", ">");
assertEquals(result, "<init>V");
result = StringUtil.replaceAll("V", "<", "<");
result = StringUtil.replaceAll(result, ">", ">");
assertEquals(result, "<init>V");
assertEquals(null, StringUtil.replaceAll(null, "something", "anything"));
}
public void testGetPercentValue() {
assertEquals("99%", StringUtil.getPercentValue((double) 199/200));
}
public static void main(String[] args)
{
new StringUtilTest().testReplace();
}
} cobertura-1.9.4.1+dfsg.orig/test/net/sourceforge/cobertura/util/FileFixture.java 0000644 0001750 0001750 00000010512 11343534513 027613 0 ustar twerner twerner /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2005 James Seigel
* Copyright (C) 2005 Grzegorz Lukasik
* Copyright (C) 2008 John Lewis
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
// Creates structre:
// src0/
// com/
// example/
// Sample1.java (contains a @Deprecated annotation to make sure the complexity works with annotations)
// Sample2.java
// src1/
// com/
// example/
// Sample3.java
// Sample4.java
// src2/
// com/
// example/
// Sample5.java
// Sample6.java
// src3/
// com/
// example/
// Sample7.java
// Sample8.java
public class FileFixture {
public static final String[] SOURCE_DIRECTORY_IDENTIFIER = { "src0", "src1", "src2", "src3" };
public HashMap sourceDirectories;
public void setUp() throws IOException {
File tempFile = File.createTempFile("temp", ".tmp");
tempFile.deleteOnExit();
sourceDirectories = new HashMap();
for( int i=0; i