You are viewing a plain text version of this content. The canonical link for it is here.
Posted to xmlbeans-cvs@xml.apache.org by da...@apache.org on 2004/07/17 00:09:46 UTC
cvs commit: xml-xmlbeans/v2/test/tools/src/tools/JUnit JUnitXRunner.java JUnitXTask.java XmlResultFormatterImpl.java
daveremy 2004/07/16 15:09:46
Modified: v2 testbuild.xml
v2/src/newstore2/org/apache/xmlbeans/impl/newstore2
CharUtil.java
v2/test/src/dom/detailed MultipleDocsTest.java
TextInsertDeleteTest.java
v2/test/tools/src/tools/JUnit JUnitXRunner.java
JUnitXTask.java XmlResultFormatterImpl.java
Log:
Contributed by: Yana Kadiyska. Fixing verbose output. Speeding up detailed tests
Revision Changes Path
1.21 +13 -4 xml-xmlbeans/v2/testbuild.xml
Index: testbuild.xml
===================================================================
RCS file: /home/cvs/xml-xmlbeans/v2/testbuild.xml,v
retrieving revision 1.20
retrieving revision 1.21
diff -u -r1.20 -r1.21
--- testbuild.xml 13 Jul 2004 20:48:55 -0000 1.20
+++ testbuild.xml 16 Jul 2004 22:09:46 -0000 1.21
@@ -226,7 +226,8 @@
${build.dir.test.schemas}/xbean/xmlobject,
${build.dir.test.schemas}/xbean/xmlobject/store,
${build.dir.test.schemas}/xbean/xmltokensource,
- ${build.dir.test.schemas}/xbean/ValidatingStream"/>
+ ${build.dir.test.schemas}/xbean/ValidatingStream,
+ ${build.dir.test.schemas}/xbean/scomp"/>
<!-- comma separated list of directories containing schemas that *must* be separately
compiled -->
<property name="schema.standalone"
@@ -546,9 +547,10 @@
<!-- =============================================================== -->
<!-- START: Incremental build targets -->
- <property name="area.names" value="compile, dom, misc, random,
+ <property name="area.names" value="compile, dom, misc, random,
ValidatingXSRTests,xmlcursor, xmlobject,
- xmltokensource, checkin"/>
+ xmltokensource, checkin,
+ scomp"/>
<target name="list.areas" description="List areas for -Dtest.area param">
<echo message="${area.names}"/>
@@ -748,7 +750,14 @@
<antcall target="unit.build"/>
</target>
-
+ <target name="build.area.scomp" depends="clean.tests">
+ <property name="includes.for.compile"
+ value="**/scomp/**/*.java"/>
+ <property name="this.schema.dirs"
+ value="${build.dir.test.schemas}/xbean/scomp"/>
+ <property name="testcasejar.update" value="true"/>
+ <antcall target="unit.build"/>
+ </target>
<!-- FREQ Target -->
<target name="build.area.checkin" depends="clean.tests,extensions.build">
<property name="includes.for.compile"
1.12 +2 -2 xml-xmlbeans/v2/src/newstore2/org/apache/xmlbeans/impl/newstore2/CharUtil.java
Index: CharUtil.java
===================================================================
RCS file: /home/cvs/xml-xmlbeans/v2/src/newstore2/org/apache/xmlbeans/impl/newstore2/CharUtil.java,v
retrieving revision 1.11
retrieving revision 1.12
diff -u -r1.11 -r1.12
--- CharUtil.java 24 Jun 2004 17:49:37 -0000 1.11
+++ CharUtil.java 16 Jul 2004 22:09:46 -0000 1.12
@@ -834,8 +834,8 @@
private static ThreadLocal tl_charIter =
new ThreadLocal() { protected Object initialValue() { return new CharIterator(); } };
- private static final int MAX_COPY = 8;
-// private static final int MAX_COPY = 64;
+ // private static final int MAX_COPY = 8;
+ private static final int MAX_COPY = 64;
// Current char buffer we're allcoating new chars to
1.3 +157 -111 xml-xmlbeans/v2/test/src/dom/detailed/MultipleDocsTest.java
Index: MultipleDocsTest.java
===================================================================
RCS file: /home/cvs/xml-xmlbeans/v2/test/src/dom/detailed/MultipleDocsTest.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- MultipleDocsTest.java 17 Jun 2004 16:26:45 -0000 1.2
+++ MultipleDocsTest.java 16 Jul 2004 22:09:46 -0000 1.3
@@ -25,133 +25,179 @@
*
*
*/
-public class MultipleDocsTest extends TestCase{
- String[] sXml=new String[]{"<foo0/>",
- "<foo1 foo1_at=\"val0\"/>",
- "<foo2 foo2_at=\"val0\">text</foo2>",
- "<foo3 foo3_at=\"val0\">text <foo2 foo2_at=\"val0\">text</foo2> </foo3>",
- "<foo4 xmlns:myns=\"foo.org\" myns:foo3_at=\"val0\">text <foo2 foo2_at=\"val0\">text</foo2> </foo4>",
- "<foo5 xmlns:myns=\"foo_OUT.org\"><myns:foo4 xmlns:myns=\"foo.org\" myns:foo3_at=\"val0\">text <foo2 foo2_at=\"val0\">text</foo2> </myns:foo4></foo5>"
+public class MultipleDocsTest extends TestCase {
+ String[] sXml = new String[]{"<foo0/>",
+ "<foo1 foo1_at=\"val0\"/>",
+ "<foo2 foo2_at=\"val0\">text</foo2>",
+ "<foo3 foo3_at=\"val0\">text <foo2 foo2_at=\"val0\">text</foo2> </foo3>",
+ "<foo4 xmlns:myns=\"foo.org\" myns:foo3_at=\"val0\">text <foo2 foo2_at=\"val0\">text</foo2> </foo4>",
+ "<foo5 xmlns:myns=\"foo_OUT.org\"><myns:foo4 xmlns:myns=\"foo.org\" myns:foo3_at=\"val0\">text <foo2 foo2_at=\"val0\">text</foo2> </myns:foo4></foo5>"
};
Thread[] threads;
- int nThreadCount=6;
- int nIterations=300;
+ int nThreadCount = 6;
+ int nIterations = 100;
Document[] m_doc;
- public MultipleDocsTest(String name){
- super(name);
+ public MultipleDocsTest(String name) {
+ super(name);
}
- public void testRunThreads(){
- for (int j=0;j<nThreadCount;j++)
- threads[j].start();
- for (int j = 0; j < nThreadCount; j++){
- try{
- threads[j].join();
- }
- catch (InterruptedException e){
- System.err.println("Thread "+j+" interrupted");
- }
- }
- }
+ public void testRunThreads() {
+
+ for (int j = 0; j < nThreadCount; j++)
+ threads[j].start();
+
+ for (int j = 0; j < nThreadCount; j++) {
+ try {
+ threads[j].join();
+ }
+ catch (InterruptedException e) {
+ System.err.println("Thread " + j + " interrupted");
+
+ }
- public void setUp() throws Exception{
- threads=new Thread[nThreadCount];
- for (int i=0;i<nThreadCount;i++){
- Loader loader=Loader.getLoader();
- if (sXml==null) throw new IllegalArgumentException("Test bug : Initialize xml strings");
- Document m_doc=(org.w3c.dom.Document)loader.load(sXml[i]);
- threads[i] = new Thread(new Worker(i,m_doc,nIterations));
- }
+ }
}
+ public void setUp() throws Exception {
+ threads = new Thread[nThreadCount];
+ for (int i = 0; i < nThreadCount; i++) {
+ Loader loader = Loader.getLoader();
+ if (sXml == null)
+ throw new IllegalArgumentException(
+ "Test bug : Initialize xml strings");
+ Document m_doc = (org.w3c.dom.Document) loader.load(sXml[i]);
+ threads[i] = new Thread(new Worker(i, m_doc, nIterations));
+ }
+ }
+
+ public void tearDown() throws Exception {
- private class Worker extends Thread{
- int _ID;
- Document doc;
- int nIter;
- public Worker(int ID,Document doc,int nIter){
- this._ID=ID;
- this.doc=doc;
- this.nIter=nIter;
- }
-
- public void run(){
- System.err.println("*** Thread "+_ID+" starting "+doc.getDocumentElement().getNodeName()+" "+nIter);
- for ( int i = 0 ; i < nIter ; i++ ){
- //System.err.println("*** Thread "+_ID+" starting ");
- switch (0){//_ID
-
- case 0:{
- doc.getDocumentElement().appendChild(doc.createElement("foobar"));
- if ( i % 5==0 ){
- NodeList nl=doc.getDocumentElement().getElementsByTagName("foobar");
- if (nl.getLength()>0){
- Element par=(Element)nl.item(0).getParentNode();
- par.removeChild((Element)nl.item(0));
- }
- }
- // break;
- }case 1:{
- ((Element)doc.getDocumentElement()).setAttributeNode(doc.createAttribute("foobar"));
- if ( i % 5==0 ){
- NamedNodeMap nl=doc.getDocumentElement().getAttributes();
- if (nl.getLength()>0){
- Element par=(Element)((Attr)nl.getNamedItem("foobar")).getOwnerElement();
- par.removeAttribute("foobar");
- }
- }
- // break;
- }case 2:{
- doc.getDocumentElement().appendChild(doc.createTextNode("foobar"));
- if ( i % 5==0 ){
- NodeList nl=((Element)doc.getDocumentElement()).getElementsByTagName("foobar");
- if (nl!=null && nl.getLength()>0){
- Element par=(Element)nl.item(i % nl.getLength()).getParentNode();
- par.removeChild((Element)nl.item(0));
- }
- }
- // break;
-
- }case 3:{
- Node n=doc.getDocumentElement().getFirstChild();
- if (n!=null && (n instanceof Text) ){
- ((Text)n).setData("newText");
- if ( i % 5==0 ){
- int len;
- if ( ( len=((Text)n).getData().length() )>0)
- ((Text)n).splitText(len/2);
- }
- }
- // break;
- }case 4:{
- // System.err.println("*** Thread "+_ID+" case 4 ");
- NodeList n=((Element)doc.getDocumentElement()).getElementsByTagNameNS("foo:org","myns:foo2");
- Attr at=doc.createAttribute("foo2_at");
- if (n!=null && n.getLength()>0){
- ((Element)n.item(0)).setAttributeNode(at);
- if ( i % 5==0 ){
- ((Element)n.item(0)).removeAttributeNode(at);
- }
- }
- }
+ }
- }
+ private class Worker extends Thread {
+ int _ID;
+ Document doc;
+ int nIter;
+
+ public Worker(int ID, Document doc, int nIter) {
+ this._ID = ID;
+ this.doc = doc;
+ this.nIter = nIter;
+ }
+
+ public void run() {
+ System.err.println("*** Thread " + _ID + " starting " +
+ doc.getDocumentElement().getNodeName() +
+ " " +
+ nIter);
+ try {
+ for (int i = 0; i < nIter; i++) {
+ // System.err.println("*** Thread "+_ID+" starting "+nIter+" "+i);
+ switch (0) {//_ID
+
+ case 0:
+ {
+ doc.getDocumentElement().appendChild(
+ doc.createElement("foobar"));
+ if (i % 5 == 0) {
+ NodeList nl = doc.getDocumentElement()
+ .getElementsByTagName("foobar");
+ if (nl.getLength() > 0) {
+ Element par = (Element) nl.item(0)
+ .getParentNode();
+ par.removeChild((Element) nl.item(0));
+ }
+ }
+ // break;
+ }
+ case 1:
+ {
+ ((Element) doc.getDocumentElement()).setAttributeNode(
+ doc.createAttribute("foobar"));
+ if (i % 5 == 0) {
+ NamedNodeMap nl = doc.getDocumentElement()
+ .getAttributes();
+ if (nl.getLength() > 0) {
+ Element par = (Element) ((Attr) nl.getNamedItem(
+ "foobar")).getOwnerElement();
+ par.removeAttribute("foobar");
+ }
+ }
+ // break;
+ }
+ case 2:
+ {
+ doc.getDocumentElement().appendChild(
+ doc.createTextNode("foobar"));
+ if (i % 5 == 0) {
+ NodeList nl = ((Element) doc.getDocumentElement()).getElementsByTagName(
+ "foobar");
+ if (nl != null && nl.getLength() > 0) {
+ Element par = (Element) nl.item(
+ i % nl.getLength())
+ .getParentNode();
+ par.removeChild((Element) nl.item(0));
+ }
+ }
+ // break;
+
+ }
+ case 3:
+ {
+ Node n = doc.getDocumentElement()
+ .getFirstChild();
+ if (n != null && (n instanceof Text)) {
+ ((Text) n).setData("newText");
+ if (i % 5 == 0) {
+ int len;
+ if ((len =
+ ((Text) n).getData().length()) >
+ 0)
+ ((Text) n).splitText(len / 2);
+ }
+ }
+ // break;
+ }
+ case 4:
+ {
+ // System.err.println("*** Thread "+_ID+" case 4 ");
+ NodeList n = ((Element) doc.getDocumentElement()).getElementsByTagNameNS(
+ "foo:org", "myns:foo2");
+ Attr at = doc.createAttribute("foo2_at");
+ if (n != null && n.getLength() > 0) {
+ ((Element) n.item(0)).setAttributeNode(at);
+ if (i % 5 == 0) {
+ ((Element) n.item(0)).removeAttributeNode(
+ at);
+ }
+ }
+ }
+
+ }
+
+ }
+
+ }
+ catch (Throwable t) {
+ System.err.println("Caught throwable");
+ // return;
- }
- }
+ }
+ }
}
- public static void main(String[] a){
- try{
- MultipleDocsTest test=new MultipleDocsTest("");
- test.setUp();
- test.testRunThreads();
- }catch (Throwable t){
- t.printStackTrace(System.err);
- }
+ public static void main(String[] a) {
+ try {
+ MultipleDocsTest test = new MultipleDocsTest("");
+ test.setUp();
+ test.testRunThreads();
+ }
+ catch (Throwable t) {
+ t.printStackTrace(System.err);
+ }
}
}
1.3 +2 -2 xml-xmlbeans/v2/test/src/dom/detailed/TextInsertDeleteTest.java
Index: TextInsertDeleteTest.java
===================================================================
RCS file: /home/cvs/xml-xmlbeans/v2/test/src/dom/detailed/TextInsertDeleteTest.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- TextInsertDeleteTest.java 17 Jun 2004 16:26:45 -0000 1.2
+++ TextInsertDeleteTest.java 16 Jul 2004 22:09:46 -0000 1.3
@@ -108,13 +108,13 @@
for (int i = 0; i < nNodeCnt; i++) {
((Text)ch.item(i++)).splitText(2);
}
-
+ System.out.println();
//delete all even entries;go fwd
for (int i = 0; i < nodes.length; i++) {
if (i % 2 == 0)
m_node.removeChild(nodes[i]);
}
-
+ System.out.println();
for (int i = 0; i < nNodeCnt / 2; i++) {
assertEquals("r" + 2 * i, ch.item(i).getNodeValue());
1.4 +3 -25 xml-xmlbeans/v2/test/tools/src/tools/JUnit/JUnitXRunner.java
Index: JUnitXRunner.java
===================================================================
RCS file: /home/cvs/xml-xmlbeans/v2/test/tools/src/tools/JUnit/JUnitXRunner.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- JUnitXRunner.java 13 Jul 2004 20:48:55 -0000 1.3
+++ JUnitXRunner.java 16 Jul 2004 22:09:46 -0000 1.4
@@ -18,37 +18,12 @@
implements JUnitXResultFormatter {
public static void main(String args[])
throws Exception {
- // TODO: A good clean way to pass arguments would be using something
- // like GetOpt, and make it flexible to change the order of the
- // arguments. right now we impose a rigid sequence on the arguments
-
- // TODO: allow specifying a single JUnit class to run.. would ideally
- // follow the above TODO.
File file = new File(args[0]);
String resListener = null;
String outFile = null;
boolean showOutput = false;
- /*if (args.length > 1)
- {
- if (args[1].equalsIgnoreCase("showoutput"))
- showOutput = true;
- else
- {
- resListener = args[1];
- if (args.length < 3)
- throw new RuntimeException("No output file specified");
- outFile = args[2];
- }
- }
- // do we have more?
- if (args.length > 3)
- {
- if (args[3].equalsIgnoreCase("showoutput"))
- showOutput = true;
- }
- */
Collection options=new TreeSet();
options.add(JUnitXTask.resultListener);
options.add(JUnitXTask.outFile);
@@ -91,7 +66,9 @@
} else
runner = new JUnitXRunner(files, showOutput);
+
int nFailureCount = runner.runTests();
+
System.exit(nFailureCount);
}
@@ -142,6 +119,7 @@
throw new RuntimeException("Unable to initialize output to file "
+ outFile + "\n" + fnfe.getMessage());
}
+
_listener.showTestOutput(showOutput);
_listener.startRun();
while (itr.hasNext()) {
1.4 +4 -2 xml-xmlbeans/v2/test/tools/src/tools/JUnit/JUnitXTask.java
Index: JUnitXTask.java
===================================================================
RCS file: /home/cvs/xml-xmlbeans/v2/test/tools/src/tools/JUnit/JUnitXTask.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- JUnitXTask.java 13 Jul 2004 20:48:55 -0000 1.3
+++ JUnitXTask.java 16 Jul 2004 22:09:46 -0000 1.4
@@ -161,8 +161,10 @@
super.createArg().setValue("-"+outFile);
super.createArg().setValue(this.reportFile);
}
- if (showOutput)
- super.createArg().setValue("showoutput");
+ if (showOutput){
+ super.createArg().setValue("-showoutput");
+ super.createArg().setValue(new Boolean(this.showOutput).toString());
+ }
super.execute();
}
1.3 +1 -492 xml-xmlbeans/v2/test/tools/src/tools/JUnit/XmlResultFormatterImpl.java
Index: XmlResultFormatterImpl.java
===================================================================
RCS file: /home/cvs/xml-xmlbeans/v2/test/tools/src/tools/JUnit/XmlResultFormatterImpl.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- XmlResultFormatterImpl.java 9 Jun 2004 02:29:46 -0000 1.2
+++ XmlResultFormatterImpl.java 16 Jul 2004 22:09:46 -0000 1.3
@@ -1,492 +1 @@
-package tools.JUnit;
-
-import java.util.*;
-import java.io.*;
-import java.text.SimpleDateFormat;
-
-import junit.framework.Test;
-import junit.framework.AssertionFailedError;
-import junit.framework.TestCase;
-
-import noNamespace.TestResultContainerDocument.TestResultContainer;
-import noNamespace.*;
-import noNamespace.TestResultType.ExecutionOutput;
-import org.apache.xmlbeans.XmlOptions;
-import tools.io.TeeOutputStream;
-import org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner;
-
-/**
- * Implementation of JUnitXResultFormatter that records JUnit results
- * and publishes the result as a XML Document
- */
-
-public class XmlResultFormatterImpl implements JUnitXResultFormatter
-{
- public static int TEST_SUCCESS = 0;
- public static int TEST_FAILURE = 1;
- public static int TEST_ERROR = 2;
- public static int TEST_UNKNOWN = 3;
-
- // Lets capture STDOUT and STDERR
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- ByteArrayOutputStream bErr = new ByteArrayOutputStream();
-
- TeeOutputStream tOut;
- TeeOutputStream tErr;
-
- PrintStream _out;
- PrintStream _err;
- private TestRecord testRecord;
- Collection records;
-
- // By default write to StdOut
- OutputStream logOut = System.out;
- // Record Stats
- int testCount = 0;
- int passCount = 0;
- int failCount = 0;
- long startTime = 0;
- boolean showOutput = false;
-
- public void startRun()
- {
- records = new ArrayList();
- // Reset stats
- testCount = 0;
- passCount = 0;
- failCount = 0;
- startTime = System.currentTimeMillis();
- System.out.println("Starting Test run");
- }
-
- public void endRun()
- {
- System.out.println("=================================================");
- System.out.println("Tests Ran: " + testCount);
- System.out.println("Success: " + passCount);
- System.out.println("Failures: " + failCount);
-
- // Generate log:
- System.out.println("Starting Publish: " + System.currentTimeMillis());
- publishResults();
- System.out.println("Finished Publish: " + System.currentTimeMillis());
- }
-
- public void setOutput(OutputStream out)
- {
- if (out != null)
- logOut = out;
- }
-
- public void showTestOutput(boolean show)
- {
- showOutput = show;
- }
-
- public void info(Object msg)
- {
- if (showOutput)
- System.out.println(msg);
- }
-
-
- /*
- * Implementation of TestListener
- */
- public synchronized void startTest(Test test)
- {
- String fullTestName = test.toString();
- info("Starting Test: " + fullTestName);
- // Lets start the capture
- System.out.flush();
- System.err.flush();
-
- _out = System.out;
- _err = System.err;
- bOut.reset();
- bErr.reset();
-
- // Redirect Stdout & Stderr to both console and our capture stream
- if (showOutput)
- {
- tOut = new TeeOutputStream(_out, bOut);
- tErr = new TeeOutputStream(_err, bErr);
- System.setOut(new PrintStream(tOut));
- System.setErr(new PrintStream(tErr));
- }
- else
- {
- System.setOut(new PrintStream(bOut));
- System.setErr(new PrintStream(bErr));
- }
-
- // Discard the previous record
- testRecord = new TestRecord(fullTestName);
- testRecord.setStartTime(System.currentTimeMillis());
- }
-
- public synchronized void endTest(Test test)
- {
- long endTime = System.currentTimeMillis();
-
- System.out.flush();
- System.err.flush();
- // Update the test record
- testRecord.setSysout(bOut.toString());
- testRecord.setSyserr(bErr.toString());
- testRecord.setEndTime(endTime);
-
-
- // this is a little hack for our reporting..
- // We could be on shaky ground if the behaviour of the JUnit task
- // ever changes.. OH Well...
- String fullTestName = test.toString();
- // Test-unit is between '(' and ')'
- int startindex = fullTestName.indexOf("(");
- int lastindex = fullTestName.indexOf(")");
- String testUnit;
- if (startindex >= 0 && lastindex > startindex)
- testUnit = fullTestName.substring(startindex+1, lastindex);
- else
- testUnit = fullTestName;
- String testMethod = ((TestCase) test).getName();
- // Get the last token from testUnit for the logical name
- startindex = testUnit.lastIndexOf(".");
- String baseClass = testUnit.substring(startindex+1);
-
- // update the extra fields of TestRecord
- testRecord.setTestUnitName(testUnit);
- testRecord.setTestLogicalName(baseClass + "." + testMethod);
-
- // If the test did not fail, record it as a success
- if (!testRecord.isFailure())
- {
- testRecord.setStatus(TEST_SUCCESS);
- passCount++;
- }
- else
- failCount++;
-
- testCount++;
-
- // Add it to the set
- records.add(testRecord);
- // set testRecord to null..
-
- // Restore STDOUT and STDERR
- System.setOut(_out);
- System.setErr(_err);
-
- info("Finished Test: " + fullTestName + " "
- + testRecord.getStatusString() + "\n");
- // Reset TestRecord
- testRecord = null;
- }
-
- public synchronized void addError(final Test test, final Throwable t)
- {
- if (testRecord == null)
- testRecord = getMissingTestRecord();
- testRecord.setStatus(TEST_ERROR);
- testRecord.setThrowable(t);
- // Special case when test class is missing...
- if (t.toString().indexOf("ClassNotFoundException") > -1)
- {
- records.add(testRecord);
- testRecord = null;
- }
- }
-
- public synchronized void addFailure(final Test test, final AssertionFailedError t)
- {
- if (testRecord == null)
- testRecord = getMissingTestRecord();
- testRecord.setStatus(TEST_FAILURE);
- testRecord.setThrowable(t);
- }
-
- /**
- * Utility class to record per test data like test name, status, start
- * and end time, STDOUT, STDERR from text execution etc.
- */
- private class TestRecord
- {
- public TestRecord(String name)
- {
- setTestname(name);
- }
-
- private String testname;
- private String sysout;
- private String syserr;
- private Throwable t;
- private long startTime;
- private long endTime;
- private int status;
- boolean failed = false;
-
- private String testUnitName;
- private String testLogicalName;
-
- public void setTestname(String name)
- {
- this.testname = name;
- }
-
- public String getTestname()
- {
- return testname;
- }
-
- public void setStatus(int status)
- {
- this.status = status;
- if (status == TEST_ERROR || status == TEST_FAILURE)
- failed = true;
- }
-
- public int getStatus()
- {
- return status;
- }
-
- public String getStatusString()
- {
- return (status == TEST_SUCCESS)?"SUCCESS":
- (status == TEST_ERROR)?"ERROR":"FAILURE";
- }
-
- public boolean isFailure()
- {
- return failed;
- }
-
- public String getSysout()
- {
- return sysout;
- }
-
- public void setSysout(String sysout)
- {
- this.sysout = sysout;
- }
-
- public String getSyserr()
- {
- return syserr;
- }
-
- public void setSyserr(String syserr)
- {
- this.syserr = syserr;
- }
-
- public Throwable getThrowable()
- {
- return t;
- }
-
- public void setThrowable(Throwable t)
- {
- this.t = t;
- }
-
- public long getStartTime()
- {
- return startTime;
- }
-
- public void setStartTime(long startTime)
- {
- this.startTime = startTime;
- }
-
- public long getEndTime()
- {
- return endTime;
- }
-
- public void setEndTime(long endTime)
- {
- this.endTime = endTime;
- }
-
- public String getTestUnitName()
- {
- return testUnitName;
- }
-
- public void setTestUnitName(String testUnitName)
- {
- this.testUnitName = testUnitName;
- }
-
- public String getTestLogicalName()
- {
- return testLogicalName;
- }
-
- public void setTestLogicalName(String testLogicalName)
- {
- this.testLogicalName = testLogicalName;
- }
-
- }
-
- private TestRecord getMissingTestRecord()
- {
- TestRecord tr = new TestRecord("Missing");
- tr.setStartTime(System.currentTimeMillis());
- tr.setEndTime(System.currentTimeMillis());
- tr.setStatus(TEST_ERROR);
- tr.setTestLogicalName("Missing");
- tr.setTestUnitName("Missing");
- return tr;
- }
-
- public void publishResults()
- {
- TestLogDocument logDoc = TestLogDocument.Factory.newInstance();
- TestLogDocument.TestLog log = logDoc.addNewTestLog();
-
- // Populate the attributes for test-log
- // testtype
- String testtype = System.getProperty("TESTTYPE", "AUTO");
- if (testtype.equalsIgnoreCase("AUTO"))
- log.setTesttype(TestLogDocument.TestLog.Testtype.AUTOMATED);
- else
- log.setTesttype(TestLogDocument.TestLog.Testtype.MANUAL);
-
- // runid
- String dateFormatStr = "_yy_MMM_dd_HH_mm_ss_SS";
- String dateStr = new SimpleDateFormat(dateFormatStr).format(new Date(startTime));
- String defRunId = System.getProperty("user.name").toUpperCase() + dateStr;
- String runId = System.getProperty("RUNID", defRunId);
- log.setRunid(runId);
- // hostname
- String hostname;
- try
- {
- hostname = java.net.InetAddress.getLocalHost().getHostName();
- } catch (Exception e)
- {
- // Ignore.. not critical
- hostname = "UNKNOWN_HOST";
- }
- log.setHostname(hostname);
- // TODO: set Defaults/check sysprop for other attributes
-
- // Add <environment> element
- EnvironmentType env = log.addNewEnvironment();
- Map envMap = new HashMap();
- envMap.put("JVM_NAME", System.getProperty("java.vm.name"));
- envMap.put("JVM_VENDOR", System.getProperty("java.vm.vendor"));
- envMap.put("JVM_VERSION", System.getProperty("java.vm.version"));
- envMap.put("OS", System.getProperty("os.name"));
- String defFreq = "checkin";
- envMap.put("Frequency", System.getProperty("test.run.frequency", defFreq));
-
- Iterator itr = envMap.keySet().iterator();
- int envCount = 0;
- while (itr.hasNext())
- {
- EnvironmentType.EnvAttribute envAttr = env.addNewEnvAttribute();
- String name = (String) itr.next();
- String value = (String) envMap.get(name);
- envAttr.setValue(value);
- envAttr.setName(name);
- }
-
- // Add <header-info> element
- TestLogDocument.TestLog.HeaderInfo hdrInfo = log.addNewHeaderInfo();
- hdrInfo.setResultcount(Integer.toString(testCount));
- hdrInfo.setChecksum(Integer.toString(testCount));
- hdrInfo.setExecdate(new Date(startTime).toString());
- hdrInfo.setExecaccount(System.getProperty("user.name"));
-
- // Add test-results
- Iterator rItr = records.iterator();
- while (rItr.hasNext())
- {
- TestResultType tr = log.addNewTestResult();
- tr.set(getTestResultType((TestRecord) rItr.next()));
- }
-
- // Publish it to the outputStream
- XmlOptions opts = new XmlOptions().setSavePrettyPrint();
- try
- {
- logOut.write(logDoc.xmlText(opts).getBytes());
- } catch (IOException ioe)
- {
- System.out.println("XmlResultFormatter: Unable to publish results");
- System.out.println(ioe.toString());
- }
-
- }
-
-
- /**
- * Creates the TestResultDocument and returns the Xml
- */
- private TestResultType getTestResultType(TestRecord rec)
- {
- TestResultType tr = TestResultType.Factory.newInstance();
- // Children of TestResult
- TestResultType.TestCase tc = tr.addNewTestCase();
- TestResultType.ExecutionOutput exo = tr.addNewExecutionOutput();
-
- // Set the logical test name... 'Class.Methodname'
- tr.setLogicalname(rec.getTestLogicalName());
- // Set the test Start time as a String
- tr.setExectime(new Date(rec.getStartTime()).toString());
- String status = rec.getStatusString();
- // Set the test result
- if (status.equals("SUCCESS"))
- tr.setResult(TestResultType.Result.SUCCESS);
- else if (status.equals("FAILURE"))
- tr.setResult(TestResultType.Result.FAILURE);
- else
- tr.setResult(TestResultType.Result.ABORT);
- // Set the test execution time.. in milliseconds
- String dur = Long.toString(rec.getEndTime() - rec.getStartTime());
- tr.setDuration(dur);
- // Set the completion status..
- tr.setIsdone(TestResultType.Isdone.TRUE);
-
- // Setup the children elements
- // test-case
- tc.setTestcasename(rec.getTestLogicalName());
- tc.setTestunit(rec.getTestUnitName());
- // This should ideally be the whole path to the class...
- tc.setTestpath(rec.getTestname());
-
- // execution-output
- // if FAILURE.. set erroname attribute
- if (rec.isFailure())
- {
- String exp = rec.getThrowable().toString();
- int index = exp.indexOf(":");
- // the above line is very flaky..
- if (index < 0) index = exp.length();
- exo.setErrorname(exp.substring(0, index));
- }
- StringBuffer output = new StringBuffer();
- String eol = System.getProperty("line.separator");
- output.append("[STDOUT]").append(eol);
- output.append(rec.getSysout()).append(eol);
- output.append("[STDERR]").append(eol);
- output.append(rec.getSyserr()).append(eol);
- if (rec.isFailure())
- {
- output.append("[EXCEPTION]").append(eol);
- output.append(JUnitTestRunner.getFilteredTrace(rec.getThrowable()));
- }
-
- exo.setOutputDetails(output.toString());
-
- return tr;
- }
-
-
-}
+package tools.JUnit;
import java.util.*;
import java.io.*;
import java.text.SimpleDateFormat;
import junit.framework.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import noNamespace.TestResultContainerDocument.TestResultContainer;
import noNamespace.*;
import noNamespace.TestResultType.ExecutionOutput;
import org.apache.xmlbeans.XmlOptions;
import tools.io.TeeOutputStream;
import org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner;
/**
* Implementation of JUnitXResultFormatter that records JUnit results
* and publishes the result as a XML Document
*/
public class XmlResultFormatterImpl implements JUnitXResultFormatter
{
public static int TEST_SUCCESS = 0;
public static int TEST_FAILURE = 1;
public static int TEST_ERROR = 2;
public static int TEST_UNKNOWN = 3;
// Lets capture STDOUT and STDERR
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ByteArrayOutputStream bErr = new ByteArrayOutputStream();
TeeOutputStream tOut;
TeeOutputStream tErr;
PrintStream _out;
PrintStream _err;
private TestRecord testRecord;
Collection records;
// By default write to StdOut
OutputStream logOut = System.out;
// Record Stats
int testCount = 0;
int passCount = 0;
int failCount = 0;
long startTime = 0;
boolean showOutput = false;
public void startRun()
{
records = new ArrayList();
// Reset stats
testCount = 0;
passCount = 0;
failCount = 0;
startTime = System.currentTimeMillis();
}
public void endRun()
{
System.out.println("=================================================");
System.out.println("Tests Ran: " + testCount);
System.out.println("Success: " + passCount);
System.out.println("Failures: " + failCount);
// Generate log:
System.out.println("Starting Publish: " + System.currentTimeMillis());
publishResults();
System.out.println("Finished Publish: " + System.currentTimeMillis());
}
public void setOutput(OutputStream out)
{
if (out != null)
logOut = out;
}
public void showTestOutput(boolean show)
{
showOutput = show;
}
public void info(Object msg)
{
if (showOutput)
System.out.println(msg);
}
/*
* Implementation of TestListener
*/
public synchronized void startTest(Test test)
{
String fullTestName = test.toString();
info("Starting Test: " + fullTestName);
// Lets start the capture
System.out.flush();
System.err.flush();
_out = System.out;
_err = System.err;
bOut.reset();
bErr.reset();
// Redirect Stdout & Stderr to both console and our capture stream
if (showOutput)
{
tOut = new TeeOutputStream(_out, bOut);
tErr = new TeeOutputStream(_err, bErr);
System.setOut(new PrintStream(tOut));
System.setErr(new PrintStream(tErr));
}
else
{
System.setOut(new PrintStream(bOut));
System.setErr(new PrintStream(bErr));
}
// Discard the previous record
testRecord = new TestRecord(fullTestName);
testRecord.setStartTime(System.currentTimeMillis());
}
public synchronized void endTest(Test test)
{
long endTime = System.currentTimeMillis();
System.out.flush();
System.err.flush();
// Update the test record
testRecord.setSysout(bOut.toString());
testRecord.setSyserr(bErr.toString());
testRecord.setEndTime(endTime);
// this is a little hack for our reporting..
// We could be on shaky ground if the behaviour of the JUnit task
// ever changes.. OH Well...
String fullTestName = test.toString();
// Test-unit is between '(' and ')'
int startindex = fullTestName.indexOf("(");
int lastindex = fullTestName.indexOf(")");
String testUnit;
if (startindex >= 0 && lastindex > startindex)
testUnit = fullTestName.substring(startindex+1, lastindex);
else
testUnit = fullTestName;
String testMethod = ((TestCase) test).getName();
// Get the last token from testUnit for the logical name
startindex = testUnit.lastIndexOf(".");
String baseClass = testUnit.substring(startindex+1);
// update the extra fields of TestRecord
testRecord.setTestUnitName(testUnit);
testRecord.setTestLogicalName(baseClass + "." + testMethod);
// If the test did not fail, record it as a success
if (!testRecord.isFailure())
{
testRecord.setStatus(TEST_SUCCESS);
passCount++;
}
else
failCount++;
testCount++;
// Add it to the set
records.add(testRecord);
// set testRecord to null..
// Restore STDOUT and STDERR
System.setOut(_out);
System.setErr(_err);
info("Finished Test: " + fullTestName + " "
+ testRecord.getStatusString() + "\n");
// Reset TestRecord
testRecord = null;
}
public synchronized void addError(final Test test, final Throwable t)
{
if (testRecord == null)
testRecord = getMissingTestRecord();
testRecord.setStatus(TEST_ERROR);
testRecord.setThrowable(t);
// Special case when test class is missing...
if (t.toString().indexOf("ClassNotFoundException") > -1)
{
records.add(testRecord);
testRecord = null;
}
}
public synchronized void addFailure(final Test test, final AssertionFailedError t)
{
if (testRecord == null)
testRecord = getMissingTestRecord();
testRecord.setStatus(TEST_FAILURE);
testRecord.setThrowable(t);
}
/**
* Utility class to record per test data like test name, status, start
* and end time, STDOUT, STDERR from text execution etc.
*/
private class TestRecord
{
public TestRecord(String name)
{
setTestname(name);
}
private String testname;
private String sysout;
private String syserr;
private Throwable t;
private long startTime;
private long endTime;
private int status;
boolean failed = false;
private String testUnitName;
private String testLogicalName;
public void setTestname(String name)
{
this.testname = name;
}
public String getTestname()
{
return testname;
}
public void setStatus(int status)
{
this.status = status;
if (status == TEST_ERROR || status == TEST_FAILURE)
failed = true;
}
public int getStatus()
{
return status;
}
public String getStatusString()
{
return (status == TEST_SUCCESS)?"SUCCESS":
(status == TEST_ERROR)?"ERROR":"FAILURE";
}
public boolean isFailure()
{
return failed;
}
public String getSysout()
{
return sysout;
}
public void setSysout(String sysout)
{
this.sysout = sysout;
}
public String getSyserr()
{
return syserr;
}
public void setSyserr(String syserr)
{
this.syserr = syserr;
}
public Throwable getThrowable()
{
return t;
}
public void setThrowable(Throwable t)
{
this.t = t;
}
public long getStartTime()
{
return startTime;
}
public void setStartTime(long startTime)
{
this.startTime = startTime;
}
public long getEndTime()
{
return endTime;
}
public void setEndTime(long endTime)
{
this.endTime = endTime;
}
public String getTestUnitName()
{
return testUnitName;
}
public void setTestUnitName(String testUnitName)
{
this.testUnitName = testUnitName;
}
public String getTestLogicalName()
{
return testLogicalName;
}
public void setTestLogicalName(String testLogicalName)
{
this.testLogicalName = testLogicalName;
}
}
private TestRecord getMissingTestRecord()
{
TestRecord tr = new TestRecord("Missing");
tr.setStartTime(System.currentTimeMillis());
tr.setEndTime(System.currentTimeMillis());
tr.setStatus(TEST_ERROR);
tr.setTestLogicalName("Missing");
tr.setTestUnitName("Missing");
return tr;
}
public void publishResults()
{
TestLogDocument logDoc = TestLogDocument.Factory.newInstance();
TestLogDocument.TestLog log = logDoc.addNewTestLog();
// Populate the attributes for test-log
// testtype
String testtype = System.getProperty("TESTTYPE", "AUTO");
if (testtype.equalsIgnoreCase("AUTO"))
log.setTesttype(TestLogDocument.TestLog.Testtype.AUTOMATED);
else
log.setTesttype(TestLogDocument.TestLog.Testtype.MANUAL);
// runid
String dateFormatStr = "_yy_MMM_dd_HH_mm_ss_SS";
String dateStr = new SimpleDateFormat(dateFormatStr).format(new Date(startTime));
String defRunId = System.getProperty("user.name").toUpperCase() + dateStr;
String runId = System.getProperty("RUNID", defRunId);
log.setRunid(runId);
// hostname
String hostname;
try
{
hostname = java.net.InetAddress.getLocalHost().getHostName();
} catch (Exception e)
{
// Ignore.. not critical
hostname = "UNKNOWN_HOST";
}
log.setHostname(hostname);
// TODO: set Defaults/check sysprop for other attributes
// Add <environment> element
EnvironmentType env = log.addNewEnvironment();
Map envMap = new HashMap();
envMap.put("JVM_NAME", System.getProperty("java.vm.name"));
envMap.put("JVM_VENDOR", System.getProperty("java.vm.vendor"));
envMap.put("JVM_VERSION", System.getProperty("java.vm.version"));
envMap.put("OS", System.getProperty("os.name"));
String defFreq = "checkin";
envMap.put("Frequency", System.getProperty("test.run.frequency", defFreq));
Iterator itr = envMap.keySet().iterator();
int envCount = 0;
while (itr.hasNext())
{
EnvironmentType.EnvAttribute envAttr = env.addNewEnvAttribute();
String name = (String) itr.next();
String value = (String) envMap.get(name);
envAttr.setValue(value);
envAttr.setName(name);
}
// Add <header-info> element
TestLogDocument.TestLog.HeaderInfo hdrInfo = log.addNewHeaderInfo();
hdrInfo.setResultcount(Integer.toString(testCount));
hdrInfo.setChecksum(Integer.toString(testCount));
hdrInfo.setExecdate(new Date(startTime).toString());
hdrInfo.setExecaccount(System.getProperty("user.name"));
// Add test-results
Iterator rItr = records.iterator();
while (rItr.hasNext())
{
TestResultType tr = log.addNewTestResult();
tr.set(getTestResultType((TestRecord) rItr.next()));
}
// Publish it to the outputStream
XmlOptions opts = new XmlOptions().setSavePrettyPrint();
try
{
logOut.write(logDoc.xmlText(opts).getBytes());
} catch (IOException ioe)
{
System.out.println("XmlResultFormatter: Unable to publish results");
System.out.println(ioe.toString());
}
}
/**
* Creates the TestResultDocument and returns the Xml
*/
private TestResultType getTestResultType(TestRecord rec)
{
TestResultType tr = TestResultType.Factory.newInstance();
// Children of TestResult
TestResultType.TestCase tc = tr.addNewTestCase();
TestResultType.ExecutionOutput exo = tr.addNewExecutionOutput();
// Set the logical test name... 'Class.Methodname'
tr.setLogicalname(rec.getTestLogicalName());
// Set the test Start time as a String
tr.setExectime(new Date(rec.getStartTime()).toString());
String status = rec.getStatusString();
// Set the test result
if (status.equals("SUCCESS"))
tr.setResult(TestResultType.Result.SUCCESS);
else if (status.equals("FAILURE"))
tr.setResult(TestResultType.Result.FAILURE);
else
tr.setResult(TestResultType.Result.ABORT);
// Set the test execution time.. in milliseconds
String dur = Long.toString(rec.getEndTime() - rec.getStartTime());
tr.setDuration(dur);
// Set the completion status..
tr.setIsdone(TestResultType.Isdone.TRUE);
// Setup the children elements
// test-case
tc.setTestcasename(rec.getTestLogicalName());
tc.setTestunit(rec.getTestUnitName());
// This should ideally be the whole path to the class...
tc.setTestpath(rec.getTestname());
// execution-output
// if FAILURE.. set erroname attribute
if (rec.isFailure())
{
String exp = rec.getThrowable().toString();
int index = exp.indexOf(":");
// the above line is very flaky..
if (index < 0) index = exp.length();
exo.setErrorname(exp.substring(0, index));
}
StringBuffer output = new StringBuffer();
String eol = System.getProperty("line.separator");
output.append("[STDOUT]").append(eol);
output.append(rec.getSysout()).append(eol);
output.append("[STDERR]").append(eol);
output.append(rec.getSyserr()).append(eol);
if (rec.isFailure())
{
output.append("[EXCEPTION]").append(eol);
output.append(JUnitTestRunner.getFilteredTrace(rec.getThrowable()));
}
exo.setOutputDetails(output.toString());
return tr;
}
}
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: xmlbeans-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: xmlbeans-cvs-help@xml.apache.org