KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jorphan > test > AllTests


1 // $Header: /home/cvs/jakarta-jmeter/src/jorphan/org/apache/jorphan/test/AllTests.java,v 1.27 2004/03/12 23:39:25 sebb Exp $
2
/*
3  * Copyright 2001-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jorphan.test;
20
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileNotFoundException JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.lang.reflect.Method JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.Properties JavaDoc;
27
28 import junit.framework.TestCase;
29 import junit.framework.TestSuite;
30 import junit.textui.TestRunner;
31
32 import org.apache.jorphan.logging.LoggingManager;
33 import org.apache.jorphan.reflect.ClassFinder;
34 import org.apache.jorphan.util.JOrphanUtils;
35 import org.apache.log.Logger;
36
37 /**
38  * Provides a quick and easy way to run all
39  * <a HREF="http://junit.sourceforge.net">junit</a> unit tests in your java
40  * project. It will find all unit test classes and run all their test methods.
41  * There is no need to configure it in any way to find these classes except to
42  * give it a path to search.
43  * <p>
44  * Here is an example Ant target (See Ant at
45  * <a HREF="http://jakarta.apache.org/ant">Apache</a>) that runs all your unit
46  * tests:
47  * <pre>
48  * &lt;target name="test" depends="compile"&gt;
49  * &lt;java classname="org.apache.jorphan.test.AllTests" fork="yes"&gt;
50  * &lt;classpath&gt;
51  * &lt;path refid="YOUR_CLASSPATH"/&gt;
52  * &lt;pathelement location="ROOT_DIR_OF_YOUR_COMPILED_CLASSES"/&gt;
53  * &lt;/classpath&gt;
54  * &lt;arg value="SEARCH_PATH/"/&gt;
55  * &lt;arg value="PROPERTY_FILE"/&gt;
56  * &lt;arg value="NAME_OF_UNITTESTMANAGER_CLASS"/&gt;
57  * &lt;/java&gt;
58  * &lt;/target&gt;
59  * </pre>
60  *
61  * <dl>
62  * <dt>YOUR_CLASSPATH</dt>
63  * <dd>Refers to the classpath that includes all jars and libraries need to
64  * run your unit tests</dd>
65  *
66  * <dt>ROOT_DIR_OF_YOUR_COMPILED_CLASSES</dt>
67  * <dd>The classpath should include the directory where all your project's
68  * classes are compiled to, if it doesn't already.</dd>
69  *
70  * <dt>SEARCH_PATH</dt>
71  * <dd>The first argument tells AllTests where to look for unit test classes
72  * to execute. In most cases, it is identical to
73  * ROOT_DIR_OF_YOUR_COMPILED_CLASSES. You can specify multiple
74  * directories or jars to search by providing a comma-delimited list.</dd>
75  *
76  * <dt>PROPERTY_FILE</dt>
77  * <dd>A simple property file that sets logging parameters. It is optional
78  * and is only relevant if you use the same logging packages that JOrphan
79  * uses.</dd>
80  *
81  * <dt>NAME_OF_UNITTESTMANAGER_CLASS</dt>
82  * <dd>If your system requires some configuration to run correctly, you can
83  * implement the {@link UnitTestManager} interface and be given an
84  * opportunity to initialize your system from a configuration file.</dd>
85  * </dl>
86  *
87  * @see UnitTestManager
88  * @author Michael Stover (mstover1 at apache.org)
89  * @version $Revision: 1.27 $
90  */

91 public final class AllTests
92 {
93     transient private static Logger log = LoggingManager.getLoggerForClass();
94
95     /**
96      * Private constructor to prevent instantiation.
97      */

98     private AllTests()
99     {
100     }
101
102     private static void logprop(String JavaDoc prop,boolean show)
103     {
104         String JavaDoc value = System.getProperty(prop);
105         log.info(prop+"="+value);
106         if (show) System.out.println(prop+"="+value);
107     }
108
109     private static void logprop(String JavaDoc prop)
110     {
111         logprop(prop,false);
112     }
113
114     /**
115      * Starts a run through all unit tests found in the specified classpaths.
116      * The first argument should be a list of paths to search. The second
117      * argument is optional and specifies a properties file used to initialize
118      * logging. The third argument is also optional, and specifies a class
119      * that implements the UnitTestManager interface. This provides a means of
120      * initializing your application with a configuration file prior to the
121      * start of any unit tests.
122      *
123      * @param args the command line arguments
124      */

125     public static void main(String JavaDoc[] args)
126     {
127         if (args.length < 1)
128         {
129             System.out.println(
130                 "You must specify a comma-delimited list of paths to search " +
131                 "for unit tests");
132             System.exit(0);
133         }
134         initializeLogging(args);
135         initializeManager(args);
136         // end : added - 11 July 2001
137

138         logprop("java.version",true);
139         logprop("java.vendor");
140         logprop("java.home",true);
141         logprop("user.home");
142         logprop("user.dir",true);
143         logprop("os.name");
144         logprop("os.version");
145         logprop("os.arch");
146         logprop("java.class.version");
147         //logprop("java.class.path");
148
String JavaDoc cp = System.getProperty("java.class.path");
149         String JavaDoc cpe[]= JOrphanUtils.split(cp,java.io.File.pathSeparator);
150         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(3000);
151         sb.append("java.class.path=");
152         for (int i=0;i<cpe.length;i++){
153             sb.append("\n");
154             sb.append(cpe[i]);
155             if (new java.io.File JavaDoc(cpe[i]).exists())
156             {
157                 sb.append(" - OK");
158             }
159             else
160             {
161                 sb.append(" - ??");
162             }
163         }
164         log.info(sb.toString());
165
166 //++
167
// GUI tests throw the error
168
// testArgumentCreation(org.apache.jmeter.config.gui.ArgumentsPanel$Test)java.lang.NoClassDefFoundError
169
// at java.lang.Class.forName0(Native Method)
170
// at java.lang.Class.forName(Class.java:141)
171
// at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:62)
172
//
173
// Try to find out why this is ...
174

175         System.out.println("+++++++++++");
176         logprop("java.awt.headless",true);
177         logprop("java.awt.graphicsenv",true);
178 //
179
// try {//
180
// Class c = Class.forName(n);
181
// System.out.println("Found class: "+n);
182
//// c.newInstance();
183
//// System.out.println("Instantiated: "+n);
184
// } catch (Exception e1) {
185
// System.out.println("Error finding class "+n+" "+e1);
186
// } catch (java.lang.InternalError e1){
187
// System.out.println("Error finding class "+n+" "+e1);
188
// }
189
//
190
System.out.println("------------");
191 // don't call isHeadless() here, as it has a side effect.
192
//--
193
System.out.println("Creating test suite");
194         TestSuite suite = suite(args[0]);
195         System.out.println("Starting test run");
196         
197         // Jeremy Arnold: This method used to attempt to write results to
198
// a file, but it had a bug and instead just wrote to System.out.
199
// Since nobody has complained about this behavior, I'm changing
200
// the code to not attempt to write to a file, so it will continue
201
// behaving as it did before. It would be simple to make it write
202
// to a file instead if that is the desired behavior.
203
TestRunner.run(suite);
204 //++
205
// Recheck settings:
206
System.out.println("+++++++++++");
207 // System.out.println(e+"="+System.getProperty(e));
208
// System.out.println(g+"="+System.getProperty(g));
209
// System.out.println("Headless? "+java.awt.GraphicsEnvironment.isHeadless());//JDK 1.4
210
// try {
211
// Class c = Class.forName(n);
212
// System.out.println("Found class: "+n);
213
// c.newInstance();
214
// System.out.println("Instantiated: "+n);
215
// } catch (Exception e1) {
216
// System.out.println("Error with class "+n+" "+e1);
217
// } catch (java.lang.InternalError e1){
218
// System.out.println("Error with class "+n+" "+e1);
219
// }
220
System.out.println("------------");
221 //--
222
System.exit(0);
223     }
224
225     /**
226      * An overridable method that initializes the logging for the unit test
227      * run, using the properties file passed in as the second argument.
228      * @param args
229      */

230     protected static void initializeLogging(String JavaDoc[] args)
231     {
232         if (args.length >= 2)
233         {
234             Properties JavaDoc props = new Properties JavaDoc();
235             try
236             {
237                 System.out.println(
238                     "Setting up logging props using file: " + args[1]);
239                 props.load(new FileInputStream JavaDoc(args[1]));
240                 LoggingManager.initializeLogging(props);
241             }
242             catch (FileNotFoundException JavaDoc e)
243             {
244             }
245             catch (IOException JavaDoc e)
246             {
247             }
248         }
249     }
250
251     /**
252      * An overridable method that that instantiates a UnitTestManager (if one
253      * was specified in the command-line arguments), and hands it the name of
254      * the properties file to use to configure the system.
255      * @param args
256      */

257     protected static void initializeManager(String JavaDoc[] args)
258     {
259         if (args.length >= 3)
260         {
261             try
262             {
263                 System.out.println(
264                     "Using initializeProperties() from " + args[2]);
265                 UnitTestManager um =
266                     (UnitTestManager) Class.forName(args[2]).newInstance();
267                 System.out.println(
268                     "Setting up initial properties using: " + args[1]);
269                 um.initializeProperties(args[1]);
270             }
271             catch (Exception JavaDoc e)
272             {
273                 System.out.println("Couldn't create: " + args[2]);
274                 e.printStackTrace();
275             }
276         }
277     }
278
279     /*
280      * Externally callable suite() method for use by JUnit
281      * Allows tests to be run directly under JUnit, rather than using the
282      * startup code in the rest of the module. No parameters can be passed in,
283      * so it is less flexible.
284      */

285     public static TestSuite suite()
286     {
287         String JavaDoc args[] = { "../lib/ext",
288                           "./jmetertest.properties",
289                           "org.apache.jmeter.util.JMeterUtils"
290                         };
291
292         initializeManager(args);
293         return suite(args[0]);
294     }
295     
296     /**
297      * A unit test suite for JUnit.
298      *
299      * @return The test suite
300      */

301     private static TestSuite suite(String JavaDoc searchPaths)
302     {
303         TestSuite suite = new TestSuite();
304         try
305         {
306             Iterator JavaDoc classes =
307                 ClassFinder
308                     .findClassesThatExtend(
309                         JOrphanUtils.split(searchPaths, ","),
310                         new Class JavaDoc[] { TestCase.class },
311                         true)
312                     .iterator();
313             while (classes.hasNext())
314             {
315                 String JavaDoc name = (String JavaDoc) classes.next();
316                 try
317                 {
318                     /*
319                      * TestSuite only finds testXXX() methods, and does not look for
320                      * suite() methods.
321                      *
322                      * To provide more compatibilty with stand-alone tests, where JUnit
323                      * does look for a suite() method, check for it first here.
324                      *
325                      */

326
327                     Class JavaDoc clazz = Class.forName(name);
328                     TestSuite t= null;
329                     try
330                     {
331                         Method JavaDoc m = clazz.getMethod("suite", new Class JavaDoc[0]);
332                         t = (TestSuite) m.invoke(clazz,null);
333                     }
334                     catch (NoSuchMethodException JavaDoc e) {} // this is not an error, the others are
335
//catch (SecurityException e) {}
336
//catch (IllegalAccessException e) {}
337
//catch (IllegalArgumentException e) {}
338
//catch (InvocationTargetException e) {}
339

340                     if (t == null)
341                     {
342                         t= new TestSuite(clazz);
343                     }
344
345                     suite.addTest(t);
346                 }
347                 catch (Exception JavaDoc ex)
348                 {
349                     System.out.println("Error adding test for class "+name+" "+ex.toString());
350                     log.error("error adding test :", ex);
351                 }
352             }
353         }
354         catch (IOException JavaDoc e)
355         {
356             log.error("", e);
357         }
358         catch (ClassNotFoundException JavaDoc e)
359         {
360             log.error("", e);
361         }
362         return suite;
363     }
364 }
365
Popular Tags