Browse Source

- Refactoring to allow running server,client or both.

- Change the formatter interface to allow parameters.


git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@270930 13f79535-47bb-0310-9956-ffa450edef68
master
Stephane Bailliez 23 years ago
parent
commit
59c0b1595d
12 changed files with 733 additions and 243 deletions
  1. +243
    -0
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/ClientElement.java
  2. +36
    -4
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java
  3. +58
    -168
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java
  4. +1
    -1
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/OutputAttribute.java
  5. +131
    -0
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/ServerElement.java
  6. +3
    -32
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/BaseFormatter.java
  7. +131
    -0
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/BaseStreamFormatter.java
  8. +2
    -4
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/BriefFormatter.java
  9. +18
    -14
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/FilterFormatter.java
  10. +7
    -13
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/Formatter.java
  11. +99
    -0
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/PlainFormatter.java
  12. +4
    -7
      proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/SummaryFormatter.java

+ 243
- 0
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/ClientElement.java View File

@@ -0,0 +1,243 @@
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.ant.taskdefs.optional.junit;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import junit.runner.TestCollector;

import org.apache.avalon.excalibur.i18n.ResourceManager;
import org.apache.avalon.excalibur.i18n.Resources;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectComponent;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.LogStreamHandler;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.FileUtils;

/**
* An element representing the client configuration.
*
* <pre>
* <!ELEMENT server (jvmarg)* (classpath)* (test)* (batchtest)*>
* <!ATTLIST server port numeric 6666>
* <!ATTLIST server host CDATA 127.0.0.1>
* </pre>

* @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
*/
public final class ClientElement extends ProjectComponent {
/** resources */
private final static Resources RES =
ResourceManager.getPackageResources(ClientElement.class);

/** port to contact the server. Default to 6666 */
private int port = 6666;

/** server hostname to connect to. Default to 127.0.0.1 */
private String host = "127.0.0.1";

/** test collector elements */
private Vector testCollectors = new Vector();

/** the command line to launch the TestRunner */
private CommandlineJava cmd = new CommandlineJava();

/** the parent task */
private JUnitTask parent;

/** create a new client */
public ClientElement(JUnitTask value) {
parent = value;
cmd.setClassname("org.apache.tools.ant.taskdefs.optional.junit.remote.TestRunner");
}

/** core entry point */
public final void execute() throws BuildException {
try {
preExecute();
doExecute();
} finally {
postExecute();
}
}

protected void preExecute() throws BuildException {
// must appended to classpath to avoid conflicts.
JUnitHelper.addClasspathEntry(createClasspath(), "/junit/framework/TestCase.class");
JUnitHelper.addClasspathEntry(createClasspath(), "/org/apache/tools/ant/Task.class");
JUnitHelper.addClasspathEntry(createClasspath(), "/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.class");
}

protected void doExecute() throws BuildException {
File tmp = configureTestRunner();
Execute execute = new Execute(new LogStreamHandler(parent, Project.MSG_INFO, Project.MSG_WARN));
execute.setCommandline(cmd.getCommandline());
execute.setAntRun(project);

log(RES.getString("task.process-cmdline.log", cmd.toString()), Project.MSG_VERBOSE);
int retVal;
try {
retVal = execute.execute();
} catch (IOException e) {
String msg = RES.getString("task.process-failed.error");
throw new BuildException(msg, e);
} finally {
tmp.delete();
}
}

protected void postExecute() {
// nothing
}

/**
* @return all collected tests specified with test elements.
*/
protected Enumeration collectTests() {
Enumeration[] tests = new Enumeration[testCollectors.size()];
for (int i = 0; i < testCollectors.size(); i++) {
TestCollector te = (TestCollector) testCollectors.elementAt(i);
tests[i] = te.collectTests();
}
return Enumerations.fromCompound(tests);
}

/**
* Configure the runner with the appropriate configuration file.
* @return the reference to the temporary configuration file
* to be deleted once the TestRunner has ended.
*/
protected File configureTestRunner() throws BuildException {
Properties props = new Properties();
props.setProperty("debug", "true");
props.setProperty("host", "127.0.0.1");
props.setProperty("port", String.valueOf(port));
// get all test classes to run...
StringBuffer buf = new StringBuffer(10240);
Enumeration classnames = collectTests();
while (classnames.hasMoreElements()) {
String classname = (String) classnames.nextElement();
buf.append(classname).append(" ");
}
props.setProperty("classnames", buf.toString());

// dump the properties to a temporary file.
FileUtils futils = FileUtils.newFileUtils();
File f = futils.createTempFile("junit-antrunner", "tmp", new File("."));
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(f));
props.store(os, "JUnit Ant Runner configuration file");
} catch (IOException e) {
throw new BuildException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}

// configure the runner
cmd.createArgument().setValue("-file");
cmd.createArgument().setValue(f.getAbsolutePath());
return f;
}

// --- Ant bean setters

/** set the port to connect to */
public void setPort(int value) {
port = value;
}

/** set the host to contact */
public void setHost(String value) {
host = value;
}

/** Create a new JVM argument. */
public Commandline.Argument createJvmarg() {
return cmd.createVmArgument();
}

/** classpath to be set for running tests */
public Path createClasspath() {
return cmd.createClasspath(project);
}

/** add a single test element */
public void addTest(TestElement value) {
testCollectors.addElement(value);
}

/** add a batch test element */
public void addBatchTest(BatchTestElement value) {
testCollectors.addElement(value);
}


}

+ 36
- 4
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/FormatterElement.java View File

@@ -54,6 +54,7 @@
package org.apache.tools.ant.taskdefs.optional.junit; package org.apache.tools.ant.taskdefs.optional.junit;


import java.io.OutputStream; import java.io.OutputStream;
import java.util.Properties;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.Vector; import java.util.Vector;


@@ -90,6 +91,9 @@ public class FormatterElement {
/** the filters to apply to this formatter */ /** the filters to apply to this formatter */
private Vector filters = new Vector(); private Vector filters = new Vector();


/** the parameters set for configuration purposes */
private Properties params = new Properties();

/** /**
* set an existing type of formatter. * set an existing type of formatter.
* @see TypeAttribute * @see TypeAttribute
@@ -131,6 +135,13 @@ public class FormatterElement {
filters.addElement(fe); filters.addElement(fe);
} }


/**
* Add a parameter that can be used for configuration.
*/
public void addParam(Parameter param) {
params.setProperty(param.getName(), param.getValue());
}

/** /**
* Set whether the formatter should log to file. * Set whether the formatter should log to file.
*/ */
@@ -158,14 +169,14 @@ public class FormatterElement {
throw new BuildException(e); throw new BuildException(e);
} }


f.setOutput(out);

// wrap filters in the reverse order: first = top, last = bottom. // wrap filters in the reverse order: first = top, last = bottom.
for (int i = filters.size() - 1; i >= 0; i--) { for (int i = filters.size() - 1; i >= 0; i--) {
FilterElement fe = (FilterElement) filters.elementAt(i); FilterElement fe = (FilterElement) filters.elementAt(i);
f = fe.createFilterFormatter(f); f = fe.createFilterFormatter(f);
} }

// it is assumed here that the filters are chaining til the
// wrapped formatter.
f.init(params);
return f; return f;
} }


@@ -173,7 +184,7 @@ public class FormatterElement {
* <p> Enumerated attribute with the values "plain", "xml" and "brief". * <p> Enumerated attribute with the values "plain", "xml" and "brief".
* <p> Use to enumerate options for <tt>type</tt> attribute. * <p> Use to enumerate options for <tt>type</tt> attribute.
*/ */
public static class TypeAttribute extends EnumeratedAttribute {
public final static class TypeAttribute extends EnumeratedAttribute {
private final static String[] VALUES = {"plain", "xml", "brief"}; private final static String[] VALUES = {"plain", "xml", "brief"};
private final static String[] CLASSNAMES = {"xxx", XMLFormatter.class.getName(), BriefFormatter.class.getName()}; private final static String[] CLASSNAMES = {"xxx", XMLFormatter.class.getName(), BriefFormatter.class.getName()};


@@ -186,5 +197,26 @@ public class FormatterElement {
} }
} }


/** a parameter that be used to configure a formatter */
public final static class Parameter {
private String name;
private String value;

public void setName(String name) {
this.name = name;
}

public void setValue(String value) {
this.value = value;
}

public String getName() {
return this.name;
}

public String getValue() {
return this.value;
}
}
} }



+ 58
- 168
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/JUnitTask.java View File

@@ -53,29 +53,10 @@
*/ */
package org.apache.tools.ant.taskdefs.optional.junit; package org.apache.tools.ant.taskdefs.optional.junit;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import junit.runner.TestCollector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.LogStreamHandler;
import org.apache.tools.ant.taskdefs.optional.junit.formatter.Formatter;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.FileUtils;
import org.apache.avalon.excalibur.i18n.ResourceManager; import org.apache.avalon.excalibur.i18n.ResourceManager;
import org.apache.avalon.excalibur.i18n.Resources; import org.apache.avalon.excalibur.i18n.Resources;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;


/** /**
* The core JUnit task. * The core JUnit task.
@@ -85,7 +66,7 @@ import org.apache.avalon.excalibur.i18n.Resources;
public class JUnitTask extends Task { public class JUnitTask extends Task {


private final static Resources RES = private final static Resources RES =
ResourceManager.getPackageResources( JUnitTask.class );
ResourceManager.getPackageResources(JUnitTask.class);


/** port to run the server on */ /** port to run the server on */
private int port = -1; private int port = -1;
@@ -93,96 +74,48 @@ public class JUnitTask extends Task {
/** timeout period in ms */ /** timeout period in ms */
private long timeout = -1; private long timeout = -1;


/** formatters that write the tests results */
private Vector formatters = new Vector();
/** client configuraiton element */
private ClientElement client = null;


/** test collector elements */
private Vector testCollectors = new Vector();

/** stop the test run if a failure occurs */
private boolean haltOnFailure = false;

/** stop the test run if an error occurs */
private boolean haltOnError = false;

/** the command line to launch the TestRunner */
private CommandlineJava cmd = new CommandlineJava();
/** server configuration element */
private ServerElement server = null;


// task implementation // task implementation


public void execute() throws BuildException { public void execute() throws BuildException {
File tmp = configureTestRunner();
Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN));
execute.setCommandline(cmd.getCommandline());
execute.setAntRun(project);

log(RES.getString("task.process-cmdline.log", cmd.toString()), Project.MSG_VERBOSE);
int retVal;
try {
retVal = execute.execute();
} catch (IOException e) {
String msg = RES.getString("task.process-failed.error");
throw new BuildException(msg, e, location);
} finally {
tmp.delete();
if (client == null && server == null) {
throw new BuildException("Invalid state: need to be server, client or both");
} }


}

/**
* Configure the runner with the appropriate configuration file.
* @return the reference to the temporary configuration file
* to be deleted once the TestRunner has ended.
*/
public File configureTestRunner() {
Properties props = new Properties();
props.setProperty("debug", "true");
props.setProperty("host", "127.0.0.1");
props.setProperty("port", String.valueOf(port));
// get all test classes to run...
StringBuffer buf = new StringBuffer(10240);
Enumeration classnames = collectTests();
while (classnames.hasMoreElements()) {
String classname = (String) classnames.nextElement();
buf.append(classname).append(" ");
}
props.setProperty("classnames", buf.toString());

// dump the properties to a temporary file.
FileUtils futils = FileUtils.newFileUtils();
File f = futils.createTempFile("junit-antrunner", "tmp", new File("."));
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(f));
props.store(os, "JUnit Ant Runner configuration file");
} catch (IOException e) {
throw new BuildException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
// 1) server and client
if (server != null && client != null) {
ServerWorker worker = new ServerWorker();
worker.start();
client.execute();
Exception caught = null;
try {
worker.join();
caught = worker.getException();
} catch (InterruptedException e){
caught = e;
}
if (caught != null){
throw new BuildException(caught);
} }
return;
} }


// configure the runner
cmd.createArgument().setValue("-file");
cmd.createArgument().setValue(f.getAbsolutePath());

return f;
}
// 2) server only (waiting for client)
if (server != null && client == null) {
server.execute();
return;
}


/**
* @return all collected tests specified with test elements.
*/
protected Enumeration collectTests() {
Enumeration[] tests = new Enumeration[testCollectors.size()];
for (int i = 0; i < testCollectors.size(); i++) {
TestCollector te = (TestCollector) testCollectors.elementAt(i);
tests[i] = te.collectTests();
// 3) client only (connecting to server)
if (server == null && client != null) {
client.execute();
return;
} }
return Enumerations.fromCompound(tests);
} }


// Ant bean accessors // Ant bean accessors
@@ -195,86 +128,43 @@ public class JUnitTask extends Task {
this.timeout = timeout; this.timeout = timeout;
} }


public void setHaltOnFailure(boolean haltOnFailure) {
this.haltOnFailure = haltOnFailure;
}

public void setHaltOnError(boolean haltOnError) {
this.haltOnError = haltOnError;
}

/** add a new formatter element */
public void addFormatter(FormatterElement fe) {
Formatter f = fe.createFormatter();
this.formatters.addElement(f);
}

/** add a single test element */
public void addTest(TestElement te) {
this.testCollectors.addElement(te);
}

/** add a batch test element */
public void addBatchTest(BatchTestElement bte) {
this.testCollectors.addElement(bte);
}

/** /**
* Set the maximum memory to be used by the TestRunner
* @param max the value as defined by <tt>-mx</tt> or <tt>-Xmx</tt>
* in the java command line options.
* create a new client in charge of running tests and sending
* the results to the server that collect them.
*/ */
public void setMaxmemory(String max) {
if (Project.getJavaVersion().startsWith("1.1")) {
createJvmarg().setValue("-mx" + max);
} else {
createJvmarg().setValue("-Xmx" + max);
public ClientElement createClient() {
if (client == null) {
client = new ClientElement(this);
} }
return client;
} }


/** /**
* 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.
* create a new client in charge of running tests and sending
* the results to the server that collect them.
*/ */
public Commandline.Argument createJvmarg() {
return cmd.createVmArgument();
public ServerElement createServer() {
if (server == null) {
server = new ServerElement(this);
}
return server;
} }


/**
* <tt>&lt;classpath&gt;</tt> allows classpath to be set for tests.
*/
public Path createClasspath() {
return cmd.createClasspath(project).createPath();
}


/**
* Creates a new JUnitRunner and enables fork of a new Java VM.
*/
public JUnitTask() throws Exception {
cmd.setClassname("org.apache.tools.ant.taskdefs.optional.junit.remote.TestRunner");
}
/** the worker to run the server on */
class ServerWorker extends Thread {
private Exception caught = null;


/**
* 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 init() {
addClasspathEntry("/junit/framework/TestCase.class");
addClasspathEntry("/org/apache/tools/ant/Task.class");
addClasspathEntry("/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunner.class");
}
public void run() {
try {
server.execute();
} catch (Exception e) {
caught = e;
}
}


/**
* Add the directory or archive containing the resource to
* the command line classpath.
* @param the resource to look for.
*/
protected void addClasspathEntry(String resource) {
File f = JUnitHelper.getResourceEntry(resource);
if (f != null) {
createClasspath().setLocation(f);
public Exception getException() {
return caught;
} }
} }
} }

+ 1
- 1
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/OutputAttribute.java View File

@@ -82,7 +82,7 @@ public class OutputAttribute extends ProjectComponent {
public final static String STDERR = "stderr"; public final static String STDERR = "stderr";


/** the selected value for output, either stdout,stderr or filepath */ /** the selected value for output, either stdout,stderr or filepath */
protected String value;
private String value;


/** /**
* Create a new output attribute from a value. * Create a new output attribute from a value.


+ 131
- 0
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/ServerElement.java View File

@@ -0,0 +1,131 @@
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.ant.taskdefs.optional.junit;

import java.util.Enumeration;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.ProjectComponent;
import org.apache.tools.ant.taskdefs.optional.junit.formatter.Formatter;
import org.apache.tools.ant.taskdefs.optional.junit.remote.Server;

/**
* An element representing the server configuration.
*
* <pre>
* <!ELEMENT server (formatter)*>
* <!ATTLIST server port numeric 6666>
* <!ATTLIST server haltonfailure (yes|no) no>
* <!ATTLIST server haltonerror (yes|no) no>
* </pre>
*
* @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
*/
public final class ServerElement extends ProjectComponent {

/** formatters that write the tests results */
private Vector formatters = new Vector();

/** port to run the server on. Default to 6666 */
private int port = 6666;

/** stop the client run if a failure occurs */
private boolean haltOnFailure = false;

/** stop the client run if an error occurs */
private boolean haltOnError = false;

/** the parent task */
private JUnitTask parent;

/** create a new server */
public ServerElement(JUnitTask value) {
parent = value;
}

/** start the server and block until client has finished */
public void execute() throws BuildException {
// configure the server...
Server server = new Server(port);
Enumeration listeners = formatters.elements();
while (listeners.hasMoreElements()) {
server.addListener((TestRunListener) listeners.nextElement());
}
// and run it. It will stop once a client has finished.
server.start();
}

/** set the port to listen to */
public void setPort(int value) {
port = value;
}

//@fixme logic problem here, should the server say to the client
// that there it should stop or should the client do it itself ?

public void setHaltOnFailure(boolean value) {
haltOnFailure = value;
}

public void setHaltOnError(boolean value) {
haltOnError = value;
}

/** add a new formatter element */
public void addFormatter(FormatterElement fe) {
Formatter f = fe.createFormatter();
formatters.addElement(f);
}
}

+ 3
- 32
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/BaseFormatter.java View File

@@ -53,13 +53,10 @@
*/ */
package org.apache.tools.ant.taskdefs.optional.junit.formatter; package org.apache.tools.ant.taskdefs.optional.junit.formatter;


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Properties; import java.util.Properties;


import org.apache.tools.ant.BuildException;

/** /**
* Provide a common set of attributes and methods to factorize * Provide a common set of attributes and methods to factorize
* *
@@ -67,9 +64,6 @@ import java.util.Properties;
*/ */
public abstract class BaseFormatter implements Formatter { public abstract class BaseFormatter implements Formatter {


/** writer to output the data to */
private PrintWriter writer;

/** number of errors */ /** number of errors */
private int errorCount; private int errorCount;


@@ -79,13 +73,7 @@ public abstract class BaseFormatter implements Formatter {
/** number of runs (success + failure + error) */ /** number of runs (success + failure + error) */
private int runCount; private int runCount;


public void setOutput(OutputStream value) {
try {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(value, "UTF8")), true);
} catch (IOException e) {
// should not happen
throw new IllegalStateException(e.getMessage());
}
public void init(Properties props) throws BuildException {
} }


protected void finalize() throws Throwable { protected void finalize() throws Throwable {
@@ -93,12 +81,6 @@ public abstract class BaseFormatter implements Formatter {
close(); close();
} }


public void setSystemOutput(String out) {
}

public void setSystemError(String err) {
}

public void onTestStdOutLine(String testname, String line) { public void onTestStdOutLine(String testname, String line) {
} }


@@ -138,13 +120,6 @@ public abstract class BaseFormatter implements Formatter {
close(); close();
} }


/**
* @return the writer used to print data.
*/
protected final PrintWriter getWriter() {
return writer;
}

/** @return the number of errors */ /** @return the number of errors */
protected final int getErrorCount() { protected final int getErrorCount() {
return errorCount; return errorCount;
@@ -162,9 +137,5 @@ public abstract class BaseFormatter implements Formatter {


/** helper method to flush and close the stream */ /** helper method to flush and close the stream */
protected void close() { protected void close() {
if (writer != null) {
writer.flush();
writer.close();
}
} }
} }

+ 131
- 0
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/BaseStreamFormatter.java View File

@@ -0,0 +1,131 @@
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.ant.taskdefs.optional.junit.formatter;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Properties;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.optional.junit.KeepAliveOutputStream;

/**
* Base formatter providing default implementation to deal with
* either stdout or a file.
* <p>
* The file is specified by initializing the formatter with
* a filepath mapped by the key 'file'.
* </p>
* <p>
* if no file key exists in the properties, it defaults to stdout.
* </p>
*
* @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
*/
public class BaseStreamFormatter extends BaseFormatter {

/** the key used to specifiy a filepath */
public final static String FILE_KEY = "file";

/** writer to output the data to */
private PrintWriter writer;

public void init(Properties props) throws BuildException {
String file = props.getProperty("file");
OutputStream os = null;
if (file != null) {
try {
// fixme need to resolve the file !!!!
os = new FileOutputStream(file);
} catch (IOException e) {
throw new BuildException(e);
}
} else {
os = new KeepAliveOutputStream(System.out);
}
setOutput(os);
}

/**
* Helper method to wrap the stream over an UTF8 buffered writer.
*/
protected void setOutput(OutputStream value) {
try {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(value, "UTF8")), true);
} catch (IOException e) {
// should not happen
throw new BuildException(e);
}
}


protected void close() {
if (writer != null) {
writer.flush();
writer.close();
}
}

/**
* @return the writer used to print data.
*/
protected final PrintWriter getWriter() {
return writer;
}

}

+ 2
- 4
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/BriefFormatter.java View File

@@ -53,10 +53,8 @@
*/ */
package org.apache.tools.ant.taskdefs.optional.junit.formatter; package org.apache.tools.ant.taskdefs.optional.junit.formatter;


import java.io.PrintWriter;

import org.apache.avalon.excalibur.i18n.Resources;
import org.apache.avalon.excalibur.i18n.ResourceManager; import org.apache.avalon.excalibur.i18n.ResourceManager;
import org.apache.avalon.excalibur.i18n.Resources;


/** /**
* Display additional messages from a <tt>SummaryFormatter</tt> * Display additional messages from a <tt>SummaryFormatter</tt>
@@ -67,7 +65,7 @@ import org.apache.avalon.excalibur.i18n.ResourceManager;
public class BriefFormatter extends SummaryFormatter { public class BriefFormatter extends SummaryFormatter {


private final static Resources RES = private final static Resources RES =
ResourceManager.getPackageResources( BriefFormatter.class );
ResourceManager.getPackageResources(BriefFormatter.class);


public void onTestFailed(int status, String testname, String trace) { public void onTestFailed(int status, String testname, String trace) {
String msg = null; String msg = null;


+ 18
- 14
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/FilterFormatter.java View File

@@ -53,9 +53,10 @@
*/ */
package org.apache.tools.ant.taskdefs.optional.junit.formatter; package org.apache.tools.ant.taskdefs.optional.junit.formatter;


import java.io.OutputStream;
import java.util.Properties; import java.util.Properties;


import org.apache.tools.ant.BuildException;

/** /**
* A base class that can be used to filter data. * A base class that can be used to filter data.
* *
@@ -63,14 +64,15 @@ import java.util.Properties;
*/ */
public abstract class FilterFormatter implements Formatter { public abstract class FilterFormatter implements Formatter {


protected Formatter formatter;
private Formatter formatter;


protected FilterFormatter(Formatter value) {
formatter = value;
protected FilterFormatter(Formatter formatter) {
setFormatter(formatter);
} }


public void setOutput(OutputStream out) {
formatter.setOutput(out);
/** final to enforce chaining of initialization */
public final void init(Properties props) throws BuildException {
formatter.init(props);
} }


public void onTestStdOutLine(String testname, String line) { public void onTestStdOutLine(String testname, String line) {
@@ -85,18 +87,10 @@ public abstract class FilterFormatter implements Formatter {
formatter.onTestStarted(testname); formatter.onTestStarted(testname);
} }


public void setSystemOutput(String out) {
formatter.setSystemOutput(out);
}

public void onTestEnded(String testname) { public void onTestEnded(String testname) {
formatter.onTestEnded(testname); formatter.onTestEnded(testname);
} }


public void setSystemError(String err) {
formatter.setSystemError(err);
}

public void onTestFailed(int status, String testname, String trace) { public void onTestFailed(int status, String testname, String trace) {
formatter.onTestFailed(status, testname, trace); formatter.onTestFailed(status, testname, trace);
} }
@@ -116,4 +110,14 @@ public abstract class FilterFormatter implements Formatter {
public void onTestRunStopped(long elapsedtime) { public void onTestRunStopped(long elapsedtime) {
formatter.onTestRunEnded(elapsedtime); formatter.onTestRunEnded(elapsedtime);
} }

/** set the wrapped formatter */
protected void setFormatter(Formatter value) {
formatter = value;
}

/** return the wrapped formatter */
protected Formatter getFormatter() {
return formatter;
}
} }

+ 7
- 13
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/Formatter.java View File

@@ -53,28 +53,22 @@
*/ */
package org.apache.tools.ant.taskdefs.optional.junit.formatter; package org.apache.tools.ant.taskdefs.optional.junit.formatter;


import java.io.OutputStream;
import java.util.Properties;


import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.optional.junit.TestRunListener; import org.apache.tools.ant.taskdefs.optional.junit.TestRunListener;


/** /**
* The formatter interface.
* *
* @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a> * @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
*/ */
public interface Formatter extends TestRunListener { public interface Formatter extends TestRunListener {
/** /**
* Sets the stream the formatter is supposed to write its results to.
* Initialize the formatter with some custom properties
* For example it could be a filename, a port and hostname,
* a database, etc...
*/ */
public void setOutput(OutputStream out);

/**
* This is what the test has written to System.out
*/
public void setSystemOutput(String out);

/**
* This is what the test has written to System.err
*/
public void setSystemError(String err);
public void init(Properties props) throws BuildException;


} }

+ 99
- 0
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/PlainFormatter.java View File

@@ -0,0 +1,99 @@
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Ant", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.tools.ant.taskdefs.optional.junit.formatter;

import java.util.Properties;

/**
* Default formatter to text.
*
* @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
*/
public class PlainFormatter extends BaseStreamFormatter {

public void onTestStarted(String testname) {
getWriter().println("Started " + testname);
}

public void onTestEnded(String testname) {
getWriter().println("Ended " + testname);
}

public void onTestFailed(int status, String testname, String trace) {
getWriter().println(testname + " failed with status " + status);
getWriter().println(trace);
}

public void onTestRunSystemProperties(Properties props) {
getWriter().println("properties: " + props);
}

public void onTestRunStarted(int testcount) {
getWriter().println("testsuite: " + testcount);
}

public void onTestStdOutLine(String testname, String line) {
}

public void onTestStdErrLine(String testname, String line) {
}

public void onTestRunEnded(long elapsedtime) {
getWriter().println("testsuite ended after: " + elapsedtime);
}

public void onTestRunStopped(long elapsedtime) {
getWriter().println("testsuite stopped after: " + elapsedtime);
}
}

+ 4
- 7
proposal/sandbox/junit/src/main/org/apache/tools/ant/taskdefs/optional/junit/formatter/SummaryFormatter.java View File

@@ -53,11 +53,8 @@
*/ */
package org.apache.tools.ant.taskdefs.optional.junit.formatter; package org.apache.tools.ant.taskdefs.optional.junit.formatter;


import java.io.PrintWriter;
import java.text.MessageFormat;

import org.apache.avalon.excalibur.i18n.Resources;
import org.apache.avalon.excalibur.i18n.ResourceManager; import org.apache.avalon.excalibur.i18n.ResourceManager;
import org.apache.avalon.excalibur.i18n.Resources;


/** /**
* Display a summary message at the end of a testsuite stating * Display a summary message at the end of a testsuite stating
@@ -65,17 +62,17 @@ import org.apache.avalon.excalibur.i18n.ResourceManager;
* *
* @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a> * @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
*/ */
public class SummaryFormatter extends BaseFormatter {
public class SummaryFormatter extends BaseStreamFormatter {


private final static Resources RES = private final static Resources RES =
ResourceManager.getPackageResources( SummaryFormatter.class );
ResourceManager.getPackageResources(SummaryFormatter.class);


protected void finished(long elapsedtime) { protected void finished(long elapsedtime) {
String msg = RES.getString("summary.finished.msg", String msg = RES.getString("summary.finished.msg",
new Integer(getRunCount()), new Integer(getRunCount()),
new Integer(getFailureCount()), new Integer(getFailureCount()),
new Integer(getErrorCount()), new Integer(getErrorCount()),
new Long(elapsedtime / 1000) );
new Long(elapsedtime / 1000));
getWriter().println(msg); getWriter().println(msg);
close(); close();
} }


Loading…
Cancel
Save