Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.mycompany.test;
- import static java.util.concurrent.TimeUnit.NANOSECONDS;
- import static java.util.concurrent.TimeUnit.SECONDS;
- import static java.util.logging.Level.WARNING;
- import static org.w3c.dom.DOMException.NOT_FOUND_ERR;
- import static org.w3c.dom.DOMException.NOT_SUPPORTED_ERR;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.PrintStream;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.net.InetAddress;
- import java.net.UnknownHostException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Set;
- import java.util.TimeZone;
- import java.util.logging.Logger;
- import java.util.logging.SimpleFormatter;
- import java.util.logging.StreamHandler;
- import junit.framework.AssertionFailedError;
- import org.junit.Ignore;
- import org.junit.internal.AssumptionViolatedException;
- import org.junit.runner.Description;
- import org.junit.runner.JUnitCore;
- import org.junit.runner.Result;
- import org.junit.runner.notification.Failure;
- import org.junit.runner.notification.RunListener;
- import org.w3c.dom.CDATASection;
- import org.w3c.dom.Comment;
- import org.w3c.dom.DOMException;
- import org.w3c.dom.DOMImplementation;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.bootstrap.DOMImplementationRegistry;
- import org.w3c.dom.ls.DOMImplementationLS;
- import org.w3c.dom.ls.LSOutput;
- import org.w3c.dom.ls.LSSerializer;
- public class Junit4Runner {
- private static final Logger LOG =
- Logger.getLogger(Junit4Runner.class.getName());
- private static String m_hostname;
- private final String[] m_argv;
- public Junit4Runner(String[] p_argv) {
- m_argv = p_argv;
- }
- public int run() {
- PrintStream sysout = System.out;
- PrintStream syserr = System.err;
- File stdout = null;
- File stderr = null;
- try {
- try {
- stdout = File.createTempFile(Junit4Runner.class.getName(), "_out.log");
- stdout.deleteOnExit();
- System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(stdout))));
- } catch (IOException e) {
- LOG.log(WARNING, "Could not redirect stdout", e);
- }
- try {
- stderr = File.createTempFile(Junit4Runner.class.getName(), "_err.log");
- stderr.deleteOnExit();
- PrintStream errStream = new PrintStream(new FileOutputStream(stderr));
- System.setErr(errStream);
- } catch (IOException e) {
- LOG.log(WARNING, "Could not redirect stderr", e);
- }
- JUnitCore core = new JUnitCore();
- XMLResultListener listener;
- listener = new XMLResultListener(stdout, stderr);
- core.addListener(listener);
- ArrayList<Class<?>> cl = new ArrayList<Class<?>>();
- for (String arg : m_argv) {
- try {
- cl.add(Class.forName(arg));
- } catch (ClassNotFoundException e) {
- LOG.log(WARNING, "Warning: Cannot find class " + arg, e);
- }
- }
- Class<?>[] tests = new Class<?>[cl.size()];
- cl.toArray(tests);
- core.run(tests);
- sysout.printf("Tests run: %d, Failures: %d, Errors: %d, Skipped: %d, Time elapsed: %.3f sec%n", listener.tests(), listener.failed(), listener.errors(), listener.skipped(), listener.time());
- return listener.internalError()? 1 : 0;
- } finally {
- System.setOut(sysout);
- System.setErr(syserr);
- }
- }
- public static void main(String[] p_argv) throws IOException {
- Junit4Runner runner = new Junit4Runner(p_argv);
- System.exit(runner.run());
- }
- private static String hostname() {
- if (m_hostname == null) {
- try {
- m_hostname = InetAddress.getLocalHost().getCanonicalHostName();
- } catch (UnknownHostException e) {
- m_hostname = "<unknown>";
- }
- }
- return m_hostname;
- }
- // convenience method
- private static String stringOf(Object p_obj) {
- return String.valueOf(p_obj);
- }
- @SuppressWarnings("unchecked")
- private static <T extends Throwable> T initCause(T p_throwable,
- Throwable p_cause)
- throws T {
- throw (T)p_throwable.initCause(p_cause);
- }
- static {
- LOG.addHandler(new StreamHandler(System.out, new SimpleFormatter()));
- LOG.setUseParentHandlers(false);
- }
- private static class XMLResultListener extends RunListener {
- private final DOMImplementation m_dom;
- private Document m_doc;
- private Element m_suite;
- private Element m_testcase;
- private long m_errors;
- private long m_failures;
- private long m_skipped;
- private long m_total;
- private long m_suiteStartTime;
- private long m_startTime;
- private final File m_stdout;
- private final File m_stderr;
- private double m_time;
- private boolean m_internalError;
- public XMLResultListener(File p_stdout, File p_stderr)
- throws DOMException {
- m_stdout = p_stdout;
- m_stderr = p_stderr;
- DOMImplementationRegistry registry;
- try {
- registry = DOMImplementationRegistry.newInstance();
- } catch (ClassCastException e) {
- throw initCause(new DOMException(NOT_SUPPORTED_ERR,
- e.getMessage()),
- e);
- } catch (ClassNotFoundException e) {
- throw initCause(new DOMException(NOT_FOUND_ERR, e.getMessage()),
- e);
- } catch (InstantiationException e) {
- throw initCause(new DOMException(NOT_SUPPORTED_ERR,
- e.getMessage()),
- e);
- } catch (IllegalAccessException e) {
- throw initCause(new DOMException(NOT_SUPPORTED_ERR,
- e.getMessage()),
- e);
- }
- m_dom = registry.getDOMImplementation("XML 3.0");
- }
- public boolean internalError() {
- return m_internalError;
- }
- public double time() {
- return m_time;
- }
- public long skipped() {
- return m_skipped;
- }
- public long errors() {
- return m_errors;
- }
- public long failed() {
- return m_failures;
- }
- public long tests() {
- return m_total;
- }
- @Override
- public void testRunStarted(Description p_description) {
- m_suiteStartTime = System.nanoTime();
- try {
- m_doc = m_dom.createDocument(null, "testsuite", null);
- m_suite = m_doc.getDocumentElement();
- TimeZone timeZone = TimeZone.getDefault();
- long ts = System.currentTimeMillis();
- int offset = timeZone.getOffset(ts);
- String date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(ts - offset);
- m_suite.setAttribute("timestamp", date);
- m_suite.setAttribute("hostname", hostname());
- String displayName = getDisplayName(p_description);
- if (displayName == null) {
- ArrayList<Description> children =
- p_description.getChildren();
- if (children != null && children.size() == 1) {
- Description child = children.get(0);
- displayName = getDisplayName(child);
- }
- }
- m_suite.setAttribute("name", displayName);
- } catch (RuntimeException e) {
- throw throwLog("testRunStarted", e);
- }
- }
- private String getDisplayName(Description p_description) {
- String displayName;
- displayName = p_description.getDisplayName();
- // if (displayName == null || "null".equals(displayName))
- // displayName = p_description.getClassName();
- // if (displayName == null || "null".equals(displayName)) {
- // Class<?> testClass = p_description.getTestClass();
- // if (testClass != null) {
- // displayName = testClass.getCanonicalName();
- // if (displayName == null || "null".equals(displayName))
- // displayName = p_description.getTestClass().getName();
- // }
- // }
- if ("null".equals(displayName))
- displayName = null;
- return displayName;
- }
- @Override
- public void testRunFinished(Result p_result) {
- try {
- long endSuiteTime = System.nanoTime();
- m_time = (endSuiteTime - m_suiteStartTime)
- / (double)NANOSECONDS.convert(1, SECONDS);
- m_suite.setAttribute("time", String.format("%.3f", m_time));
- m_suite.setAttribute("errors", stringOf(m_errors));
- m_suite.setAttribute("failures", stringOf(m_failures));
- m_suite.setAttribute("skipped", stringOf(m_skipped));
- m_suite.setAttribute("tests", stringOf(m_total));
- @SuppressWarnings({"unchecked", "rawtypes"})
- ArrayList<String> l = new ArrayList<String>((Set)System.getProperties().keySet());
- Collections.sort(l);
- Element props = m_doc.createElement("properties");
- for (String propKey : l) {
- Element prop = m_doc.createElement("property");
- prop.setAttribute("name", xmlEscape(propKey));
- prop.setAttribute("value", xmlEscape(System.getProperty(propKey)));
- props.appendChild(prop);
- }
- m_suite.insertBefore(props, m_suite.getFirstChild());
- Comment comment =
- m_doc.createComment("Created by "
- + Junit4Runner.class.getName());
- m_suite.insertBefore(comment, props);
- System.out.flush();
- System.err.flush();
- Element sysout = m_doc.createElement("system-out");
- extractOutputData(m_stdout, sysout);
- m_suite.appendChild(sysout);
- Element syserr = m_doc.createElement("system-err");
- extractOutputData(m_stderr, syserr);
- m_suite.appendChild(syserr);
- // Save the test output
- String testName = m_suite.getAttribute("name");
- DOMImplementationLS ls = (DOMImplementationLS)m_dom;
- LSOutput output = ls.createLSOutput();
- output.setByteStream(new FileOutputStream("TEST-" + testName + ".xml"));
- LSSerializer serializer = ls.createLSSerializer();
- serializer.getDomConfig().setParameter("format-pretty-print", true);
- serializer.getDomConfig().setParameter("element-content-whitespace", true);
- serializer.write(m_doc, output);
- } catch (RuntimeException e) {
- throw throwLog("testRunFinished", e);
- } catch (IOException e) {
- throw throwLog("testRunFinished", e);
- }
- }
- public void extractOutputData(File p_file, Element p_element)
- throws FileNotFoundException, IOException {
- FileReader fr = new FileReader(p_file);
- BufferedReader r = new BufferedReader(fr);
- String line;
- while ((line = r.readLine()) != null) {
- CDATASection cdata = m_doc.createCDATASection(line);
- cdata.appendData("\n");
- p_element.appendChild(cdata);
- }
- }
- @Override
- public void testStarted(Description p_description) {
- try {
- createTestCaseNode(p_description);
- } catch (RuntimeException e) {
- throw throwLog("testStarted", e);
- }
- }
- public void createTestCaseNode(Description p_description) {
- m_testcase = m_doc.createElement("testcase");
- m_suite.appendChild(m_testcase);
- try {
- Method m;
- try {
- m = p_description.getClass().getMethod("getClassName");
- } catch (NoSuchMethodException e) {
- m = null;
- }
- if (m != null) {
- Object o = m.invoke(p_description);
- if (o != null) {
- m_testcase.setAttribute("classname", stringOf(o));
- }
- } else {
- m_testcase.setAttribute("classname",
- p_description.getDisplayName());
- }
- m_testcase.setAttribute("name", p_description.getDisplayName());
- } catch (IllegalAccessException e) {
- throw throwLog("setting name", e);
- } catch (InvocationTargetException e) {
- throw throwLog("setting name", e);
- }
- m_startTime = System.nanoTime();
- }
- @Override
- public void testFinished(Description p_description) {
- try {
- long endTime = System.nanoTime();
- m_total++;
- m_testcase.setAttribute("time", stringOf((endTime - m_startTime) / 1000000.0));
- } catch (RuntimeException e) {
- throw throwLog("testFinished", e);
- }
- }
- @Override
- public void testAssumptionFailure(Failure p_failure) {
- try {
- Throwable ex = p_failure.getException();
- Element skippedElem = m_doc.createElement("skipped");
- m_skipped++;
- skippedElem.setAttribute("message", xmlEscape(ex.getMessage()));
- // skippedElem.setAttribute("type", ex.getClass().getName());
- // This modifies the exception, and the failure uses the
- // same exception to produce the text content, so this
- // allows us to eat our cake and have it too.
- filterStackTraces(ex);
- skippedElem.setTextContent(xmlEscape(p_failure.getTrace()));
- m_testcase.appendChild(skippedElem);
- } catch (RuntimeException e) {
- throw throwLog("testAssumptionFailure", e);
- }
- }
- @Override
- public void testFailure(Failure p_failure) {
- Throwable ex = p_failure.getException();
- Element failureElem;
- Ignore ann;
- try {
- if ((ann = p_failure.getDescription().getAnnotation(Ignore.class))
- != null) {
- failureElem = m_doc.createElement("skipped");
- m_skipped++;
- failureElem.setAttribute("message", xmlEscape(ann.value()));
- } else {
- if ((ex instanceof AssertionError)
- || (ex instanceof AssertionFailedError)) {
- failureElem = m_doc.createElement("failure");
- m_failures++;
- } else if (ex instanceof AssumptionViolatedException
- || ex.getClass().getName().equals(AssumptionViolatedException.class.getName())) {
- testAssumptionFailure(p_failure);
- return;
- } else {
- failureElem = m_doc.createElement("error");
- m_errors++;
- }
- failureElem.setAttribute("message", xmlEscape(ex.getMessage()));
- failureElem.setAttribute("type", ex.getClass().getName());
- // This modifies the exception, and the failure uses the
- // same exception to produce the text content, so this
- // allows us to eat our cake and have it too.
- filterStackTraces(ex);
- failureElem.setTextContent(xmlEscape(p_failure.getTrace()));
- }
- m_testcase.appendChild(failureElem);
- } catch (RuntimeException e) {
- throw throwLog("testFailure", e);
- }
- }
- private void filterStackTraces(Throwable p_ex) {
- ArrayList<StackTraceElement> l = new ArrayList<StackTraceElement>();
- for (StackTraceElement elem : p_ex.getStackTrace()) {
- if (! elem.getClassName().startsWith("org.junit.")
- && ! elem.getClassName().startsWith("junit.framework.")
- && ! elem.getClassName().startsWith("sun.reflect.")
- && ! elem.getClassName().startsWith("java.lang.reflect.")) {
- l.add(elem);
- }
- }
- p_ex.setStackTrace(l.toArray(new StackTraceElement[l.size()]));
- if (p_ex.getCause() != null)
- filterStackTraces(p_ex.getCause());
- }
- @Override
- public void testIgnored(Description p_description) throws Exception {
- try {
- createTestCaseNode(p_description);
- Ignore annotation = p_description.getAnnotation(Ignore.class);
- Element skippedElem = m_doc.createElement("skipped");
- skippedElem.setAttribute("message", xmlEscape(annotation.value()));
- // skippedElem.setAttribute("type", Ignore.class.getName());
- m_testcase.appendChild(skippedElem);
- m_skipped++;
- } catch (RuntimeException e) {
- throw throwLog("testIgnored", e);
- }
- }
- private RuntimeException throwLog(String p_message,
- Throwable p_exception)
- throws RuntimeException {
- m_internalError = true;
- LOG.log(WARNING, p_message, p_exception);
- throw new RuntimeException(p_message, p_exception);
- }
- public static String xmlEscape(String p_input) {
- if (p_input == null)
- return null;
- StringBuilder buf = null;
- int last = -1;
- for (int i = 0; i < p_input.length(); ++i) {
- char c = p_input.charAt(i);
- if (Character.isISOControl(c)
- && c != '\n'
- && c != '\r'
- && c != '\t'
- && c != '\u0085') {
- if (buf == null)
- buf = new StringBuilder(p_input.length() + 24); // Allow for 4 chars.
- buf.append(p_input.substring(last + 1, i));
- // XML doesn't allow '0' at all, so we have to escape it.
- if (c == 0) {
- buf.append("\\0");
- } else {
- buf.append("&#x")
- .append(Integer.toHexString(c))
- .append( ';' );
- last = i;
- }
- }
- }
- String ret;
- if (buf != null) {
- buf.append(p_input.substring(last + 1));
- ret = buf.toString();
- } else {
- ret = p_input;
- }
- return ret;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement