Browse Source

finally, 7552 audit of <junit> - leave information in tests untouched

by cloning the instances.


git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@272412 13f79535-47bb-0310-9956-ffa450edef68
master
Stefan Bodewig 23 years ago
parent
commit
c52b908bf7
5 changed files with 253 additions and 114 deletions
  1. +1
    -1
      docs/manual/CoreTypes/filelist.html
  2. +2
    -2
      src/main/org/apache/tools/ant/taskdefs/Ant.java
  3. +1
    -1
      src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java
  4. +228
    -105
      src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java
  5. +21
    -5
      src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java

+ 1
- 1
docs/manual/CoreTypes/filelist.html View File

@@ -68,7 +68,7 @@ actually exist.
<p>Same files as the example above.</p> <p>Same files as the example above.</p>


<hr> <hr>
<p align="center">Copyright &copy; 2001 Apache Software Foundation. All rights
<p align="center">Copyright &copy; 2001-2002 Apache Software Foundation. All rights
Reserved.</p> Reserved.</p>


</body> </body>


+ 2
- 2
src/main/org/apache/tools/ant/taskdefs/Ant.java View File

@@ -135,7 +135,7 @@ public class Ant extends Task {
* inside the ant call itself * inside the ant call itself
*/ */
public void setInheritAll(boolean value) { public void setInheritAll(boolean value) {
inheritAll = value;
inheritAll = value;
} }


/** /**
@@ -144,7 +144,7 @@ public class Ant extends Task {
* inside the ant call itself * inside the ant call itself
*/ */
public void setInheritRefs(boolean value) { public void setInheritRefs(boolean value) {
inheritRefs = value;
inheritRefs = value;
} }


/** /**


+ 1
- 1
src/main/org/apache/tools/ant/taskdefs/compilers/CompilerAdapterFactory.java View File

@@ -1,7 +1,7 @@
/* /*
* The Apache Software License, Version 1.1 * The Apache Software License, Version 1.1
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights
* Copyright (c) 2001-2002 The Apache Software Foundation. All rights
* reserved. * reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without


+ 228
- 105
src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java View File

@@ -67,6 +67,7 @@ import org.apache.tools.ant.types.Environment;
import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.util.FileUtils;


import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@@ -76,7 +77,6 @@ import java.io.OutputStream;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Properties; import java.util.Properties;
import java.util.Random;
import java.util.Vector; import java.util.Vector;


import java.net.URL; import java.net.URL;
@@ -88,7 +88,8 @@ import java.net.URL;
* created by Erich Gamma and Kent Beck. JUnit can be found at <a * created by Erich Gamma and Kent Beck. JUnit can be found at <a
* href="http://www.junit.org">http://www.junit.org</a>. * href="http://www.junit.org">http://www.junit.org</a>.
* *
* <p> <code>JUnitTask</code> can run a single specific <code>JUnitTest</code> using the <code>test</code> element.
* <p> <code>JUnitTask</code> can run a single specific
* <code>JUnitTest</code> using the <code>test</code> element.</p>
* For example, the following target <code><pre> * For example, the following target <code><pre>
* &lt;target name="test-int-chars" depends="jar-test"&gt; * &lt;target name="test-int-chars" depends="jar-test"&gt;
* &lt;echo message="testing international characters"/&gt; * &lt;echo message="testing international characters"/&gt;
@@ -98,14 +99,19 @@ import java.net.URL;
* &lt;test name="org.apache.ecs.InternationalCharTest" /&gt; * &lt;test name="org.apache.ecs.InternationalCharTest" /&gt;
* &lt;/junit&gt; * &lt;/junit&gt;
* &lt;/target&gt; * &lt;/target&gt;
* </pre></code> runs a single junit test (<code>org.apache.ecs.InternationalCharTest</code>)
* in the current VM using the path with id <code>classpath</code> as classpath
* and presents the results formatted using the standard <code>plain</code> formatter on the command line.
* </pre></code>
* <p>runs a single junit test
* (<code>org.apache.ecs.InternationalCharTest</code>) in the current
* VM using the path with id <code>classpath</code> as classpath and
* presents the results formatted using the standard
* <code>plain</code> formatter on the command line.</p>
* *
* <p> This task can also run batches of tests.
* The <code>batchtest</code> element creates a <code>BatchTest</code> based on a fileset.
* This allows, for example, all classes found in directory to be run as testcases.
* For example, <code><pre>
* <p> This task can also run batches of tests. The
* <code>batchtest</code> element creates a <code>BatchTest</code>
* based on a fileset. This allows, for example, all classes found in
* directory to be run as testcases.</p>
*
* <p>For example,</p><code><pre>
* &lt;target name="run-tests" depends="dump-info,compile-tests" if="junit.present"&gt; * &lt;target name="run-tests" depends="dump-info,compile-tests" if="junit.present"&gt;
* &lt;junit printsummary="no" haltonfailure="yes" fork="${junit.fork}"&gt; * &lt;junit printsummary="no" haltonfailure="yes" fork="${junit.fork}"&gt;
* &lt;jvmarg value="-classic"/&gt; * &lt;jvmarg value="-classic"/&gt;
@@ -119,22 +125,21 @@ import java.net.URL;
* &lt;/batchtest&gt; * &lt;/batchtest&gt;
* &lt;/junit&gt; * &lt;/junit&gt;
* &lt;/target&gt; * &lt;/target&gt;
* </pre></code> this target finds any classes with a <code>test</code> directory anywhere in their path
* (under the top <code>${tests.dir}</code>, of course) and creates <code>JUnitTest</code>'s for each one.
* </pre></code>
* <p>this target finds any classes with a <code>test</code> directory
* anywhere in their path (under the top <code>${tests.dir}</code>, of
* course) and creates <code>JUnitTest</code>'s for each one.</p>
* *
* <p> Of course, <code>&lt;junit&gt;</code> and <code>&lt;batch&gt;</code> elements can be combined
* for more complex tests. For an example, see the ant <code>build.xml</code> target <code>run-tests</code>
* (the second example is an edited version).
* <p> Of course, <code>&lt;junit&gt;</code> and
* <code>&lt;batch&gt;</code> elements can be combined for more
* complex tests. For an example, see the ant <code>build.xml</code>
* target <code>run-tests</code> (the second example is an edited
* version).</p>
* *
* <p> To spawn a new Java VM to prevent interferences between * <p> To spawn a new Java VM to prevent interferences between
* different testcases, you need to enable <code>fork</code>.
* A number of attributes and elements allow you to set up how this JVM runs.
* <ul>
* <li>{@link #setTimeout} property sets the maximum time allowed before a test is 'timed out'
* <li>{@link #setMaxmemory} property sets memory assignment for the forked jvm
* <li>{@link #setJvm} property allows the jvm to be specified
* <li>The <code>&lt;jvmarg&gt;</code> element sets arguements to be passed to the forked jvm
* </ul>
* different testcases, you need to enable <code>fork</code>. A
* number of attributes and elements allow you to set up how this JVM
* runs.
* @author Thomas Haas * @author Thomas Haas
* @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a> * @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>
* @author <a href="mailto:sbailliez@imediation.com">Stephane Bailliez</a> * @author <a href="mailto:sbailliez@imediation.com">Stephane Bailliez</a>
@@ -143,6 +148,8 @@ import java.net.URL;
* *
* @version $Revision$ * @version $Revision$
* *
* @since Ant 1.2
*
* @see JUnitTest * @see JUnitTest
* @see BatchTest * @see BatchTest
*/ */
@@ -166,11 +173,16 @@ public class JUnitTask extends Task {
private Path antRuntimeClasses = null; private Path antRuntimeClasses = null;


/** /**
* Tells this task whether to smartly filter the stack frames of JUnit testcase
* errors and failures before reporting them. This property is applied on all
* BatchTest (batchtest) and JUnitTest (test) however it can possibly be
* overridden by their own properties.
* @param value <tt>false</tt> if it should not filter, otherwise <tt>true<tt>
* Tells this task whether to smartly filter the stack frames of
* JUnit testcase errors and failures before reporting them.
*
* <p>This property is applied on all BatchTest (batchtest) and
* JUnitTest (test) however it can possibly be overridden by their
* own properties.</p>
* @param value <tt>false</tt> if it should not filter, otherwise
* <tt>true<tt>
*
* @since Ant 1.5
*/ */
public void setFiltertrace(boolean value) { public void setFiltertrace(boolean value) {
Enumeration enum = allTests(); Enumeration enum = allTests();
@@ -181,10 +193,14 @@ public class JUnitTask extends Task {
} }


/** /**
* Tells this task to halt when there is an error in a test.
* this property is applied on all BatchTest (batchtest) and JUnitTest (test)
* however it can possibly be overridden by their own properties.
* @param value <tt>true</tt> if it should halt, otherwise <tt>false</tt>
* Tells this task to halt when there is an error in a test. this
* property is applied on all BatchTest (batchtest) and JUnitTest
* (test) however it can possibly be overridden by their own
* properties.
* @param value <tt>true</tt> if it should halt, otherwise
* <tt>false</tt>
*
* @since Ant 1.2
*/ */
public void setHaltonerror(boolean value) { public void setHaltonerror(boolean value) {
Enumeration enum = allTests(); Enumeration enum = allTests();
@@ -195,10 +211,16 @@ public class JUnitTask extends Task {
} }


/** /**
* Tells this task to set the named property to "true" when there is a error in a test.
* This property is applied on all BatchTest (batchtest) and JUnitTest (test),
* however, it can possibly be overriden by their own properties.
* @param propertyName the name of the property to set in the event of an error.
* Tells this task to set the named property to "true" when there
* is a error in a test.
*
* <p>This property is applied on all BatchTest (batchtest) and
* JUnitTest (test), however, it can possibly be overriden by
* their own properties.</p>
* @param propertyName the name of the property to set in the
* event of an error.
*
* @since Ant 1.4
*/ */
public void setErrorProperty(String propertyName) { public void setErrorProperty(String propertyName) {
Enumeration enum = allTests(); Enumeration enum = allTests();
@@ -210,9 +232,13 @@ public class JUnitTask extends Task {


/** /**
* Tells this task to halt when there is a failure in a test. * Tells this task to halt when there is a failure in a test.
* this property is applied on all BatchTest (batchtest) and JUnitTest (test)
* however it can possibly be overridden by their own properties.
* @param value <tt>true</tt> if it should halt, otherwise <tt>false</tt>
* this property is applied on all BatchTest (batchtest) and
* JUnitTest (test) however it can possibly be overridden by their
* own properties.
* @param value <tt>true</tt> if it should halt, otherwise
* <tt>false</tt>
*
* @since Ant 1.2
*/ */
public void setHaltonfailure(boolean value) { public void setHaltonfailure(boolean value) {
Enumeration enum = allTests(); Enumeration enum = allTests();
@@ -223,10 +249,16 @@ public class JUnitTask extends Task {
} }


/** /**
* Tells this task to set the named property to "true" when there is a failure in a test.
* This property is applied on all BatchTest (batchtest) and JUnitTest (test),
* however, it can possibly be overriden by their own properties.
* @param propertyName the name of the property to set in the event of an failure.
* Tells this task to set the named property to "true" when there
* is a failure in a test.
*
* <p>This property is applied on all BatchTest (batchtest) and
* JUnitTest (test), however, it can possibly be overriden by
* their own properties.</p>
* @param propertyName the name of the property to set in the
* event of an failure.
*
* @since Ant 1.4
*/ */
public void setFailureProperty(String propertyName) { public void setFailureProperty(String propertyName) {
Enumeration enum = allTests(); Enumeration enum = allTests();
@@ -237,12 +269,17 @@ public class JUnitTask extends Task {
} }


/** /**
* Tells whether a JVM should be forked for each testcase. It avoids interference
* between testcases and possibly avoids hanging the build.
* this property is applied on all BatchTest (batchtest) and JUnitTest (test)
* however it can possibly be overridden by their own properties.
* @param value <tt>true</tt> if a JVM should be forked, otherwise <tt>false</tt>
* Tells whether a JVM should be forked for each testcase.
*
* <p>It avoids interference between testcases and possibly avoids
* hanging the build. this property is applied on all BatchTest
* (batchtest) and JUnitTest (test) however it can possibly be
* overridden by their own properties.</p>
* @param value <tt>true</tt> if a JVM should be forked, otherwise
* <tt>false</tt>
* @see #setTimeout * @see #setTimeout
*
* @since Ant 1.2
*/ */
public void setFork(boolean value) { public void setFork(boolean value) {
Enumeration enum = allTests(); Enumeration enum = allTests();
@@ -253,11 +290,14 @@ public class JUnitTask extends Task {
} }


/** /**
* Tells whether the task should print a short summary of the task.
* Tells whether the task should print a short summary of the
* task.
* @param value <tt>true</tt> to print a summary, * @param value <tt>true</tt> to print a summary,
* <tt>withOutAndErr</tt> to include the test&apos;s output as
* well, <tt>false</tt> otherwise.
* <tt>withOutAndErr</tt> to include the test&apos;s output as
* well, <tt>false</tt> otherwise.
* @see SummaryJUnitResultFormatter * @see SummaryJUnitResultFormatter
*
* @since Ant 1.2
*/ */
public void setPrintsummary(SummaryAttribute value) { public void setPrintsummary(SummaryAttribute value) {
summaryValue = value.getValue(); summaryValue = value.getValue();
@@ -283,11 +323,15 @@ public class JUnitTask extends Task {
} }


/** /**
* Set the timeout value (in milliseconds). If the test is running for more than this
* value, the test will be canceled. (works only when in 'fork' mode).
* @param value the maximum time (in milliseconds) allowed before declaring the test
* as 'timed-out'
* Set the timeout value (in milliseconds).
*
* <p>If the test is running for more than this value, the test
* will be canceled. (works only when in 'fork' mode).</p>
* @param value the maximum time (in milliseconds) allowed before
* declaring the test as 'timed-out'
* @see #setFork(boolean) * @see #setFork(boolean)
*
* @since 1.2
*/ */
public void setTimeout(Integer value) { public void setTimeout(Integer value) {
timeout = value; timeout = value;
@@ -297,19 +341,20 @@ public class JUnitTask extends Task {
* Set the maximum memory to be used by all forked JVMs. * Set the maximum memory to be used by all forked JVMs.
* @param max the value as defined by <tt>-mx</tt> or <tt>-Xmx</tt> * @param max the value as defined by <tt>-mx</tt> or <tt>-Xmx</tt>
* in the java command line options. * in the java command line options.
*
* @since 1.2
*/ */
public void setMaxmemory(String max) { public void setMaxmemory(String max) {
if (Project.getJavaVersion().startsWith("1.1")) {
createJvmarg().setValue("-mx"+max);
} else {
createJvmarg().setValue("-Xmx"+max);
}
commandline.setMaxmemory(max);
} }


/** /**
* Set a new VM to execute the testcase. Default is <tt>java</tt>. Ignored if no JVM is forked.
* Set a new VM to execute the testcase. Default is
* <tt>java</tt>. Ignored if no JVM is forked.
* @param value the new VM to use instead of <tt>java</tt> * @param value the new VM to use instead of <tt>java</tt>
* @see #setFork(boolean) * @see #setFork(boolean)
*
* @since 1.2
*/ */
public void setJvm(String value) { public void setJvm(String value) {
commandline.setVm(value); commandline.setVm(value);
@@ -317,8 +362,11 @@ public class JUnitTask extends Task {


/** /**
* Create a new JVM argument. Ignored if no JVM is forked. * Create a new JVM argument. Ignored if no JVM is forked.
* @return create a new JVM argument so that any argument can be passed to the JVM.
* @return create a new JVM argument so that any argument can be
* passed to the JVM.
* @see #setFork(boolean) * @see #setFork(boolean)
*
* @since 1.2
*/ */
public Commandline.Argument createJvmarg() { public Commandline.Argument createJvmarg() {
return commandline.createVmArgument(); return commandline.createVmArgument();
@@ -328,6 +376,8 @@ public class JUnitTask extends Task {
* The directory to invoke the VM in. Ignored if no JVM is forked. * The directory to invoke the VM in. Ignored if no JVM is forked.
* @param dir the directory to invoke the JVM from. * @param dir the directory to invoke the JVM from.
* @see #setFork(boolean) * @see #setFork(boolean)
*
* @since 1.2
*/ */
public void setDir(File dir) { public void setDir(File dir) {
this.dir = dir; this.dir = dir;
@@ -336,6 +386,8 @@ public class JUnitTask extends Task {
/** /**
* Add a nested sysproperty element. This might be useful to tranfer * Add a nested sysproperty element. This might be useful to tranfer
* Ant properties to the testcases when JVM forking is not enabled. * Ant properties to the testcases when JVM forking is not enabled.
*
* @since 1.3
*/ */
public void addSysproperty(Environment.Variable sysp) { public void addSysproperty(Environment.Variable sysp) {
commandline.addSysproperty(sysp); commandline.addSysproperty(sysp);
@@ -343,6 +395,8 @@ public class JUnitTask extends Task {


/** /**
* <code>&lt;classpath&gt;</code> allows classpath to be set for tests. * <code>&lt;classpath&gt;</code> allows classpath to be set for tests.
*
* @since 1.2
*/ */
public Path createClasspath() { public Path createClasspath() {
return commandline.createClasspath(project).createPath(); return commandline.createClasspath(project).createPath();
@@ -351,9 +405,9 @@ public class JUnitTask extends Task {
/** /**
* Add a nested env element - an environment variable. * Add a nested env element - an environment variable.
* *
* <p>Will be ignored if we are not forking a new VM.
* <p>Will be ignored if we are not forking a new VM.</p>
* *
* @since 1.33, Ant 1.5
* @since Ant 1.5
*/ */
public void addEnv(Environment.Variable var) { public void addEnv(Environment.Variable var) {
env.addVariable(var); env.addVariable(var);
@@ -362,9 +416,9 @@ public class JUnitTask extends Task {
/** /**
* Use a completely new environment. * Use a completely new environment.
* *
* <p>Will be ignored if we are not forking a new VM.
* <p>Will be ignored if we are not forking a new VM.</p>
* *
* @since 1.33, Ant 1.5
* @since Ant 1.5
*/ */
public void setNewenvironment(boolean newenv) { public void setNewenvironment(boolean newenv) {
newEnvironment = newenv; newEnvironment = newenv;
@@ -374,15 +428,20 @@ public class JUnitTask extends Task {
* Add a new single testcase. * Add a new single testcase.
* @param test a new single testcase * @param test a new single testcase
* @see JUnitTest * @see JUnitTest
*
* @since 1.2
*/ */
public void addTest(JUnitTest test) { public void addTest(JUnitTest test) {
tests.addElement(test); tests.addElement(test);
} }


/** /**
* Create a new set of testcases (also called ..batchtest) and add it to the list.
* Create a new set of testcases (also called ..batchtest) and add
* it to the list.
* @return a new instance of a batch test. * @return a new instance of a batch test.
* @see BatchTest * @see BatchTest
*
* @since 1.2
*/ */
public BatchTest createBatchTest() { public BatchTest createBatchTest() {
BatchTest test = new BatchTest(project); BatchTest test = new BatchTest(project);
@@ -392,6 +451,8 @@ public class JUnitTask extends Task {


/** /**
* Add a new formatter to all tests of this task. * Add a new formatter to all tests of this task.
*
* @since 1.2
*/ */
public void addFormatter(FormatterElement fe) { public void addFormatter(FormatterElement fe) {
formatters.addElement(fe); formatters.addElement(fe);
@@ -400,7 +461,7 @@ public class JUnitTask extends Task {
/** /**
* Whether to include ant.jar, optional.jar and junit.jar in the forked VM. * Whether to include ant.jar, optional.jar and junit.jar in the forked VM.
* *
* @since 1.37, Ant 1.5
* @since Ant 1.5
*/ */
public void setIncludeantruntime(boolean b) { public void setIncludeantruntime(boolean b) {
includeAntRuntime = b; includeAntRuntime = b;
@@ -408,15 +469,20 @@ public class JUnitTask extends Task {


/** /**
* Creates a new JUnitRunner and enables fork of a new Java VM. * Creates a new JUnitRunner and enables fork of a new Java VM.
*
* @since 1.2
*/ */
public JUnitTask() throws Exception { public JUnitTask() throws Exception {
commandline.setClassname("org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner");
commandline
.setClassname("org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner");
} }


/** /**
* Adds the jars or directories containing Ant, this task and * Adds the jars or directories containing Ant, this task and
* JUnit to the classpath - this should make the forked JVM work * JUnit to the classpath - this should make the forked JVM work
* without having to specify them directly. * without having to specify them directly.
*
* @since 1.4
*/ */
public void init() { public void init() {
antRuntimeClasses = new Path(getProject()); antRuntimeClasses = new Path(getProject());
@@ -427,6 +493,8 @@ public class JUnitTask extends Task {


/** /**
* Runs the testcase. * Runs the testcase.
*
* @since 1.2
*/ */
public void execute() throws BuildException { public void execute() throws BuildException {
Enumeration list = getIndividualTests(); Enumeration list = getIndividualTests();
@@ -441,7 +509,8 @@ public class JUnitTask extends Task {
/** /**
* Run the tests. * Run the tests.
*/ */
protected void execute(JUnitTest test) throws BuildException {
protected void execute(JUnitTest arg) throws BuildException {
JUnitTest test = (JUnitTest) arg.clone();
// set the default values if not specified // set the default values if not specified
//@todo should be moved to the test class instead. //@todo should be moved to the test class instead.
if (test.getTodir() == null) { if (test.getTodir() == null) {
@@ -466,8 +535,8 @@ public class JUnitTask extends Task {
} }
} }


// if there is an error/failure and that it should halt, stop everything otherwise
// just log a statement
// if there is an error/failure and that it should halt, stop
// everything otherwise just log a statement
boolean errorOccurredHere = exitValue == JUnitTestRunner.ERRORS; boolean errorOccurredHere = exitValue == JUnitTestRunner.ERRORS;
boolean failureOccurredHere = exitValue != JUnitTestRunner.SUCCESS; boolean failureOccurredHere = exitValue != JUnitTestRunner.SUCCESS;
if (errorOccurredHere || failureOccurredHere) { if (errorOccurredHere || failureOccurredHere) {
@@ -480,10 +549,10 @@ public class JUnitTask extends Task {
log("TEST "+test.getName()+" FAILED" log("TEST "+test.getName()+" FAILED"
+ (wasKilled ? " (timeout)" : ""), Project.MSG_ERR); + (wasKilled ? " (timeout)" : ""), Project.MSG_ERR);
if (errorOccurredHere && test.getErrorProperty() != null) { if (errorOccurredHere && test.getErrorProperty() != null) {
project.setProperty(test.getErrorProperty(), "true");
project.setNewProperty(test.getErrorProperty(), "true");
} }
if (failureOccurredHere && test.getFailureProperty() != null) { if (failureOccurredHere && test.getFailureProperty() != null) {
project.setProperty(test.getFailureProperty(), "true");
project.setNewProperty(test.getFailureProperty(), "true");
} }
} }
} }
@@ -498,14 +567,17 @@ public class JUnitTask extends Task {
* exceeds a certain amount of time. Can be <tt>null</tt>, in this case * exceeds a certain amount of time. Can be <tt>null</tt>, in this case
* the test could probably hang forever. * the test could probably hang forever.
*/ */
private int executeAsForked(JUnitTest test, ExecuteWatchdog watchdog) throws BuildException {
private int executeAsForked(JUnitTest test, ExecuteWatchdog watchdog)
throws BuildException {

CommandlineJava cmd = (CommandlineJava) commandline.clone(); CommandlineJava cmd = (CommandlineJava) commandline.clone();


cmd.setClassname("org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner"); cmd.setClassname("org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner");
cmd.createArgument().setValue(test.getName()); cmd.createArgument().setValue(test.getName());
cmd.createArgument().setValue("filtertrace=" + test.getFiltertrace()); cmd.createArgument().setValue("filtertrace=" + test.getFiltertrace());
cmd.createArgument().setValue("haltOnError=" + test.getHaltonerror()); cmd.createArgument().setValue("haltOnError=" + test.getHaltonerror());
cmd.createArgument().setValue("haltOnFailure=" + test.getHaltonfailure());
cmd.createArgument().setValue("haltOnFailure="
+ test.getHaltonfailure());
if (includeAntRuntime) { if (includeAntRuntime) {
log("Implicitly adding "+antRuntimeClasses+" to CLASSPATH", log("Implicitly adding "+antRuntimeClasses+" to CLASSPATH",
Project.MSG_VERBOSE); Project.MSG_VERBOSE);
@@ -515,7 +587,8 @@ public class JUnitTask extends Task {


if (summary) { if (summary) {
log("Running " + test.getName(), Project.MSG_INFO); log("Running " + test.getName(), Project.MSG_INFO);
cmd.createArgument().setValue("formatter=org.apache.tools.ant.taskdefs.optional.junit.SummaryJUnitResultFormatter");
cmd.createArgument()
.setValue("formatter=org.apache.tools.ant.taskdefs.optional.junit.SummaryJUnitResultFormatter");
} }


StringBuffer formatterArg = new StringBuffer(128); StringBuffer formatterArg = new StringBuffer(128);
@@ -533,9 +606,13 @@ public class JUnitTask extends Task {
formatterArg.setLength(0); formatterArg.setLength(0);
} }


// Create a temporary file to pass the Ant properties to the forked test
File propsFile = new File("junit" + (new Random(System.currentTimeMillis())).nextLong() + ".properties");
cmd.createArgument().setValue("propsfile=" + propsFile.getAbsolutePath());
// Create a temporary file to pass the Ant properties to the
// forked test
File propsFile =
FileUtils.newFileUtils().createTempFile("junit", ".properties",
project.getBaseDir());
cmd.createArgument().setValue("propsfile="
+ propsFile.getAbsolutePath());
Hashtable p = project.getProperties(); Hashtable p = project.getProperties();
Properties props = new Properties(); Properties props = new Properties();
for (Enumeration enum = p.keys(); enum.hasMoreElements(); ) { for (Enumeration enum = p.keys(); enum.hasMoreElements(); ) {
@@ -547,10 +624,15 @@ public class JUnitTask extends Task {
props.save(outstream,"Ant JUnitTask generated properties file"); props.save(outstream,"Ant JUnitTask generated properties file");
outstream.close(); outstream.close();
} catch (java.io.IOException e) { } catch (java.io.IOException e) {
throw new BuildException("Error creating temporary properties file.", e, location);
propsFile.delete();
throw new BuildException("Error creating temporary properties "
+ "file.", e, location);
} }


Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN), watchdog);
Execute execute = new Execute(new LogStreamHandler(this,
Project.MSG_INFO,
Project.MSG_WARN),
watchdog);
execute.setCommandline(cmd.getCommandline()); execute.setCommandline(cmd.getCommandline());
execute.setAntRun(project); execute.setAntRun(project);
if (dir != null) { if (dir != null) {
@@ -574,58 +656,73 @@ public class JUnitTask extends Task {
} catch (IOException e) { } catch (IOException e) {
throw new BuildException("Process fork failed.", e, location); throw new BuildException("Process fork failed.", e, location);
} finally { } finally {
if (! propsFile.delete()) {
throw new BuildException("Could not delete temporary properties file.");
}
if (!propsFile.delete()) {
throw new BuildException("Could not delete temporary "
+ "properties file.");
}
} }


return retVal; return retVal;
} }


// in VM is not very nice since it could probably hang the
// whole build. IMHO this method should be avoided and it would be best
// to remove it in future versions. TBD. (SBa)



/**
* Pass output sent to System.out to the TestRunner so it can
* collect ot for the formatters.
*
* @since Ant 1.5
*/
protected void handleOutput(String line) { protected void handleOutput(String line) {
if (runner != null) { if (runner != null) {
runner.handleOutput(line); runner.handleOutput(line);
}
else {
} else {
super.handleOutput(line); super.handleOutput(line);
} }
} }


/**
* Pass output sent to System.err to the TestRunner so it can
* collect ot for the formatters.
*
* @since Ant 1.5
*/
protected void handleErrorOutput(String line) { protected void handleErrorOutput(String line) {
if (runner != null) { if (runner != null) {
runner.handleErrorOutput(line); runner.handleErrorOutput(line);
}
else {
} else {
super.handleErrorOutput(line); super.handleErrorOutput(line);
} }
} }


// in VM is not very nice since it could probably hang the
// whole build. IMHO this method should be avoided and it would be best
// to remove it in future versions. TBD. (SBa)

/** /**
* Execute inside VM. * Execute inside VM.
*/ */
private int executeInVM(JUnitTest test) throws BuildException {
private int executeInVM(JUnitTest arg) throws BuildException {
JUnitTest test = (JUnitTest) arg.clone();
test.setProperties(project.getProperties()); test.setProperties(project.getProperties());
if (dir != null) { if (dir != null) {
log("dir attribute ignored if running in the same VM", Project.MSG_WARN);
log("dir attribute ignored if running in the same VM",
Project.MSG_WARN);
} }


if (newEnvironment || null != env.getVariables()) { if (newEnvironment || null != env.getVariables()) {
log("Changes to environment variables are ignored if running in the same VM.",
Project.MSG_WARN);
log("Changes to environment variables are ignored if running in "
+ "the same VM.", Project.MSG_WARN);
} }


CommandlineJava.SysProperties sysProperties = commandline.getSystemProperties();
CommandlineJava.SysProperties sysProperties =
commandline.getSystemProperties();
if (sysProperties != null) { if (sysProperties != null) {
sysProperties.setSystem(); sysProperties.setSystem();
} }
AntClassLoader cl = null; AntClassLoader cl = null;
try { try {
log("Using System properties " + System.getProperties(), Project.MSG_VERBOSE);
log("Using System properties " + System.getProperties(),
Project.MSG_VERBOSE);
Path classpath = (Path) commandline.getClasspath().clone(); Path classpath = (Path) commandline.getClasspath().clone();
if (includeAntRuntime) { if (includeAntRuntime) {
log("Implicitly adding "+antRuntimeClasses+" to CLASSPATH", log("Implicitly adding "+antRuntimeClasses+" to CLASSPATH",
@@ -644,13 +741,16 @@ public class JUnitTask extends Task {
cl.addSystemPackageRoot("org.apache.tools.ant"); cl.addSystemPackageRoot("org.apache.tools.ant");
cl.setThreadContextLoader(); cl.setThreadContextLoader();
} }
runner = new JUnitTestRunner(test, test.getHaltonerror(), test.getFiltertrace(), test.getHaltonfailure(), cl);
runner = new JUnitTestRunner(test, test.getHaltonerror(),
test.getFiltertrace(),
test.getHaltonfailure(), cl);
if (summary) { if (summary) {
log("Running " + test.getName(), Project.MSG_INFO); log("Running " + test.getName(), Project.MSG_INFO);


SummaryJUnitResultFormatter f =
new SummaryJUnitResultFormatter();
f.setWithOutAndErr( "withoutanderr".equalsIgnoreCase( summaryValue ));
SummaryJUnitResultFormatter f =
new SummaryJUnitResultFormatter();
f.setWithOutAndErr("withoutanderr"
.equalsIgnoreCase( summaryValue ));
f.setOutput( getDefaultOutput() ); f.setOutput( getDefaultOutput() );
runner.addFormatter(f); runner.addFormatter(f);
} }
@@ -680,6 +780,8 @@ public class JUnitTask extends Task {
/** /**
* @return <tt>null</tt> if there is a timeout value, otherwise the * @return <tt>null</tt> if there is a timeout value, otherwise the
* watchdog instance. * watchdog instance.
*
* @since 1.2
*/ */
protected ExecuteWatchdog createWatchdog() throws BuildException { protected ExecuteWatchdog createWatchdog() throws BuildException {
if (timeout == null){ if (timeout == null){
@@ -690,6 +792,8 @@ public class JUnitTask extends Task {


/** /**
* Get the default output for a formatter. * Get the default output for a formatter.
*
* @since 1.3
*/ */
protected OutputStream getDefaultOutput(){ protected OutputStream getDefaultOutput(){
return new LogOutputStream(this, Project.MSG_INFO); return new LogOutputStream(this, Project.MSG_INFO);
@@ -698,6 +802,8 @@ public class JUnitTask extends Task {
/** /**
* Merge all individual tests from the batchtest with all individual tests * Merge all individual tests from the batchtest with all individual tests
* and return an enumeration over all <tt>JUnitTest</tt>. * and return an enumeration over all <tt>JUnitTest</tt>.
*
* @since 1.3
*/ */
protected Enumeration getIndividualTests(){ protected Enumeration getIndividualTests(){
final int count = batchTests.size(); final int count = batchTests.size();
@@ -710,11 +816,17 @@ public class JUnitTask extends Task {
return Enumerations.fromCompound(enums); return Enumerations.fromCompound(enums);
} }


/**
* @since 1.3
*/
protected Enumeration allTests() { protected Enumeration allTests() {
Enumeration[] enums = { tests.elements(), batchTests.elements() }; Enumeration[] enums = { tests.elements(), batchTests.elements() };
return Enumerations.fromCompound(enums); return Enumerations.fromCompound(enums);
} }


/**
* @since 1.3
*/
private FormatterElement[] mergeFormatters(JUnitTest test){ private FormatterElement[] mergeFormatters(JUnitTest test){
Vector feVector = (Vector)formatters.clone(); Vector feVector = (Vector)formatters.clone();
test.addFormattersTo(feVector); test.addFormattersTo(feVector);
@@ -723,7 +835,12 @@ public class JUnitTask extends Task {
return feArray; return feArray;
} }


/** return the file or null if does not use a file */
/**
* If the formatter sends output to a file, return that file.
* null otherwise.
*
* @since 1.3
*/
protected File getOutput(FormatterElement fe, JUnitTest test){ protected File getOutput(FormatterElement fe, JUnitTest test){
if (fe.getUseFile()) { if (fe.getUseFile()) {
String filename = test.getOutfile() + fe.getExtension(); String filename = test.getOutfile() + fe.getExtension();
@@ -740,6 +857,8 @@ public class JUnitTask extends Task {
* *
* <p>Doesn't work for archives in JDK 1.1 as the URL returned by * <p>Doesn't work for archives in JDK 1.1 as the URL returned by
* getResource doesn't contain the name of the archive.</p> * getResource doesn't contain the name of the archive.</p>
*
* @since 1.4
*/ */
protected void addClasspathEntry(String resource) { protected void addClasspathEntry(String resource) {
URL url = getClass().getResource(resource); URL url = getClass().getResource(resource);
@@ -749,12 +868,16 @@ public class JUnitTask extends Task {
int pling = u.indexOf("!"); int pling = u.indexOf("!");
String jarName = u.substring(9, pling); String jarName = u.substring(9, pling);
log("Found "+jarName, Project.MSG_DEBUG); log("Found "+jarName, Project.MSG_DEBUG);
antRuntimeClasses.createPath().setLocation(new File((new File(jarName)).getAbsolutePath()));
antRuntimeClasses.createPath()
.setLocation(new File((new File(jarName))
.getAbsolutePath()));
} else if (u.startsWith("file:")) { } else if (u.startsWith("file:")) {
int tail = u.indexOf(resource); int tail = u.indexOf(resource);
String dirName = u.substring(5, tail); String dirName = u.substring(5, tail);
log("Found "+dirName, Project.MSG_DEBUG); log("Found "+dirName, Project.MSG_DEBUG);
antRuntimeClasses.createPath().setLocation(new File((new File(dirName)).getAbsolutePath()));
antRuntimeClasses.createPath()
.setLocation(new File((new File(dirName))
.getAbsolutePath()));
} else { } else {
log("Don\'t know how to handle resource URL "+u, log("Don\'t know how to handle resource URL "+u,
Project.MSG_DEBUG); Project.MSG_DEBUG);


+ 21
- 5
src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTest.java View File

@@ -1,7 +1,7 @@
/* /*
* The Apache Software License, Version 1.1 * The Apache Software License, Version 1.1
* *
* Copyright (c) 2000-2001 The Apache Software Foundation. All rights
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved. * reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
@@ -56,8 +56,6 @@ package org.apache.tools.ant.taskdefs.optional.junit;


import org.apache.tools.ant.Project; import org.apache.tools.ant.Project;




import java.util.Enumeration; import java.util.Enumeration;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Properties; import java.util.Properties;
@@ -73,10 +71,12 @@ import java.util.Vector;
* @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>, * @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>,
* @author <a href="mailto:sbailliez@imediation.com">Stephane Bailliez</a> * @author <a href="mailto:sbailliez@imediation.com">Stephane Bailliez</a>
* *
* @since Ant 1.2
*
* @see JUnitTask * @see JUnitTask
* @see JUnitTestRunner * @see JUnitTestRunner
*/ */
public class JUnitTest extends BaseTest {
public class JUnitTest extends BaseTest implements Cloneable {
/** the name of the test case */ /** the name of the test case */
private String name = null; private String name = null;
@@ -100,7 +100,8 @@ public class JUnitTest extends BaseTest {
this.name = name; this.name = name;
} }


public JUnitTest(String name, boolean haltOnError, boolean haltOnFailure, boolean filtertrace) {
public JUnitTest(String name, boolean haltOnError, boolean haltOnFailure,
boolean filtertrace) {
this.name = name; this.name = name;
this.haltOnError = haltOnError; this.haltOnError = haltOnError;
this.haltOnFail = haltOnFailure; this.haltOnFail = haltOnFailure;
@@ -187,4 +188,19 @@ public class JUnitTest extends BaseTest {
v.addElement( formatters.elementAt(i) ); v.addElement( formatters.elementAt(i) );
} }
} }

/**
* @since Ant 1.5
*/
public Object clone() {
try {
JUnitTest t = (JUnitTest) super.clone();
t.props = props == null ? null : (Properties) props.clone();
t.formatters = (Vector) formatters.clone();
return t;
} catch (CloneNotSupportedException e) {
// plain impossible
return this;
}
}
} }

Loading…
Cancel
Save