| Method from org.apache.tools.ant.taskdefs.optional.junit.JUnitTask Detail: |
protected void actOnTestResult(TestResultHolder result,
JUnitTest test,
String name) {
// if there is an error/failure and that it should halt, stop
// everything otherwise just log a statement
boolean fatal = result.timedOut || result.crashed;
boolean errorOccurredHere =
result.exitCode == JUnitTaskMirror.JUnitTestRunnerMirror.ERRORS || fatal;
boolean failureOccurredHere =
result.exitCode != JUnitTaskMirror.JUnitTestRunnerMirror.SUCCESS || fatal;
if (errorOccurredHere || failureOccurredHere) {
if ((errorOccurredHere && test.getHaltonerror())
|| (failureOccurredHere && test.getHaltonfailure())) {
throw new BuildException(name + " failed"
+ (result.timedOut ? " (timeout)" : "")
+ (result.crashed ? " (crashed)" : ""), getLocation());
} else {
if (logFailedTests) {
log(name + " FAILED"
+ (result.timedOut ? " (timeout)" : "")
+ (result.crashed ? " (crashed)" : ""),
Project.MSG_ERR);
}
if (errorOccurredHere && test.getErrorProperty() != null) {
getProject().setNewProperty(test.getErrorProperty(), "true");
}
if (failureOccurredHere && test.getFailureProperty() != null) {
getProject().setNewProperty(test.getFailureProperty(), "true");
}
}
}
}
Logs information about failed tests, potentially stops
processing (by throwing a BuildException) if a failure/error
occurred or sets a property. |
protected void actOnTestResult(int exitValue,
boolean wasKilled,
JUnitTest test,
String name) {
TestResultHolder t = new TestResultHolder();
t.exitCode = exitValue;
t.timedOut = wasKilled;
actOnTestResult(t, test, name);
}
Logs information about failed tests, potentially stops
processing (by throwing a BuildException) if a failure/error
occurred or sets a property. |
public void addAssertions(Assertions asserts) {
if (getCommandline().getAssertions() != null) {
throw new BuildException("Only one assertion declaration is allowed");
}
getCommandline().setAssertions(asserts);
}
Assertions to enable in this program (if fork=true) |
protected void addClasspathEntry(String resource) {
addClasspathResource(resource);
}
Search for the given resource and add the directory or archive
that contains it to the classpath.
Doesn't work for archives in JDK 1.1 as the URL returned by
getResource doesn't contain the name of the archive. |
public void addConfiguredSysproperty(Variable sysp) {
// get a build exception if there is a missing key or value
// see bugzilla report 21684
String testString = sysp.getContent();
getProject().log("sysproperty added : " + testString, Project.MSG_DEBUG);
getCommandline().addSysproperty(sysp);
}
Adds a system property that tests can access.
This might be useful to tranfer Ant properties to the
testcases when JVM forking is not enabled. |
public void addEnv(Variable var) {
env.addVariable(var);
}
|
public void addFormatter(FormatterElement fe) {
formatters.addElement(fe);
}
Add a new formatter to all tests of this task. |
public void addSysproperty(Variable sysp) {
getCommandline().addSysproperty(sysp);
} Deprecated! since - ant 1.6
Adds a system property that tests can access.
This might be useful to tranfer Ant properties to the
testcases when JVM forking is not enabled. |
public void addSyspropertyset(PropertySet sysp) {
getCommandline().addSyspropertyset(sysp);
}
Adds a set of properties that will be used as system properties
that tests can access.
This might be useful to tranfer Ant properties to the
testcases when JVM forking is not enabled. |
public void addTest(JUnitTest test) {
tests.addElement(test);
preConfigure(test);
}
Add a new single testcase. |
protected Enumeration allTests() {
Enumeration[] enums = {tests.elements(), batchTests.elements()};
return Enumerations.fromCompound(enums);
}
return an enumeration listing each test, then each batchtest |
protected void cleanup() {
deleteClassLoader();
delegate = null;
}
Removes resources.
Is invoked in execute . Subclasses that
don't invoke execute should invoke this method in a finally
block. |
public BatchTest createBatchTest() {
BatchTest test = new BatchTest(getProject());
batchTests.addElement(test);
preConfigure(test);
return test;
}
Adds a set of tests based on pattern matching. |
public Path createBootclasspath() {
return getCommandline().createBootclasspath(getProject()).createPath();
}
Adds a path to the bootclasspath. |
public Path createClasspath() {
return getCommandline().createClasspath(getProject()).createPath();
}
Adds path to classpath used for tests. |
public Argument createJvmarg() {
return getCommandline().createVmArgument();
}
Adds a JVM argument; ignored if not forking. |
public Permissions createPermissions() {
if (perm == null) {
perm = new Permissions();
}
return perm;
}
Sets the permissions for the application run inside the same JVM. |
protected ExecuteWatchdog createWatchdog() throws BuildException {
if (timeout == null) {
return null;
}
return new ExecuteWatchdog((long) timeout.intValue());
}
|
public void execute() throws BuildException {
setupJUnitDelegate();
List testLists = new ArrayList();
boolean forkPerTest = forkMode.getValue().equals(ForkMode.PER_TEST);
if (forkPerTest || forkMode.getValue().equals(ForkMode.ONCE)) {
testLists.addAll(executeOrQueue(getIndividualTests(),
forkPerTest));
} else { /* forkMode.getValue().equals(ForkMode.PER_BATCH) */
final int count = batchTests.size();
for (int i = 0; i < count; i++) {
BatchTest batchtest = (BatchTest) batchTests.elementAt(i);
testLists.addAll(executeOrQueue(batchtest.elements(), false));
}
testLists.addAll(executeOrQueue(tests.elements(), forkPerTest));
}
try {
Iterator iter = testLists.iterator();
while (iter.hasNext()) {
List l = (List) iter.next();
if (l.size() == 1) {
execute((JUnitTest) l.get(0));
} else {
execute(l);
}
}
} finally {
cleanup();
}
}
|
protected void execute(JUnitTest arg) throws BuildException {
validateTestName(arg.getName());
JUnitTest test = (JUnitTest) arg.clone();
// set the default values if not specified
//@todo should be moved to the test class instead.
if (test.getTodir() == null) {
test.setTodir(getProject().resolveFile("."));
}
if (test.getOutfile() == null) {
test.setOutfile("TEST-" + test.getName());
}
// execute the test and get the return code
TestResultHolder result = null;
if (!test.getFork()) {
result = executeInVM(test);
} else {
ExecuteWatchdog watchdog = createWatchdog();
result = executeAsForked(test, watchdog, null);
// null watchdog means no timeout, you'd better not check with null
}
actOnTestResult(result, test, "Test " + test.getName());
}
|
protected void execute(List testList) throws BuildException {
JUnitTest test = null;
// Create a temporary file to pass the test cases to run to
// the runner (one test case per line)
File casesFile = createTempPropertiesFile("junittestcases");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(casesFile));
log("Creating casesfile '" + casesFile.getAbsolutePath()
+ "' with content: ", Project.MSG_VERBOSE);
PrintStream logWriter =
new PrintStream(new LogOutputStream(this, Project.MSG_VERBOSE));
Iterator iter = testList.iterator();
while (iter.hasNext()) {
test = (JUnitTest) iter.next();
printDual(writer, logWriter, test.getName());
if (test.getTodir() == null) {
printDual(writer, logWriter,
"," + getProject().resolveFile("."));
} else {
printDual(writer, logWriter, "," + test.getTodir());
}
if (test.getOutfile() == null) {
printlnDual(writer, logWriter,
"," + "TEST-" + test.getName());
} else {
printlnDual(writer, logWriter, "," + test.getOutfile());
}
}
writer.flush();
writer.close();
writer = null;
// execute the test and get the return code
ExecuteWatchdog watchdog = createWatchdog();
TestResultHolder result =
executeAsForked(test, watchdog, casesFile);
actOnTestResult(result, test, "Tests");
} catch (IOException e) {
log(e.toString(), Project.MSG_ERR);
throw new BuildException(e);
} finally {
FILE_UTILS.close(writer);
try {
casesFile.delete();
} catch (Exception e) {
log(e.toString(), Project.MSG_ERR);
}
}
}
Execute a list of tests in a single forked Java VM. |
protected Collection executeOrQueue(Enumeration testList,
boolean runIndividual) {
Map testConfigurations = new HashMap();
while (testList.hasMoreElements()) {
JUnitTest test = (JUnitTest) testList.nextElement();
if (test.shouldRun(getProject())) {
if (runIndividual || !test.getFork()) {
execute(test);
} else {
ForkedTestConfiguration c =
new ForkedTestConfiguration(test);
List l = (List) testConfigurations.get(c);
if (l == null) {
l = new ArrayList();
testConfigurations.put(c, l);
}
l.add(test);
}
}
}
return testConfigurations.values();
}
Executes all tests that don't need to be forked (or all tests
if the runIndividual argument is true. Returns a collection of
lists of tests that share the same VM configuration and haven't
been executed yet. |
protected CommandlineJava getCommandline() {
if (commandline == null) {
commandline = new CommandlineJava();
}
return commandline;
}
Get the command line used to run the tests. |
protected OutputStream getDefaultOutput() {
return new LogOutputStream(this, Project.MSG_INFO);
}
Get the default output for a formatter. |
protected Enumeration getIndividualTests() {
final int count = batchTests.size();
final Enumeration[] enums = new Enumeration[ count + 1];
for (int i = 0; i < count; i++) {
BatchTest batchtest = (BatchTest) batchTests.elementAt(i);
enums[i] = batchtest.elements();
}
enums[enums.length - 1] = tests.elements();
return Enumerations.fromCompound(enums);
}
Merge all individual tests from the batchtest with all individual tests
and return an enumeration over all JUnitTest. |
protected File getOutput(FormatterElement fe,
JUnitTest test) {
if (fe.getUseFile()) {
String base = test.getOutfile();
if (base == null) {
base = JUnitTaskMirror.JUnitTestRunnerMirror.IGNORED_FILE_NAME;
}
String filename = base + fe.getExtension();
File destFile = new File(test.getTodir(), filename);
String absFilename = destFile.getAbsolutePath();
return getProject().resolveFile(absFilename);
}
return null;
}
If the formatter sends output to a file, return that file.
null otherwise. |
public void handleErrorFlush(String output) {
if (runner != null) {
runner.handleErrorFlush(output);
if (showOutput) {
super.handleErrorFlush(output);
}
} else {
super.handleErrorFlush(output);
}
}
Pass output sent to System.err to the TestRunner so it can
collect it for the formatters. |
public void handleErrorOutput(String output) {
if (runner != null) {
runner.handleErrorOutput(output);
if (showOutput) {
super.handleErrorOutput(output);
}
} else {
super.handleErrorOutput(output);
}
}
Pass output sent to System.err to the TestRunner so it can
collect it for the formatters. |
protected void handleFlush(String output) {
if (runner != null) {
runner.handleFlush(output);
if (showOutput) {
super.handleFlush(output);
}
} else {
super.handleFlush(output);
}
}
Pass output sent to System.out to the TestRunner so it can
collect ot for the formatters. |
protected int handleInput(byte[] buffer,
int offset,
int length) throws IOException {
if (runner != null) {
return runner.handleInput(buffer, offset, length);
} else {
return super.handleInput(buffer, offset, length);
}
}
Handle an input request by this task. |
protected void handleOutput(String output) {
if (output.startsWith(TESTLISTENER_PREFIX)) {
log(output, Project.MSG_VERBOSE);
} else if (runner != null) {
if (outputToFormatters) {
runner.handleOutput(output);
}
if (showOutput) {
super.handleOutput(output);
}
} else {
super.handleOutput(output);
}
}
Pass output sent to System.out to the TestRunner so it can
collect ot for the formatters. |
public void init() {
antRuntimeClasses = new Path(getProject());
splitJunit = !addClasspathResource("/junit/framework/TestCase.class");
addClasspathEntry("/org/apache/tools/ant/launch/AntMain.class");
addClasspathEntry("/org/apache/tools/ant/Task.class");
addClasspathEntry("/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.class");
}
Adds the jars or directories containing Ant, this task and
JUnit to the classpath - this should make the forked JVM work
without having to specify them directly. |
public void setCloneVm(boolean cloneVm) {
getCommandline().setCloneVm(cloneVm);
}
|
public void setDir(File dir) {
this.dir = dir;
}
The directory to invoke the VM in. Ignored if no JVM is forked. |
public void setErrorProperty(String propertyName) {
this.errorProperty = propertyName;
}
Property to set to "true" if 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. |
public void setFailureProperty(String propertyName) {
this.failureProperty = propertyName;
}
Property to set to "true" if 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. |
public void setFiltertrace(boolean value) {
this.filterTrace = value;
}
If true, smartly filter the stack frames of
JUnit 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. |
public void setFork(boolean value) {
this.fork = value;
}
If true, JVM should be forked for each test.
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. |
public void setForkMode(ForkMode mode) {
this.forkMode = mode;
}
Set the behavior when fork fork has been enabled.
Possible values are "once", "perTest" and "perBatch". If
set to "once", only a single Java VM will be forked for all
tests, with "perTest" (the default) each test will run in a
fresh Java VM and "perBatch" will run all tests from the same
<batchtest> in the same Java VM.
This attribute will be ignored if tests run in the same VM
as Ant.
Only tests with the same configuration of haltonerror,
haltonfailure, errorproperty, failureproperty and filtertrace
can share a forked Java VM, so even if you set the value to
"once", Ant may need to fork mutliple VMs. |
public void setHaltonerror(boolean value) {
this.haltOnError = value;
}
If true, stop the build process 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. |
public void setHaltonfailure(boolean value) {
this.haltOnFail = value;
}
If true, stop the build process if a test fails
(errors are considered failures as well).
This property is applied on all BatchTest (batchtest) and
JUnitTest (test) however it can possibly be overridden by their
own properties. |
public void setIncludeantruntime(boolean b) {
includeAntRuntime = b;
}
If true, include ant.jar, optional.jar and junit.jar in the forked VM. |
public void setJvm(String value) {
getCommandline().setVm(value);
}
The command used to invoke the Java Virtual Machine,
default is 'java'. The command is resolved by
java.lang.Runtime.exec(). Ignored if fork is disabled. |
public void setLogFailedTests(boolean logFailedTests) {
this.logFailedTests = logFailedTests;
}
If true, write a single "FAILED" line for failed tests to Ant's
log system. |
public void setMaxmemory(String max) {
getCommandline().setMaxmemory(max);
}
Set the maximum memory to be used by all forked JVMs. |
public void setNewenvironment(boolean newenv) {
newEnvironment = newenv;
}
|
public void setOutputToFormatters(boolean outputToFormatters) {
this.outputToFormatters = outputToFormatters;
}
If true, send any output generated by tests to the formatters. |
public void setPrintsummary(SummaryAttribute value) {
summaryValue = value.getValue();
summary = value.asBoolean();
}
If true, print one-line statistics for each test, or "withOutAndErr"
to also show standard output and error.
Can take the values on, off, and withOutAndErr. |
public void setReloading(boolean value) {
reloading = value;
}
If true, force ant to re-classload all classes for each JUnit TestCase |
public void setShowOutput(boolean showOutput) {
this.showOutput = showOutput;
}
If true, send any output generated by tests to Ant's logging system
as well as to the formatters.
By default only the formatters receive the output.
Output will always be passed to the formatters and not by
shown by default. This option should for example be set for
tests that are interactive and prompt the user to do
something. |
public void setTempdir(File tmpDir) {
if (tmpDir != null) {
if (!tmpDir.exists() || !tmpDir.isDirectory()) {
throw new BuildException(tmpDir.toString()
+ " is not a valid temp directory");
}
}
this.tmpDir = tmpDir;
}
Where Ant should place temporary files. |
public void setTimeout(Integer value) {
timeout = value;
}
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). |
protected void setupJUnitDelegate() {
ClassLoader myLoader = JUnitTask.class.getClassLoader();
if (splitJunit) {
Path path = new Path(getProject());
path.add(antRuntimeClasses);
Path extra = getCommandline().getClasspath();
if (extra != null) {
path.add(extra);
}
mirrorLoader =
new SplitClassLoader(myLoader, path, getProject(),
new String[] {
"BriefJUnitResultFormatter",
"JUnitResultFormatter",
"JUnitTaskMirrorImpl",
"JUnitTestRunner",
"JUnitVersionHelper",
"OutErrSummaryJUnitResultFormatter",
"PlainJUnitResultFormatter",
"SummaryJUnitResultFormatter",
"TearDownOnVmCrash",
"XMLJUnitResultFormatter",
});
} else {
mirrorLoader = myLoader;
}
delegate = createMirror(this, mirrorLoader);
}
|