This is an automated email from the ASF dual-hosted git repository. mbenson pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/ant-antlibs-antunit.git
The following commit(s) were added to refs/heads/master by this push: new 35caae0 code cleanup/updates 35caae0 is described below commit 35caae04d08e659f76a134bd8f29d08e6a496ff2 Author: Matt Benson <mben...@apache.org> AuthorDate: Sat Feb 12 15:44:54 2022 -0600 code cleanup/updates --- NOTICE | 2 +- build.xml | 4 +- src/main/org/apache/ant/antunit/AntUnit.java | 131 +++++++++------------ .../ant/antunit/AntUnitExecutionNotifier.java | 10 +- .../apache/ant/antunit/AntUnitScriptRunner.java | 75 ++++++------ src/main/org/apache/ant/antunit/LogCapturer.java | 14 +-- .../apache/ant/antunit/junit3/AntUnitSuite.java | 38 +++--- .../apache/ant/antunit/junit3/AntUnitTestCase.java | 32 ++--- .../antunit/junit3/JUnitNotificationAdapter.java | 16 +-- .../ant/antunit/junit4/AntUnitSuiteRunner.java | 91 +++++++------- .../ant/antunit/listener/BaseAntUnitListener.java | 94 ++++++++------- .../antunit/listener/FailureAntUnitListener.java | 76 ++++++------ .../ant/antunit/listener/PlainAntUnitListener.java | 10 +- .../ant/antunit/listener/XMLAntUnitListener.java | 13 +- .../org/apache/ant/antunit/LogCapturerTest.java | 9 +- .../org/apache/ant/antunit/LogContentTest.java | 29 ++--- .../apache/ant/antunit/SetUpAndTearDownTest.java | 16 +-- .../ant/antunit/junit4/AntUnitSuiteRunnerTest.java | 47 ++++---- 18 files changed, 329 insertions(+), 378 deletions(-) diff --git a/NOTICE b/NOTICE index e8e650c..719e344 100644 --- a/NOTICE +++ b/NOTICE @@ -1,5 +1,5 @@ Apache AntUnit -Copyright 2005-2018,2021 The Apache Software Foundation +Copyright 2005-2018,2021-2022 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (https://www.apache.org/). diff --git a/build.xml b/build.xml index e8cbd91..22a4ba6 100644 --- a/build.xml +++ b/build.xml @@ -25,8 +25,8 @@ under the License. <!-- don't fork junit; regexp classes not available --> <property name="junit.fork" value="false" /> - <property name="javac.test-source" value="1.5"/> - <property name="javac.test-target" value="1.5"/> + <property name="javac.-source" value="1.5" /> + <property name="javac.-target" value="1.5" /> <import file="common/build.xml"/> </project> diff --git a/src/main/org/apache/ant/antunit/AntUnit.java b/src/main/org/apache/ant/antunit/AntUnit.java index 9222c2d..9ed4169 100644 --- a/src/main/org/apache/ant/antunit/AntUnit.java +++ b/src/main/org/apache/ant/antunit/AntUnit.java @@ -27,9 +27,9 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildException; @@ -42,6 +42,7 @@ import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.Ant; import org.apache.tools.ant.types.Mapper; import org.apache.tools.ant.types.PropertySet; +import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.FileResource; import org.apache.tools.ant.types.resources.Union; @@ -107,24 +108,24 @@ public class AntUnit extends Task { * The object responsible for the execution of the unit test. * scriptRunner is invoked to executes the targets and keep the * reference to the project. scriptRunner is defined only when the - * antunit script is running. + * antunit script is running. */ private AntUnitScriptRunner scriptRunner; /** * listeners. */ - private ArrayList listeners = new ArrayList(); + private ArrayList<AntUnitListener> listeners = new ArrayList<AntUnitListener>(); /** * propertysets. */ - private ArrayList propertySets = new ArrayList(); + private ArrayList<PropertySet> propertySets = new ArrayList<PropertySet>(); /** * Holds references to be inherited by the test project */ - private ArrayList referenceSets = new ArrayList(); + private ArrayList<ReferenceSet> referenceSets = new ArrayList<ReferenceSet>(); /** * has a failure occured? @@ -241,15 +242,15 @@ public class AntUnit extends Task { if (!rc.isFilesystemOnly()) { throw new BuildException(ERROR_NON_FILES); } + @SuppressWarnings("unchecked") + Iterable<Resource> iterable = (Iterable<Resource>) rc; - Iterator i = rc.iterator(); - while (i.hasNext()) { - FileResource r = (FileResource) i.next(); + for (Resource resource : iterable) { + FileResource r = (FileResource) resource; if (r.isExists()) { doFile(r.getFile()); } else { - log("Skipping " + r + " since it doesn't exist", - Project.MSG_VERBOSE); + log("Skipping " + r + " since it doesn't exist", Project.MSG_VERBOSE); } } } @@ -266,20 +267,19 @@ public class AntUnit extends Task { }; try { scriptRunner = new AntUnitScriptRunner(prjFactory); - List testTargets = scriptRunner.getTestTartgets(); + List<String> testTargets = scriptRunner.getTestTargets(); scriptRunner.runSuite(testTargets, notifier); } finally { scriptRunner=null; } } - /** * Redirect output to new project instance. * @param outputToHandle the output to handle. */ public void handleOutput(String outputToHandle) { - if (scriptRunner!=null) { + if (scriptRunner != null) { scriptRunner.getCurrentProject().demuxOutput(outputToHandle, false); } else { super.handleOutput(outputToHandle); @@ -294,7 +294,7 @@ public class AntUnit extends Task { */ public int handleInput(byte[] buffer, int offset, int length) throws IOException { - if (scriptRunner!=null) { + if (scriptRunner != null) { return scriptRunner.getCurrentProject().demuxInput(buffer, offset, length); } return super.handleInput(buffer, offset, length); @@ -305,7 +305,7 @@ public class AntUnit extends Task { * @param toFlush the output String to flush. */ public void handleFlush(String toFlush) { - if (scriptRunner!=null) { + if (scriptRunner != null) { scriptRunner.getCurrentProject().demuxFlush(toFlush, false); } else { super.handleFlush(toFlush); @@ -317,7 +317,7 @@ public class AntUnit extends Task { * @param errorOutputToHandle the error output to handle. */ public void handleErrorOutput(String errorOutputToHandle) { - if (scriptRunner!=null) { + if (scriptRunner != null) { scriptRunner.getCurrentProject().demuxOutput(errorOutputToHandle, true); } else { super.handleErrorOutput(errorOutputToHandle); @@ -329,7 +329,7 @@ public class AntUnit extends Task { * @param errorOutputToFlush the error output to flush. */ public void handleErrorFlush(String errorOutputToFlush) { - if (scriptRunner!=null) { + if (scriptRunner != null) { scriptRunner.getCurrentProject().demuxFlush(errorOutputToFlush, true); } else { super.handleErrorFlush(errorOutputToFlush); @@ -347,19 +347,15 @@ public class AntUnit extends Task { p.setInputHandler(getProject().getInputHandler()); getProject().initSubProject(p); //pass through inherited properties - for (Iterator outer = propertySets.iterator(); outer.hasNext(); ) { - PropertySet set = (PropertySet) outer.next(); - Map props = set.getProperties(); - for (Iterator keys = props.keySet().iterator(); - keys.hasNext(); ) { - String key = keys.next().toString(); - if (MagicNames.PROJECT_BASEDIR.equals(key) - || MagicNames.ANT_FILE.equals(key)) { + for (PropertySet set : propertySets) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + Map<String,Object> props = (Map) set.getProperties(); + for (String key : props.keySet()) { + if (MagicNames.PROJECT_BASEDIR.equals(key) || MagicNames.ANT_FILE.equals(key)) { continue; } Object value = props.get(key); - if (value != null && value instanceof String - && p.getProperty(key) == null) { + if (value instanceof String && p.getProperty(key) == null) { p.setNewProperty(key, (String) value); } } @@ -369,8 +365,7 @@ public class AntUnit extends Task { //with significant modification from taskdefs.Ant in Ant core. //unfortunately the only way we can share the code directly //would be to extend Ant (which might not be a bad idea?) - for (int i = 0; i < referenceSets.size(); ++i) { - ReferenceSet set = (ReferenceSet) referenceSets.get(i); + for (ReferenceSet set : referenceSets) { set.copyReferencesInto(p); } @@ -390,12 +385,8 @@ public class AntUnit extends Task { * @param p the Project to attach to. */ private void attachListeners(File buildFile, Project p) { - Iterator it = listeners.iterator(); - while (it.hasNext()) { - AntUnitListener al = (AntUnitListener) it.next(); - p.addBuildListener(new BuildToAntUnitListener(buildFile - .getAbsolutePath(), - al)); + for (AntUnitListener al : listeners) { + p.addBuildListener(new BuildToAntUnitListener(buildFile.getAbsolutePath(), al)); al.setCurrentTestProject(p); } } @@ -405,9 +396,7 @@ public class AntUnit extends Task { * @param targetName the name of the target. */ private void fireStartTest(String targetName) { - Iterator it = listeners.iterator(); - while (it.hasNext()) { - AntUnitListener al = (AntUnitListener) it.next(); + for (AntUnitListener al : listeners) { al.startTest(targetName); } } @@ -419,9 +408,7 @@ public class AntUnit extends Task { */ private void fireFail(String targetName, AssertionFailedException ae) { failures++; - Iterator it = listeners.iterator(); - while (it.hasNext()) { - AntUnitListener al = (AntUnitListener) it.next(); + for (AntUnitListener al : listeners) { al.addFailure(targetName, ae); } } @@ -433,9 +420,7 @@ public class AntUnit extends Task { */ private void fireError(String targetName, Throwable t) { errors++; - Iterator it = listeners.iterator(); - while (it.hasNext()) { - AntUnitListener al = (AntUnitListener) it.next(); + for (AntUnitListener al : listeners) { al.addError(targetName, t); } } @@ -445,9 +430,7 @@ public class AntUnit extends Task { * @param targetName the name of the current target. */ private void fireEndTest(String targetName) { - Iterator it = listeners.iterator(); - while (it.hasNext()) { - AntUnitListener al = (AntUnitListener) it.next(); + for (AntUnitListener al : listeners) { al.endTest(targetName); } } @@ -461,7 +444,7 @@ public class AntUnit extends Task { /** * references inherited from parent project by antunit scripts */ - private ArrayList references = new ArrayList(); + private List<Reference> references = new ArrayList<Reference>(); /** * maps source reference ID to target reference ID */ @@ -471,13 +454,16 @@ public class AntUnit extends Task { references.add(reference); } + /** + * Create a nested mapper element. + * @return {@link Mapper} + */ public Mapper createMapper() { if (mapper == null) { return mapper = new Mapper(getProject()); - } else { - throw new BuildException("Only one mapper element is allowed" - + " per referenceSet", getLocation()); } + throw new BuildException("Only one mapper element is allowed per referenceSet", + getLocation()); } /** @@ -503,19 +489,16 @@ public class AntUnit extends Task { * @param newProject the target project to copy references into */ public void copyReferencesInto(Project newProject) { - FileNameMapper mapper = this.mapper == null - ? null : this.mapper.getImplementation(); - HashSet matches = new HashSet(); - Hashtable src = getProject().getReferences(); - - for (Iterator it = references.iterator(); it.hasNext(); ) { - Reference ref = (Reference) it.next(); + FileNameMapper mapper = this.mapper == null ? null : this.mapper.getImplementation(); + Set<String> matches = new HashSet<String>(); + @SuppressWarnings("unchecked") + Hashtable<String,Object> src = getProject().getReferences(); + for (Reference ref : references) { matches.clear(); ref.addMatchingReferences(src, matches); - for (Iterator ids = matches.iterator(); ids.hasNext(); ) { - String refid = (String) ids.next(); + for (String refid : matches) { String toRefid = ref.getToRefid(); //transform the refid with the mapper if necessary @@ -556,12 +539,12 @@ public class AntUnit extends Task { return; } - Class c = orig.getClass(); + Class<?> c = orig.getClass(); Object copy = orig; try { - Method cloneM = c.getMethod("clone", new Class[0]); + Method cloneM = c.getMethod("clone"); if (cloneM != null) { - copy = cloneM.invoke(orig, new Object[0]); + copy = cloneM.invoke(orig); log("Adding clone of reference " + oldKey, Project.MSG_DEBUG); } @@ -569,15 +552,14 @@ public class AntUnit extends Task { // not Clonable } - if (copy instanceof ProjectComponent) { ((ProjectComponent) copy).setProject(newProject); } else { try { Method setProjectM = - c.getMethod("setProject", new Class[] {Project.class}); + c.getMethod("setProject", Project.class); if (setProjectM != null) { - setProjectM.invoke(copy, new Object[] {newProject}); + setProjectM.invoke(copy, newProject); } } catch (NoSuchMethodException e) { // ignore this if the class being referenced does not have @@ -590,8 +572,6 @@ public class AntUnit extends Task { } newProject.addReference(newKey, copy); } - - } public static class Reference extends Ant.Reference { @@ -620,22 +600,21 @@ public class AntUnit extends Task { * @param src table of references to check * @param dest set of reference IDs matching this reference pattern */ - public void addMatchingReferences(Hashtable src, Collection dest) { + public void addMatchingReferences(Hashtable<String, Object> src, Collection<String> dest) { String id = getRefId(); if (id != null) { if (src.containsKey(id)) { dest.add(id); } } else if (matcher != null) { - for (Iterator it = src.keySet().iterator(); it.hasNext(); ) { - String refid = (String)it.next(); + for (String refid : src.keySet()) { if (matcher.matches(refid)) { dest.add(refid); } } } else { - throw new BuildException("either the refid or regex attribute " - + "is required for reference elements"); + throw new BuildException( + "either the refid or regex attribute is required for reference elements"); } } } @@ -658,10 +637,8 @@ public class AntUnit extends Task { public void buildFinished(BuildEvent event) { a.endTestSuite(event.getProject(), buildFile); } - public void targetStarted(BuildEvent event) { - } - public void targetFinished(BuildEvent event) { - } + public void targetStarted(BuildEvent event) {} + public void targetFinished(BuildEvent event) {} public void taskStarted(BuildEvent event) {} public void taskFinished(BuildEvent event) {} public void messageLogged(BuildEvent event) {} diff --git a/src/main/org/apache/ant/antunit/AntUnitExecutionNotifier.java b/src/main/org/apache/ant/antunit/AntUnitExecutionNotifier.java index 6cb47be..d73a794 100644 --- a/src/main/org/apache/ant/antunit/AntUnitExecutionNotifier.java +++ b/src/main/org/apache/ant/antunit/AntUnitExecutionNotifier.java @@ -21,7 +21,7 @@ package org.apache.ant.antunit; -/** +/** * Provides methods that allow the AntUnitScriptRunner to notify the test progress. * @since 1.2 */ @@ -31,26 +31,26 @@ public interface AntUnitExecutionNotifier { * invokes start on all registered test listeners. * @param targetName the name of the target. */ - public void fireStartTest(String targetName); + void fireStartTest(String targetName); /** * invokes addFailure on all registered test listeners. * @param targetName the name of the failed target. * @param ae the associated AssertionFailedException. */ - public void fireFail(String targetName, AssertionFailedException ae); + void fireFail(String targetName, AssertionFailedException ae); /** * invokes addError on all registered test listeners. * @param targetName the name of the failed target. * @param t the associated Throwable. */ - public void fireError(String targetName, Throwable t); + void fireError(String targetName, Throwable t); /** * invokes endTest on all registered test listeners. * @param targetName the name of the current target. */ - public void fireEndTest(String targetName); + void fireEndTest(String targetName); } diff --git a/src/main/org/apache/ant/antunit/AntUnitScriptRunner.java b/src/main/org/apache/ant/antunit/AntUnitScriptRunner.java index 891b22e..6a68616 100644 --- a/src/main/org/apache/ant/antunit/AntUnitScriptRunner.java +++ b/src/main/org/apache/ant/antunit/AntUnitScriptRunner.java @@ -20,7 +20,6 @@ package org.apache.ant.antunit; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -28,15 +27,16 @@ import java.util.Vector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; +import org.apache.tools.ant.Target; -/** - * Run antunit tests suites. This AntUnitScriptRunner is responsible for the - * management of the ant project and the correct invocation the target (taking +/** + * Run antunit tests suites. This AntUnitScriptRunner is responsible for the + * management of the ant project and the correct invocation the target (taking * into account properly the [case]setUp and [case]tearDown targets). * The user can however provide the order of the test targets and or can filter * the list of test targets to execute. * The user must also provide its ProjectFactory and an AntUnitExecutionNotifier. - * @since 1.2 + * @since 1.2 */ public class AntUnitScriptRunner { @@ -69,13 +69,13 @@ public class AntUnitScriptRunner { * Object used to create projects in order to support test isolation. */ private final ProjectFactory prjFactory; - + /** * Indicates if the startSuite method has been invoked. Use to fail fast if the * the caller forget to call the startSuite method */ private boolean isSuiteStarted; - + /** * Does that script have a setUp target (defined when scanning the script) */ @@ -99,20 +99,20 @@ public class AntUnitScriptRunner { /** * List of target names */ - private final List testTargets; + private final List<String> testTargets = new LinkedList<String>(); - /** + /** * The project currently used. */ private Project project = null; - /** - * Indicates if a target has already be executed using this project. + /** + * Indicates if a target has already be executed using this project. * Value is undefined when project is null. */ private boolean projectIsDirty; - + /** * Create a new AntScriptRunner on the given environment. * @param prjFactory A factory for the ant project that will contains the antunit test to execute. @@ -122,17 +122,16 @@ public class AntUnitScriptRunner { public AntUnitScriptRunner(ProjectFactory prjFactory) throws BuildException { this.prjFactory = prjFactory; Project newProject = getCurrentProject(); - Map targets = newProject.getTargets(); + @SuppressWarnings("unchecked") + Map<String, Target> targets = newProject.getTargets(); hasSetUp = targets.containsKey(SETUP); hasTearDown = targets.containsKey(TEARDOWN); hasSuiteSetUp = targets.containsKey(SUITESETUP); hasSuiteTearDown = targets.containsKey(SUITETEARDOWN); - testTargets = new LinkedList(); - Iterator it = targets.keySet().iterator(); - while (it.hasNext()) { - String name = (String) it.next(); - if (name.startsWith(TEST) && !name.equals(TEST)) { - testTargets.add(name); + + for (String name : targets.keySet()) { + if (name.startsWith(TEST) && !TEST.equals(name)) { + getTestTargets().add(name); } } } @@ -160,7 +159,7 @@ public class AntUnitScriptRunner { project = prjFactory.createProject(); } //we already set isDirty to true in order to make sure we didn't reuse - //this project next time getCleanProject is called. + //this project next time getCleanProject is called. projectIsDirty = true; return project; } @@ -168,7 +167,16 @@ public class AntUnitScriptRunner { /** * @return List<String> List of test targets of the script file */ - public List getTestTartgets() { + @Deprecated + public List<String> getTestTartgets() { + return getTestTargets(); + } + + /** + * Get the (names of the) test targets to execute. + * @return {@link List} of {@link String} + */ + public List<String> getTestTargets() { return testTargets; } @@ -184,7 +192,7 @@ public class AntUnitScriptRunner { * Executes the suiteSetUp target if presents and report any execution error. * <p>A failure is reported to the notifier and by returning false. * Note that if the method return false, you are not allowed to run targets.</p> - * @return false in case of execution failure. true in case of success. + * @return false in case of execution failure. true in case of success. */ private boolean startSuite(AntUnitExecutionNotifier notifier) { getCurrentProject().fireBuildStarted(); @@ -202,7 +210,7 @@ public class AntUnitScriptRunner { return true; } - /** + /** * Run the specific test target, possibly between the setUp and tearDown targets if * it exists. Exception or failures are reported to the notifier. * @param name name of the test target to execute. @@ -214,13 +222,13 @@ public class AntUnitScriptRunner { throw new AssertionError(); } Project newProject = getCleanProject(); - Vector v = new Vector(); + Vector<String> v = new Vector<String>(); if (hasSetUp) { v.add(SETUP); } v.add(name); // create and register a logcapturer on the newProject - LogCapturer lc = new LogCapturer(newProject); + new LogCapturer(newProject); try { notifier.fireStartTest(name); newProject.executeTargets(v); @@ -246,8 +254,8 @@ public class AntUnitScriptRunner { /** * Executes the suiteTearDown target if presents and report any execution error. - * @param caught Any internal exception triggered (and caught) by the caller indicating that - * the execution could not be invoked as expected. + * @param caught Any internal exception triggered (and caught) by the caller indicating that + * the execution could not be invoked as expected. * @param notifier will receive execution notifications. */ private void endSuite(Throwable caught, AntUnitExecutionNotifier notifier) { @@ -266,14 +274,14 @@ public class AntUnitScriptRunner { /** * Try to see whether the BuildException e is an AssertionFailedException - * or is caused by an AssertionFailedException. If so, fire a failure for + * or is caused by an AssertionFailedException. If so, fire a failure for * given targetName. Otherwise fire an error. */ - private void fireFailOrError(String targetName, BuildException e, + private void fireFailOrError(String targetName, BuildException e, AntUnitExecutionNotifier notifier) { boolean failed = false; Throwable t = e; - while (t != null && t instanceof BuildException) { + while (t instanceof BuildException) { if (t instanceof AssertionFailedException) { failed = true; notifier.fireFail(targetName, (AssertionFailedException) t); @@ -293,15 +301,13 @@ public class AntUnitScriptRunner { * @param suiteTargets An ordered list of test targets. It must be a sublist of getTestTargets * @param notifier is notified on test progress */ - public void runSuite(List suiteTargets, AntUnitExecutionNotifier notifier) { + public void runSuite(List<String> suiteTargets, AntUnitExecutionNotifier notifier) { Throwable caught = null; try { if (!startSuite(notifier)) { return; } - Iterator iter = suiteTargets.iterator(); - while (iter.hasNext()) { - String name = (String) iter.next(); + for (String name : suiteTargets) { runTarget(name, notifier); } } catch (Throwable e) { @@ -310,5 +316,4 @@ public class AntUnitScriptRunner { endSuite(caught, notifier); } } - } diff --git a/src/main/org/apache/ant/antunit/LogCapturer.java b/src/main/org/apache/ant/antunit/LogCapturer.java index 0da6e73..6c64888 100644 --- a/src/main/org/apache/ant/antunit/LogCapturer.java +++ b/src/main/org/apache/ant/antunit/LogCapturer.java @@ -8,7 +8,7 @@ * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -20,7 +20,6 @@ package org.apache.ant.antunit; -import java.util.Iterator; import java.util.List; import java.util.LinkedList; import java.util.Collections; @@ -41,7 +40,7 @@ import org.apache.tools.ant.util.StringUtils; public class LogCapturer implements BuildListener { public static final String REFERENCE_ID = "ant.antunit.log"; - private List/*<BuildEvent>*/ events = Collections.synchronizedList(new LinkedList()); + private List<BuildEvent> events = Collections.synchronizedList(new LinkedList<BuildEvent>()); private Project p; public LogCapturer(Project p) { @@ -184,15 +183,14 @@ public class LogCapturer implements BuildListener { } private String getLog(int minPriority, boolean mergeLines) { - StringBuffer sb = new StringBuffer(); - for (Iterator/*<BuildEvent>*/ it = new LinkedList(events).iterator(); - it.hasNext(); ) { - append(sb, (BuildEvent) it.next(), minPriority, mergeLines); + StringBuilder sb = new StringBuilder(); + for (BuildEvent buildEvent : new LinkedList<BuildEvent>(events)) { + append(sb, buildEvent, minPriority, mergeLines); } return sb.toString(); } - private static void append(StringBuffer sb, BuildEvent event, + private static void append(StringBuilder sb, BuildEvent event, int minPriority, boolean mergeLines) { if (event.getPriority() <= minPriority) { sb.append(event.getMessage()); diff --git a/src/main/org/apache/ant/antunit/junit3/AntUnitSuite.java b/src/main/org/apache/ant/antunit/junit3/AntUnitSuite.java index 74fe3dc..f399a2f 100644 --- a/src/main/org/apache/ant/antunit/junit3/AntUnitSuite.java +++ b/src/main/org/apache/ant/antunit/junit3/AntUnitSuite.java @@ -23,7 +23,6 @@ package org.apache.ant.antunit.junit3; import java.io.File; import java.io.PrintStream; import java.util.Collections; -import java.util.Iterator; import java.util.List; import junit.framework.Test; @@ -57,16 +56,16 @@ public class AntUnitSuite extends TestSuite { * File reference. Namely, if the File is a relative file, it will * be resolve relatively to the execution directory (which might be * different different from the project root directory).</p> - * + * * @param scriptFile * AntUnit script file * @param rootClass * The test class that creates this suite. This is used to give * a name to the suite so that an IDE can reexecute this suite. */ - public AntUnitSuite(File scriptFile, Class rootClass) { + public AntUnitSuite(File scriptFile, Class<?> rootClass) { setName(rootClass.getName()); //This name allows eclipse to reexecute the test - AntUnitScriptRunner createdScriptRunner = null; + final AntUnitScriptRunner createdScriptRunner; try { MyProjectFactory prjFactory = new MyProjectFactory(scriptFile); createdScriptRunner = new AntUnitScriptRunner(prjFactory); @@ -82,11 +81,8 @@ public class AntUnitSuite extends TestSuite { initializationReportingTest = null; stdout = new MultiProjectDemuxOutputStream(antScriptRunner, false); stderr = new MultiProjectDemuxOutputStream(antScriptRunner, true); - List testTargets = antScriptRunner.getTestTartgets(); - for (Iterator it = testTargets.iterator(); it.hasNext();) { - String target = (String) it.next(); - AntUnitTestCase tc = new AntUnitTestCase(this, scriptFile, target); - addTest(tc); + for (String target : antScriptRunner.getTestTargets()) { + addTest(new AntUnitTestCase(this, scriptFile, target)); } } @@ -100,28 +96,28 @@ public class AntUnitSuite extends TestSuite { MyProjectFactory prjFactory = new MyProjectFactory(scriptFile); antScriptRunner = new AntUnitScriptRunner(prjFactory); //the exception is throwed, and it is up to the AntUnitTestCase to handle it. - initializationReportingTest = null; + initializationReportingTest = null; stdout = new MultiProjectDemuxOutputStream(antScriptRunner, false); stderr = new MultiProjectDemuxOutputStream(antScriptRunner, true); setName(antScriptRunner.getName() + "[" + scriptFile + "]"); addTest(singleTc); } - + /** * {@inheritDoc} * <p>Run the full AntUnit suite.</p> */ public void run(TestResult testResult) { - if (initializationReportingTest!=null) { + if (initializationReportingTest != null) { initializationReportingTest.run(testResult); } else { - List testTartgets = antScriptRunner.getTestTartgets(); + List<String> testTargets = antScriptRunner.getTestTargets(); JUnitNotificationAdapter notifier = new JUnitNotificationAdapter( testResult, tests()); - runInContainer(testTartgets, notifier); + runInContainer(testTargets, notifier); } } - + /** * {@inheritDoc} * <p>Run a single test target of the AntUnit suite. suiteSetUp, @@ -132,7 +128,7 @@ public class AntUnitSuite extends TestSuite { initializationReportingTest.run(result); } else { String targetName = ((AntUnitTestCase) test).getTarget(); - List singleTargetList = Collections.singletonList(targetName); + List<String> singleTargetList = Collections.singletonList(targetName); JUnitNotificationAdapter notifier = new JUnitNotificationAdapter( result, tests()); runInContainer(singleTargetList, notifier); @@ -144,13 +140,13 @@ public class AntUnitSuite extends TestSuite { * <p>When ant executes a project it redirect the input and the output. In this * context we will only redirect output (unit test are not supposed to be * interactive).</p> - * + * * @param targetList * The list of test target to execute * @param notifier * The AntUnit notifier that will receive execution notifications */ - public void runInContainer(List targetList, AntUnitExecutionNotifier notifier) { + public void runInContainer(List<String> targetList, AntUnitExecutionNotifier notifier) { PrintStream savedErr = System.err; PrintStream savedOut = System.out; try { @@ -176,7 +172,7 @@ public class AntUnitSuite extends TestSuite { this.scriptFile = scriptFile; } - public Project createProject() { + public Project createProject() { ProjectHelper prjHelper = ProjectHelper.getProjectHelper(); Project prj = new Project(); DefaultLogger logger = new DefaultLogger(); @@ -198,8 +194,6 @@ public class AntUnitSuite extends TestSuite { } public BuildException getAntInitialisationException() { - return hasAntInitError() ? - initializationReportingTest.getAntScriptError() : - null; + return hasAntInitError() ? initializationReportingTest.getAntScriptError() : null; } } diff --git a/src/main/org/apache/ant/antunit/junit3/AntUnitTestCase.java b/src/main/org/apache/ant/antunit/junit3/AntUnitTestCase.java index 3442ddf..2cd7e2f 100644 --- a/src/main/org/apache/ant/antunit/junit3/AntUnitTestCase.java +++ b/src/main/org/apache/ant/antunit/junit3/AntUnitTestCase.java @@ -28,16 +28,16 @@ import junit.framework.TestCase; import junit.framework.TestResult; /** - * JUnit TestCase that will executes a single AntUnit target. + * JUnit TestCase that executes a single AntUnit target. * <p>This class is not * supposed to be used directly.</p> * <p>It is public only because junit must access it as a public.</p> */ public class AntUnitTestCase extends TestCase { - // We have to extends TestCase, and not implements Test because otherwise - // JUnit4 will derive the Description composing the suite description from + // We have to extends TestCase, and not implements Test because otherwise + // JUnit4 will derive the Description composing the suite description from // this className only (AntUnitTestCase), and not from the name. - // However, during execution it use the right Description (base on the + // However, during execution it use the right Description (base on the // toString) /** @@ -56,25 +56,25 @@ public class AntUnitTestCase extends TestCase { * class has been created directly by the IDE from its name. * In case of initialisation problem when the test is build from the suite, * the problem is handled at the level of the suite (and this object is never - * created) + * created) */ private final BuildException initialisationException; - + /** * Prepare an AntUnitTestCase that will be executed alone. - * <p>This constructor - * is typically used by a junit 3 runner that will reexecute a specific + * <p>This constructor + * is typically used by a junit 3 runner that will reexecute a specific * test.</p> - * <p>The execution of this test will be embed in a suiteSetUp and + * <p>The execution of this test will be embed in a suiteSetUp and * suiteTearDown.</p> - * @param name The name of the AntUnitTestCase, normally obtained from a - * previous execution. + * @param name The name of the AntUnitTestCase, normally obtained from a + * previous execution. */ public AntUnitTestCase(String name) { super(name); BuildException catchedEx = null; AntUnitSuite createdSuite = null; - TestCaseName nameParser = new TestCaseName(name); + TestCaseName nameParser = new TestCaseName(name); try { createdSuite = new AntUnitSuite(this, nameParser.getScript()); } catch (BuildException e) { @@ -92,8 +92,8 @@ public class AntUnitTestCase extends TestCase { * suite that prepare the antScriptRunner and the JUnitExcutionPlatform. It * is the responsibility of the suite to execute the suiteSetUp and the * suiteTearDown. - * - * @param target test target + * + * @param target test target * @param suite test suite * @param scriptFile test file */ @@ -113,7 +113,7 @@ public class AntUnitTestCase extends TestCase { return target; } - /** + /** * Called by a Junit Runner that want to executes specifically * this test target. * <p>This implementation delegates the call to the suite.</p> @@ -139,7 +139,7 @@ public class AntUnitTestCase extends TestCase { protected void runTest() throws BuildException { throw initialisationException; } - + /** * Handle the serialization and the parsing of the name of a TestCase. The * name of the TestCase contains the filename of the script and the target, diff --git a/src/main/org/apache/ant/antunit/junit3/JUnitNotificationAdapter.java b/src/main/org/apache/ant/antunit/junit3/JUnitNotificationAdapter.java index 4b09202..39808b0 100644 --- a/src/main/org/apache/ant/antunit/junit3/JUnitNotificationAdapter.java +++ b/src/main/org/apache/ant/antunit/junit3/JUnitNotificationAdapter.java @@ -36,9 +36,9 @@ import org.apache.ant.antunit.AssertionFailedException; class JUnitNotificationAdapter implements AntUnitExecutionNotifier { private final TestResult junitTestResult; - private Map testByTarget = new HashMap(); + private Map<String, AntUnitTestCase> testByTarget = new HashMap<String, AntUnitTestCase>(); - public JUnitNotificationAdapter(TestResult testResult, Enumeration tests) { + public JUnitNotificationAdapter(TestResult testResult, Enumeration<Test> tests) { this.junitTestResult = testResult; while(tests.hasMoreElements()) { AntUnitTestCase test = (AntUnitTestCase) tests.nextElement(); @@ -48,22 +48,22 @@ class JUnitNotificationAdapter implements AntUnitExecutionNotifier { public void fireStartTest(String targetName) { //TODO : if it is null, eclipse stop the unit test (add a unit test) - junitTestResult.startTest((Test) testByTarget.get(targetName)); + junitTestResult.startTest(testByTarget.get(targetName)); } - + public void fireEndTest(String targetName) { - junitTestResult.endTest((Test) testByTarget.get(targetName)); + junitTestResult.endTest(testByTarget.get(targetName)); } public void fireError(String targetName, Throwable t) { - junitTestResult.addError((Test) testByTarget.get(targetName), t); + junitTestResult.addError(testByTarget.get(targetName), t); } public void fireFail(String targetName, AssertionFailedException ae) { - //I don't see how to transform the AntUnit assertion exception into + //I don't see how to transform the AntUnit assertion exception into //junit assertion exception (we would loose the stack trace). //So failures will be reported as errors - junitTestResult.addError((Test) testByTarget.get(targetName), ae); + junitTestResult.addError(testByTarget.get(targetName), ae); } } diff --git a/src/main/org/apache/ant/antunit/junit4/AntUnitSuiteRunner.java b/src/main/org/apache/ant/antunit/junit4/AntUnitSuiteRunner.java index e3d69d4..337e5f5 100644 --- a/src/main/org/apache/ant/antunit/junit4/AntUnitSuiteRunner.java +++ b/src/main/org/apache/ant/antunit/junit4/AntUnitSuiteRunner.java @@ -20,7 +20,6 @@ package org.apache.ant.antunit.junit4; -import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -33,8 +32,8 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Map.Entry; +import junit.framework.Test; import junit.framework.TestCase; import org.apache.ant.antunit.AntUnitExecutionNotifier; @@ -60,43 +59,40 @@ import org.junit.runner.notification.RunNotifier; * around every test target). Also, more features are available when this runner * is used (filtering & sorting) */ +@SuppressWarnings("deprecation") public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable { private final AntUnitSuite junit3Suite; - private final Map/*<String, Description>*/ targetDescriptions = new HashMap(); - private final List/*<String>*/ targetsOrder = new LinkedList(); - - private AntUnitSuiteRunner(AntUnitSuite suite, Class junitTestClass) throws InitializationError { + private final Map<String, Description> targetDescriptions = new HashMap<String, Description>(); + private final List<String> targetsOrder = new LinkedList<String>(); + + private AntUnitSuiteRunner(AntUnitSuite suite, Class<?> junitTestClass) throws InitializationError { junit3Suite = suite; if (suite.hasAntInitError()) { - throw new InitializationError( - new Throwable[] { suite.getAntInitialisationException() } - ); - } else { - Enumeration tests = suite.tests(); - while (tests.hasMoreElements()) { - TestCase nextTc = (TestCase) tests.nextElement(); - //TODO Handle the possibility for the user to define suite of AntUnit scripts - AntUnitTestCase tc = (AntUnitTestCase) nextTc; - Description tc_desc = Description.createTestDescription(junitTestClass, tc.getName()); - targetDescriptions.put(tc.getTarget(), tc_desc); - targetsOrder.add(tc.getTarget()); - } + throw new InitializationError(suite.getAntInitialisationException()); + } + for (Enumeration<Test> tests = suite.tests(); tests.hasMoreElements();) { + TestCase nextTc = (TestCase) tests.nextElement(); + //TODO Handle the possibility for the user to define suite of AntUnit scripts + AntUnitTestCase tc = (AntUnitTestCase) nextTc; + Description tc_desc = Description.createTestDescription(junitTestClass, tc.getName()); + targetDescriptions.put(tc.getTarget(), tc_desc); + targetsOrder.add(tc.getTarget()); } } - public AntUnitSuiteRunner(Class testCaseClass) throws InitializationError { + public AntUnitSuiteRunner(Class<?> testCaseClass) throws InitializationError { this(getJUnit3AntSuite(testCaseClass), testCaseClass); } - private static AntUnitSuite getJUnit3AntSuite(Class testCaseClass) + private static AntUnitSuite getJUnit3AntSuite(Class<?> testCaseClass) throws InitializationError { try { - Method suiteMethod = testCaseClass.getMethod("suite", new Class[0]); + Method suiteMethod = testCaseClass.getMethod("suite"); if (!Modifier.isStatic(suiteMethod.getModifiers())) { throw new InitializationError("suite method must be static"); } - Object suite = suiteMethod.invoke(null, new Object[0]); + Object suite = suiteMethod.invoke(null); if (suite == null) { throw new InitializationError("suite method can not return null"); } @@ -105,11 +101,11 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable { } return (AntUnitSuite) suite; } catch (NoSuchMethodException e) { - throw new InitializationError(new Throwable[] { e }); + throw new InitializationError(e); } catch (IllegalAccessException e) { - throw new InitializationError(new Throwable[] { e }); + throw new InitializationError(e); } catch (InvocationTargetException e) { - throw new InitializationError(new Throwable[] { e }); + throw new InitializationError(e); } } @@ -117,11 +113,13 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable { * Filterable implementation */ public void filter(Filter filter) throws NoTestsRemainException { - for (Iterator iter= targetDescriptions.entrySet().iterator(); iter.hasNext();) { - Map.Entry mapEntry = (Entry) iter.next(); - if (!filter.shouldRun((Description) mapEntry.getValue())) + for (Iterator<Map.Entry<String, Description>> iter = + targetDescriptions.entrySet().iterator(); iter.hasNext();) { + Map.Entry<String, Description> mapEntry = iter.next(); + if (!filter.shouldRun(mapEntry.getValue())) { iter.remove(); targetsOrder.remove(mapEntry.getKey()); + } } } @@ -129,28 +127,23 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable { * Sortable implementation */ public void sort(final Sorter sorter) { - Collections.sort(targetsOrder, new Comparator/*<String>*/() { - public int compare(Object target1, Object target2) { - Description d2 = (Description)targetDescriptions.get(target2); - Description d1 = (Description)targetDescriptions.get(target1); + Collections.sort(targetsOrder, new Comparator<String>() { + public int compare(String target1, String target2) { + Description d2 = targetDescriptions.get(target2); + Description d1 = targetDescriptions.get(target1); return sorter.compare(d1, d2); } }); - /*for (Runner each : fRunners) - sorter.apply(each); - */ } /** * Runner implementation */ public Description getDescription() { - Description r = Description.createSuiteDescription( - junit3Suite.getName(), new Annotation[0]); - - Collection childDesc = targetDescriptions.values(); - for (Iterator iterator = childDesc.iterator(); iterator.hasNext();) { - Description desc = (Description) iterator.next(); + Description r = Description.createSuiteDescription(junit3Suite.getName()); + + Collection<Description> childDesc = targetDescriptions.values(); + for (Description desc : childDesc) { r.addChild(desc); } return r; @@ -160,14 +153,14 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable { * Runner implementation */ public void run(final RunNotifier junitNotifier) { - LinkedList targetList = new LinkedList(targetDescriptions.keySet()); - - AntUnitExecutionNotifier antUnitNotifier = new AntUnitExecutionNotifier() { + List<String> targetList = new LinkedList<String>(targetDescriptions.keySet()); + + AntUnitExecutionNotifier antUnitNotifier = new AntUnitExecutionNotifier() { public void fireStartTest(String targetName) { junitNotifier.fireTestStarted(getDescription(targetName)); } public void fireEndTest(String targetName) { - junitNotifier.fireTestFinished(getDescription(targetName)); + junitNotifier.fireTestFinished(getDescription(targetName)); } public void fireError(String targetName, Throwable t) { Failure failure = new Failure(getDescription(targetName), t); @@ -176,12 +169,12 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable { public void fireFail(String targetName, AssertionFailedException ae) { Failure failure = new Failure(getDescription(targetName), ae); junitNotifier.fireTestFailure(failure); - } + } private Description getDescription(String targetName) { - return (Description) targetDescriptions.get(targetName); + return targetDescriptions.get(targetName); } }; - + junit3Suite.runInContainer(targetList, antUnitNotifier); } diff --git a/src/main/org/apache/ant/antunit/listener/BaseAntUnitListener.java b/src/main/org/apache/ant/antunit/listener/BaseAntUnitListener.java index c55216a..199f619 100644 --- a/src/main/org/apache/ant/antunit/listener/BaseAntUnitListener.java +++ b/src/main/org/apache/ant/antunit/listener/BaseAntUnitListener.java @@ -8,7 +8,7 @@ * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -37,21 +37,14 @@ import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.LogOutputStream; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.util.FileUtils; +import org.apache.tools.ant.util.KeepAliveOutputStream; import org.apache.tools.ant.util.TeeOutputStream; /** * A test listener for <antunit> modeled aftern the Plain JUnit * test listener that is part of Ant. */ -public abstract class BaseAntUnitListener - implements AntUnitListener { - - protected BaseAntUnitListener(SendLogTo defaultReportTarget, - String extension) { - logTo = defaultReportTarget; - this.extension = extension; - logLevel = BaseAntUnitListener.AntUnitLogLevel.NONE; - } +public abstract class BaseAntUnitListener implements AntUnitListener { /** * Formatter for timings. @@ -59,6 +52,17 @@ public abstract class BaseAntUnitListener protected static final NumberFormat nf = NumberFormat.getInstance(); /** + * Create a new {@link BaseAntUnitListener} instance. + * @param defaultReportTarget + * @param extension + */ + protected BaseAntUnitListener(SendLogTo defaultReportTarget, String extension) { + logTo = defaultReportTarget; + this.extension = extension; + logLevel = BaseAntUnitListener.AntUnitLogLevel.NONE; + } + + /** * Directory to write reports to. */ private File toDir; @@ -118,9 +122,7 @@ public abstract class BaseAntUnitListener } protected final void close(OutputStream out) { - if (out != System.out && out != System.err) { - FileUtils.close(out); - } + FileUtils.close(out); } public void startTest(String target) { @@ -135,36 +137,43 @@ public abstract class BaseAntUnitListener } protected final OutputStream getOut(String buildFile) { - OutputStream l, f; - l = f = null; - if (logTo.getValue().equals(SendLogTo.ANT_LOG) - || logTo.getValue().equals(SendLogTo.BOTH)) { + final String dest = logTo.getValue(); + + if (logTo.getIndex() < 0) { + throw new BuildException(String.format("Invalid @sendlogto value '%s'", dest)); + } + OutputStream l; + + if (SendLogTo.ANT_LOG.equals(dest) || SendLogTo.BOTH.equals(dest)) { if (parentTask != null) { l = new LogOutputStream(parentTask, Project.MSG_INFO); } else { - l = System.out; + l = new KeepAliveOutputStream(System.out); } - if (logTo.getValue().equals(SendLogTo.ANT_LOG)) { + if (SendLogTo.ANT_LOG.equals(dest)) { return l; } + } else { + l = null; } - if (logTo.getValue().equals(SendLogTo.FILE) - || logTo.getValue().equals(SendLogTo.BOTH)) { - - String fileName = "TEST-" + normalize(buildFile) + "." + extension; - File file = toDir == null - ? (parentTask != null - ? parentTask.getProject().resolveFile(fileName) - : new File(fileName)) - : new File(toDir, fileName); - try { - f = new FileOutputStream(file); - } catch (IOException e) { - throw new BuildException(e); - } - if (logTo.getValue().equals(SendLogTo.FILE)) { - return f; - } + OutputStream f; + + String fileName = "TEST-" + normalize(buildFile) + "." + extension; + File file; + if (toDir != null) { + file = new File(toDir, fileName); + } else if (parentTask == null) { + file = new File(fileName); + } else { + file = parentTask.getProject().resolveFile(fileName); + } + try { + f = new FileOutputStream(file); + } catch (IOException e) { + throw new BuildException(e); + } + if (SendLogTo.FILE.equals(dest)) { + return f; } return new TeeOutputStream(l, f); } @@ -177,18 +186,13 @@ public abstract class BaseAntUnitListener * @return the normalized name */ protected final String normalize(String buildFile) { - File base = parentTask != null - ? parentTask.getProject().getBaseDir() + File base = parentTask != null ? parentTask.getProject().getBaseDir() : new File(System.getProperty("user.dir")); - buildFile = FileUtils.getFileUtils() - .removeLeadingPath(base, new File(buildFile)); - if (buildFile.length() > 0 - && buildFile.charAt(0) == File.separatorChar) { + buildFile = FileUtils.getFileUtils().removeLeadingPath(base, new File(buildFile)); + if (buildFile.length() > 0 && buildFile.charAt(0) == File.separatorChar) { buildFile = buildFile.substring(1); } - - return buildFile.replace('.', '_').replace(':', '_') - .replace(File.separatorChar, '.'); + return buildFile.replace('.', '_').replace(':', '_').replace(File.separatorChar, '.'); } protected final Location getLocation(Throwable t) { diff --git a/src/main/org/apache/ant/antunit/listener/FailureAntUnitListener.java b/src/main/org/apache/ant/antunit/listener/FailureAntUnitListener.java index a26d01e..6d0f5d5 100644 --- a/src/main/org/apache/ant/antunit/listener/FailureAntUnitListener.java +++ b/src/main/org/apache/ant/antunit/listener/FailureAntUnitListener.java @@ -8,7 +8,7 @@ * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -38,27 +38,27 @@ import org.apache.tools.ant.util.FileUtils; * This AntUnitListener creates a new buildfile with a target for each * failed test target in the AntUnit run. The generated target calls * the failed target (with setUp and tearDown if present in the called - * project). + * project). * This is intended for rerunning just failed tests. */ public class FailureAntUnitListener extends BaseAntUnitListener { - + /** LineSeparator just for beautifying the output. */ - private static final String BR = System.getProperty("line.separator"); + private static final String BR = System.getProperty("line.separator"); /** A sorted list (without duplicates) of failed tests. */ - private static SortedSet failedTests = new TreeSet(); - + private static SortedSet<TestInfos> failedTests = new TreeSet<TestInfos>(); + /** Where to write the generated buildfile. */ private static File failureBuildfile; - + /** The current running test project. Needed for addError()/addFailure(). */ private Project currentTestProject; /** The current running build file. Needed for addError()/addFailure(). */ private String currentBuildFile; - - + + /** No-arg constructor. */ public FailureAntUnitListener() { super(new BaseAntUnitListener.SendLogTo(SendLogTo.ANT_LOG), "txt"); @@ -73,23 +73,23 @@ public class FailureAntUnitListener extends BaseAntUnitListener { currentTestProject = testProject; currentBuildFile = buildFile; } - + public void addError(String target, Throwable ae) { super.addError(target, ae); failedTests.add(new TestInfos(currentTestProject, currentBuildFile, target, ae.getMessage())); } - + public void addFailure(String target, AssertionFailedException ae) { super.addFailure(target, ae); failedTests.add(new TestInfos(currentTestProject, currentBuildFile, target, ae.getMessage())); - } - + } + /** not in use */ - public void endTest(String target) { + public void endTest(String target) { } public void endTestSuite(Project testProject, String buildFile) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); // <project> and antunit-target for direct run sb.append("<project default=\"antunit\" xmlns:au=\"antlib:org.apache.ant.antunit\">"); sb.append(BR); @@ -102,23 +102,23 @@ public class FailureAntUnitListener extends BaseAntUnitListener { sb.append(" </target>").append(BR); sb.append(BR); sb.append(BR); - + // one target for each failed test int testNumber = 0; NumberFormat f = NumberFormat.getIntegerInstance(); - for (Iterator it = failedTests.iterator(); it.hasNext();) { + for (Iterator<TestInfos> it = failedTests.iterator(); it.hasNext();) { sb.append(" <target name=\"test"); sb.append(f.format(testNumber++)); sb.append("\">").append(BR); - TestInfos testInfos = (TestInfos) it.next(); + TestInfos testInfos = it.next(); sb.append(testInfos); sb.append(" </target>").append(BR); sb.append(BR); } - + // close the <project> sb.append("</project>").append(BR); - + // write the whole file try { FileOutputStream fos = new FileOutputStream(failureBuildfile); @@ -130,41 +130,40 @@ public class FailureAntUnitListener extends BaseAntUnitListener { throw new BuildException(e); } } - - + /** * Class for collecting needed information about failed tests. */ - public class TestInfos implements Comparable { + public class TestInfos implements Comparable<TestInfos> { /** Does the project has a setUp target? */ boolean projectHasSetup = false; - + /** Does the project has a tearDown target? */ boolean projectHasTearDown = false; - + /** The called target. */ String target; - + /** The buildfile of the project. */ String buildfile; - + /** The error message which was shown. */ String errorMessage; - + public TestInfos(Project project, String buildfile, String target, String errorMessage) { projectHasSetup = project.getTargets().containsKey("setUp"); projectHasTearDown = project.getTargets().containsKey("tearDown"); this.buildfile = buildfile; - this.target = target; + this.target = target; this.errorMessage = errorMessage; } - - /** - * Creates an <ant> call according to the stored information. + + /** + * Creates an <ant> call according to the stored information. * @see java.lang.Object#toString() */ public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); // make the reader of the buildfile happy sb.append(" <!-- "); sb.append(errorMessage); @@ -191,15 +190,10 @@ public class FailureAntUnitListener extends BaseAntUnitListener { sb.append(" </ant>").append(BR); return sb.toString(); } - + // Needed, so that a SortedSet could sort this class into the list. - public int compareTo(Object other) { - if (!(other instanceof TestInfos)) { - return -1; - } else { - TestInfos that = (TestInfos)other; - return this.toString().compareTo(that.toString()); - } + public int compareTo(TestInfos other) { + return this.toString().compareTo((other).toString()); } } diff --git a/src/main/org/apache/ant/antunit/listener/PlainAntUnitListener.java b/src/main/org/apache/ant/antunit/listener/PlainAntUnitListener.java index 980055e..58a310c 100644 --- a/src/main/org/apache/ant/antunit/listener/PlainAntUnitListener.java +++ b/src/main/org/apache/ant/antunit/listener/PlainAntUnitListener.java @@ -8,7 +8,7 @@ * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -37,7 +37,7 @@ import org.apache.tools.ant.Project; * test listener that is part of Ant. */ public class PlainAntUnitListener extends BaseAntUnitListener { - private OutputStream out = null; + private OutputStream out; /** * Helper to store intermediate output. */ @@ -69,9 +69,7 @@ public class PlainAntUnitListener extends BaseAntUnitListener { inner = new StringWriter(); wri = new PrintWriter(inner); out = getOut(buildFile); - StringBuffer sb = new StringBuffer("Build File: "); - sb.append(buildFile); - sb.append(NEW_LINE); + StringBuilder sb = new StringBuilder("Build File: ").append(buildFile).append(NEW_LINE); try { out.write(sb.toString().getBytes()); out.flush(); @@ -82,7 +80,7 @@ public class PlainAntUnitListener extends BaseAntUnitListener { public void endTestSuite(Project testProject, String buildFile) { long runTime = System.currentTimeMillis() - start; - StringBuffer sb = new StringBuffer("Tests run: "); + StringBuilder sb = new StringBuilder("Tests run: "); sb.append(runCount); sb.append(", Failures: "); sb.append(failureCount); diff --git a/src/main/org/apache/ant/antunit/listener/XMLAntUnitListener.java b/src/main/org/apache/ant/antunit/listener/XMLAntUnitListener.java index 23eddae..7a91be5 100644 --- a/src/main/org/apache/ant/antunit/listener/XMLAntUnitListener.java +++ b/src/main/org/apache/ant/antunit/listener/XMLAntUnitListener.java @@ -8,7 +8,7 @@ * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -96,14 +96,15 @@ public class XMLAntUnitListener extends BaseAntUnitListener { Element propertiesElement = DOMUtils.createChildElement(root, XMLConstants.PROPERTIES); - Hashtable propertiesMap = testProject.getProperties(); - for (final Iterator iterator = propertiesMap.entrySet().iterator(); + @SuppressWarnings("unchecked") + Hashtable<String,Object> propertiesMap = testProject.getProperties(); + for (final Iterator<Map.Entry<String, Object>> iterator = propertiesMap.entrySet().iterator(); iterator.hasNext();) { - final Map.Entry property = (Map.Entry) iterator.next(); + final Map.Entry<String, Object> property = iterator.next(); Element e = DOMUtils.createChildElement(propertiesElement, XMLConstants.PROPERTY); e.setAttribute(XMLConstants.ATTR_NAME, - property.getKey().toString()); + property.getKey()); e.setAttribute(XMLConstants.ATTR_VALUE, property.getValue().toString()); } @@ -122,7 +123,7 @@ public class XMLAntUnitListener extends BaseAntUnitListener { log.setLength(0); domWri.write(e, wri, 1, INDENT); } - e = DOMUtils.createChildElement(root, XMLConstants.ATTR_TESTS); + e = DOMUtils.createChildElement(root, XMLConstants.ATTR_TESTS); DOMUtils.appendText(e, String.valueOf(runCount)); domWri.write(e, wri, 1, INDENT); e = DOMUtils.createChildElement(root, XMLConstants.ATTR_FAILURES); diff --git a/src/tests/junit/org/apache/ant/antunit/LogCapturerTest.java b/src/tests/junit/org/apache/ant/antunit/LogCapturerTest.java index 4674478..5a041a3 100644 --- a/src/tests/junit/org/apache/ant/antunit/LogCapturerTest.java +++ b/src/tests/junit/org/apache/ant/antunit/LogCapturerTest.java @@ -8,7 +8,7 @@ * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -42,8 +42,8 @@ public class LogCapturerTest extends TestCase { Project p = new Project(); LogCapturer c = new LogCapturer(p); - String[] messages = new String[] {"err", "warn", "info", "verbose", - "debug"}; + String[] messages = new String[] { "err", "warn", "info", "verbose", "debug" }; + for (int i = 0; i < messages.length; i++) { BuildEvent be = new BuildEvent(p); be.setMessage(messages[i], i); @@ -66,8 +66,7 @@ public class LogCapturerTest extends TestCase { c.messageLogged(be); } Assert.assertEquals(c.getErrLog(false), - "0" + StringUtils.LINE_SEP - + "1" + StringUtils.LINE_SEP); + "0" + StringUtils.LINE_SEP + "1" + StringUtils.LINE_SEP); } public void testWithMerge() { diff --git a/src/tests/junit/org/apache/ant/antunit/LogContentTest.java b/src/tests/junit/org/apache/ant/antunit/LogContentTest.java index 5c3aae8..de6721b 100644 --- a/src/tests/junit/org/apache/ant/antunit/LogContentTest.java +++ b/src/tests/junit/org/apache/ant/antunit/LogContentTest.java @@ -8,7 +8,7 @@ * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -52,23 +52,18 @@ public class LogContentTest extends TestCase { Project p = new Project(); LogCapturer c = new LogCapturer(p); - String[] msgs = new String[] {"err", "warn", "info", "verbose", - "debug"}; + String[] msgs = new String[] { "err", "warn", "info", "verbose", "debug" }; + for (int i = 0; i < msgs.length; i++) { BuildEvent be = new BuildEvent(p); be.setMessage(msgs[i], i); c.messageLogged(be); } - assertMessages(new LogContent(p, LogLevel.ERR), msgs, - Project.MSG_ERR); - assertMessages(new LogContent(p, LogLevel.WARN), msgs, - Project.MSG_WARN); - assertMessages(new LogContent(p, LogLevel.INFO), msgs, - Project.MSG_INFO); - assertMessages(new LogContent(p, LogLevel.VERBOSE), msgs, - Project.MSG_VERBOSE); - assertMessages(new LogContent(p, LogLevel.DEBUG), msgs, - Project.MSG_DEBUG); + assertMessages(new LogContent(p, LogLevel.ERR), msgs, Project.MSG_ERR); + assertMessages(new LogContent(p, LogLevel.WARN), msgs, Project.MSG_WARN); + assertMessages(new LogContent(p, LogLevel.INFO), msgs, Project.MSG_INFO); + assertMessages(new LogContent(p, LogLevel.VERBOSE), msgs, Project.MSG_VERBOSE); + assertMessages(new LogContent(p, LogLevel.DEBUG), msgs, Project.MSG_DEBUG); } public void testWithoutMerge() throws IOException { @@ -85,9 +80,7 @@ public class LogContentTest extends TestCase { StringResource s = new StringResource(); ResourceUtils.copyResource(content, s); - Assert.assertEquals(s.getValue(), - "0" + StringUtils.LINE_SEP - + "1" + StringUtils.LINE_SEP); + Assert.assertEquals(s.getValue(), "0" + StringUtils.LINE_SEP + "1" + StringUtils.LINE_SEP); } public void testWithExplicitMerge() throws IOException { @@ -132,11 +125,11 @@ public class LogContentTest extends TestCase { String actual = s.getValue(); for (int i = 0; i <= upTo && i < messages.length; i++) { Assert.assertTrue("checking for " + messages[i] + " in " + actual, - actual.indexOf(messages[i]) > -1); + actual.indexOf(messages[i]) > -1); } for (int i = upTo + 1; i < messages.length; i++) { Assert.assertTrue("checking for " + messages[i] + " in " + actual, - actual.indexOf(messages[i]) == -1); + actual.indexOf(messages[i]) == -1); } } } diff --git a/src/tests/junit/org/apache/ant/antunit/SetUpAndTearDownTest.java b/src/tests/junit/org/apache/ant/antunit/SetUpAndTearDownTest.java index 8c79740..18336a1 100644 --- a/src/tests/junit/org/apache/ant/antunit/SetUpAndTearDownTest.java +++ b/src/tests/junit/org/apache/ant/antunit/SetUpAndTearDownTest.java @@ -30,10 +30,10 @@ import org.apache.tools.ant.BuildFileTest; import org.apache.tools.ant.Project; public class SetUpAndTearDownTest extends BuildFileTest { - + public static class TestReportListener extends BaseAntUnitListener { - private OutputStream out = null; + private OutputStream out; /** * Helper to store intermediate output. */ @@ -82,12 +82,12 @@ public class SetUpAndTearDownTest extends BuildFileTest { super.addFailure(target, ae); wri.println("failure:" + target + "(" + ae.getMessage() + ")"); } - + public void addError(String target, Throwable ae) { super.addError(target, ae); wri.println("error:" + target + "(" + ae.getMessage() + ")"); } - + public void messageLogged(int level, String message) {} } @@ -124,7 +124,7 @@ public class SetUpAndTearDownTest extends BuildFileTest { int index = log.indexOf("Tests run: 3, Failures: 3, Errors: 0,"); assertTrue("summary", index > -1); } - + public void testErrorSetup() { executeTarget("testErrorSetup"); String log = getLog(); @@ -138,7 +138,7 @@ public class SetUpAndTearDownTest extends BuildFileTest { int index = log.indexOf("Tests run: 3, Failures: 3, Errors: 0,"); assertTrue("summary", index > -1); } - + public void testErrorTeardown() { executeTarget("testErrorTeardown"); String log = getLog(); @@ -180,7 +180,7 @@ public class SetUpAndTearDownTest extends BuildFileTest { index = log.indexOf("error:suiteSetUp(Expected error)"); assertTrue("testname", index > -1); } - + public void testFailureSuiteTearDown() { executeTarget("testFailureSuiteTearDown"); String log = getLog(); @@ -189,7 +189,7 @@ public class SetUpAndTearDownTest extends BuildFileTest { index = log.indexOf("failure:suiteTearDown(Expected failure)"); assertTrue("testname", index > -1); } - + public void testErrorSuiteTearDown() { executeTarget("testErrorSuiteTearDown"); String log = getLog(); diff --git a/src/tests/junit/org/apache/ant/antunit/junit4/AntUnitSuiteRunnerTest.java b/src/tests/junit/org/apache/ant/antunit/junit4/AntUnitSuiteRunnerTest.java index 73dd8ec..a08e660 100644 --- a/src/tests/junit/org/apache/ant/antunit/junit4/AntUnitSuiteRunnerTest.java +++ b/src/tests/junit/org/apache/ant/antunit/junit4/AntUnitSuiteRunnerTest.java @@ -23,7 +23,7 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; -import java.util.ArrayList; +import java.util.List; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -42,10 +42,8 @@ public class AntUnitSuiteRunnerTest extends TestCase { /** * Validates the execution sequence. */ - public void testRunFullSuite() throws FileNotFoundException, IOException, - InitializationError { - AntUnitSuiteRunner runner = new AntUnitSuiteRunner( - JUnit4AntUnitRunnable.class); + public void testRunFullSuite() throws FileNotFoundException, IOException, InitializationError { + AntUnitSuiteRunner runner = new AntUnitSuiteRunner(JUnit4AntUnitRunnable.class); runner.run(new RunNotifier()); File outFile = new File("target/test_output/junit_out.xml"); @@ -53,47 +51,46 @@ public class AntUnitSuiteRunnerTest extends TestCase { String output = FileUtils.readFully(new FileReader(outFile)); String EXPECT1 = "suiteSetUp-setUp-test1-tearDown-setUp-test2-tearDown-suiteTearDown"; String EXPECT2 = "suiteSetUp-setUp-test2-tearDown-setUp-test1-tearDown-suiteTearDown"; - assertTrue("unexted output : " + output, EXPECT1.equals(output) - || EXPECT2.equals(output)); + assertTrue("unexted output : " + output, EXPECT1.equals(output) || EXPECT2.equals(output)); } - + /** * When a test is executed, the description used in the notification must be * equals to the description declared, otherwise the runner is confused (for * example in eclipse you have all the tests listed twice, but reported only * once as executed. - * + * * @throws InitializationError */ public void testDescriptionsReportedInNotifier() throws InitializationError { final AntUnitSuiteRunner runner = new AntUnitSuiteRunner( JUnit4AntUnitRunnable.class); - final ArrayList tDescs = runner.getDescription().getChildren(); + final List<Description> tDescs = runner.getDescription().getChildren(); RunNotifier notifierMock = new RunNotifier() { Description curTest = null; public void fireTestStarted(Description description) { if (curTest != null) { - mockExecutionError += "Unexpected fireTestStarted(" - + description.getDisplayName() + "\n"; + mockExecutionError += + "Unexpected fireTestStarted(" + description.getDisplayName() + "\n"; } if (!tDescs.contains(description)) { - mockExecutionError += "Unexpected fireTestStarted(" - + description.getDisplayName() + ")\n"; + mockExecutionError += + "Unexpected fireTestStarted(" + description.getDisplayName() + ")\n"; } curTest = description; } public void fireTestFinished(Description description) { if (curTest == null) { - mockExecutionError += "Unexpected fireTestFinished(" - + description.getDisplayName() + "\n"; + mockExecutionError += + "Unexpected fireTestFinished(" + description.getDisplayName() + "\n"; } if (!curTest.equals(description)) { - mockExecutionError += "Unexpected fireTestFinished(" - + description.getDisplayName() + "); expect " + mockExecutionError += + "Unexpected fireTestFinished(" + description.getDisplayName() + "); expect " + curTest.getDisplayName() + "\n"; } curTest = null; @@ -170,8 +167,7 @@ public class AntUnitSuiteRunnerTest extends TestCase { public static class JUnit4AntUnitRunnableWithNonStaticSuite { public AntUnitSuite suite() { File f = new File("src/etc/testcases/antunit/junit.xml"); - return new AntUnitSuite(f, - JUnit4AntUnitRunnableWithNonStaticSuite.class); + return new AntUnitSuite(f, JUnit4AntUnitRunnableWithNonStaticSuite.class); } } @@ -180,23 +176,22 @@ public class AntUnitSuiteRunnerTest extends TestCase { public static class JUnit4AntUnitRunnableWithInvalidSuiteReturnType { public static TestSuite suite() { - return new TestSuite("We don't support returning generic TestSuite." + - " The Runner can not handle that"); + return new TestSuite( + "We don't support returning generic TestSuite. The Runner can not handle that"); } } - + public static class JUnit4AntUnitRunnableWithInvalidSuiteReturningNull { public static TestSuite suite() { return null; } } - + public static class JUnit4AntUnitRunnableRefferencingIncorrectFile { public static AntUnitSuite suite() { File f = new File("build_script_not_found.xml"); - return new AntUnitSuite(f, - JUnit4AntUnitRunnableWithNonStaticSuite.class); + return new AntUnitSuite(f, JUnit4AntUnitRunnableWithNonStaticSuite.class); } }