test/com/sun/javadoc/lib/JavadocTester.java

Sat, 01 Dec 2007 00:00:00 +0000

author
duke
date
Sat, 01 Dec 2007 00:00:00 +0000
changeset 1
9a66ca7c79fa
child 140
22c4c1143a3a
permissions
-rw-r--r--

Initial load

     1 /*
     2  * Copyright 2002-2004 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  */
    24 import com.sun.javadoc.*;
    25 import java.util.*;
    26 import java.io.*;
    29 /**
    30  * Runs javadoc and then runs regression tests on the resulting output.
    31  * This class currently contains three tests:
    32  * <ul>
    33  * <li> String search: Reads each file, complete with newlines,
    34  *      into a string.  Lets you search for strings that contain
    35  *      newlines.  String matching is case-sensitive.
    36  *      You can run javadoc multiple times with different arguments,
    37  *      generating output into different destination directories, and
    38  *      then perform a different array of tests on each one.
    39  *      To do this, the run method accepts a test array for testing
    40  *      that a string is found, and a negated test array for testing
    41  *      that a string is not found.
    42  * <li> Run diffs: Iterate through the list of given file pairs
    43  *      and diff the pairs.
    44  * <li> Check exit code: Check the exit code of Javadoc and
    45  *      record whether the test passed or failed.
    46  * </ul>
    47  *
    48  * @author Doug Kramer
    49  * @author Jamie Ho
    50  * @since 1.4.2
    51  */
    52 public abstract class JavadocTester {
    54     protected static final String FS = System.getProperty("file.separator");
    55     protected static final String PS = System.getProperty("path.separator");
    56     protected static final String NL = System.getProperty("line.separator");
    57     protected static final String SRC_DIR = System.getProperty("test.src", ".");
    58     protected static final String JAVA_VERSION = System.getProperty("java.version");
    59     protected static final String[][] NO_TEST = new String[][] {};
    61     /**
    62      * Use this as the file name in the test array when you want to search
    63      * for a string in the error output.
    64      */
    65     public static final String ERROR_OUTPUT = "ERROR_OUTPUT";
    67     /**
    68      * Use this as the file name in the test array when you want to search
    69      * for a string in the notice output.
    70      */
    71     public static final String NOTICE_OUTPUT = "NOTICE_OUTPUT";
    73     /**
    74      * Use this as the file name in the test array when you want to search
    75      * for a string in the warning output.
    76      */
    77     public static final String WARNING_OUTPUT = "WARNING_OUTPUT";
    79     /**
    80      * Use this as the file name in the test array when you want to search
    81      * for a string in standard output.
    82      */
    83     public static final String STANDARD_OUTPUT = "STANDARD_OUTPUT";
    85     /**
    86      * The default doclet.
    87      */
    88     public static final String DEFAULT_DOCLET_CLASS = "com.sun.tools.doclets.formats.html.HtmlDoclet";
    89     public static final String DEFAULT_DOCLET_CLASS_OLD = "com.sun.tools.doclets.standard.Standard";
    91     /**
    92      * The writer to write error messages.
    93      */
    94     public StringWriter errors;
    96     /**
    97      * The writer to write notices.
    98      */
    99     public StringWriter notices;
   101     /**
   102      * The writer to write warnings.
   103      */
   104     public StringWriter warnings;
   106     /**
   107      * The buffer of warning output..
   108      */
   109     public StringBuffer standardOut;
   111     /**
   112      * The current subtest number.
   113      */
   114     private static int numTestsRun = 0;
   116     /**
   117      * The number of subtests passed.
   118      */
   119     private static int numTestsPassed = 0;
   121     /**
   122      * The current run of javadoc
   123      */
   124     private static int javadocRunNum = 0;
   126     /**
   127      * Construct a JavadocTester.
   128      */
   129     public JavadocTester() {
   130     }
   132     /**
   133      * Return the bug id.
   134      * @return the bug id
   135      */
   136     public abstract String getBugId();
   138     /**
   139      * Return the name of the bug.
   140      * @return the name of the bug
   141      */
   142     public abstract String getBugName();
   144     /**
   145      * Execute the tests.
   146      *
   147      * @param tester           the tester to execute
   148      * @param args             the arguments to pass to Javadoc
   149      * @param testArray        the array of tests
   150      * @param negatedTestArray the array of negated tests
   151      * @return                 the return code for the execution of Javadoc
   152      */
   153     public static int run(JavadocTester tester, String[] args,
   154             String[][] testArray, String[][] negatedTestArray) {
   155         int returnCode = tester.runJavadoc(args);
   156         tester.runTestsOnHTML(testArray, negatedTestArray);
   157         return returnCode;
   158     }
   160     /**
   161      * Execute Javadoc using the default doclet.
   162      *
   163      * @param args  the arguments to pass to Javadoc
   164      * @return      the return code from the execution of Javadoc
   165      */
   166     public int runJavadoc(String[] args) {
   167         float javaVersion = Float.parseFloat(JAVA_VERSION.substring(0,3));
   168         String docletClass = javaVersion < 1.5 ?
   169             DEFAULT_DOCLET_CLASS_OLD : DEFAULT_DOCLET_CLASS;
   170         return runJavadoc(docletClass, args);
   171     }
   174     /**
   175      * Execute Javadoc.
   176      *
   177      * @param docletClass the doclet being tested.
   178      * @param args  the arguments to pass to Javadoc
   179      * @return      the return code from the execution of Javadoc
   180      */
   181     public int runJavadoc(String docletClass, String[] args) {
   182         javadocRunNum++;
   183         if (javadocRunNum == 1) {
   184             System.out.println("\n" + "Running javadoc...");
   185         } else {
   186             System.out.println("\n" + "Running javadoc (run "
   187                                     + javadocRunNum + ")...");
   188         }
   189         initOutputBuffers();
   191         ByteArrayOutputStream stdout = new ByteArrayOutputStream();
   192         PrintStream prev = System.out;
   193         System.setOut(new PrintStream(stdout));
   194         int returnCode = com.sun.tools.javadoc.Main.execute(
   195                 getBugName(),
   196                 new PrintWriter(errors, true),
   197                 new PrintWriter(warnings, true),
   198                 new PrintWriter(notices, true),
   199                 docletClass,
   200                 args);
   201         System.setOut(prev);
   202         standardOut = new StringBuffer(stdout.toString());
   203         printJavadocOutput();
   204         return returnCode;
   205     }
   207     /**
   208      * Create new string writer buffers
   209      */
   210     private void initOutputBuffers() {
   211         errors   = new StringWriter();
   212         notices  = new StringWriter();
   213         warnings = new StringWriter();
   214     }
   216     /**
   217      * Run array of tests on the resulting HTML.
   218      * This method accepts a testArray for testing that a string is found
   219      * and a negatedTestArray for testing that a string is not found.
   220      *
   221      * @param testArray         the array of tests
   222      * @param negatedTestArray  the array of negated tests
   223      */
   224     public void runTestsOnHTML(String[][] testArray, String[][] negatedTestArray) {
   225         runTestsOnHTML(testArray, false);
   226         runTestsOnHTML(negatedTestArray, true);
   227     }
   229     /**
   230      * Run the array of tests on the resulting HTML.
   231      *
   232      * @param testArray the array of tests
   233      * @param isNegated true if test is negated; false otherwise
   234      */
   235     private void runTestsOnHTML(String[][] testArray , boolean isNegated) {
   236         for (int i = 0; i < testArray.length; i++) {
   238             numTestsRun++;
   240             System.out.print("Running subtest #" + numTestsRun + "... ");
   242             // Get string to find
   243             String stringToFind = testArray[i][1];
   245             // Read contents of file into a string
   246             String fileString;
   247             try {
   248                 fileString = readFileToString(testArray[i][0]);
   249             } catch (Error e) {
   250                 if (isNegated) {
   251                   numTestsPassed += 1;
   252                   System.out.println("Passed\n not found:\n"
   253                     + stringToFind + " in non-existent " + testArray[i][0] + "\n");
   254                   continue;
   255                 }
   256                 throw e;
   257             }
   258             // Find string in file's contents
   259             boolean isFound = findString(fileString, stringToFind);
   260             if ((isNegated && !isFound) || (!isNegated && isFound) ) {
   261                 numTestsPassed += 1;
   262                 System.out.println( "Passed" + "\n"
   263                                     + (isNegated ? "not found:" : "found:") + "\n"
   264                                     + stringToFind + " in " + testArray[i][0] + "\n");
   265             } else {
   266                 System.out.println( "FAILED" + "\n"
   267                                     + "for bug " + getBugId()
   268                                     + " (" + getBugName() + ")" + "\n"
   269                                     + "when searching for:" + "\n"
   270                                     + stringToFind
   271                                     + " in " + testArray[i][0] + "\n");
   272             }
   273         }
   274     }
   276     /**
   277      * Iterate through the list of given file pairs and diff each file.
   278      *
   279      * @param filePairs the pairs of files to diff.
   280      * @throws an Error is thrown if any differences are found between
   281      * file pairs.
   282      */
   283     public void runDiffs(String[][] filePairs) throws Error {
   284         runDiffs(filePairs, true);
   285     }
   287     /**
   288      * Iterate through the list of given file pairs and diff each file.
   289      *
   290      * @param filePairs the pairs of files to diff.
   291      * @param throwErrorIFNoMatch flag to indicate whether or not to throw
   292      * an error if the files do not match.
   293      *
   294      * @throws an Error is thrown if any differences are found between
   295      * file pairs and throwErrorIFNoMatch is true.
   296      */
   297     public void runDiffs(String[][] filePairs, boolean throwErrorIfNoMatch) throws Error {
   298         for (int i = 0; i < filePairs.length; i++) {
   299             diff(filePairs[i][0], filePairs[i][1], throwErrorIfNoMatch);
   300         }
   301     }
   303     /**
   304      * Check the exit code of Javadoc and record whether the test passed
   305      * or failed.
   306      *
   307      * @param expectedExitCode The exit code that is required for the test
   308      * to pass.
   309      * @param actualExitCode The actual exit code from the previous run of
   310      * Javadoc.
   311      */
   312     public void checkExitCode(int expectedExitCode, int actualExitCode) {
   313         numTestsRun++;
   314         if (expectedExitCode == actualExitCode) {
   315             System.out.println( "Passed" + "\n" + " got return code " +
   316                 actualExitCode);
   317             numTestsPassed++;
   318         } else {
   319             System.out.println( "FAILED" + "\n" + "for bug " + getBugId()
   320                 + " (" + getBugName() + ")" + "\n" + "Expected return code " +
   321                 expectedExitCode + " but got " + actualExitCode);
   322         }
   323     }
   325     /**
   326      * Print a summary of the test results.
   327      */
   328     protected void printSummary() {
   329         if ( numTestsRun != 0 && numTestsPassed == numTestsRun ) {
   330             // Test passed
   331             System.out.println("\n" + "All " + numTestsPassed
   332                                              + " subtests passed");
   333         } else {
   334             // Test failed
   335             throw new Error("\n" + (numTestsRun - numTestsPassed)
   336                                     + " of " + (numTestsRun)
   337                                     + " subtests failed for bug " + getBugId()
   338                                     + " (" + getBugName() + ")" + "\n");
   339         }
   340     }
   342     /**
   343      * Print the output stored in the buffers.
   344      */
   345     protected void printJavadocOutput() {
   346         System.out.println(STANDARD_OUTPUT + " : \n" + getStandardOutput());
   347         System.err.println(ERROR_OUTPUT + " : \n" + getErrorOutput());
   348         System.err.println(WARNING_OUTPUT + " : \n" + getWarningOutput());
   349         System.out.println(NOTICE_OUTPUT + " : \n" + getNoticeOutput());
   350     }
   352     /**
   353      * Read the file and return it as a string.
   354      *
   355      * @param fileName  the name of the file to read
   356      * @return          the file in string format
   357      */
   358     public String readFileToString(String fileName) throws Error {
   359         if (fileName.equals(ERROR_OUTPUT)) {
   360             return getErrorOutput();
   361         } else if (fileName.equals(NOTICE_OUTPUT)) {
   362             return getNoticeOutput();
   363         } else if (fileName.equals(WARNING_OUTPUT)) {
   364             return getWarningOutput();
   365         } else if (fileName.equals(STANDARD_OUTPUT)) {
   366             return getStandardOutput();
   367         }
   368         try {
   369             File file = new File(fileName);
   370             if ( !file.exists() ) {
   371                 System.out.println("\n" + "FILE DOES NOT EXIST: " + fileName);
   372             }
   373             BufferedReader in = new BufferedReader(new FileReader(file));
   375             // Create an array of characters the size of the file
   376             char[] allChars = new char[(int)file.length()];
   378             // Read the characters into the allChars array
   379             in.read(allChars, 0, (int)file.length());
   380             in.close();
   382             // Convert to a string
   383             String allCharsString = new String(allChars);
   384             return allCharsString;
   385         } catch (FileNotFoundException e) {
   386             System.err.println(e);
   387             throw new Error("File not found: " + fileName);
   388         } catch (IOException e) {
   389             System.err.println(e);
   390             throw new Error("Error reading file: " + fileName);
   391         }
   392     }
   394     /**
   395      * Compare the two given files.
   396      *
   397      * @param file1 the first file to compare.
   398      * @param file2 the second file to compare.
   399      * @param throwErrorIFNoMatch flag to indicate whether or not to throw
   400      * an error if the files do not match.
   401      * @return true if the files are the same and false otherwise.
   402      */
   403     public boolean diff(String file1, String file2, boolean throwErrorIFNoMatch) throws Error {
   404         String file1Contents = readFileToString(file1);
   405         String file2Contents = readFileToString(file2);
   406         numTestsRun++;
   407         if (file1Contents.trim().compareTo(file2Contents.trim()) == 0) {
   408             System.out.println("Diff successful: " + file1 + ", " + file2);
   409             numTestsPassed++;
   410             return true;
   411         } else if (throwErrorIFNoMatch) {
   412             throw new Error("Diff failed: " + file1 + ", " + file2);
   413         } else {
   414             return false;
   415         }
   416     }
   418     /**
   419      * Search for the string in the given file and return true
   420      * if the string was found.
   421      *
   422      * @param fileString    the contents of the file to search through
   423      * @param stringToFind  the string to search for
   424      * @return              true if the string was found
   425      */
   426     private boolean findString(String fileString, String stringToFind) {
   427         return fileString.indexOf(stringToFind) >= 0;
   428     }
   430     /**
   431      * Return the standard output.
   432      * @return the standard output
   433      */
   434     public String getStandardOutput() {
   435         return standardOut.toString();
   436     }
   438     /**
   439      * Return the error output.
   440      * @return the error output
   441      */
   442     public String getErrorOutput() {
   443         return errors.getBuffer().toString();
   444     }
   446     /**
   447      * Return the notice output.
   448      * @return the notice output
   449      */
   450     public String getNoticeOutput() {
   451         return notices.getBuffer().toString();
   452     }
   454     /**
   455      * Return the warning output.
   456      * @return the warning output
   457      */
   458     public String getWarningOutput() {
   459         return warnings.getBuffer().toString();
   460     }
   462     /**
   463      * A utility to copy a directory from one place to another.
   464      * We may possibly want to move this to our doclet toolkit in
   465      * the near future and maintain it from there.
   466      *
   467      * @param targetDir the directory to copy.
   468      * @param destDir the destination to copy the directory to.
   469      */
   470     public static void copyDir(String targetDir, String destDir) {
   471         if (targetDir.endsWith("SCCS")) {
   472             return;
   473         }
   474         try {
   475             File targetDirObj = new File(targetDir);
   476             File destDirParentObj = new File(destDir);
   477             File destDirObj = new File(destDirParentObj, targetDirObj.getName());
   478             if (! destDirParentObj.exists()) {
   479                 destDirParentObj.mkdir();
   480             }
   481             if (! destDirObj.exists()) {
   482                 destDirObj.mkdir();
   483             }
   484             String[] files = targetDirObj.list();
   485             for (int i = 0; i < files.length; i++) {
   486                 File srcFile = new File(targetDirObj, files[i]);
   487                 File destFile = new File(destDirObj, files[i]);
   488                 if (srcFile.isFile()) {
   489                     System.out.println("Copying " + srcFile + " to " + destFile);
   490                         copyFile(destFile, srcFile);
   491                 } else if(srcFile.isDirectory()) {
   492                     copyDir(srcFile.getAbsolutePath(), destDirObj.getAbsolutePath());
   493                 }
   494             }
   495         } catch (IOException exc) {
   496             throw new Error("Could not copy " + targetDir + " to " + destDir);
   497         }
   498     }
   500     /**
   501      * Copy source file to destination file.
   502      *
   503      * @throws SecurityException
   504      * @throws IOException
   505      */
   506     public static void copyFile(File destfile, File srcfile)
   507         throws IOException {
   508         byte[] bytearr = new byte[512];
   509         int len = 0;
   510         FileInputStream input = new FileInputStream(srcfile);
   511         File destDir = destfile.getParentFile();
   512         destDir.mkdirs();
   513         FileOutputStream output = new FileOutputStream(destfile);
   514         try {
   515             while ((len = input.read(bytearr)) != -1) {
   516                 output.write(bytearr, 0, len);
   517             }
   518         } catch (FileNotFoundException exc) {
   519         } catch (SecurityException exc) {
   520         } finally {
   521             input.close();
   522             output.close();
   523         }
   524     }
   525 }

mercurial