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/13 22:48:55 UTC

cvs commit: xml-xmlbeans/v2/test/tools/src/tools/JUnit JUnitXRunner.java JUnitXTask.java

daveremy    2004/07/13 13:48:55

  Modified:    v2       testbuild.xml
               v2/test/docs BuildingAndRunningTests.txt
               v2/test/tools/src/tools/JUnit JUnitXRunner.java
                        JUnitXTask.java
  Log:
  Contributed by:Yana Kadiyska. Adding ability to run a specified class
  
  Revision  Changes    Path
  1.20      +1 -0      xml-xmlbeans/v2/testbuild.xml
  
  Index: testbuild.xml
  ===================================================================
  RCS file: /home/cvs/xml-xmlbeans/v2/testbuild.xml,v
  retrieving revision 1.19
  retrieving revision 1.20
  diff -u -r1.19 -r1.20
  --- testbuild.xml	12 Jul 2004 21:38:21 -0000	1.19
  +++ testbuild.xml	13 Jul 2004 20:48:55 -0000	1.20
  @@ -845,6 +845,7 @@
               formatter="tools.JUnit.XmlResultFormatterImpl"
               showOutput="${showoutput}"
               reportFile="${report.log.file}"
  +            classes="${test.area.run}"
               fork="true"
               resultproperty="junit.failcount"
               failonerror="false">
  
  
  
  1.4       +4 -1      xml-xmlbeans/v2/test/docs/BuildingAndRunningTests.txt
  
  Index: BuildingAndRunningTests.txt
  ===================================================================
  RCS file: /home/cvs/xml-xmlbeans/v2/test/docs/BuildingAndRunningTests.txt,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- BuildingAndRunningTests.txt	25 Jun 2004 18:33:25 -0000	1.3
  +++ BuildingAndRunningTests.txt	13 Jul 2004 20:48:55 -0000	1.4
  @@ -59,11 +59,14 @@
   (Alternatively, you can chain the targets like this:
          ant testbuild run.junit -Dtest.area=dom -Dtest.spec="**/dom/checkin/**" )
   
  +To run a single class:
  +   * ant run.junit -Dtest.spec="xmlobject.detailed.NilTest"
   
   Parameters:
     - test.area:   specifies an area to build and run
     - test.spec:   this option is valid at runtime only, 
  -                 and is used to allow the user to specify a fileset of their liking.
  +                 and is used to allow the user to specify a fileset of their liking.It could also be
  +		 used to specify a class to be run.
                    It should be used <b>INSTEAD</b> of test.area
                    ***If you provide both, -Dtest.spec will take precedence, and the area will be disregarded.
   
  
  
  
  1.3       +62 -77    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.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- JUnitXRunner.java	10 Jun 2004 03:31:30 -0000	1.2
  +++ JUnitXRunner.java	13 Jul 2004 20:48:55 -0000	1.3
  @@ -7,17 +7,17 @@
   import java.io.*;
   import java.util.*;
   
  +import org.apache.xmlbeans.impl.tool.CommandLine;
  +
   /**
    * User: rajus
    * Date: May 25, 2004
    */
   
   public class JUnitXRunner extends BaseTestRunner
  -                          implements JUnitXResultFormatter
  -{
  +        implements JUnitXResultFormatter {
       public static void main(String args[])
  -        throws Exception
  -    {
  +            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
  @@ -29,7 +29,7 @@
           String resListener = null;
           String outFile = null;
           boolean showOutput = false;
  -        if (args.length > 1)
  +        /*if (args.length > 1)
           {
               if (args[1].equalsIgnoreCase("showoutput"))
                   showOutput = true;
  @@ -48,41 +48,50 @@
               if (args[3].equalsIgnoreCase("showoutput"))
                   showOutput = true;
           }
  -
  +        */
  +        Collection options=new TreeSet();
  +        options.add(JUnitXTask.resultListener);
  +        options.add(JUnitXTask.outFile);
  +        options.add("showoutput");
  +
  +        CommandLine cmdl = new CommandLine(args, options);
  +        showOutput = cmdl.getOpt("showoutput") != null;
  +        resListener = cmdl.getOpt(JUnitXTask.resultListener);
  +        if (resListener != null) {
  +            outFile = cmdl.getOpt(JUnitXTask.outFile);
  +            if (outFile == null)
  +                throw new RuntimeException("No output file specified");
  +        }
           ArrayList files = new ArrayList();
  -        try
  -        {
  +        try {
               BufferedReader in = new BufferedReader(new FileReader(file));
               String line;
               while ((line = in.readLine()) != null)
                   files.add(line);
               in.close();
   
  -        } catch (Exception e)
  -        {
  +        }
  +        catch (Exception e) {
               e.printStackTrace();
           }
   
           JUnitXRunner runner;
  -        if (resListener != null)
  -        {
  +        if (resListener != null) {
               // Try to instantiate a class of resListener
               Object obj;
  -            try
  -            {
  +            try {
                   Class c = Class.forName(resListener);
                   obj = c.newInstance();
  -            } catch (Exception e)
  -            {
  +            }
  +            catch (Exception e) {
                   throw new RuntimeException(e);
               }
               JUnitXResultFormatter fmt = (JUnitXResultFormatter) obj;
               runner = new JUnitXRunner(files, fmt, outFile, showOutput);
  -        }
  -        else
  +        } else
               runner = new JUnitXRunner(files, showOutput);
   
  -        int nFailureCount=runner.runTests();
  +        int nFailureCount = runner.runTests();
           System.exit(nFailureCount);
       }
   
  @@ -96,8 +105,7 @@
       String outFile = null;
       boolean showOutput = false;
   
  -    public JUnitXRunner(ArrayList classes, boolean showOutput)
  -    {
  +    public JUnitXRunner(ArrayList classes, boolean showOutput) {
           this.classes = classes;
           tests = new ArrayList();
           _listener = this;
  @@ -107,40 +115,36 @@
       public JUnitXRunner(ArrayList classes,
                           JUnitXResultFormatter listener,
                           String outFile,
  -                        boolean showOutput)
  -    {
  +                        boolean showOutput) {
           this.classes = classes;
           tests = new ArrayList();
           _listener = listener;
           this.outFile = outFile;
           this.showOutput = showOutput;
  +
       }
   
   
  -    public int runTests()
  -    {
  +    public int runTests() {
           collectTests();
           Iterator itr = tests.iterator();
   
           TestResult res = new TestResult();
           res.addListener(_listener);
   
  -        try
  -        {
  -            if (outFile != null)
  -            {
  +        try {
  +            if (outFile != null) {
                   FileOutputStream fos = new FileOutputStream(new File(outFile));
                   _listener.setOutput(fos);
               }
  -        } catch (FileNotFoundException fnfe)
  -        {
  +        }
  +        catch (FileNotFoundException fnfe) {
               throw new RuntimeException("Unable to initialize output to file "
  -                                       + outFile + "\n" + fnfe.getMessage());
  +                    + outFile + "\n" + fnfe.getMessage());
           }
           _listener.showTestOutput(showOutput);
           _listener.startRun();
  -        while (itr.hasNext())
  -        {
  +        while (itr.hasNext()) {
               Test test = (Test) itr.next();
               test.run(res);
           }
  @@ -148,84 +152,68 @@
           return res.failureCount();
       }
   
  -    private void collectTests()
  -    {
  +    private void collectTests() {
           Iterator itr = classes.iterator();
   
  -        while (itr.hasNext())
  -        {
  +        while (itr.hasNext()) {
               Test suite = null;
               String className = (String) itr.next();
               suite = getTest(className);
   
  -            if (suite != null && suite.countTestCases() > 0)
  -            {
  +            if (suite != null && suite.countTestCases() > 0) {
                   tests.addAll(getSubTests(suite));
  -            } else
  -            {
  +            } else {
                   //System.out.println("No tests found in " + testClassName);
                   // Ignore files which are not Junit tests.
               }
           }
       }
   
  -    private Collection getSubTests(Test test)
  -    {
  +    private Collection getSubTests(Test test) {
           Collection ret = new ArrayList();
   
  -        if (TestSuite.class.isAssignableFrom(test.getClass()))
  -        {
  +        if (TestSuite.class.isAssignableFrom(test.getClass())) {
               Enumeration e = ((TestSuite) test).tests();
  -            while (e.hasMoreElements())
  -            {
  -                ret.addAll(getSubTests((Test)e.nextElement()));
  +            while (e.hasMoreElements()) {
  +                ret.addAll(getSubTests((Test) e.nextElement()));
               }
  -        }
  -        else if (TestCase.class.isAssignableFrom(test.getClass()))
  -        {
  -            ret.add(((TestCase)test));
  -        }
  -        else
  -        {
  -            System.out.println("Could not find any tests in " + test.toString());
  +        } else if (TestCase.class.isAssignableFrom(test.getClass())) {
  +            ret.add(((TestCase) test));
  +        } else {
  +            System.out.println(
  +                    "Could not find any tests in " + test.toString());
           }
   
           return ret;
       }
   
       // JUnitXResultFormatter Implementation
  -    public void startRun()
  -    {
  +    public void startRun() {
   
       }
   
  -    public void endRun()
  -    {
  +    public void endRun() {
   
       }
   
  -    public void setOutput(OutputStream out)
  -    {
  +    public void setOutput(OutputStream out) {
           // Ignored. Custom ResultFormatters will use
       }
   
  -    public void showTestOutput(boolean show)
  -    {
  +    public void showTestOutput(boolean show) {
           // Ignore. We don't capture stdout or stderr.
       }
   
       // TestRunListener implementation
  -	public void testStarted(String testName)
  -    {
  +    public void testStarted(String testName) {
           System.out.println("\nStarted: " + testName);
       }
  -	public void testEnded(String testName)
  -    {
  +
  +    public void testEnded(String testName) {
           System.out.println("Ended: " + testName);
       }
   
  -	public void testFailed(int status, Test test, Throwable t)
  -    {
  +    public void testFailed(int status, Test test, Throwable t) {
           if (status == TestRunListener.STATUS_FAILURE)
               System.out.println("Failure: ");
           else
  @@ -234,8 +222,7 @@
           System.out.println(getFilteredTrace(t));
       }
   
  -    protected void runFailed(String message)
  -    {
  +    protected void runFailed(String message) {
           //System.out.println("RUN had failures");
       }
   
  @@ -245,13 +232,11 @@
        *
        * @see junit.runner.BaseTestRunner#useReloadingTestSuiteLoader()
        */
  -    protected boolean useReloadingTestSuiteLoader()
  -    {
  +    protected boolean useReloadingTestSuiteLoader() {
           return false;
       }
   
  -    private String getStackTraceAsString(Throwable t)
  -    {
  +    private String getStackTraceAsString(Throwable t) {
           StringWriter sw = new StringWriter();
           t.printStackTrace(new PrintWriter(sw, true));
   
  
  
  
  1.3       +91 -66    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.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- JUnitXTask.java	9 Jun 2004 02:29:46 -0000	1.2
  +++ JUnitXTask.java	13 Jul 2004 20:48:55 -0000	1.3
  @@ -12,13 +12,13 @@
   /**
    * <p>This task runs tests from the JUnit testing framework. The latest version
    * of JUnit can be found at <a href="http://www.junit.org">http://www.junit.org</a>.
  - *
  + * <p/>
    * <p><strong>Note:</strong> This task depends on external libraries not included
    * in the Ant distribution.  See <a href="http://ant.apache.org/manual/install.html#librarydependencies">
  - *
  + * <p/>
    * Library Dependencies</a> for more information.
    * </p>
  - * <p>
  + * <p/>
    * <strong>Note</strong>:
    * You must have <code>junit.jar</code> and the class files for the
    * <code>&lt;junit&gt;</code> task in the same classpath.
  @@ -26,7 +26,7 @@
    * </p><ol>
    * <li>
    * Put both <code>junit.jar</code> and the optional tasks jar file in
  - *
  + * <p/>
    * <code>ANT_HOME/lib</code>.
    * </li>
    * <li>
  @@ -36,16 +36,16 @@
    * <li>
    * Do neither of the above, and instead, specify their locations using
    * a <code>&lt;classpath&gt;</code> element in the build file.
  - *
  + * <p/>
    * See <a href="http://ant.apache.org/faq.html#delegating-classloader" target="_top">the
    * FAQ</a> for details.</p>
  - *
  - *
  + * <p/>
  + * <p/>
    * <pre>
    * Usage:
    * This task is derived from the Java task and supports all attributes and nested
    * elements of the Java task. Additionally it supports the following attributes
  - *
  + * <p/>
    * formatter       =  Optional class that implements tools.JUnit.JUnitXResultFormatter
    *                    to be passed to the JUnit runner for formatting the results
    * reportFile      =  File for the formatter to write too.
  @@ -54,96 +54,111 @@
    * showOutput      =  Tells the formatter to show the output of the tests.
    *                    The default formatter ignores this flag, since it anyway
    *                    displays everything to stdout/stderr.
  - *
  + * classes        = Ignored unless the fileset is not valid. If the user has specified
  + *                  valid classnames, this variable is used to run the classes. Hacky but
  + *                  allows the user to use the same command line parameter as when specifying filesets.
  + * <p/>
    * The tests to run are specified using nested <code>Fileset</code>s elements
    * The task picks up any .class or .java files from the filesets and tries to run
    * them as JUnit tests.
    * </pre>
    */
   
  -public class JUnitXTask extends org.apache.tools.ant.taskdefs.Java
  -{
  +public class JUnitXTask extends org.apache.tools.ant.taskdefs.Java {
       // Task attributes vars
       private String reportFile;
       private boolean showOutput = false;
       private String formatterClass;
  +    private String[] classFiles = null;
   
  -    /** the list of filesets containing the testcase filename rules */
  +    public final static String resultListener="listener";
  +    public final static String outFile="file";
  +
  +    /**
  +     * the list of filesets containing the testcase filename rules
  +     */
       private Vector filesets = new Vector();
   
       /**
        * Add a new fileset instance to this batchtest. Whatever the fileset is,
        * only filename that are <tt>.java</tt> or <tt>.class</tt> will be
        * considered as 'candidates'.
  -     * @param     fs the new fileset containing the rules to get the testcases.
  +     *
  +     * @param fs the new fileset containing the rules to get the testcases.
        */
  -    public void addFileSet(FileSet fs)
  -    {
  +    public void addFileSet(FileSet fs) {
           filesets.addElement(fs);
       }
   
       // Additional Attributes
       /**
  +     *
  +     */
  +    public void setClasses(String classes) {
  +        this.classFiles = classes.split(",");
  +    }
  +
  +    /**
        * Set the file to write the test run report to
  +     *
        * @param reportFile
        */
  -    public void setReportFile(String reportFile)
  -    {
  +    public void setReportFile(String reportFile) {
           this.reportFile = reportFile;
       }
   
       /**
        * Sets the class to be used as the Result formatter for the test results
        * This class should implement tools.JUnit.JUnitXResultFormatter
  +     *
        * @param fmtClass
        */
  -    public void setFormatter(String fmtClass)
  -    {
  +    public void setFormatter(String fmtClass) {
           this.formatterClass = fmtClass;
       }
   
       /**
        * Controls whether the output from the tests is sent to stdout/stderr.
  +     *
        * @param show
        */
  -    public void setShowOutput(boolean show)
  -    {
  +    public void setShowOutput(boolean show) {
           this.showOutput = show;
       }
   
  -    public void execute() throws BuildException
  -    {
  +    public void execute() throws BuildException {
           validate();
           String[] files = getFilenames();
  -        File temp=null;
  -        String fName=Long.toString(System.currentTimeMillis());
  -                                      
  -      
  -            //issue w/ JDK 1.4 IOException
  -            // temp = File.createTempFile(,null);
  -            temp=new File(fName);
  -
  -        try{
  -             temp.deleteOnExit();
  -             // System.out.println(temp.toString());
  +        File temp = null;
  +        String fName = Long.toString(System.currentTimeMillis());
  +
  +
  +        //issue w/ JDK 1.4 IOException
  +        // temp = File.createTempFile(,null);
  +        temp = new File(fName);
  +
  +        try {
  +            temp.deleteOnExit();
  +            // System.out.println(temp.toString());
               BufferedWriter out = new BufferedWriter(new FileWriter(temp));
               System.out.println(temp.toString());
               for (int i = 0; i < files.length; i++)
                   out.write(javaToClass(files[i]) + "\n");
               out.close();
  -        } catch (java.io.IOException ioe)
  -        {
  +        }
  +        catch (java.io.IOException ioe) {
               throw new BuildException("Could not write out temporary file for " +
  -                                     "passing arguments to the JUnit runner: " +
  -                                     ioe.getMessage());
  +                    "passing arguments to the JUnit runner: " +
  +                    ioe.getMessage());
           }
   
           super.setClassname("tools.JUnit.JUnitXRunner");
           // Args: tempFile reportFormatter outFile <showOutput>
           super.createArg().setFile(temp);
  -        if (formatterClass != null)
  -        {
  +        if (formatterClass != null) {
  +            super.createArg().setValue("-"+resultListener);
               super.createArg().setValue(this.formatterClass);
  +            super.createArg().setValue("-"+outFile);
               super.createArg().setValue(this.reportFile);
           }
           if (showOutput)
  @@ -154,8 +169,7 @@
       /**
        * Validates the attributes
        */
  -    private void validate()
  -    {
  +    private void validate() {
           // Check if any filesets have been specified
           if (filesets.size() == 0)
               throw new BuildException("You have to specify atleast one Fileset");
  @@ -163,46 +177,57 @@
           // If Custom ResultFormatter is specified, then an outfile should be
           // specified. The default ResultFormatter write only to Stdout
           if ((formatterClass != null) && (reportFile == null))
  -            throw new BuildException("Using custom ReportFormatter: " +
  -                                     "reportFile attribute should be specified");
  +            throw new BuildException(
  +                    "Using custom ReportFormatter: " +
  +                    "reportFile attribute should be specified");
   
       }
   
  -     /**
  +    /**
        * Iterate over all filesets and return the filename of all files
        * that end with <tt>.java</tt> or <tt>.class</tt>. This is to avoid
        * wrapping a <tt>JUnitTest</tt> over an xml file for example. A Testcase
        * is obviously a java file (compiled or not).
  +     *
        * @return an array of filenames without their extension. As they should
  -     * normally be taken from their root, filenames should match their fully
  -     * qualified class name (If it is not the case it will fail when running the test).
  -     * For the class <tt>org/apache/Whatever.class</tt> it will return <tt>org/apache/Whatever</tt>.
  +     *         normally be taken from their root, filenames should match their fully
  +     *         qualified class name (If it is not the case it will fail when running the test).
  +     *         For the class <tt>org/apache/Whatever.class</tt> it will return <tt>org/apache/Whatever</tt>.
        */
  -    private String[] getFilenames()
  -    {
  +    private String[] getFilenames() {
           Vector v = new Vector();
           final int size = this.filesets.size();
  -        for (int j = 0; j < size; j++)
  -        {
  +        for (int j = 0; j < size; j++) {
               FileSet fs = (FileSet) filesets.elementAt(j);
  -            DirectoryScanner ds = fs.getDirectoryScanner(project);
  +            //    DirectoryScanner ds = fs.getDirectoryScanner(project);
  +            DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject());
               ds.scan();
               String[] f = ds.getIncludedFiles();
  -            for (int k = 0; k < f.length; k++)
  -            {
  +            //check for an actual class here
  +            if (f.length == 0 && size == 1)
  +                f = classFiles;
  +            for (int k = 0; k < f.length; k++) {
                   String pathname = f[k];
  -                if (pathname.endsWith(".java"))
  -                {
  -                    v.addElement(pathname.substring(0, pathname.length() - ".java".length()));
  -                } else if (pathname.endsWith(".class"))
  -                {
  +                if (pathname.endsWith(".java")) {
  +                    v.addElement(
  +                            pathname.substring(0,
  +                                    pathname.length() - ".java".length()));
  +                } else if (pathname.endsWith(".class")) {
                       // DOn't try to run inner classes
  -                    if ( pathname.indexOf("$") == -1 )
  -                        v.addElement(pathname.substring(0, pathname.length() - ".class".length()));
  -                }
  +                    if (pathname.indexOf("$") == -1)
  +                        v.addElement(
  +                                pathname.substring(0,
  +                                        pathname.length() - ".class".length()));
  +                } else
  +                    try {
  +                        Class.forName(pathname);
  +                        v.addElement(pathname);
  +                    }
  +                    catch (ClassNotFoundException e) {
  +                        ;//filename is not a class
  +                    }
               }
           }
  -
           String[] files = new String[v.size()];
           v.copyInto(files);
           return files;
  @@ -212,11 +237,11 @@
        * Convenient method to convert a pathname without extension to a
        * fully qualified classname. For example <tt>org/apache/Whatever</tt> will
        * be converted to <tt>org.apache.Whatever</tt>
  +     *
        * @param filename the filename to "convert" to a classname.
        * @return the classname matching the filename.
        */
  -    public static final String javaToClass(String filename)
  -    {
  +    public static final String javaToClass(String filename) {
           return filename.replace(File.separatorChar, '.');
       }
   
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: xmlbeans-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: xmlbeans-cvs-help@xml.apache.org