KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > test > OzoneTestRunner


1 // You can redistribute this software and/or modify it under the terms of
2
// the Ozone Library License version 1 published by ozone-db.org.
3
//
4
// The original code and portions created by SMB are
5
// Copyright (C) 1997-2000 by SMB GmbH. All rights reserved.
6
//
7
// $Id$
8

9
10 package test;
11
12
13 import junit.framework.AssertionFailedError;
14 import junit.framework.Test;
15 import junit.framework.TestFailure;
16 import junit.framework.TestResult;
17 import junit.runner.BaseTestRunner;
18 import junit.runner.TestSuiteLoader;
19 import org.apache.log4j.*;
20 import org.ozoneDB.ExternalDatabase;
21 import org.ozoneDB.Setup;
22 import org.ozoneDB.util.OzoneDebugLevel;
23 import org.ozoneDB.tools.Install;
24
25 import java.io.*;
26 import java.util.Enumeration JavaDoc;
27
28
29 /**
30  * OzoneTestRunner is the JUnit test runner for Ozone
31  * environment.
32  *
33  * @author <a HREF="http://www.softwarebuero.de/">SMB</a>
34  * @author <a HREF="mailto:david@d11e.com">David Li</a>
35  * @author Per Nyfelt
36  * @version $Revision$Date$
37  */

38
39 public class OzoneTestRunner extends BaseTestRunner {
40
41     /**
42      * log4j logger
43      */

44     private static Logger log = Logger.getLogger(OzoneTestRunner.class);
45
46     private String JavaDoc dbUrl;
47     /**
48      * Print the usage of the program
49      */

50     private static void printUsage() {
51         System.out.println("usage: ojvm "
52                 + OzoneTestRunner.class.getName()
53                 + " {-local | -remote [-host=HOST] [-port=PORT]} [-debug=LEVEL]"
54                 + " TestCase");
55         System.exit(1);
56     }
57
58     /**
59      * The database
60      */

61     private ExternalDatabase fDatabase;
62
63     /**
64      * whether to use remote database
65      */

66     private boolean isRemote = false;
67
68     /**
69      * whether to use local database
70      */

71     private boolean isLocal = false;
72
73     /**
74      * database server hostname
75      */

76     private String JavaDoc dbHost = "localhost";
77
78     /**
79      * database server port
80      */

81     private int dbPort = 3333;
82
83     /**
84      * default dir to create test database
85      */

86     private File localTestDir = new File(System.getProperty("java.io.tmpdir")
87             + File.separator + "OzoneTest");
88
89     /**
90      * name of the test suite to run
91      */

92     private String JavaDoc testClass;
93
94     /**
95      * Constructor
96      */

97     private OzoneTestRunner(String JavaDoc[] args) {
98         for (int i = 0; i < args.length; i++) {
99             if (args[i].equals("-local")) {
100                 isLocal = true;
101             } else if (args[i].equals("-remote")) {
102                 isRemote = true;
103             } else if (args[i].startsWith("-host=")) {
104                 dbHost = args[i].substring(6);
105             } else if (args[i].startsWith("-port=")) {
106                 dbPort = Integer.parseInt(args[i].substring(6));
107             } else if (args[i].startsWith("-debug=")) {
108                 Category.getRoot().setLevel(OzoneDebugLevel.toLevel(args[i].substring(7)));
109             } else {
110                 testClass = args[i];
111                 try {
112                     // make sure the test class exist, it might be a typo or bogus argument
113
this.getClass().getClassLoader().loadClass(testClass);
114                 } catch (ClassNotFoundException JavaDoc e) {
115                     System.out.println(e.toString() + " maybe a typo?");
116                     printUsage();
117                 }
118
119             }
120         }
121     }
122
123     /**
124      * initialize the database
125      * @param dbURL the database url
126      */

127     private void initDB(String JavaDoc dbURL) throws Exception JavaDoc {
128         log.debug("initDB(): open database at '" + dbURL + "'");
129         fDatabase = ExternalDatabase.openDatabase(dbURL);
130         fDatabase.reloadClasses();
131     }
132
133     /**
134      * Initialize a remote database.
135      * @param host hostname of the database machine
136      * @param port port number of the db server
137      */

138     private void initRemoteDB(String JavaDoc host, int port) throws Exception JavaDoc {
139         dbUrl = "ozonedb:remote://" + host + ":" + port;
140         initDB(dbUrl);
141     }
142
143     /**
144      * The test class loader for the runner.
145      */

146     private static TestSuiteLoader fTestSuiteLoader = new OzoneTestSuiteLoader();
147
148     /**
149      * overrideing this method from BaseTestRunner is necessary
150      * because of the default behavior of getLoader creates new
151      * classloader everytime it's called. This cause problem with
152      * Ozone.
153      */

154     public TestSuiteLoader getLoader() {
155         log.debug("getLoader ()");
156         return fTestSuiteLoader;
157     }
158
159     /**
160      * initialize a local database
161      * if one doesn't exists, create it.
162      */

163     private void initLocalDB() throws Exception JavaDoc {
164         localTestDir.mkdirs();
165         File dbDir = File.createTempFile("OZT", null, localTestDir);
166         Setup defaults = new Setup(null);
167         defaults.addProperties(System.getProperties(), "ozoneDB.");
168         Install.createDB(dbDir.getPath() + ".dir", defaults, new PrintWriter(System.out, true));
169         dbUrl = "ozonedb:local://" + dbDir.getPath() + ".dir";
170         initDB(dbUrl);
171     }
172
173     /**
174      * set up the database
175      */

176     private void setUpDatabase() throws Exception JavaDoc {
177         log.info("Test: remote= " + isRemote + " local= " + isLocal);
178         if (isLocal)
179             initLocalDB();
180         else if (isRemote)
181             initRemoteDB(dbHost, dbPort);
182     }
183
184     /**
185      * run the test suite
186      */

187     private TestResult doRun() throws Exception JavaDoc {
188         TestResult result = new TestResult();
189         Test test = getTest(testClass);
190         result.addListener(this);
191         try {
192             setUpDatabase();
193             test.run(result);
194         } finally {
195             if (fDatabase != null)
196                 fDatabase.close();
197         }
198         return result;
199     }
200
201     /**
202      * run the tests and return a report of the result
203      */

204     public String JavaDoc runTests() throws Exception JavaDoc {
205         long startTime = System.currentTimeMillis();
206         TestResult testResult = doRun();
207         long endTime = System.currentTimeMillis();
208         long runTime = endTime - startTime;
209
210         String JavaDoc result = "Time: " + elapsedTimeAsString(runTime);
211         return result + getResultInfo(testResult);
212     }
213
214     /**
215      * main
216      */

217     public static void main(String JavaDoc[] args) {
218         setupLogging();
219         if (args.length == 0) {
220             printUsage();
221         }
222         try {
223             OzoneTestRunner runner = new OzoneTestRunner(args);
224             log.info(runner.runTests());
225         } catch (Exception JavaDoc e) {
226             log.error("run fails", e);
227         }
228     }
229
230     private static void setupLogging() {
231         Logger logger = Logger.getLogger("test");
232         logger.removeAllAppenders();
233         Appender appender = new ConsoleAppender(new PatternLayout("%-6p %c{1} - %m%n"));
234         appender.setName(logger.getName());
235         BasicConfigurator.configure(appender);
236         Category.getRoot().setLevel(Level.INFO);
237     }
238
239     public void startTest(Test test) {
240         log.info("starting test: " + test);
241         if (test instanceof OzoneTestCase) {
242             ((OzoneTestCase) test).setDB(fDatabase);
243             ((OzoneTestCase) test).setDbUrl(dbUrl);
244         }
245     }
246
247     private synchronized String JavaDoc getResultInfo(TestResult result) {
248         String JavaDoc info = getErrors(result);
249         info += getFailures(result);
250         info += getHeader(result);
251         return info;
252     }
253
254     /**
255      * Gathers the errors
256      */

257     private String JavaDoc getErrors(TestResult result) {
258         String JavaDoc errors = "";
259         if (result.errorCount() != 0) {
260             if (result.errorCount() == 1) {
261                 errors += "\nThere was " + result.errorCount() + " error:\n";
262             } else {
263                 errors += "\nThere were " + result.errorCount() + " errors:\n";
264             }
265             int i = 1;
266             for (Enumeration JavaDoc e = result.errors(); e.hasMoreElements(); i++) {
267                 TestFailure failure = (TestFailure) e.nextElement();
268                 errors += i + ") " + failure.failedTest();
269                 errors += "\n" + filterTrace(failure.thrownException());
270             }
271         }
272         return errors;
273     }
274
275     /**
276      * Gathers the failures
277      */

278     private String JavaDoc getFailures(TestResult result) {
279         String JavaDoc failures = "";
280         if (result.failureCount() != 0) {
281             if (result.failureCount() == 1) {
282                 failures += "\nThere was " + result.failureCount() + " failure:\n";
283             } else {
284                 failures += "\nThere were " + result.failureCount() + " failures:\n";
285             }
286             int i = 1;
287             for (Enumeration JavaDoc e = result.failures(); e.hasMoreElements(); i++) {
288                 TestFailure failure = (TestFailure) e.nextElement();
289                 failures += i + ") " + failure.failedTest();
290                 failures += "\n" + filterTrace(failure.thrownException());
291             }
292         }
293         return failures;
294     }
295
296     /**
297      * Create the header of the report
298      */

299     private String JavaDoc getHeader(TestResult result) {
300         String JavaDoc header = "\n";
301         if (result.wasSuccessful()) {
302             header += "OK";
303             header += "\n (" + result.runCount() + " tests)";
304
305         } else {
306             header += "FAILURES!!!";
307             header += "Tests run: " + result.runCount() +
308                     ", Failures: " + result.failureCount() +
309                     ", Errors: " + result.errorCount();
310         }
311         return header;
312     }
313
314     /**
315      * Returns a filtered stack trace
316      */

317     public String JavaDoc filterTrace(Throwable JavaDoc t) {
318         StringWriter stringWriter = new StringWriter();
319         PrintWriter writer = new PrintWriter(stringWriter);
320         t.printStackTrace(writer);
321
322         StringBuffer JavaDoc buffer = stringWriter.getBuffer();
323         String JavaDoc trace = buffer.toString();
324
325         StringWriter sw = new StringWriter();
326         PrintWriter pw = new PrintWriter(sw);
327         BufferedReader br = new BufferedReader(new StringReader(trace));
328
329         String JavaDoc line;
330         try {
331             while ((line = br.readLine()) != null) {
332                 if (!filterNoice(line))
333                     pw.println(line);
334             }
335         } catch (Exception JavaDoc IOException) {
336             return trace; // return the stack unfiltered
337
}
338         return sw.toString();
339     }
340
341     /**
342      * Filter out unwanted noice from the testing framework iteself
343      */

344     private boolean filterNoice(String JavaDoc line) {
345         final String JavaDoc[] patterns = new String JavaDoc[]{
346             "junit.framework.TestResult",
347             "junit.framework.TestSuite",
348             "junit.framework.TestCase",
349             "junit.framework.Assert.", // don't filter AssertionFailure
350
"junit.textui.TestRunner",
351             "java.lang.reflect.Method.invoke(",
352             "sun.reflect.",
353             "test.OzoneTestRunner"
354         };
355         for (int i = 0; i < patterns.length; i++) {
356             if (line.indexOf(patterns[i]) > 0)
357                 return true;
358         }
359         return false;
360     }
361
362     // todo check to see if we need to something for these methods
363
public void testStarted(String JavaDoc s) {
364     }
365
366     public void testEnded(String JavaDoc s) {
367     }
368
369     public void testFailed(int i, Test test, Throwable JavaDoc throwable) {
370     }
371
372     public void addError(Test test, Throwable JavaDoc throwable) {
373     }
374
375     public void addFailure(Test test, AssertionFailedError error) {
376     }
377
378     public void endTest(Test test) {
379     }
380
381     protected void runFailed(String JavaDoc s) {
382     }
383 }
384
Popular Tags