add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / backwards / src / test-framework / org / apache / lucene / util / LuceneJUnitResultFormatter.java
1 /**
2  *  Licensed to the Apache Software Foundation (ASF) under one or more
3  *  contributor license agreements.  See the NOTICE file distributed with
4  *  this work for additional information regarding copyright ownership.
5  *  The ASF licenses this file to You under the Apache License, Version 2.0
6  *  (the "License"); you may not use this file except in compliance with
7  *  the License.  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.lucene.util;
20
21 import java.io.ByteArrayOutputStream;
22 import java.io.File;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.text.NumberFormat;
26 import java.util.logging.LogManager;
27
28 import junit.framework.AssertionFailedError;
29 import junit.framework.Test;
30
31 import org.apache.lucene.store.LockReleaseFailedException;
32 import org.apache.lucene.store.NativeFSLockFactory;
33 import org.apache.tools.ant.taskdefs.optional.junit.JUnitResultFormatter;
34 import org.apache.tools.ant.taskdefs.optional.junit.JUnitTest;
35 import org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner;
36 import org.apache.tools.ant.util.FileUtils;
37 import org.apache.tools.ant.util.StringUtils;
38 import org.junit.Ignore;
39
40 /**
41  * Just like BriefJUnitResultFormatter "brief" bundled with ant,
42  * except all formatted text is buffered until the test suite is finished.
43  * At this point, the output is written at once in synchronized fashion.
44  * This way tests can run in parallel without interleaving output.
45  */
46 public class LuceneJUnitResultFormatter implements JUnitResultFormatter {
47   private static final double ONE_SECOND = 1000.0;
48   
49   private static final NativeFSLockFactory lockFactory;
50   
51   /** Where to write the log to. */
52   private OutputStream out;
53   
54   /** Formatter for timings. */
55   private NumberFormat numberFormat = NumberFormat.getInstance();
56   
57   /** Output suite has written to System.out */
58   private String systemOutput = null;
59   
60   /** Output suite has written to System.err */
61   private String systemError = null;
62   
63   /** Buffer output until the end of the test */
64   private ByteArrayOutputStream sb; // use a BOS for our mostly ascii-output
65
66   private static final org.apache.lucene.store.Lock lock;
67
68   static {
69     File lockDir = new File(System.getProperty("java.io.tmpdir"),
70         "lucene_junit_lock");
71     lockDir.mkdirs();
72     if (!lockDir.exists()) {
73       throw new RuntimeException("Could not make Lock directory:" + lockDir);
74     }
75     try {
76       lockFactory = new NativeFSLockFactory(lockDir);
77       lock = lockFactory.makeLock("junit_lock");
78     } catch (IOException e) {
79       throw new RuntimeException(e);
80     }
81   }
82
83   /** Constructor for LuceneJUnitResultFormatter. */
84   public LuceneJUnitResultFormatter() {
85   }
86   
87   /**
88    * Sets the stream the formatter is supposed to write its results to.
89    * @param out the output stream to write to
90    */
91   public void setOutput(OutputStream out) {
92     this.out = out;
93   }
94   
95   /**
96    * @see JUnitResultFormatter#setSystemOutput(String)
97    */
98   /** {@inheritDoc}. */
99   public void setSystemOutput(String out) {
100     systemOutput = out;
101   }
102   
103   /**
104    * @see JUnitResultFormatter#setSystemError(String)
105    */
106   /** {@inheritDoc}. */
107   public void setSystemError(String err) {
108     systemError = err;
109   }
110   
111   
112   /**
113    * The whole testsuite started.
114    * @param suite the test suite
115    */
116   public synchronized void startTestSuite(JUnitTest suite) {
117     if (out == null) {
118       return; // Quick return - no output do nothing.
119     }
120     sb = new ByteArrayOutputStream(); // don't reuse, so its gc'ed
121     try {
122       LogManager.getLogManager().readConfiguration();
123     } catch (Exception e) {}
124     append("Testsuite: ");
125     append(suite.getName());
126     append(StringUtils.LINE_SEP);
127   }
128   
129   /**
130    * The whole testsuite ended.
131    * @param suite the test suite
132    */
133   public synchronized void endTestSuite(JUnitTest suite) {
134     append("Tests run: ");
135     append(suite.runCount());
136     append(", Failures: ");
137     append(suite.failureCount());
138     append(", Errors: ");
139     append(suite.errorCount());
140     append(", Time elapsed: ");
141     append(numberFormat.format(suite.getRunTime() / ONE_SECOND));
142     append(" sec");
143     append(StringUtils.LINE_SEP);
144     append(StringUtils.LINE_SEP);
145     
146     // append the err and output streams to the log
147     if (systemOutput != null && systemOutput.length() > 0) {
148       append("------------- Standard Output ---------------")
149       .append(StringUtils.LINE_SEP)
150       .append(systemOutput)
151       .append("------------- ---------------- ---------------")
152       .append(StringUtils.LINE_SEP);
153     }
154     
155     // HACK: junit gives us no way to do this in LuceneTestCase
156     try {
157       Class<?> clazz = Class.forName(suite.getName());
158       Ignore ignore = clazz.getAnnotation(Ignore.class);
159       if (ignore != null) {
160         if (systemError == null) systemError = "";
161         systemError += "NOTE: Ignoring test class '" + clazz.getSimpleName() + "': " 
162                     + ignore.value() + StringUtils.LINE_SEP;
163       }
164     } catch (ClassNotFoundException e) { /* no problem */ }
165     // END HACK
166     
167     if (systemError != null && systemError.length() > 0) {
168       append("------------- Standard Error -----------------")
169       .append(StringUtils.LINE_SEP)
170       .append(systemError)
171       .append("------------- ---------------- ---------------")
172       .append(StringUtils.LINE_SEP);
173     }
174     
175     if (out != null) {
176       try {
177         lock.obtain(5000);
178         try {
179           sb.writeTo(out);
180           out.flush();
181         } finally {
182           try {
183             lock.release();
184           } catch(LockReleaseFailedException e) {
185             // well lets pretend its released anyway
186           }
187         }
188       } catch (IOException e) {
189         throw new RuntimeException("unable to write results", e);
190       } finally {
191         if (out != System.out && out != System.err) {
192           FileUtils.close(out);
193         }
194       }
195     }
196   }
197   
198   /**
199    * A test started.
200    * @param test a test
201    */
202   public void startTest(Test test) {
203   }
204   
205   /**
206    * A test ended.
207    * @param test a test
208    */
209   public void endTest(Test test) {
210   }
211   
212   /**
213    * Interface TestListener for JUnit &lt;= 3.4.
214    *
215    * <p>A Test failed.
216    * @param test a test
217    * @param t    the exception thrown by the test
218    */
219   public void addFailure(Test test, Throwable t) {
220     formatError("\tFAILED", test, t);
221   }
222   
223   /**
224    * Interface TestListener for JUnit &gt; 3.4.
225    *
226    * <p>A Test failed.
227    * @param test a test
228    * @param t    the assertion failed by the test
229    */
230   public void addFailure(Test test, AssertionFailedError t) {
231     addFailure(test, (Throwable) t);
232   }
233   
234   /**
235    * A test caused an error.
236    * @param test  a test
237    * @param error the error thrown by the test
238    */
239   public void addError(Test test, Throwable error) {
240     formatError("\tCaused an ERROR", test, error);
241   }
242   
243   /**
244    * Format the test for printing..
245    * @param test a test
246    * @return the formatted testname
247    */
248   protected String formatTest(Test test) {
249     if (test == null) {
250       return "Null Test: ";
251     } else {
252       return "Testcase: " + test.toString() + ":";
253     }
254   }
255   
256   /**
257    * Format an error and print it.
258    * @param type the type of error
259    * @param test the test that failed
260    * @param error the exception that the test threw
261    */
262   protected synchronized void formatError(String type, Test test,
263       Throwable error) {
264     if (test != null) {
265       endTest(test);
266     }
267     
268     append(formatTest(test) + type);
269     append(StringUtils.LINE_SEP);
270     append(error.getMessage());
271     append(StringUtils.LINE_SEP);
272     String strace = JUnitTestRunner.getFilteredTrace(error);
273     append(strace);
274     append(StringUtils.LINE_SEP);
275     append(StringUtils.LINE_SEP);
276   }
277
278   public LuceneJUnitResultFormatter append(String s) {
279     if (s == null)
280       s = "(null)";
281     try {
282       sb.write(s.getBytes()); // intentionally use default charset, its a console.
283     } catch (IOException e) {
284       throw new RuntimeException(e);
285     }
286     return this;
287   }
288   
289   public LuceneJUnitResultFormatter append(long l) {
290     return append(Long.toString(l));
291   }
292 }
293