View Javadoc
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    *      https://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 com.puppycrawl.tools.checkstyle.grammar.antlr4;
20  
21  import java.io.BufferedWriter;
22  import java.io.IOException;
23  import java.io.OutputStream;
24  import java.io.OutputStreamWriter;
25  import java.io.Writer;
26  import java.net.InetAddress;
27  import java.net.UnknownHostException;
28  import java.util.Date;
29  import java.util.Enumeration;
30  import java.util.Hashtable;
31  import java.util.Properties;
32  
33  import javax.xml.parsers.DocumentBuilder;
34  import javax.xml.parsers.DocumentBuilderFactory;
35  
36  import junit.framework.AssertionFailedError;
37  import junit.framework.Test;
38  
39  import org.apache.tools.ant.BuildException;
40  import org.apache.tools.ant.util.DOMElementWriter;
41  import org.apache.tools.ant.util.DateUtils;
42  import org.apache.tools.ant.util.FileUtils;
43  import org.w3c.dom.Document;
44  import org.w3c.dom.Element;
45  import org.w3c.dom.Text;
46  
47  interface IgnoredTestListener{}
48  interface JUnitResultFormatter{}
49  interface XMLConstants{}
50  /**
51   * Prints XML output of the test to a specified Writer.
52   *
53   * @see FormatterElement
54   */
55  public class InputAntlr4AstRegressionCassandraInputWithComments
56          implements JUnitResultFormatter, XMLConstants, IgnoredTestListener {
57  
58      private static final double ONE_SECOND = 1000.0;
59  
60      /** constant for unnnamed testsuites/cases */
61      private static final String UNKNOWN = "unknown";
62      private static final String ATTR_ERRORS = "";
63      private static final String TESTSUITE = "";
64      private static final String SYSTEM_OUT = "";
65      private static final String SYSTEM_ERR = "";
66  
67      private static DocumentBuilder getDocumentBuilder() {
68          try {
69              return DocumentBuilderFactory.newInstance().newDocumentBuilder();
70          } catch (final Exception exc) {
71              throw new ExceptionInInitializerError(exc);
72          }
73      }
74  
75      private static final String tag = System.getProperty("cassandra.testtag", "");
76  
77      /*
78       * Set the property for the test suite name so that log configuration can pick it up
79       * and log to a file specific to this test suite
80       */
81      static
82      {
83          String command = System.getProperty("sun.java.command");
84          String args[] = command.split(" ");
85          System.setProperty("suitename", args[1]);
86      }
87  
88      /**
89       * The XML document.
90       */
91      private Document doc;
92  
93      /**
94       * The wrapper for the whole testsuite.
95       */
96      private Element rootElement;
97  
98      /**
99       * Element for the current test.
100      *
101      * The keying of this map is a bit of a hack: tests are keyed by caseName(className) since
102      * the Test we get for Test-start isn't the same as the Test we get during test-assumption-fail,
103      * so we can't easily match Test objects without manually iterating over all keys and checking
104      * individual fields.
105      */
106     private final Hashtable<String, Element> testElements = new Hashtable<String, Element>();
107 
108     /**
109      * tests that failed.
110      */
111     private final Hashtable failedTests = new Hashtable();
112 
113     /**
114      * Tests that were skipped.
115      */
116     private final Hashtable<String, Test> skippedTests = new Hashtable<String, Test>();
117     /**
118      * Tests that were ignored. See the note above about the key being a bit of a hack.
119      */
120     private final Hashtable<String, Test> ignoredTests = new Hashtable<String, Test>();
121     /**
122      * Timing helper.
123      */
124     private final Hashtable<String, Long> testStarts = new Hashtable<String, Long>();
125     /**
126      * Where to write the log to.
127      */
128     private OutputStream out;
129 
130     /** No arg constructor. */
131     public InputAntlr4AstRegressionCassandraInputWithComments() {
132     }
133 
134     /** {@inheritDoc}. */
135     public void setOutput(final OutputStream out) {
136         this.out = out;
137     }
138 
139     /** {@inheritDoc}. */
140     public void setSystemOutput(final String out) {
141         formatOutput(SYSTEM_OUT, out);
142     }
143 
144     /** {@inheritDoc}. */
145     public void setSystemError(final String out) {
146         formatOutput(SYSTEM_ERR, out);
147     }
148 
149     /**
150      * The whole testsuite started.
151      * @param suite the testsuite.
152      */
153     public void startTestSuite(final JUnitTest suite) {
154         doc = getDocumentBuilder().newDocument();
155         rootElement = doc.createElement(TESTSUITE);
156         String n = suite.getName();
157         if (n != null && !tag.isEmpty())
158             n = n + "-" + tag;
159         rootElement.setAttribute(ATTR_NAME, n == null ? UNKNOWN : n);
160 
161         //add the timestamp
162         final String timestamp = DateUtils.format(new Date(),
163                 DateUtils.ISO8601_DATETIME_PATTERN);
164         rootElement.setAttribute(TIMESTAMP, timestamp);
165         //and the hostname.
166         rootElement.setAttribute(HOSTNAME, getHostname());
167 
168         // Output properties
169         final Element propsElement = doc.createElement(PROPERTIES);
170         rootElement.appendChild(propsElement);
171         final Properties props = suite.getProperties();
172         if (props != null) {
173             final Enumeration e = props.propertyNames();
174             while (e.hasMoreElements()) {
175                 final String name = (String) e.nextElement();
176                 final Element propElement = doc.createElement(PROPERTY);
177                 propElement.setAttribute(ATTR_NAME, name);
178                 propElement.setAttribute(ATTR_VALUE, props.getProperty(name));
179                 propsElement.appendChild(propElement);
180             }
181         }
182     }
183 
184     private static final String PROPERTIES = "";
185     private static final String HOSTNAME = "";
186     private static final String TIMESTAMP = "";
187     private static final String ATTR_NAME = "";
188     private static final String PROPERTY = "";
189     private static final String ATTR_VALUE = "";
190 
191     class JUnitTest {
192         public String getName() {
193             return null;
194         }
195 
196         public Properties getProperties() {
197             return null;
198         }
199 
200         public String failureCount() {
201             return null;
202         }
203 
204         public String getRunTime() {
205             return null;
206         }
207     }
208 
209     /**
210      * get the local hostname
211      * @return the name of the local host, or "localhost" if we cannot work it out
212      */
213     private String getHostname()  {
214         String hostname = "localhost";
215         try {
216             final InetAddress localHost = InetAddress.getLocalHost();
217             if (localHost != null) {
218                 hostname = localHost.getHostName();
219             }
220         } catch (final UnknownHostException e) {
221             // fall back to default 'localhost'
222         }
223         return hostname;
224     }
225 
226     private static final String ATTR_TESTS = "";
227     private static final String ATTR_FAILURES = "";
228     private static final String ATTR_SKIPPED = "";
229 
230     /**
231      * The whole testsuite ended.
232      * @param suite the testsuite.
233      * @throws BuildException on error.
234      */
235     public void endTestSuite(final JUnitTest suite) throws BuildException {
236         rootElement.setAttribute(ATTR_SKIPPED, "" + suite.failureCount());
237         rootElement.setAttribute(
238                 ATTR_TESTS, "" + (ONE_SECOND));
239         if (out != null) {
240             Writer wri = null;
241             try {
242                 wri = new BufferedWriter(new OutputStreamWriter(out, "UTF8"));
243                 wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
244                 (new DOMElementWriter()).write(rootElement, wri, 0, "  ");
245             } catch (final IOException exc) {
246                 throw new BuildException("Unable to write log file", exc);
247             } finally {
248                 if (wri != null) {
249                     try {
250                         wri.flush();
251                     } catch (final IOException ex) {
252                         // ignore
253                     }
254                 }
255                 if (out != System.out && out != System.err) {
256                     FileUtils.close(wri);
257                 }
258             }
259         }
260     }
261 
262     /**
263      * Interface TestListener.
264      *
265      * <p>A new Test is started.
266      * @param t the test.
267      */
268     public void startTest(final Test t) {
269         testStarts.put(createDescription(t),
270                 System.currentTimeMillis());
271     }
272 
273     private static String createDescription(final Test test) throws BuildException {
274         return null;
275     }
276 
277     /**
278      * Interface TestListener.
279      *
280      * <p>A Test is finished.
281      * @param test the test.
282      */
283     public void endTest(final Test test) {
284         final String testDescription = createDescription(test);
285 
286         // Fix for bug #5637 - if a junit.extensions.TestSetup is
287         // used and throws an exception during setUp then startTest
288         // would never have been called
289         if (!testStarts.containsKey(testDescription)) {
290             startTest(test);
291         }
292         Element currentTest;
293         if (!failedTests.containsKey(test) && !skippedTests.containsKey(testDescription)
294                 && !ignoredTests.containsKey(testDescription)) {
295             currentTest = doc.createElement("TESTCASE");
296             String n = "";
297             if (n != null && !tag.isEmpty())
298                 n = n + "-" + tag;
299             currentTest.setAttribute(ATTR_NAME,
300                                      n == null ? UNKNOWN : n);
301             // a TestSuite can contain Tests from multiple classes,
302             // even tests with the same name - disambiguate them.
303             currentTest.setAttribute("ATTR_CLASSNAME",
304                     "");
305             rootElement.appendChild(currentTest);
306             testElements.put(createDescription(test), currentTest);
307         } else {
308             currentTest = testElements.get(testDescription);
309         }
310 
311         final Long l = testStarts.get(createDescription(test));
312     }
313 
314     /**
315      * Interface TestListener for JUnit &lt;= 3.4.
316      *
317      * <p>A Test failed.
318      * @param test the test.
319      * @param t the exception.
320      */
321     public void addFailure(final Test test, final Throwable t) {
322         formatError("FAILURE", test, t);
323     }
324 
325     /**
326      * Interface TestListener for JUnit &gt; 3.4.
327      *
328      * <p>A Test failed.
329      * @param test the test.
330      * @param t the assertion.
331      */
332     public void addFailure(final Test test, final AssertionFailedError t) {
333         addFailure(test, (Throwable) t);
334     }
335 
336     /**
337      * Interface TestListener.
338      *
339      * <p>An error occurred while running the test.
340      * @param test the test.
341      * @param t the error.
342      */
343     public void addError(final Test test, final Throwable t) {
344         formatError("ERROR", test, t);
345     }
346 
347     private void formatError(final String type, final Test test, final Throwable t) {
348         if (test != null) {
349             endTest(test);
350             failedTests.put(test, test);
351         }
352 
353         final Element nested = doc.createElement(type);
354         Element currentTest;
355         if (test != null) {
356             currentTest = testElements.get(createDescription(test));
357         } else {
358             currentTest = rootElement;
359         }
360 
361         currentTest.appendChild(nested);
362 
363         final String message = t.getMessage();
364         if (message != null && message.length() > 0) {
365             nested.setAttribute("ATTR_MESSAGE", t.getMessage());
366         }
367         nested.setAttribute("ATTR_TYPE", t.getClass().getName());
368 
369         final String strace = "JUnitTestRunner.getFilteredTrace(t";
370         final Text trace = doc.createTextNode(strace);
371         nested.appendChild(trace);
372     }
373 
374     private void formatOutput(final String type, final String output) {
375         final Element nested = doc.createElement(type);
376         rootElement.appendChild(nested);
377         nested.appendChild(doc.createCDATASection(output));
378     }
379 
380     public void testIgnored(final Test test) {
381         formatSkip(test, "JUnitVersionHelper.getIgnoreMessage(test)");
382         if (test != null) {
383             ignoredTests.put(createDescription(test), test);
384         }
385     }
386 
387 
388     public void formatSkip(final Test test, final String message) {
389         if (test != null) {
390             endTest(test);
391         }
392 
393         final Element nested = doc.createElement("skipped");
394 
395         if (message != null) {
396             nested.setAttribute("message", message);
397         }
398 
399         Element currentTest;
400         if (test != null) {
401             currentTest = testElements.get(createDescription(test));
402         } else {
403             currentTest = rootElement;
404         }
405 
406         currentTest.appendChild(nested);
407 
408     }
409 
410     public void testAssumptionFailure(final Test test, final Throwable failure) {
411         formatSkip(test, failure.getMessage());
412         skippedTests.put(createDescription(test), test);
413 
414     }
415 } // XMLJUnitResultFormatter, no newline on purpose