http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java index bfcbfed..26ef424 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FailureRecorder.java @@ -23,12 +23,11 @@ import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; +import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; -import java.util.Vector; - import junit.framework.AssertionFailedError; import junit.framework.Test; @@ -89,7 +88,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm private static final String LOG_PREFIX = " [junit]"; /** Class names of failed tests without duplicates. */ - private static SortedSet/*<TestInfos>*/ failedTests = new TreeSet(); + private static SortedSet<TestInfos> failedTests = new TreeSet<>(); /** A writer for writing the generated source to. */ private BufferedWriter writer; @@ -146,20 +145,13 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @param project * project reference */ + @Override public void setProject(Project project) { // store project reference for logging super.setProject(project); // check if already registered - boolean alreadyRegistered = false; - Vector allListeners = project.getBuildListeners(); - final int size = allListeners.size(); - for (int i = 0; i < size; i++) { - Object listener = allListeners.get(i); - if (listener instanceof FailureRecorder) { - alreadyRegistered = true; - break; - } - } + boolean alreadyRegistered = project.getBuildListeners().stream() + .anyMatch(FailureRecorder.class::isInstance); // register if needed if (!alreadyRegistered) { verbose("Register FailureRecorder (@" + this.hashCode() + ") as BuildListener"); @@ -173,6 +165,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void endTestSuite(JUnitTest suite) throws BuildException { } @@ -182,6 +175,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @param throwable the reason it errored. * @see junit.framework.TestListener#addError(junit.framework.Test, java.lang.Throwable) */ + @Override public void addError(Test test, Throwable throwable) { failedTests.add(new TestInfos(test)); } @@ -194,6 +188,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @see junit.framework.TestListener#addFailure(junit.framework.Test, junit.framework.AssertionFailedError) */ // CheckStyle:LineLengthCheck ON + @Override public void addFailure(Test test, AssertionFailedError error) { failedTests.add(new TestInfos(test)); } @@ -202,6 +197,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void setOutput(OutputStream out) { // unused, close output file so it can be deleted before the VM exits if (out != System.out) { @@ -213,6 +209,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void setSystemError(String err) { } @@ -220,6 +217,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void setSystemOutput(String out) { } @@ -227,6 +225,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void startTestSuite(JUnitTest suite) throws BuildException { } @@ -234,6 +233,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void endTest(Test test) { } @@ -241,6 +241,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void startTest(Test test) { } @@ -248,7 +249,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm private void writeJavaClass() { try { - File sourceFile = new File((getLocationName() + ".java")); + File sourceFile = new File(getLocationName() + ".java"); verbose("Write collector class to '" + sourceFile.getAbsolutePath() + "'"); if (sourceFile.exists() && !sourceFile.delete()) { @@ -299,8 +300,8 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm writer.newLine(); writer.write(" TestSuite suite = new TestSuite();"); writer.newLine(); - for (Iterator iter = failedTests.iterator(); iter.hasNext();) { - TestInfos testInfos = (TestInfos) iter.next(); + for (Iterator<TestInfos> iter = failedTests.iterator(); iter.hasNext();) { + TestInfos testInfos = iter.next(); writer.write(" suite.addTest("); writer.write(String.valueOf(testInfos)); writer.write(");"); @@ -323,6 +324,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Logging facade in INFO-mode. * @param message Log-message */ + @Override public void log(String message) { getProject().log(LOG_PREFIX + " " + message, Project.MSG_INFO); } @@ -338,7 +340,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm /** * TestInfos holds information about a given test for later use. */ - public static class TestInfos implements Comparable { + public static class TestInfos implements Comparable<TestInfos> { /** The class name of the test. */ private final String className; @@ -363,6 +365,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @see java.lang.Object#toString() * @see FailureRecorder#createSuiteMethod() */ + @Override public String toString() { return "new " + className + "(\"" + methodName + "\")"; } @@ -374,17 +377,18 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @see java.lang.Comparable#compareTo * @see SortedSet#comparator() */ - public int compareTo(Object other) { - if (other instanceof TestInfos) { - TestInfos otherInfos = (TestInfos) other; - return toString().compareTo(otherInfos.toString()); - } else { - return -1; - } + @Override + public int compareTo(TestInfos other) { + return Comparator.comparing(Object::toString).compare(this, other); } + + @Override public boolean equals(Object obj) { - return obj instanceof TestInfos && toString().equals(obj.toString()); + return obj == this || obj instanceof TestInfos + && toString().equals(obj.toString()); } + + @Override public int hashCode() { return toString().hashCode(); } @@ -396,6 +400,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void buildFinished(BuildEvent event) { } @@ -403,6 +408,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void buildStarted(BuildEvent event) { } @@ -410,6 +416,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void messageLogged(BuildEvent event) { } @@ -417,6 +424,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void targetFinished(BuildEvent event) { } @@ -424,6 +432,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void targetStarted(BuildEvent event) { } @@ -433,6 +442,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * @param event not used * @see org.apache.tools.ant.BuildListener#taskFinished(org.apache.tools.ant.BuildEvent) */ + @Override public void taskFinished(BuildEvent event) { if (!failedTests.isEmpty()) { writeJavaClass(); @@ -443,6 +453,7 @@ public class FailureRecorder extends ProjectComponent implements JUnitResultForm * Not used * {@inheritDoc} */ + @Override public void taskStarted(BuildEvent event) { }
http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java index 6587b1d..81841a0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java @@ -31,6 +31,7 @@ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.PropertyHelper; import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.optional.junit.JUnitTaskMirror.JUnitResultFormatterMirror; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.util.KeepAliveOutputStream; @@ -58,6 +59,18 @@ import org.apache.tools.ant.util.KeepAliveOutputStream; * @see JUnitResultFormatter */ public class FormatterElement { + /** xml formatter class */ + public static final String XML_FORMATTER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter"; + /** brief formatter class */ + public static final String BRIEF_FORMATTER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"; + /** plain formatter class */ + public static final String PLAIN_FORMATTER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter"; + /** failure recorder class */ + public static final String FAILURE_RECORDER_CLASS_NAME = + "org.apache.tools.ant.taskdefs.optional.junit.FailureRecorder"; private String classname; private String extension; @@ -73,19 +86,6 @@ public class FormatterElement { */ private Project project; - /** xml formatter class */ - public static final String XML_FORMATTER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter"; - /** brief formatter class */ - public static final String BRIEF_FORMATTER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.BriefJUnitResultFormatter"; - /** plain formatter class */ - public static final String PLAIN_FORMATTER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter"; - /** failure recorder class */ - public static final String FAILURE_RECORDER_CLASS_NAME = - "org.apache.tools.ant.taskdefs.optional.junit.FailureRecorder"; - /** * <p> Quick way to use a standard formatter. * @@ -102,18 +102,19 @@ public class FormatterElement { * @param type the enumerated value to use. */ public void setType(TypeAttribute type) { - if ("xml".equals(type.getValue())) { + switch (type.getValue()) { + case "xml": setClassname(XML_FORMATTER_CLASS_NAME); - } else { - if ("brief".equals(type.getValue())) { - setClassname(BRIEF_FORMATTER_CLASS_NAME); - } else { - if ("failure".equals(type.getValue())) { - setClassname(FAILURE_RECORDER_CLASS_NAME); - } else { // must be plain, ensured by TypeAttribute - setClassname(PLAIN_FORMATTER_CLASS_NAME); - } - } + break; + case "brief": + setClassname(BRIEF_FORMATTER_CLASS_NAME); + break; + case "failure": + setClassname(FAILURE_RECORDER_CLASS_NAME); + break; + default: + setClassname(PLAIN_FORMATTER_CLASS_NAME); + break; } } @@ -125,12 +126,18 @@ public class FormatterElement { */ public void setClassname(String classname) { this.classname = classname; - if (XML_FORMATTER_CLASS_NAME.equals(classname)) { - setExtension(".xml"); - } else if (PLAIN_FORMATTER_CLASS_NAME.equals(classname)) { - setExtension(".txt"); - } else if (BRIEF_FORMATTER_CLASS_NAME.equals(classname)) { - setExtension(".txt"); + if (classname != null) { + switch (classname) { + case XML_FORMATTER_CLASS_NAME: + setExtension(".xml"); + break; + case PLAIN_FORMATTER_CLASS_NAME: + setExtension(".txt"); + break; + case BRIEF_FORMATTER_CLASS_NAME: + setExtension(".txt"); + break; + } } } @@ -266,7 +273,6 @@ public class FormatterElement { this.project = project; } - /** * @since Ant 1.6 */ @@ -279,7 +285,7 @@ public class FormatterElement { //although this code appears to duplicate that of ClasspathUtils.newInstance, //we cannot use that because this formatter may run in a forked process, //without that class. - Class f = null; + Class<?> f; try { if (loader == null) { f = Class.forName(classname); @@ -296,26 +302,21 @@ public class FormatterElement { + ": " + e, e); } - Object o = null; + JUnitResultFormatterMirror r; try { - o = f.newInstance(); - } catch (InstantiationException e) { - throw new BuildException(e); - } catch (IllegalAccessException e) { + r = f.asSubclass(JUnitResultFormatterMirror.class).newInstance(); + } catch (ClassCastException e) { + throw new BuildException("%s is not a JUnitResultFormatter", + classname); + } catch (InstantiationException | IllegalAccessException e) { throw new BuildException(e); } - if (!(o instanceof JUnitTaskMirror.JUnitResultFormatterMirror)) { - throw new BuildException(classname + " is not a JUnitResultFormatter"); - } - JUnitTaskMirror.JUnitResultFormatterMirror r = - (JUnitTaskMirror.JUnitResultFormatterMirror) o; if (useFile && outFile != null) { out = new DelayedFileOutputStream(outFile); } r.setOutput(out); - boolean needToSetProjectReference = true; try { Field field = r.getClass().getField("project"); @@ -333,8 +334,8 @@ public class FormatterElement { if (needToSetProjectReference) { Method setter; try { - setter = r.getClass().getMethod("setProject", new Class[] {Project.class}); - setter.invoke(r, new Object[] {project}); + setter = r.getClass().getMethod("setProject", Project.class); + setter.invoke(r, project); } catch (NoSuchMethodException e) { // no setProject to invoke; just ignore } catch (IllegalAccessException e) { @@ -354,8 +355,9 @@ public class FormatterElement { */ public static class TypeAttribute extends EnumeratedAttribute { /** {@inheritDoc}. */ + @Override public String[] getValues() { - return new String[] {"plain", "xml", "brief", "failure"}; + return new String[] { "plain", "xml", "brief", "failure" }; } } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java index c3bb18d..ef51fff 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/IgnoredTestResult.java @@ -33,15 +33,15 @@ import junit.framework.TestResult; public class IgnoredTestResult extends TestResult { - private List<IgnoredTestListener> listeners = new ArrayList<IgnoredTestListener>(); - private List<TestIgnored> ignored = new ArrayList<TestIgnored>(); - private List<TestIgnored> skipped = new ArrayList<TestIgnored>(); + private List<IgnoredTestListener> listeners = new ArrayList<>(); + private List<TestIgnored> ignored = new ArrayList<>(); + private List<TestIgnored> skipped = new ArrayList<>(); public IgnoredTestResult() { super(); } - + @Override public synchronized void addListener(TestListener listener) { if (listener instanceof IgnoredTestListener) { listeners.add((IgnoredTestListener)listener); @@ -49,6 +49,7 @@ public class IgnoredTestResult extends TestResult { super.addListener(listener); } + @Override public synchronized void removeListener(TestListener listener) { if (listener instanceof IgnoredTestListener) { listeners.remove(listener); http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java index f03a409..c797a87 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.java @@ -18,8 +18,8 @@ package org.apache.tools.ant.taskdefs.optional.junit; -import java.util.Iterator; import java.util.List; +import java.util.function.Predicate; import junit.framework.Test; import junit.framework.TestResult; @@ -41,7 +41,7 @@ import org.junit.runner.manipulation.Filter; */ public class JUnit4TestMethodAdapter implements Test { - private final Class testClass; + private final Class<?> testClass; private final String[] methodNames; private final Runner runner; private final CustomJUnit4TestAdapterCache cache; @@ -55,7 +55,7 @@ public class JUnit4TestMethodAdapter implements Test { * if any of the arguments is {@code null} * or if any of the given method names is {@code null} or empty */ - public JUnit4TestMethodAdapter(final Class testClass, + public JUnit4TestMethodAdapter(final Class<?> testClass, final String[] methodNames) { if (testClass == null) { throw new IllegalArgumentException("testClass is <null>"); @@ -87,6 +87,7 @@ public class JUnit4TestMethodAdapter implements Test { runner = request.getRunner(); } + @Override public int countTestCases() { return runner.testCount(); } @@ -95,14 +96,15 @@ public class JUnit4TestMethodAdapter implements Test { return runner.getDescription(); } - public List/*<Test>*/ getTests() { + public List<Test> getTests() { return cache.asTestList(getDescription()); } - public Class getTestClass() { + public Class<?> getTestClass() { return testClass; } + @Override public void run(final TestResult result) { runner.run(cache.getNotifier(result)); } @@ -126,10 +128,10 @@ public class JUnit4TestMethodAdapter implements Test { private static final class MultipleMethodsFilter extends Filter { private final Description methodsListDescription; - private final Class testClass; + private final Class<?> testClass; private final String[] methodNames; - private MultipleMethodsFilter(Class testClass, String[] methodNames) { + private MultipleMethodsFilter(Class<?> testClass, String[] methodNames) { if (testClass == null) { throw new IllegalArgumentException("testClass is <null>"); } @@ -151,23 +153,10 @@ public class JUnit4TestMethodAdapter implements Test { return false; } if (description.isTest()) { - Iterator/*<Description>*/ it = methodsListDescription.getChildren().iterator(); - while (it.hasNext()) { - Description methodDescription = (Description) it.next(); - if (methodDescription.equals(description)) { - return true; - } - } - } else { - Iterator/*<Description>*/ it = description.getChildren().iterator(); - while (it.hasNext()) { - Description each = (Description) it.next(); - if (shouldRun(each)) { - return true; - } - } + return methodsListDescription.getChildren().stream() + .anyMatch(Predicate.isEqual(description)); } - return false; + return description.getChildren().stream().anyMatch(this::shouldRun); } @Override @@ -189,5 +178,4 @@ public class JUnit4TestMethodAdapter implements Test { } - } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java index dcb2a98..e32403c 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java @@ -33,6 +33,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; @@ -135,10 +136,26 @@ public class JUnitTask extends Task { private static final String LINE_SEP = System.getProperty("line.separator"); private static final String CLASSPATH = "CLASSPATH"; + + private static final int STRING_BUFFER_SIZE = 128; + /** + * @since Ant 1.7 + */ + public static final String TESTLISTENER_PREFIX = + "junit.framework.TestListener: "; + + /** + * Name of magic property that enables test listener events. + */ + public static final String ENABLE_TESTLISTENER_EVENTS = + "ant.junit.enabletestlistenerevents"; + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + private CommandlineJava commandline; - private final Vector<JUnitTest> tests = new Vector<JUnitTest>(); - private final Vector<BatchTest> batchTests = new Vector<BatchTest>(); - private final Vector<FormatterElement> formatters = new Vector<FormatterElement>(); + private final List<JUnitTest> tests = new Vector<>(); + private final List<BatchTest> batchTests = new Vector<>(); + private final Vector<FormatterElement> formatters = new Vector<>(); private File dir = null; private Integer timeout = null; @@ -186,21 +203,6 @@ public class JUnitTask extends Task { private String failureProperty; private String errorProperty; - private static final int STRING_BUFFER_SIZE = 128; - /** - * @since Ant 1.7 - */ - public static final String TESTLISTENER_PREFIX = - "junit.framework.TestListener: "; - - /** - * Name of magic property that enables test listener events. - */ - public static final String ENABLE_TESTLISTENER_EVENTS = - "ant.junit.enabletestlistenerevents"; - - private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); - /** * If true, force ant to re-classload all classes for each JUnit TestCase * @@ -368,8 +370,8 @@ public class JUnitTask extends Task { */ @Override public String[] getValues() { - return new String[] {"true", "yes", "false", "no", - "on", "off", "withOutAndErr"}; + return new String[] { "true", "yes", "false", "no", "on", "off", + "withOutAndErr" }; } /** @@ -584,7 +586,7 @@ public class JUnitTask extends Task { * @since Ant 1.2 */ public void addTest(final JUnitTest test) { - tests.addElement(test); + tests.add(test); preConfigure(test); } @@ -598,7 +600,7 @@ public class JUnitTask extends Task { */ public BatchTest createBatchTest() { final BatchTest test = new BatchTest(getProject()); - batchTests.addElement(test); + batchTests.add(test); preConfigure(test); return test; } @@ -610,7 +612,7 @@ public class JUnitTask extends Task { * @since Ant 1.2 */ public void addFormatter(final FormatterElement fe) { - formatters.addElement(fe); + formatters.add(fe); } /** @@ -714,11 +716,9 @@ public class JUnitTask extends Task { * @since Ant 1.6 */ public void setTempdir(final File tmpDir) { - if (tmpDir != null) { - if (!tmpDir.exists() || !tmpDir.isDirectory()) { - throw new BuildException(tmpDir.toString() - + " is not a valid temp directory"); - } + if (tmpDir != null && (!tmpDir.exists() || !tmpDir.isDirectory())) { + throw new BuildException("%s is not a valid temp directory", + tmpDir); } this.tmpDir = tmpDir; } @@ -776,12 +776,12 @@ public class JUnitTask extends Task { e, task.getLocation()); } try { - final Class c = loader.loadClass(JUnitTaskMirror.class.getName() + "Impl"); + final Class<? extends JUnitTaskMirror> c = loader.loadClass(JUnitTaskMirror.class.getName() + "Impl").asSubclass(JUnitTaskMirror.class); if (c.getClassLoader() != loader) { throw new BuildException("Overdelegating loader", task.getLocation()); } - final Constructor cons = c.getConstructor(new Class[] {JUnitTask.class}); - return (JUnitTaskMirror) cons.newInstance(new Object[] {task}); + final Constructor<? extends JUnitTaskMirror> cons = c.getConstructor(JUnitTask.class); + return cons.newInstance(task); } catch (final Exception e) { throw new BuildException(e, task.getLocation()); } @@ -807,28 +807,19 @@ public class JUnitTask extends Task { if (extra != null && !hasJunit(path)) { path.add(expandModulePath(extra)); } - mirrorLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - return new SplitClassLoader(myLoader, path, getProject(), - new String[] { - "BriefJUnitResultFormatter", - "JUnit4TestMethodAdapter", - "JUnitResultFormatter", - "JUnitTaskMirrorImpl", - "JUnitTestRunner", - "JUnitVersionHelper", - "OutErrSummaryJUnitResultFormatter", - "PlainJUnitResultFormatter", - "SummaryJUnitResultFormatter", - "TearDownOnVmCrash", - "XMLJUnitResultFormatter", - "IgnoredTestListener", - "IgnoredTestResult", - "CustomJUnit4TestAdapterCache", - "TestListenerWrapper" - }); - } - }); + mirrorLoader = AccessController.doPrivileged( + (PrivilegedAction<ClassLoader>) () -> new SplitClassLoader( + myLoader, path, getProject(), + new String[] { "BriefJUnitResultFormatter", + "JUnit4TestMethodAdapter", "JUnitResultFormatter", + "JUnitTaskMirrorImpl", "JUnitTestRunner", + "JUnitVersionHelper", + "OutErrSummaryJUnitResultFormatter", + "PlainJUnitResultFormatter", + "SummaryJUnitResultFormatter", "TearDownOnVmCrash", + "XMLJUnitResultFormatter", "IgnoredTestListener", + "IgnoredTestResult", "CustomJUnit4TestAdapterCache", + "TestListenerWrapper" })); } else { mirrorLoader = myLoader; } @@ -847,25 +838,22 @@ public class JUnitTask extends Task { checkModules(); setupJUnitDelegate(); - final List<List> testLists = new ArrayList<List>(); + final List<List<JUnitTest>> testLists = new ArrayList<>(); /* parallel test execution is only supported for multi-process execution */ final int threads = ((!fork) || (forkMode.getValue().equals(ForkMode.ONCE)) ? 1 : this.threads); - final boolean forkPerTest = forkMode.getValue().equals(ForkMode.PER_TEST); - if (forkPerTest || forkMode.getValue().equals(ForkMode.ONCE)) { + final boolean forkPerTest = ForkMode.PER_TEST.equals(forkMode.getValue()); + if (forkPerTest || ForkMode.ONCE.equals(forkMode.getValue())) { testLists.addAll(executeOrQueue(getIndividualTests(), forkPerTest)); } else { /* forkMode.getValue().equals(ForkMode.PER_BATCH) */ - final int count = batchTests.size(); - for (int i = 0; i < count; i++) { - final BatchTest batchtest = batchTests.elementAt(i); - testLists.addAll(executeOrQueue(batchtest.elements(), false)); - } - testLists.addAll(executeOrQueue(tests.elements(), forkPerTest)); + batchTests.stream().map(b -> executeOrQueue(b.elements(), false)) + .forEach(testLists::addAll); + testLists.addAll( + executeOrQueue(Collections.enumeration(tests), forkPerTest)); } - try { /* prior to parallel the code in 'oneJunitThread' used to be here. */ runTestsInThreads(testLists, threads); @@ -890,12 +878,13 @@ public class JUnitTask extends Task { */ private class JunitTestThread implements Runnable { - JunitTestThread(final JUnitTask master, final Iterator<List> iterator, final int id) { + JunitTestThread(final JUnitTask master, final Iterator<List<JUnitTest>> iterator, final int id) { this.masterTask = master; this.iterator = iterator; this.id = id; } + @Override public void run() { try { masterTask.oneJunitThread(iterator, id); @@ -906,7 +895,7 @@ public class JUnitTask extends Task { } private final JUnitTask masterTask; - private final Iterator<List> iterator; + private final Iterator<List<JUnitTest>> iterator; private final int id; } @@ -917,8 +906,8 @@ public class JUnitTask extends Task { * threads get the same test, or two threads simultaneously pop the list so that a test * gets skipped! */ - private List getNextTest(final Iterator<List> iter) { - synchronized(iter) { + private List<JUnitTest> getNextTest(final Iterator<List<JUnitTest>> iter) { + synchronized (iter) { if (iter.hasNext()) { return iter.next(); } @@ -937,14 +926,14 @@ public class JUnitTask extends Task { * fatal reason, no new tests/batches will be started but the running threads will be * permitted to complete. Additional tests may start in already-running batch-test threads. */ - private void oneJunitThread(final Iterator<List> iter, final int threadId) { + private void oneJunitThread(final Iterator<List<JUnitTest>> iter, final int threadId) { - List l; + List<JUnitTest> l; log("Starting test thread " + threadId, Project.MSG_VERBOSE); while ((caughtBuildException == null) && ((l = getNextTest(iter)) != null)) { log("Running test " + l.get(0).toString() + "(" + l.size() + ") in thread " + threadId, Project.MSG_VERBOSE); if (l.size() == 1) { - execute((JUnitTest) l.get(0), threadId); + execute(l.get(0), threadId); } else { execute(l, threadId); } @@ -953,9 +942,9 @@ public class JUnitTask extends Task { } - private void runTestsInThreads(final List<List> testList, final int numThreads) { + private void runTestsInThreads(final List<List<JUnitTest>> testList, final int numThreads) { - Iterator<List> iter = testList.iterator(); + Iterator<List<JUnitTest>> iter = testList.iterator(); if (numThreads == 1) { /* with just one thread just run the test - don't create any threads */ @@ -968,24 +957,25 @@ public class JUnitTask extends Task { /* Need to split apart tests, which are still grouped in batches */ /* is there a simpler Java mechanism to do this? */ /* I assume we don't want to do this with "per batch" forking. */ - List<List> newlist = new ArrayList<List>(); + List<List<JUnitTest>> newlist = new ArrayList<>(); if (forkMode.getValue().equals(ForkMode.PER_TEST)) { - final Iterator<List> i1 = testList.iterator(); + final Iterator<List<JUnitTest>> i1 = testList.iterator(); while (i1.hasNext()) { - final List l = i1.next(); + final List<JUnitTest> l = i1.next(); if (l.size() == 1) { - newlist.add(l); + newlist.add(l); } else { - final Iterator i2 = l.iterator(); - while (i2.hasNext()) { - final List tmpSingleton = new ArrayList(); - tmpSingleton.add(i2.next()); - newlist.add(tmpSingleton); - } + final Iterator<JUnitTest> i2 = l.iterator(); + while (i2.hasNext()) { + final List<JUnitTest> tmpSingleton = + new ArrayList<>(); + tmpSingleton.add(i2.next()); + newlist.add(tmpSingleton); + } } } } else { - newlist = testList; + newlist = testList; } iter = newlist.iterator(); @@ -1028,7 +1018,7 @@ public class JUnitTask extends Task { protected void execute(final JUnitTest arg, final int thread) throws BuildException { validateTestName(arg.getName()); - final JUnitTest test = (JUnitTest) arg.clone(); + final JUnitTest test = arg.clone(); test.setThread(thread); // set the default values if not specified @@ -1042,13 +1032,13 @@ public class JUnitTask extends Task { } // execute the test and get the return code - TestResultHolder result = null; - if (!test.getFork()) { - result = executeInVM(test); - } else { + TestResultHolder result; + if (test.getFork()) { final ExecuteWatchdog watchdog = createWatchdog(); result = executeAsForked(test, watchdog, null); // null watchdog means no timeout, you'd better not check with null + } else { + result = executeInVM(test); } actOnTestResult(result, test, "Test " + test.getName()); } @@ -1070,8 +1060,8 @@ public class JUnitTask extends Task { * @throws BuildException if <code>testName</code> is not a valid test name */ private void validateTestName(final String testName) throws BuildException { - if (testName == null || testName.length() == 0 - || testName.equals("null")) { + if (testName == null || testName.isEmpty() + || "null".equals(testName)) { throw new BuildException("test name must be specified"); } } @@ -1082,23 +1072,21 @@ public class JUnitTask extends Task { * @param thread Identifies which thread is test running in (0 for single-threaded runs) * @throws BuildException on error. */ - protected void execute(final List testList, final int thread) throws BuildException { - JUnitTest test = null; + protected void execute(final List<JUnitTest> testList, final int thread) throws BuildException { // Create a temporary file to pass the test cases to run to // the runner (one test case per line) final File casesFile = createTempPropertiesFile("junittestcases"); - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(casesFile)); + try (BufferedWriter writer = + new BufferedWriter(new FileWriter(casesFile))) { log("Creating casesfile '" + casesFile.getAbsolutePath() + "' with content: ", Project.MSG_VERBOSE); final PrintStream logWriter = new PrintStream(new LogOutputStream(this, Project.MSG_VERBOSE)); - final Iterator iter = testList.iterator(); - while (iter.hasNext()) { - test = (JUnitTest) iter.next(); + JUnitTest test = null; + for (JUnitTest t : testList) { + test = t; test.setThread(thread); printDual(writer, logWriter, test.getName()); if (test.getMethods() != null) { @@ -1119,8 +1107,6 @@ public class JUnitTask extends Task { } } writer.flush(); - writer.close(); - writer = null; // execute the test and get the return code final ExecuteWatchdog watchdog = createWatchdog(); @@ -1131,8 +1117,6 @@ public class JUnitTask extends Task { log(e.toString(), Project.MSG_ERR); throw new BuildException(e); } finally { - FileUtils.close(writer); - try { FILE_UTILS.tryHardToDelete(casesFile); } catch (final Exception e) { @@ -1146,7 +1130,7 @@ public class JUnitTask extends Task { * @param testList the list of tests to execute. * @throws BuildException on error. */ - protected void execute(final List testList) throws BuildException { + protected void execute(final List<JUnitTest> testList) throws BuildException { execute(testList, 0); } @@ -1177,7 +1161,7 @@ public class JUnitTask extends Task { CommandlineJava cmd; try { - cmd = (CommandlineJava) (getCommandline().clone()); + cmd = getCommandline().clone(); } catch (final CloneNotSupportedException e) { throw new BuildException("This shouldn't happen", e, getLocation()); } @@ -1213,7 +1197,7 @@ public class JUnitTask extends Task { cmd.createArgument().setValue(Constants.LOGTESTLISTENEREVENTS + String.valueOf(getEnableTestListenerEvents())); - StringBuffer formatterArg = new StringBuffer(STRING_BUFFER_SIZE); + StringBuilder formatterArg = new StringBuilder(STRING_BUFFER_SIZE); final FormatterElement[] feArray = mergeFormatters(test); for (int i = 0; i < feArray.length; i++) { final FormatterElement fe = feArray[i]; @@ -1226,7 +1210,7 @@ public class JUnitTask extends Task { formatterArg.append(outFile); } cmd.createArgument().setValue(formatterArg.toString()); - formatterArg = new StringBuffer(); + formatterArg = new StringBuilder(); } } @@ -1236,17 +1220,14 @@ public class JUnitTask extends Task { final File propsFile = createTempPropertiesFile("junit"); cmd.createArgument().setValue(Constants.PROPSFILE + propsFile.getAbsolutePath()); - final Hashtable p = getProject().getProperties(); + final Hashtable<String, Object> p = getProject().getProperties(); final Properties props = new Properties(); - for (final Enumeration e = p.keys(); e.hasMoreElements();) { - final Object key = e.nextElement(); - props.put(key, p.get(key)); - } + p.forEach(props::put); try { final OutputStream outstream = Files.newOutputStream(propsFile.toPath()); props.store(outstream, "Ant JUnitTask generated properties file"); outstream.close(); - } catch (final java.io.IOException e) { + } catch (final IOException e) { FILE_UTILS.tryHardToDelete(propsFile); throw new BuildException("Error creating temporary properties " + "file.", e, getLocation()); @@ -1328,9 +1309,9 @@ public class JUnitTask extends Task { + propsFile.getAbsolutePath() + "'."; if (success) { throw new BuildException(msg); //NOSONAR - } else { // don't hide inner exception - log(msg, Project.MSG_ERR); } + // don't hide inner exception + log(msg, Project.MSG_ERR); } } @@ -1343,8 +1324,8 @@ public class JUnitTask extends Task { */ private void checkIncludeAntRuntime(final CommandlineJava cmd) { if (includeAntRuntime) { - final Map/*<String, String>*/ env = Execute.getEnvironmentVariables(); - final String cp = (String) env.get(CLASSPATH); + final Map<String, String> env = Execute.getEnvironmentVariables(); + final String cp = env.get(CLASSPATH); if (cp != null) { cmd.createClasspath(getProject()).createPath() .append(new Path(getProject(), cp)); @@ -1356,7 +1337,6 @@ public class JUnitTask extends Task { } } - /** * check for the parameter being "withoutanderr" in a locale-independent way. * @param summaryOption the summary option -can be null @@ -1400,9 +1380,9 @@ public class JUnitTask extends Task { LoaderUtils.classNameToResource(Project.class.getName()); URL previous = null; try { - for (final Enumeration e = loader.getResources(projectResourceName); + for (final Enumeration<URL> e = loader.getResources(projectResourceName); e.hasMoreElements();) { - final URL current = (URL) e.nextElement(); + final URL current = e.nextElement(); if (previous != null && !urlEquals(current, previous)) { log("WARNING: multiple versions of ant detected " + "in path for junit " @@ -1501,9 +1481,8 @@ public class JUnitTask extends Task { throws IOException { if (runner != null) { return runner.handleInput(buffer, offset, length); - } else { - return super.handleInput(buffer, offset, length); } + return super.handleInput(buffer, offset, length); } @@ -1580,7 +1559,7 @@ public class JUnitTask extends Task { setupJUnitDelegate(); } - final JUnitTest test = (JUnitTest) arg.clone(); + final JUnitTest test = arg.clone(); test.setProperties(getProject().getProperties()); if (dir != null) { log("dir attribute ignored if running in the same VM", @@ -1691,12 +1670,14 @@ public class JUnitTask extends Task { */ protected Enumeration<JUnitTest> getIndividualTests() { final int count = batchTests.size(); - final Enumeration[] enums = new Enumeration[ count + 1]; + @SuppressWarnings("unchecked") + final Enumeration<JUnitTest>[] enums = new Enumeration[ count + 1]; + for (int i = 0; i < count; i++) { - final BatchTest batchtest = batchTests.elementAt(i); + final BatchTest batchtest = batchTests.get(i); enums[i] = batchtest.elements(); } - enums[enums.length - 1] = tests.elements(); + enums[enums.length - 1] = Collections.enumeration(tests); return Enumerations.fromCompound(enums); } @@ -1713,10 +1694,7 @@ public class JUnitTask extends Task { if (tests.isEmpty()) { return; } - - final Enumeration<JUnitTest> testsEnum = tests.elements(); - while (testsEnum.hasMoreElements()) { - final JUnitTest test = testsEnum.nextElement(); + for (JUnitTest test : tests) { if (test.hasMethodsSpecified() && test.shouldRun(getProject())) { test.resolveMethods(); } @@ -1730,15 +1708,10 @@ public class JUnitTask extends Task { private void checkModules() { if (hasPath(getCommandline().getModulepath()) || hasPath(getCommandline().getUpgrademodulepath())) { - for (int i = 0, count = batchTests.size(); i < count; i++) { - if(!batchTests.elementAt(i).getFork()) { - throw new BuildException("The module path requires fork attribute to be set to true."); - } - } - for (int i = 0, count = tests.size(); i < count; i++) { - if (!tests.elementAt(i).getFork()) { - throw new BuildException("The module path requires fork attribute to be set to true."); - } + if (!(batchTests.stream().allMatch(BaseTest::getFork) + && tests.stream().allMatch(BaseTest::getFork))) { + throw new BuildException( + "The module path requires fork attribute to be set to true."); } } } @@ -1775,7 +1748,8 @@ public class JUnitTask extends Task { for (String path : modulePath.list()) { final File modulePathEntry = getProject().resolveFile(path); if (modulePathEntry.isDirectory() && !hasModuleInfo(modulePathEntry)) { - final File[] modules = modulePathEntry.listFiles((dir,name)->name.toLowerCase(Locale.ENGLISH).endsWith(".jar")); + final File[] modules = modulePathEntry.listFiles((dir, + name) -> name.toLowerCase(Locale.ENGLISH).endsWith(".jar")); if (modules != null) { for (File module : modules) { expanded.add(new Path(getProject(), String.format( @@ -1797,9 +1771,9 @@ public class JUnitTask extends Task { * @return enumeration * @since Ant 1.3 */ - protected Enumeration<JUnitTest> allTests() { - final Enumeration[] enums = {tests.elements(), batchTests.elements()}; - return Enumerations.fromCompound(enums); + protected Enumeration<BaseTest> allTests() { + return Enumerations.fromCompound(Collections.enumeration(tests), + Collections.enumeration(batchTests)); } /** @@ -1808,6 +1782,7 @@ public class JUnitTask extends Task { * @since Ant 1.3 */ private FormatterElement[] mergeFormatters(final JUnitTest test) { + @SuppressWarnings("unchecked") final Vector<FormatterElement> feVector = (Vector<FormatterElement>) formatters.clone(); test.addFormattersTo(feVector); final FormatterElement[] feArray = new FormatterElement[feVector.size()]; @@ -2181,7 +2156,7 @@ public class JUnitTask extends Task { /** {@inheritDoc}. */ @Override public String[] getValues() { - return new String[] {ONCE, PER_TEST, PER_BATCH}; + return new String[] { ONCE, PER_TEST, PER_BATCH }; } } @@ -2195,9 +2170,10 @@ public class JUnitTask extends Task { * @return a list of tasks to be executed. * @since 1.6.2 */ - protected Collection<List> executeOrQueue(final Enumeration<JUnitTest> testList, - final boolean runIndividual) { - final Map<ForkedTestConfiguration, List> testConfigurations = new HashMap<ForkedTestConfiguration, List>(); + protected Collection<List<JUnitTest>> executeOrQueue( + final Enumeration<JUnitTest> testList, final boolean runIndividual) { + final Map<ForkedTestConfiguration, List<JUnitTest>> testConfigurations = + new HashMap<>(); while (testList.hasMoreElements()) { final JUnitTest test = testList.nextElement(); if (test.shouldRun(getProject())) { @@ -2206,14 +2182,10 @@ public class JUnitTask extends Task { if ((runIndividual || !test.getFork()) && (threads == 1)) { execute(test, 0); } else { - final ForkedTestConfiguration c = - new ForkedTestConfiguration(test); - List<JUnitTest> l = testConfigurations.get(c); - if (l == null) { - l = new ArrayList<JUnitTest>(); - testConfigurations.put(c, l); - } - l.add(test); + testConfigurations + .computeIfAbsent(new ForkedTestConfiguration(test), + k -> new ArrayList<>()) + .add(test); } } } @@ -2361,7 +2333,7 @@ public class JUnitTask extends Task { * @see "https://issues.apache.org/bugzilla/show_bug.cgi?id=45227" */ private static JUnitTest createDummyTestForBatchTest(final JUnitTest test) { - final JUnitTest t = (JUnitTest) test.clone(); + final JUnitTest t = test.clone(); final int index = test.getName().lastIndexOf('.'); // make sure test looks as if it was in the same "package" as // the last test of the batch http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java index c7dae25..894b6a0 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskMirrorImpl.java @@ -35,6 +35,7 @@ import org.apache.tools.ant.AntClassLoader; */ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { + @SuppressWarnings("unused") private final JUnitTask task; /** @@ -46,6 +47,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { } /** {@inheritDoc}. */ + @Override public void addVmExit(JUnitTest test, JUnitTaskMirror.JUnitResultFormatterMirror aFormatter, OutputStream out, String message, String testCase) { JUnitResultFormatter formatter = (JUnitResultFormatter) aFormatter; @@ -61,6 +63,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { } /** {@inheritDoc}. */ + @Override public JUnitTaskMirror.JUnitTestRunnerMirror newJUnitTestRunner(JUnitTest test, String[] methods, boolean haltOnError, boolean filterTrace, boolean haltOnFailure, @@ -70,6 +73,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { } /** {@inheritDoc}. */ + @Override public JUnitTaskMirror.SummaryJUnitResultFormatterMirror newSummaryJUnitResultFormatter() { return new SummaryJUnitResultFormatter(); } @@ -86,14 +90,17 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { testCase = aTestCase; } + @Override public int countTestCases() { return 1; } + @Override public void run(TestResult r) { throw new AssertionFailedError(message); } + @Override public String getName() { return testCase; } @@ -102,6 +109,7 @@ public final class JUnitTaskMirrorImpl implements JUnitTaskMirror { return test.getName(); } + @Override public String toString() { return test.getName() + ":" + testCase; } http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java index 835c013..2ec5653 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java @@ -18,7 +18,6 @@ package org.apache.tools.ant.taskdefs.optional.junit; -import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; import java.util.Vector; @@ -228,7 +227,7 @@ public class JUnitTest extends BaseTest implements Cloneable { } else if (methods.length == 1) { methodsList = methods[0]; } else { - StringBuffer buf = new StringBuffer(methods.length * 16); + StringBuilder buf = new StringBuilder(methods.length * 16); buf.append(methods[0]); for (int i = 1; i < methods.length; i++) { buf.append(',').append(methods[i]); @@ -482,12 +481,9 @@ public class JUnitTest extends BaseTest implements Cloneable { * @param p the properties. * This is a copy of the projects ant properties. */ - public void setProperties(Hashtable p) { + public void setProperties(Hashtable<?,?> p) { props = new Properties(); - for (Enumeration e = p.keys(); e.hasMoreElements();) { - Object key = e.nextElement(); - props.put(key, p.get(key)); - } + p.forEach(props::put); } /** @@ -516,7 +512,7 @@ public class JUnitTest extends BaseTest implements Cloneable { /** * Convenient method to add formatters to a vector */ - void addFormattersTo(Vector v) { + void addFormattersTo(Vector<? super FormatterElement> v) { final int count = formatters.size(); for (int i = 0; i < count; i++) { v.addElement(formatters.elementAt(i)); @@ -527,12 +523,13 @@ public class JUnitTest extends BaseTest implements Cloneable { * @since Ant 1.5 * @return a clone of this test. */ + @SuppressWarnings("unchecked") @Override - public Object clone() { + public JUnitTest clone() { try { JUnitTest t = (JUnitTest) super.clone(); t.props = props == null ? null : (Properties) props.clone(); - t.formatters = (Vector) formatters.clone(); + t.formatters = (Vector<FormatterElement>) formatters.clone(); return t; } catch (CloneNotSupportedException e) { // plain impossible http://git-wip-us.apache.org/repos/asf/ant/blob/b7d1e9bd/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java ---------------------------------------------------------------------- diff --git a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java index ea7524d..4009666 100644 --- a/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java +++ b/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.java @@ -29,12 +29,12 @@ import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.io.StringWriter; +import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Enumeration; -import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; @@ -73,21 +73,49 @@ import org.apache.tools.ant.util.TeeOutputStream; */ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestRunnerMirror { + private static final String JUNIT_4_TEST_ADAPTER + = "junit.framework.JUnit4TestAdapter"; + + 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", + " more", + }; /** - * Holds the registered formatters. + * Do we filter junit.*.* stack frames out of failure and error exceptions. */ - private final Vector<JUnitTaskMirror.JUnitResultFormatterMirror> formatters = new Vector(); + private static boolean filtertrace = true; + + /** Running more than one test suite? */ + private static boolean multipleTests = false; /** - * Collects TestResults. + * The file used to indicate that the build crashed. + * File will be empty in case the build did not crash. */ - private IgnoredTestResult res; + private static String crashFile = null; /** - * Do we filter junit.*.* stack frames out of failure and error exceptions. + * Holds the registered formatters. */ - private static boolean filtertrace = true; + private final Vector<JUnitTaskMirror.JUnitResultFormatterMirror> formatters = new Vector<>(); + + /** + * Collects TestResults. + */ + private IgnoredTestResult res; /** * Do we send output to System.out/.err in addition to the formatters? @@ -101,27 +129,6 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR */ private Permissions perm = null; - private static final String JUNIT_4_TEST_ADAPTER - = "junit.framework.JUnit4TestAdapter"; - - 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", - " more", - }; - - /** * Do we stop on errors. */ @@ -151,9 +158,6 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** is this runner running in forked mode? */ private boolean forked = false; - /** Running more than one test suite? */ - private static boolean multipleTests = false; - /** ClassLoader passed in in non-forked mode. */ private final ClassLoader loader; @@ -163,12 +167,6 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** Turned on if we are using JUnit 4 for this test suite. see #38811 */ private boolean junit4; - /** - * The file used to indicate that the build crashed. - * File will be empty in case the build did not crash. - */ - private static String crashFile = null; - /** Names of test methods to execute */ private String[] methods = null; @@ -357,6 +355,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR /** * Run the test. */ + @Override public void run() { res = new IgnoredTestResult(); res.addListener(wrapListener(this)); @@ -377,7 +376,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR try { try { - Class testClass = null; + Class<?> testClass; if (loader == null) { testClass = Class.forName(junitTest.getName()); } else { @@ -391,24 +390,24 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR // JUnit 4 Method suiteMethod = null; if (!testMethodsSpecified) { - try { - // check if there is a suite method - suiteMethod = testClass.getMethod("suite", new Class[0]); - } catch (final NoSuchMethodException e) { - // no appropriate suite method found. We don't report any - // error here since it might be perfectly normal. - } + try { + // check if there is a suite method + suiteMethod = testClass.getMethod("suite"); + } catch (final NoSuchMethodException e) { + // no appropriate suite method found. We don't report any + // error here since it might be perfectly normal. + } } if (suiteMethod != null) { // if there is a suite method available, then try // to extract the suite from it. If there is an error // here it will be caught below and reported. - suite = (Test) suiteMethod.invoke(null, new Object[0]); + suite = (Test) suiteMethod.invoke(null); } else { - Class junit4TestAdapterClass = null; - Class junit4TestAdapterCacheClass = null; + Class<?> junit4TestAdapterClass = null; + Class<?> junit4TestAdapterCacheClass = null; boolean useSingleMethodAdapter = false; if (junit.framework.TestCase.class.isAssignableFrom(testClass)) { @@ -434,64 +433,69 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR // In that case first C.fN will fail with CNFE and we // will avoid UnsupportedClassVersionError. - try { - Class.forName("java.lang.annotation.Annotation"); - junit4TestAdapterCacheClass = Class.forName("org.apache.tools.ant.taskdefs.optional.junit.CustomJUnit4TestAdapterCache"); - if (loader == null) { - junit4TestAdapterClass = - Class.forName(JUNIT_4_TEST_ADAPTER); - if (testMethodsSpecified) { - /* - * We cannot try to load the JUnit4TestAdapter - * before trying to load JUnit4TestMethodAdapter - * because it might fail with - * NoClassDefFoundException, instead of plain - * ClassNotFoundException. - */ - junit4TestAdapterClass = Class.forName( - "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter"); - useSingleMethodAdapter = true; - } - } else { - junit4TestAdapterClass = - Class.forName(JUNIT_4_TEST_ADAPTER, - true, loader); - if (testMethodsSpecified) { + try { + Class.forName("java.lang.annotation.Annotation"); + junit4TestAdapterCacheClass = Class.forName( + "org.apache.tools.ant.taskdefs.optional.junit.CustomJUnit4TestAdapterCache"); + if (loader == null) { junit4TestAdapterClass = - Class.forName( - "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter", - true, loader); - useSingleMethodAdapter = true; + Class.forName(JUNIT_4_TEST_ADAPTER); + if (testMethodsSpecified) { + /* + * We cannot try to load the JUnit4TestAdapter + * before trying to load JUnit4TestMethodAdapter + * because it might fail with + * NoClassDefFoundException, instead of plain + * ClassNotFoundException. + */ + junit4TestAdapterClass = Class.forName( + "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter"); + useSingleMethodAdapter = true; + } + } else { + junit4TestAdapterClass = + Class.forName(JUNIT_4_TEST_ADAPTER, + true, loader); + if (testMethodsSpecified) { + junit4TestAdapterClass = + Class.forName( + "org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter", + true, loader); + useSingleMethodAdapter = true; + } } + } catch (final ClassNotFoundException e) { + // OK, fall back to JUnit 3. } - } catch (final ClassNotFoundException e) { - // OK, fall back to JUnit 3. - } } junit4 = junit4TestAdapterClass != null; - if (junitTest.isSkipNonTests()) { - if (!containsTests(testClass, junit4)) { - return; - } + if (junitTest.isSkipNonTests() + && !containsTests(testClass, junit4)) { + return; } - if (junit4) { // Let's use it! - Class[] formalParams; + Class<?>[] formalParams; Object[] actualParams; if (useSingleMethodAdapter) { - formalParams = new Class[] {Class.class, String[].class}; - actualParams = new Object[] {testClass, methods}; + formalParams = + new Class[] { Class.class, String[].class }; + actualParams = new Object[] { testClass, methods }; } else { - formalParams = new Class[] {Class.class, Class.forName("junit.framework.JUnit4TestAdapterCache")}; - actualParams = new Object[] {testClass, junit4TestAdapterCacheClass.getMethod("getInstance").invoke(null)}; + formalParams = + new Class[] { Class.class, Class.forName( + "junit.framework.JUnit4TestAdapterCache") }; + actualParams = + new Object[] { testClass, + junit4TestAdapterCacheClass + .getMethod("getInstance") + .invoke(null) }; } - suite = - (Test) junit4TestAdapterClass - .getConstructor(formalParams). - newInstance(actualParams); + suite = junit4TestAdapterClass.asSubclass(Test.class) + .getConstructor(formalParams) + .newInstance(actualParams); } else { // Use JUnit 3. @@ -511,9 +515,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR suite = testSuite; } } - } - } catch (final Throwable e) { retCode = ERRORS; exception = e; @@ -588,12 +590,13 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } private static boolean containsTests(final Class<?> testClass, final boolean isJUnit4) { - Class testAnnotation = null; - Class suiteAnnotation = null; - Class runWithAnnotation = null; + Class<? extends Annotation> testAnnotation = null; + Class<? extends Annotation> suiteAnnotation = null; + Class<? extends Annotation> runWithAnnotation = null; try { - testAnnotation = Class.forName("org.junit.Test"); + testAnnotation = + Class.forName("org.junit.Test").asSubclass(Annotation.class); } catch (final ClassNotFoundException e) { if (isJUnit4) { // odd - we think we're JUnit4 but don't support the test annotation. We therefore can't have any tests! @@ -603,17 +606,18 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } try { - suiteAnnotation = Class.forName("org.junit.Suite.SuiteClasses"); + suiteAnnotation = Class.forName("org.junit.Suite.SuiteClasses") + .asSubclass(Annotation.class); } catch(final ClassNotFoundException ex) { // ignore - we don't have this annotation so make sure we don't check for it } try { - runWithAnnotation = Class.forName("org.junit.runner.RunWith"); + runWithAnnotation = Class.forName("org.junit.runner.RunWith") + .asSubclass(Annotation.class); } catch(final ClassNotFoundException ex) { // also ignore as this annotation doesn't exist so tests can't use it } - if (!isJUnit4 && !TestCase.class.isAssignableFrom(testClass)) { //a test we think is JUnit3 but does not extend TestCase. Can't really be a test. return false; @@ -621,22 +625,26 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR // check if we have any inner classes that contain suitable test methods for (final Class<?> innerClass : testClass.getDeclaredClasses()) { - if (containsTests(innerClass, isJUnit4) || containsTests(innerClass, !isJUnit4)) { + if (containsTests(innerClass, isJUnit4) + || containsTests(innerClass, !isJUnit4)) { return true; } } - if (Modifier.isAbstract(testClass.getModifiers()) || Modifier.isInterface(testClass.getModifiers())) { + if (Modifier.isAbstract(testClass.getModifiers()) + || Modifier.isInterface(testClass.getModifiers())) { // can't instantiate class and no inner classes are tests either return false; } if (isJUnit4) { - if (suiteAnnotation != null && testClass.getAnnotation(suiteAnnotation) != null) { + if (suiteAnnotation != null + && testClass.getAnnotation(suiteAnnotation) != null) { // class is marked as a suite. Let JUnit try and work its magic on it. return true; - } - if (runWithAnnotation != null && testClass.getAnnotation(runWithAnnotation) != null) { + } + if (runWithAnnotation != null + && testClass.getAnnotation(runWithAnnotation) != null) { /* Class is marked with @RunWith. If this class is badly written (no test methods, multiple * constructors, private constructor etc) then the class is automatically run and fails in the * IDEs I've tried... so I'm happy handing the class to JUnit to try and run, and let JUnit @@ -656,16 +664,19 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } } else { // check if JUnit3 class have public or protected no-args methods starting with names starting with test - if (m.getName().startsWith("test") && m.getParameterTypes().length == 0 - && (Modifier.isProtected(m.getModifiers()) || Modifier.isPublic(m.getModifiers()))) { + if (m.getName().startsWith("test") + && m.getParameterTypes().length == 0 + && (Modifier.isProtected(m.getModifiers()) + || Modifier.isPublic(m.getModifiers()))) { return true; } } // check if JUnit3 or JUnit4 test have a public or protected, static, // no-args 'suite' method - if (m.getName().equals("suite") && m.getParameterTypes().length == 0 - && (Modifier.isProtected(m.getModifiers()) || Modifier.isPublic(m.getModifiers())) - && Modifier.isStatic(m.getModifiers())) { + if ("suite".equals(m.getName()) && m.getParameterTypes().length == 0 + && (Modifier.isProtected(m.getModifiers()) + || Modifier.isPublic(m.getModifiers())) + && Modifier.isStatic(m.getModifiers())) { return true; } } @@ -679,6 +690,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * * @return 2 if errors occurred, 1 if tests failed else 0. */ + @Override public int getRetCode() { return retCode; } @@ -689,6 +701,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * <p>A new Test is started. * @param t the test. */ + @Override public void startTest(final Test t) { final String testName = JUnitVersionHelper.getTestCaseName(t); logTestListenerEvent("startTest(" + testName + ")"); @@ -700,6 +713,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * <p>A Test is finished. * @param test the test. */ + @Override public void endTest(final Test test) { final String testName = JUnitVersionHelper.getTestCaseName(test); logTestListenerEvent("endTest(" + testName + ")"); @@ -709,10 +723,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR if (logTestListenerEvents) { final PrintStream out = savedOut != null ? savedOut : System.out; out.flush(); - if (msg == null) { - msg = "null"; - } - final StringTokenizer msgLines = new StringTokenizer(msg, "\r\n", false); + final StringTokenizer msgLines = + new StringTokenizer(String.valueOf(msg), "\r\n", false); while (msgLines.hasMoreTokens()) { out.println(JUnitTask.TESTLISTENER_PREFIX + msgLines.nextToken()); @@ -743,6 +755,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param test the test. * @param t the assertion thrown by the test. */ + @Override public void addFailure(final Test test, final AssertionFailedError t) { addFailure(test, (Throwable) t); } @@ -754,6 +767,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @param test the test. * @param t the error thrown by the test. */ + @Override public void addError(final Test test, final Throwable t) { final String testName = JUnitVersionHelper.getTestCaseName(test); logTestListenerEvent("addError(" + testName + ", " + t.getMessage() + ")"); @@ -767,6 +781,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * @since Ant 1.6 * @param permissions the permissions to use. */ + @Override public void setPermissions(final Permissions permissions) { perm = permissions; } @@ -775,6 +790,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * Handle a string destined for standard output. * @param output the string to output */ + @Override public void handleOutput(final String output) { if (!logTestListenerEvents && output.startsWith(JUnitTask.TESTLISTENER_PREFIX)) { // ignore @@ -794,12 +810,14 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR * * @since Ant 1.6 */ + @Override public int handleInput(final byte[] buffer, final int offset, final int length) throws IOException { return -1; } /** {@inheritDoc}. */ + @Override public void handleErrorOutput(final String output) { if (systemError != null) { systemError.print(output); @@ -807,6 +825,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } /** {@inheritDoc}. */ + @Override public void handleFlush(final String output) { if (systemOut != null) { systemOut.print(output); @@ -814,6 +833,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } /** {@inheritDoc}. */ + @Override public void handleErrorFlush(final String output) { if (systemError != null) { systemError.print(output); @@ -824,7 +844,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR final int size = formatters.size(); for (int i = 0; i < size; i++) { final JUnitResultFormatter formatter = - ((JUnitResultFormatter) formatters.elementAt(i)); + (JUnitResultFormatter) formatters.get(i); formatter.setSystemOutput(out); formatter.setSystemError(err); @@ -856,6 +876,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } /** {@inheritDoc}. */ + @Override public void addFormatter(final JUnitTaskMirror.JUnitResultFormatterMirror f) { formatters.addElement(f); } @@ -966,19 +987,13 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR } // Add/overlay system properties on the properties from the Ant project - final Hashtable p = System.getProperties(); - for (final Enumeration e = p.keys(); e.hasMoreElements();) { - final Object key = e.nextElement(); - props.put(key, p.get(key)); - } + System.getProperties().forEach(props::put); int returnCode = SUCCESS; if (multipleTests) { - try { - final java.io.BufferedReader reader = - new java.io.BufferedReader(new java.io.FileReader(args[0])); - String testCaseName; - String[] testMethodNames; + try ( + final BufferedReader reader = + new BufferedReader(new java.io.FileReader(args[0]))){ int code = 0; boolean errorOccurred = false; boolean failureOccurred = false; @@ -987,6 +1002,8 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR final StringTokenizer st = new StringTokenizer(line, ","); final String testListSpec = st.nextToken(); final int colonIndex = testListSpec.indexOf(':'); + String testCaseName; + String[] testMethodNames; if (colonIndex == -1) { testCaseName = testListSpec; testMethodNames = null; @@ -1041,43 +1058,52 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR System.exit(returnCode); } - private static Vector fromCmdLine = new Vector(); + private static Vector<FormatterElement> fromCmdLine = new Vector<>(); private static void transferFormatters(final JUnitTestRunner runner, final JUnitTest test) { runner.addFormatter(new JUnitResultFormatter() { + @Override public void startTestSuite(final JUnitTest suite) throws BuildException { } + @Override public void endTestSuite(final JUnitTest suite) throws BuildException { } + @Override public void setOutput(final OutputStream out) { } + @Override public void setSystemOutput(final String out) { } + @Override public void setSystemError(final String err) { } + @Override public void addError(final Test arg0, final Throwable arg1) { } + @Override public void addFailure(final Test arg0, final AssertionFailedError arg1) { } + @Override public void endTest(final Test arg0) { } + @Override public void startTest(final Test arg0) { registerTestCase(JUnitVersionHelper.getTestCaseName(arg0)); } }); final int size = fromCmdLine.size(); for (int i = 0; i < size; i++) { - final FormatterElement fe = (FormatterElement) fromCmdLine.elementAt(i); + final FormatterElement fe = fromCmdLine.elementAt(i); if (multipleTests && fe.getUseFile()) { final File destFile = new File(test.getTodir(), @@ -1279,14 +1305,19 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR private int[] findJUnit4FailureErrorCount(final TestResult result) { int failures = 0; int errors = 0; - Enumeration e = result.failures(); - while (e.hasMoreElements()) { - e.nextElement(); - failures++; + { + @SuppressWarnings("unchecked") + Enumeration<TestFailure> e = result.failures(); + while (e.hasMoreElements()) { + e.nextElement(); + failures++; + } } - e = result.errors(); + @SuppressWarnings("unchecked") + Enumeration<TestFailure> e = result.errors(); while (e.hasMoreElements()) { - final Throwable t = ((TestFailure) e.nextElement()).thrownException(); + final Throwable t = + e.nextElement().thrownException(); if (t instanceof AssertionFailedError || t instanceof AssertionError) { failures++; @@ -1294,7 +1325,7 @@ public class JUnitTestRunner implements TestListener, JUnitTaskMirror.JUnitTestR errors++; } } - return new int[] {failures, errors}; + return new int[] { failures, errors }; } } // JUnitTestRunner
