oaatest.java

来自「SRI international 发布的OAA框架软件」· Java 代码 · 共 320 行

JAVA
320
字号
/*
#=========================================================================
# Copyright 2003 SRI International.  All rights reserved.
#
# The material contained in this file is confidential and proprietary to SRI
# International and may not be reproduced, published, or disclosed to others
# without authorization from SRI International.
#
# DISCLAIMER OF WARRANTIES
#
# SRI International MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
# SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SRI International SHALL NOT BE
# LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
# OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES
#=========================================================================
*/
package com.sri.oaa2.tools.oaatest;

import java.util.*;
import java.io.*;
import junit.framework.*;
import junit.extensions.TestSetup;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;



/** OaaTest is the entry point to the OaaTest testing tool. */
public class OaaTest {
  private static String version; // Something like "1.02" or null if unknown.  

  // If we don't force logging to get set up early, ANT doesn't display our log4j
  // messages.
  static {
    Log.singleton();   
    // Force LibOaa to set up logging.
    try {
      Class.forName("com.sri.oaa2.lib.LibOaa");
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();      
    }

    // Get version number.
    InputStream verStream = ClassLoader.getSystemResourceAsStream("com/sri/oaa2/tools/oaatest/version.properties");
    if (verStream != null) {
      Properties props = new Properties();
      try {
        props.load(verStream);
      }
      catch (IOException e) {
        e.printStackTrace();      
      }
      String major = props.getProperty("oaatest.version.major");
      String minor = props.getProperty("oaatest.version.minor");
      if (major != null && minor != null) {
        version = major + "." + minor;
      }
    }
    if (version == null) {
      Log.singleton().error("Could not find OaaTest version number.");
    }
  }
  
  /** 
   *  Run the OaaTest tool in standalone mode, with graphical (default) or text
   *  test-result viewer.  
   *  Specify the input test directory with the "oaatest.in" java property, e.g.
   *  "java -Doaatest.in=c:\mytests com.sri.oaa2.tools.oaatest.OaaTest"
   *  Command line arguments:
   *    -version ->  Print version number and exit.
   *    -help    ->  Print usage info and exit.
   *    -text    ->  Run in text mode.
   *
   *  If using an external JUnit tool, use OaaTest.suite() instead of OaaTest.main().
   */
  public static void main(String args[]) {
    // Parse command line.
    boolean gui = true;
    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-text")) {
        gui = false;
      }
      else if (args[i].equals("-help") || args[i].equals("-h") ||
               args[i].equals("-?")) {
        printHelp();
        System.exit(0);
      }
      else if (args[i].equals("-version")) {
        printVersion();
        System.exit(0);
      }
    }
    try {
      if (gui) {
        junit.swingui.TestRunner.run(OaaTest.class);
      }
      else {
        junit.textui.TestRunner.run(suite());
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static void printHelp() {
    System.out.println("usage:   OaaTest <options>");
    System.out.println("  where options are:");
    System.out.println("    -help     Print this message.");
    System.out.println("    -version  Print version number.");
    System.out.println("    -text     Run text-based interface (otherwise use Swing-based gui).");
    System.out.println("OR use your own JUnit test runner and point it at " + OaaTest.class.getName());
  }  

  private static void printVersion() {
    if (version != null) {
      System.out.println("This is OaaTest version " + version + ".");
    }
    else {
      System.out.println("ERROR: OaaTest version unknown.");
    }
  }

  /** This is the JUnit entry point.  Read in test files and generate test suites.  
   *  Set the "oaatest.in" property to specify the location of the test case files.
   *  Otherwise will default to current directory.
   */ 
  public static Test suite() throws IOException, ParserConfigurationException, 
                                    SAXException, ClassNotFoundException {
    // The instantiated OaaTest object itself is only used for reading in test files,
    // and creating oaaTest.suite.  After suite() reutrns, the OaaTest object can 
    // be disposed.
    OaaTest oaaTest = new OaaTest();
    return oaaTest.suite;
  }
  
  /** This method is provided so OaaTest_T is sure to use the same parser as OaaTest. */
  static SAXParser createParser() throws ParserConfigurationException, SAXException {
    // Create a JAXP parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    // spf.setValidating(true);  TODO use oaatest.dtd
  
    // Want to create one parser for parsing all test files.
    SAXParser parser = factory.newSAXParser();
    return parser;
  }
    
  private OaaTest() throws IOException, ParserConfigurationException, 
                           SAXException, ClassNotFoundException {
    // Get location of test files or default to current directory. 
    String testFileName = System.getProperty("oaatest.in");
    if (testFileName == null) {
      testFileName = System.getProperty("user.dir");
    }
    Log.singleton().info("Looking for test files in " + testFileName);
    File testDir = new File(testFileName);

    // For parsing XML files.
    parser = createParser();
    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    docBuilder = f.newDocumentBuilder();

    // Load all tests from test directory hierarchy.
    Test innerSuite = readFiles(testDir);
    if (innerSuite == null) {
      // Might not be the best exception to throw, but it'll work and the
      // user will see the error message.
      throw new IOException("No test cases found under " + testDir);
    }

    // Connect OaaConnector to facilitator before starting any tests and 
    // disconnect after all tests complete.
    suite = new TestSetup(innerSuite) {
      protected void setUp() throws Exception {
        super.setUp();
        OaaConnector.connect();
      }
      protected void tearDown() throws Exception {
        Log.singleton().info("Test run complete.");
        OaaConnector.disconnect();
        super.tearDown();
      }
    };

    // this.suite is now valid.
  }

  /** Read test files from directory and return Test or TestSuite with OaaTestCases. 
   * Return null if file is not an OaaTML file, index file, or directory.  
   * For directories, use index file if present else read all .otml files and recurse
   * on subdirectories. 
   * @param file may be a file or directory
   */
  private Test readFiles(File file)
    throws IOException, SAXException {

    if (file.isDirectory()) {
      // If the directory has an index file, use that.
      File indexFile = new File(file,INDEX_FILENAME + INDEX_FILE_SUFFIX);
      if (indexFile.canRead()) {
        return readFilesFromIndex(indexFile); 
      }

      // If no index file, read all .otml files and recurse on subdirectories.
      TestSuite suite = new TestSuite(TEST_SUITE_NAME_PREFIX + file); 
      File[] subFiles = file.listFiles();
      for (int i = 0; i < subFiles.length; i++) {
        File subFile = subFiles[i];
        Test subTest = readFiles(subFile);
        if (subTest != null) {
          suite.addTest(subTest);
        }
      }
      if (suite.countTestCases() > 0) {
        return suite;
      }
    }
    else if (file.canRead()) {
      if (file.getName().endsWith(INDEX_FILE_SUFFIX)) {
        return readFilesFromIndex(file); 
      }
      else if (file.getName().endsWith(TEST_FILE_SUFFIX)) {
        return new OaaTestCase(parser,file);
      }      
    }

    return null;
  }

  /** Read files specified in index file and return TestSuite. */
  private Test readFilesFromIndex(File index) throws IOException, SAXException {
    Document doc = docBuilder.parse(index);    
    TestSuite suite = new TestSuite(TEST_SUITE_NAME_PREFIX + index.getParent()); 
    
    Element root = doc.getDocumentElement();
    if (!root.getNodeName().equals("index")) {
      throw new ParseException("root element must be <index>",index);
    }
    readFilesFromIndexNode(root,suite,index);

    if (suite.countTestCases() > 0) {
      return suite;
    }
    return null;
  }

  /** Parse <testcase> nodes under node and fill suite with OaaTestCase objects.
   * Handle <repeat> and <dir> tags.
   * @param indexFile filename of XML file we are reading.
   */
  private void readFilesFromIndexNode(Node node,TestSuite suite,File indexFile) throws IOException, SAXException {
    NodeList kids = node.getChildNodes();
    for (int n = 0; n < kids.getLength(); n++) {
      Node kid = kids.item(n);
      if (kid instanceof Element) {
        Element element = (Element)kid;
        if (element.getNodeName().equals("testcase")) {
          String fname = element.getAttribute("file");
          if (fname.length() == 0) {
            throw new ParseException("<testcase> must have 'file' attribute",indexFile);
          }
          File file = new File(indexFile.getParent(),fname);
          suite.addTest(new OaaTestCase(parser,file)); 
        }
        else if (element.getNodeName().equals("dir")) {
          String fname = element.getAttribute("dir");
          if (fname.length() == 0) {
            throw new ParseException("<dir> must have 'dir' attribute",indexFile);
          }
          File file = new File(indexFile.getParent(),fname);
          if (!file.isDirectory()) {
            throw new ParseException(file + "is not a directory",indexFile);            
          }
          Test test = readFiles(file);
          if (test != null) {
            suite.addTest(test);
          }
        }
        else if (element.getNodeName().equals("repeat")) {
          String countS = element.getAttribute("count");
          if (countS.length() == 0) {
            throw new ParseException("<repeat> must have 'count' attribute",indexFile);
          }
          int count;
          try {
            count = Integer.parseInt(countS);
          }
          catch (NumberFormatException e) {
            count = -1;
          }
          if (count <= 0) {
            throw new ParseException("'count' attribute must be an integer > 0",indexFile);
          }
          TestSuite repeatSuite = new RepeatTestSuite(count);
          suite.addTest(repeatSuite);
          readFilesFromIndexNode(element,repeatSuite,indexFile); 
        }
        else {
          throw new ParseException("unknown element <" + element.getLocalName() + ">",indexFile);          
        }
      }
    }
  }
  
  // Added along with directory to make name of TestSuite. 
  private static final String TEST_SUITE_NAME_PREFIX = "Tests from: ";
  private static final String INDEX_FILENAME = "index";
  private static final String INDEX_FILE_SUFFIX = ".idx";
  private static final String TEST_FILE_SUFFIX = ".otml";
  
  private SAXParser parser; // For reading .otml files
  private DocumentBuilder docBuilder; // For reading index files
  private Test suite;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?