KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > cobertura > ant > FunctionalTest


1 /*
2  * Cobertura - http://cobertura.sourceforge.net/
3  *
4  * Copyright (C) 2006 John Lewis
5  * Copyright (C) 2006 Mark Doliner
6  *
7  * Note: This file is dual licensed under the GPL and the Apache
8  * Source License 1.1 (so that it can be used from both the main
9  * Cobertura classes and the ant tasks).
10  *
11  * Cobertura is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published
13  * by the Free Software Foundation; either version 2 of the License,
14  * or (at your option) any later version.
15  *
16  * Cobertura is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with Cobertura; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24  * USA
25  */

26
27 package net.sourceforge.cobertura.ant;
28
29 import java.io.File JavaDoc;
30 import java.io.FilenameFilter JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.util.Arrays JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.List JavaDoc;
35
36 import junit.framework.TestCase;
37 import net.sourceforge.cobertura.reporting.JUnitXMLHelper;
38
39 import org.apache.tools.ant.Project;
40 import org.apache.tools.ant.taskdefs.Java;
41 import org.apache.tools.ant.types.Path;
42 import org.apache.tools.ant.types.Path.PathElement;
43 import org.jdom.Document;
44 import org.jdom.Element;
45 import org.jdom.JDOMException;
46 import org.jdom.xpath.XPath;
47
48 /**
49  * These tests generally exec ant to run a test.xml file. A different target is used for
50  * each test. The text.xml file sets up a test, instruments, runs junit, and generates a
51  * coverage xml report. Then the xml report is parsed and checked.
52  *
53  * @author jwlewi
54  */

55 public class FunctionalTest extends TestCase
56 {
57
58     private final static File JavaDoc BASEDIR = new File JavaDoc((System.getProperty("basedir") != null) ? System
59             .getProperty("basedir") : ".", "examples/functionaltest1");
60
61     public static void testInstrumentUsingIncludesAndExcludes() throws Exception JavaDoc
62     {
63         runTestAntScript("includes-and-excludes", "test-includes-and-excludes");
64         verify("includes-and-excludes");
65     }
66
67     public static void testInstrumentUsingClassPath() throws Exception JavaDoc
68     {
69         runTestAntScript("classpath", "test-classpath");
70         verify("classpath");
71     }
72
73     public static void testInstrumentUsingWar() throws Exception JavaDoc
74     {
75         runTestAntScript("classpath", "test-war");
76         verify("war");
77     }
78
79     private static void verify(String JavaDoc testName) throws Exception JavaDoc
80     {
81         verifyXml(testName);
82         verifyHtml(testName);
83     }
84
85     private static void verifyXml(String JavaDoc testName) throws Exception JavaDoc
86     {
87         // Get a list of all classes listed in the XML report
88
List JavaDoc classesList = getClassElements();
89         assertTrue("Test " + testName + ": Did not find any classes listed in the XML report.",
90                 classesList.size() > 0);
91
92         // text.xml only instruments the two "A" classes, so make
93
// sure hose are the only classes listed in the XML report.
94
boolean firstPackageFound = false;
95         boolean secondPackageFound = false;
96         for (Iterator JavaDoc iter = classesList.iterator(); iter.hasNext();)
97         {
98             Element classElement = (Element)iter.next();
99             String JavaDoc className = classElement.getAttributeValue("name");
100             if (className.equals("test.first.A"))
101             {
102                 firstPackageFound = true;
103             }
104             else if (className.equals("test.second.A"))
105             {
106                 secondPackageFound = true;
107             }
108             else
109                 fail("Test "
110                         + testName
111                         + ": Found a class with the name '"
112                         + className
113                         + "' in the XML report, but was only expecting either 'test.first.A' or 'test.second.A'.");
114             verifyClass(testName, classElement);
115         }
116         assertTrue("Test " + testName + ": Did not find class 'test.first.A' in the XML report.",
117                 firstPackageFound);
118         assertTrue("Test " + testName + ": Did not find class 'test.second.A' in the XML report.",
119                 secondPackageFound);
120     }
121
122     /**
123      * Use XPath to get all <class> elements in the
124      * cobertura.xml file under the given directory.
125      * @return A list of JDOM Elements.
126      */

127     private static List JavaDoc getClassElements() throws IOException JavaDoc, JDOMException
128     {
129         File JavaDoc xmlFile = new File JavaDoc(BASEDIR, "reports/cobertura-xml/coverage.xml");
130         Document document = JUnitXMLHelper.readXmlFile(xmlFile, true);
131         XPath xpath = XPath.newInstance("/coverage/packages/package/classes/class");
132         List JavaDoc classesList = xpath.selectNodes(document);
133         return classesList;
134     }
135
136     /**
137      * Verify that the class's expected methods are found. Look for
138      * a method called "call" which should have a hit count of 1.
139      * The method called "dontCall" should have a hit count of 0.
140      */

141     private static void verifyClass(String JavaDoc testName, Element classElement)
142     {
143         // Get a list of methods
144
Element methodsElement = classElement.getChild("methods");
145         List JavaDoc methodList = methodsElement.getChildren("method");
146         assertTrue("Test " + testName + ": Did not find any methods listed in the class "
147                 + classElement.getAttributeValue("name"), methodList.size() > 0);
148         boolean callMethodFound = false;
149         boolean dontCallMethodFound = false;
150         for (Iterator JavaDoc iter = methodList.iterator(); iter.hasNext();)
151         {
152             Element methodElement = (Element)iter.next();
153             String JavaDoc methodName = methodElement.getAttributeValue("name");
154             if (methodName.equals("call"))
155             {
156                 if (callMethodFound)
157                 {
158                     fail("Test " + testName
159                             + ": Found more than one instance of the method 'call' in the class "
160                             + classElement.getAttributeValue("name"));
161                 }
162                 callMethodFound = true;
163                 verifyMethod(testName, classElement, methodElement, 1);
164             }
165             else if (methodName.equals("dontCall"))
166             {
167                 if (dontCallMethodFound)
168                 {
169                     fail("Test "
170                             + testName
171                             + ": Found more than one instance of the method 'dontCall' in the class "
172                             + classElement.getAttributeValue("name"));
173                 }
174                 dontCallMethodFound = true;
175                 verifyMethod(testName, classElement, methodElement, 0);
176             }
177             else if (methodName.equals("<init>") || methodName.equals("someMethod"))
178             {
179                 // These methods are ok--ignore them.
180
}
181             else
182             {
183                 fail("Test " + testName + ": Found method " + methodName + " in the class "
184                         + classElement.getAttributeValue("name")
185                         + ", but was only expecting either 'call' or 'dontCall'.");
186             }
187         }
188         assertTrue("Test " + testName + ": Did not find method 'call' in the class "
189                 + classElement.getAttributeValue("name"), callMethodFound);
190         assertTrue("Test " + testName + ": Did not find method 'dontCall' in the class "
191                 + classElement.getAttributeValue("name"), dontCallMethodFound);
192     }
193
194     /**
195      * Look at all lines in a method and make sure they have hit counts that
196      * match the expectedHits.
197      */

198     private static void verifyMethod(String JavaDoc testName, Element classElement, Element methodElement,
199             int expectedHits)
200     {
201         Element linesElement = methodElement.getChild("lines");
202         List JavaDoc lineList = linesElement.getChildren("line");
203         assertTrue("Test " + testName + ", class " + classElement.getAttributeValue("name")
204                 + ": Did not find any lines in the method "
205                 + methodElement.getAttributeValue("name"), lineList.size() > 0);
206
207         for (Iterator JavaDoc iter = lineList.iterator(); iter.hasNext();)
208         {
209             Element lineElement = (Element)iter.next();
210             String JavaDoc hitsString = lineElement.getAttributeValue("hits");
211             int hits = Integer.parseInt(hitsString);
212             assertEquals("Test " + testName + ", class " + classElement.getAttributeValue("name")
213                     + ": Found incorrect hit count for the method "
214                     + methodElement.getAttributeValue("name"), expectedHits, hits);
215         }
216     }
217
218     private static void verifyHtml(String JavaDoc testName) throws Exception JavaDoc
219     {
220         File JavaDoc htmlReportDir = new File JavaDoc(BASEDIR, "reports/cobertura-html");
221
222         // Get all files from report directory
223
String JavaDoc htmlFiles[] = htmlReportDir.list(new FilenameFilter JavaDoc()
224         {
225
226             public boolean accept(File JavaDoc dir, String JavaDoc name)
227             {
228                 return name.endsWith(".html");
229             }
230         });
231         Arrays.sort(htmlFiles);
232
233         assertTrue(htmlFiles.length >= 5);
234
235         // Assert that all required files are there
236
String JavaDoc[] requiredFiles = { "index.html", "help.html", "frame-packages.html",
237                 "frame-summary.html", "frame-sourcefiles.html" };
238
239         for (int i = 0; i < requiredFiles.length; i++)
240         {
241             if (!containsFile(htmlFiles, requiredFiles[i]))
242             {
243                 fail("Test " + testName + ": File " + requiredFiles[i]
244                         + " not found among report files");
245             }
246         }
247
248         // Validate selected files
249
String JavaDoc previousPrefix = "NONE";
250         for (int i = 0; i < htmlFiles.length; i++)
251         {
252             // Validate file if has prefix different than previous one, or is required file
253
if (containsFile(requiredFiles, htmlFiles[i])
254                     || !htmlFiles[i].startsWith(previousPrefix))
255             {
256                 JUnitXMLHelper.readXmlFile(new File JavaDoc(htmlReportDir, htmlFiles[i]), true);
257             }
258             if (htmlFiles[i].length() > 7)
259             {
260                 previousPrefix = htmlFiles[i].substring(0, 7);
261             }
262             else
263             {
264                 previousPrefix = htmlFiles[i];
265             }
266         }
267     }
268
269     private static boolean containsFile(String JavaDoc[] files, String JavaDoc fileName)
270     {
271         for (int i = 0; i < files.length; i++)
272         {
273             if (files[i].equals(fileName))
274                 return true;
275         }
276         return false;
277     }
278
279     /**
280      * Use the ant 'java' task to run the test.xml
281      * file and the specified target.
282      */

283     private static void runTestAntScript(String JavaDoc testName, String JavaDoc target) throws IOException JavaDoc
284     {
285         Java task = new Java();
286         task.setTaskName("java");
287         task.setProject(new Project());
288         task.init();
289
290         // Call ant launcher. Requires ant-lancher.jar.
291
task.setClassname("org.apache.tools.ant.launch.Launcher");
292         task.setFork(true);
293
294         AntUtil.transferCoberturaDataFileProperty(task);
295
296         task.createArg().setValue("-f");
297         task.createArg().setValue(BASEDIR + "/build.xml");
298         task.createArg().setValue(target);
299
300         task.setFailonerror(true);
301
302         // Set output to go to a temp file
303
File JavaDoc outputFile = Util.createTemporaryTextFile("cobertura-test");
304         task.setOutput(outputFile);
305
306         // Set the classpath to the same classpath as this JVM
307
Path classpath = task.createClasspath();
308         PathElement pathElement = classpath.createPathElement();
309         pathElement.setPath(System.getProperty("java.class.path"));
310
311         try
312         {
313             task.execute();
314         }
315         finally
316         {
317             if (outputFile.exists())
318             {
319                 // Put the contents of the output file in the exception
320
System.out.println("\n\n\nOutput from Ant for " + testName
321                         + " test:\n----------------------------------------\n"
322                         + Util.getText(outputFile) + "----------------------------------------");
323                 outputFile.delete();
324             }
325         }
326     }
327
328 }
329
Popular Tags