code cleanup/updates

This commit is contained in:
Matt Benson 2022-02-12 15:44:54 -06:00
parent b64de44027
commit 35caae04d0
18 changed files with 328 additions and 377 deletions

2
NOTICE
View File

@ -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/).

View File

@ -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>

View File

@ -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;
@ -114,17 +115,17 @@ public class AntUnit extends Task {
/**
* 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) {}

View File

@ -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);
}

View File

@ -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,6 +27,7 @@ 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
@ -99,7 +99,7 @@ public class AntUnitScriptRunner {
/**
* List of target names
*/
private final List testTargets;
private final List<String> testTargets = new LinkedList<String>();
/**
* The project currently used.
@ -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);
}
}
}
@ -168,7 +167,16 @@ public class AntUnitScriptRunner {
/**
* @return List&lt;String&gt; 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;
}
@ -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);
@ -273,7 +281,7 @@ public class AntUnitScriptRunner {
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);
}
}
}

View File

@ -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());

View File

@ -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;
@ -64,9 +63,9 @@ public class AntUnitSuite extends TestSuite {
* 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));
}
}
@ -112,13 +108,13 @@ public class AntUnitSuite extends TestSuite {
* <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);
}
}
@ -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);
@ -150,7 +146,7 @@ public class AntUnitSuite extends TestSuite {
* @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 {
@ -198,8 +194,6 @@ public class AntUnitSuite extends TestSuite {
}
public BuildException getAntInitialisationException() {
return hasAntInitError() ?
initializationReportingTest.getAntScriptError() :
null;
return hasAntInitError() ? initializationReportingTest.getAntScriptError() : null;
}
}

View File

@ -28,7 +28,7 @@ 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>

View File

@ -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
//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);
}
}

View File

@ -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,21 +59,19 @@ import org.junit.runner.notification.RunNotifier;
* around every test target). Also, more features are available when this runner
* is used (filtering &amp; 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 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 {
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()) {
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;
@ -83,20 +80,19 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable {
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,40 +113,37 @@ 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());
}
}
}
/**
* 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]);
Description r = Description.createSuiteDescription(junit3Suite.getName());
Collection childDesc = targetDescriptions.values();
for (Iterator iterator = childDesc.iterator(); iterator.hasNext();) {
Description desc = (Description) iterator.next();
Collection<Description> childDesc = targetDescriptions.values();
for (Description desc : childDesc) {
r.addChild(desc);
}
return r;
@ -160,7 +153,7 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable {
* Runner implementation
*/
public void run(final RunNotifier junitNotifier) {
LinkedList targetList = new LinkedList(targetDescriptions.keySet());
List<String> targetList = new LinkedList<String>(targetDescriptions.keySet());
AntUnitExecutionNotifier antUnitNotifier = new AntUnitExecutionNotifier() {
public void fireStartTest(String targetName) {
@ -178,7 +171,7 @@ public class AntUnitSuiteRunner extends Runner implements Filterable, Sortable {
junitNotifier.fireTestFailure(failure);
}
private Description getDescription(String targetName) {
return (Description) targetDescriptions.get(targetName);
return targetDescriptions.get(targetName);
}
};

View File

@ -37,27 +37,31 @@ 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 &lt;antunit&gt; 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.
*/
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.
*/
@ -118,10 +122,8 @@ public abstract class BaseAntUnitListener
}
protected final void close(OutputStream out) {
if (out != System.out && out != System.err) {
FileUtils.close(out);
}
}
public void startTest(String target) {
testStart = System.currentTimeMillis();
@ -135,37 +137,44 @@ 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)) {
OutputStream f;
String fileName = "TEST-" + normalize(buildFile) + "." + extension;
File file = toDir == null
? (parentTask != null
? parentTask.getProject().resolveFile(fileName)
: new File(fileName))
: new File(toDir, fileName);
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 (logTo.getValue().equals(SendLogTo.FILE)) {
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) {

View File

@ -47,7 +47,7 @@ public class FailureAntUnitListener extends BaseAntUnitListener {
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;
@ -89,7 +89,7 @@ public class FailureAntUnitListener extends BaseAntUnitListener {
}
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);
@ -106,11 +106,11 @@ public class FailureAntUnitListener extends BaseAntUnitListener {
// 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);
@ -131,11 +131,10 @@ public class FailureAntUnitListener extends BaseAntUnitListener {
}
}
/**
* 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;
@ -164,7 +163,7 @@ public class FailureAntUnitListener extends BaseAntUnitListener {
* @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);
@ -193,13 +192,8 @@ public class FailureAntUnitListener extends BaseAntUnitListener {
}
// 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());
}
}

View File

@ -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);

View File

@ -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());
}

View File

@ -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() {

View File

@ -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 {

View File

@ -33,7 +33,7 @@ public class SetUpAndTearDownTest extends BuildFileTest {
public static class TestReportListener extends BaseAntUnitListener {
private OutputStream out = null;
private OutputStream out;
/**
* Helper to store intermediate output.
*/

View File

@ -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,8 +51,7 @@ 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));
}
@ -69,31 +66,31 @@ public class AntUnitSuiteRunnerTest extends TestCase {
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,8 +176,8 @@ 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");
}
}
@ -195,8 +191,7 @@ public class AntUnitSuiteRunnerTest extends TestCase {
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);
}
}