/
AntXmlRunListener.java
465 lines (412 loc) · 14.2 KB
/
AntXmlRunListener.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/* Schmant, the build tool, http://www.schmant.org
* Copyright (C) 2007, 2008 Karl Gustafsson, Holocene Software,
* http://www.holocene.se
*
* Schmant is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Schmant is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* This class contains code copied from Apache Ant's
* org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter class
* from Ant verson 1.7.1.
*/
package barrypitman.junitXmlFormatter;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* This {@link RunListener} produces an XML report formatted like Ant's JUnit
* XML report.
*
* @author Karl Gustafsson
* @taskpackage org.junit.junit4
* @since 0.9
*/
public class AntXmlRunListener extends RunListener {
private static final double ONE_SECOND = 1000.0;
// XML constants
/**
* the testsuite element
*/
private static String TESTSUITE = "testsuite";
/**
* the testcase element
*/
private static String TESTCASE = "testcase";
/**
* the failure element
*/
private static String FAILURE = "failure";
/** the system-err element */
// private static String SYSTEM_ERR = "system-err";
/** the system-out element */
// private static String SYSTEM_OUT = "system-out";
/**
* name attribute for property, testcase and testsuite elements
*/
private static String ATTR_NAME = "name";
/**
* time attribute for testcase and testsuite elements
*/
private static String ATTR_TIME = "time";
/**
* errors attribute for testsuite elements
*/
private static String ATTR_ERRORS = "errors";
/**
* failures attribute for testsuite elements
*/
private static String ATTR_FAILURES = "failures";
/**
* tests attribute for testsuite elements
*/
private static String ATTR_TESTS = "tests";
/**
* type attribute for failure and error elements
*/
private static String ATTR_TYPE = "type";
/**
* message attribute for failure elements
*/
private static String ATTR_MESSAGE = "message";
/**
* the properties element
*/
private static String PROPERTIES = "properties";
/**
* classname attribute for testcase elements
*/
private static String ATTR_CLASSNAME = "classname";
/**
* timestamp of test cases
*/
private static String TIMESTAMP = "timestamp";
/**
* name of host running the tests
*/
private static String HOSTNAME = "hostname";
private OutputStream outputStream;
/**
* The XML document.
*/
private Document m_doc;
/**
* The wrapper for the whole testsuite.
*/
private Element m_rootElement;
/**
* Mapping between test Description:s -> Start timestamp (Long)
*/
private Map m_testStarts = new HashMap();
/**
* Mapping between test Description:s -> Failure objects
*/
private Map m_failedTests = new HashMap();
/**
* Mapping between test Description:s -> XML Element:s
*/
private Map m_testElements = new HashMap();
/**
* Convenient method to retrieve the full stacktrace from a given exception.
*
* @param t the exception to get the stacktrace from.
* @return the stacktrace from the given exception.
*/
private static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
pw.close();
return sw.toString();
}
/**
* Returns a filtered stack trace.
* This is ripped out of junit.runner.BaseTestRunner.
*
* @param t the exception to filter.
* @return the filtered stack trace.
*/
private static String getFilteredTrace(Throwable t) {
return filterStack(getStackTrace(t));
}
/**
* Filters stack frames from internal JUnit and Ant classes
*
* @param stack the stack trace to filter.
* @return the filtered stack.
*/
public static String filterStack(String stack) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
StringReader sr = new StringReader(stack);
BufferedReader br = new BufferedReader(sr);
String line;
try {
while ((line = br.readLine()) != null) {
if (!filterLine(line)) {
pw.println(line);
}
}
} catch (Exception e) {
return stack; // return the stack unfiltered
}
return sw.toString();
}
private static final String[] DEFAULT_TRACE_FILTERS = new String[]{"junit.framework.TestCase", "junit.framework.TestResult", "junit.framework.TestSuite", "junit.framework.Assert.", // don't filter AssertionFailure
"junit.swingui.TestRunner", "junit.awtui.TestRunner", "junit.textui.TestRunner", "java.lang.reflect.Method.invoke(", "sun.reflect.", "org.apache.tools.ant.",
// JUnit 4 support:
"org.junit.", "junit.framework.JUnit4TestAdapter",
// See wrapListener for reason:
"Caused by: java.lang.AssertionError", " more",};
private static boolean filterLine(String line) {
for (int i = 0; i < DEFAULT_TRACE_FILTERS.length; i++) {
if (line.indexOf(DEFAULT_TRACE_FILTERS[i]) != -1) {
return true;
}
}
return false;
}
private static String getTestCaseName(String s) {
if (s == null) {
return "unknown";
}
if (s.endsWith(")")) {
int paren = s.lastIndexOf('(');
return s.substring(0, paren);
} else {
return s;
}
}
private static String getTestCaseClassName(String s) {
if (s == null) {
return "unknown";
}
// JUnit 4 wraps solo tests this way. We can extract
// the original test name with a little hack.
int paren = s.lastIndexOf('(');
if (paren != -1 && s.endsWith(")")) {
return s.substring(paren + 1, s.length() - 1);
} else {
return s;
}
}
private static DocumentBuilder getDocumentBuilder() {
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public AntXmlRunListener() {
String filePath = System.getProperty("org.schmant.task.junit4.target");
if (filePath != null) {
File target = new File(filePath);
try {
this.outputStream = new BufferedOutputStream(new FileOutputStream(target));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
/**
* get the local hostname
*
* @return the name of the local host, or "localhost" if we cannot work it out
*/
private String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
/**
* The whole test suite started.
*
* @param descr The test suite description.
*/
public void testRunStarted(Description descr) {
m_doc = getDocumentBuilder().newDocument();
m_rootElement = m_doc.createElement(TESTSUITE);
String n = descr.getDisplayName();
m_rootElement.setAttribute(ATTR_NAME, n == null ? "unknown" : n);
//add the timestamp
final String timestamp = DateUtils.format(new Date(), DateUtils.ISO8601_DATETIME_PATTERN);
m_rootElement.setAttribute(TIMESTAMP, timestamp);
//and the hostname.
m_rootElement.setAttribute(HOSTNAME, getHostname());
// Output properties
Element propsElement = m_doc.createElement(PROPERTIES);
m_rootElement.appendChild(propsElement);
// Where do these come from?
// Properties props = suite.getProperties();
// if (props != null)
// {
// Enumeration e = props.propertyNames();
// while (e.hasMoreElements())
// {
// String name = (String) e.nextElement();
// Element propElement = doc.createElement(PROPERTY);
// propElement.setAttribute(ATTR_NAME, name);
// propElement.setAttribute(ATTR_VALUE, props.getProperty(name));
// propsElement.appendChild(propElement);
// }
// }
}
/**
* Interface TestListener.
* <p/>
* <p>A new Test is started.
*
* @param descr The test description.
*/
public void testStarted(Description descr) {
m_testStarts.put(descr, new Long(System.currentTimeMillis()));
}
private void formatError(String type, Failure f) {
testFinished(f.getDescription());
m_failedTests.put(f.getDescription(), f);
Element nested = m_doc.createElement(type);
Element currentTest = (Element) m_testElements.get(f.getDescription());
currentTest.appendChild(nested);
String message = f.getMessage();
if (message != null && message.length() > 0) {
nested.setAttribute(ATTR_MESSAGE, message);
}
nested.setAttribute(ATTR_TYPE, f.getDescription().getDisplayName());
String strace = getFilteredTrace(f.getException());
Text trace = m_doc.createTextNode(strace);
nested.appendChild(trace);
}
/**
* Interface TestListener for JUnit <= 3.4.
* <p/>
* <p>A Test failed.
*
* @param f The failure.
*/
public void testFailure(Failure f) {
formatError(FAILURE, f);
}
public void testAssumptionFailure(Failure f) {
formatError(FAILURE, f);
}
/**
* Interface TestListener.
* <p/>
* <p>A Test is finished.
*
* @param descr The test description.
*/
public void testFinished(Description descr) {
// Fix for bug #5637 - if a junit.extensions.TestSetup is
// used and throws an exception during setUp then startTest
// would never have been called
if (!m_testStarts.containsKey(descr)) {
testStarted(descr);
}
Element currentTest = null;
if (!m_failedTests.containsKey(descr)) {
// Test test = (Test) descr.getAnnotation(Test.class);
currentTest = m_doc.createElement(TESTCASE);
String n = getTestCaseName(descr.getDisplayName());
currentTest.setAttribute(ATTR_NAME, n == null ? "unknown" : n);
// a TestSuite can contain Tests from multiple classes,
// even tests with the same name - disambiguate them.
currentTest.setAttribute(ATTR_CLASSNAME, getTestCaseClassName(descr.getDisplayName()));
m_rootElement.appendChild(currentTest);
m_testElements.put(descr, currentTest);
} else {
currentTest = (Element) m_testElements.get(descr);
}
Long l = (Long) m_testStarts.get(descr);
currentTest.setAttribute(ATTR_TIME, "" + ((System.currentTimeMillis() - l.longValue()) / ONE_SECOND));
}
/**
* The whole test suite ended.
*
* @param result The test suite result.
* @throws BuildException on error.
*/
public void testRunFinished(Result result) {
try {
try {
m_rootElement.setAttribute(ATTR_TESTS, "" + result.getRunCount());
m_rootElement.setAttribute(ATTR_FAILURES, "" + result.getFailureCount());
// JUnit4 does not seem to discern between failures and errors.
m_rootElement.setAttribute(ATTR_ERRORS, "" + 0);
m_rootElement.setAttribute(ATTR_TIME, "" + (result.getRunTime() / ONE_SECOND));
Writer wri = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF8"));
wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
(new DOMElementWriter()).write(m_rootElement, wri, 0, " ");
wri.flush();
} finally {
outputStream.close();
}
} catch (IOException exc) {
throw new RuntimeException("Unable to write log file", exc);
}
}
protected void finalize() throws Throwable {
if (outputStream != null) {
outputStream.close();
}
super.finalize();
}
//
// /**
// * Where to write the log to.
// */
// private OutputStream out;
//
// /** {@inheritDoc}. */
// public void setOutput(OutputStream out)
// {
// this.out = out;
// }
//
// /** {@inheritDoc}. */
// public void setSystemOutput(String out)
// {
// formatOutput(SYSTEM_OUT, out);
// }
//
// /** {@inheritDoc}. */
// public void setSystemError(String out)
// {
// formatOutput(SYSTEM_ERR, out);
// }
//
// private void formatOutput(String type, String output)
// {
// Element nested = doc.createElement(type);
// rootElement.appendChild(nested);
// nested.appendChild(doc.createCDATASection(output));
// }
}