momeunittask.java

来自「MoMEUnit是一个单元测试的J2ME的应用程序xUnit架构实例。这是来自J」· Java 代码 · 共 1,807 行 · 第 1/4 页

JAVA
1,807
字号
      if (this.preverify.isOnlyAppJar()) executePreverifier(this.appJar,          this.appJar.getParentFile(), getTempDir());      File jadFile = new File(this.appDir, this.getAppName() + ".jad");      if (this.delOnExit) this.filesToDelete.add(jadFile);      makeJAD(jadFile, this.appJar);      if (this.testListHolder.size() > 0) this.executeEmulator(jadFile,          this.appJar);      else log("No tests found.", Project.MSG_WARN);    } finally    {      for (int i = this.filesToDelete.size() - 1; i >= 0; i--)        ((File) this.filesToDelete.elementAt(i)).delete();    }  }  /**   * Starts preverifier if needed.   *    * @since 1.1   */  private void executePreverifier(File jar, File toDir, File atDir)  {    log("Preverifying app: " + jar.getAbsolutePath(), Project.MSG_VERBOSE);    Process p = getPreverifier().execute(jar, toDir, atDir);    if (this.showOutput)    {      new OutputLogger(p.getInputStream(), this, Project.MSG_INFO).start();      new OutputLogger(p.getErrorStream(), this, Project.MSG_ERR).start();    }    try    {      int exitCode = p.waitFor();      if (exitCode != 0) throw new BuildException("preverifier failed with :"          + exitCode);      log("Preverifier returned normally", Project.MSG_VERBOSE);    } catch (InterruptedException e)    {      throw new BuildException("build interrupted while executing preverifier.");    }  }  /**   * Adds collected tests to libs and classpath.   *    * @since 1.1   */  private void addTestsToLibsAndClasspath()  {    for (Iterator i = this.tests.iterator(); i.hasNext();)    {      TestElement test = (TestElement) i.next();      if (test.shouldUse(this) && (test.containsClasses()))      {        FileSet fs = test.getFileSet();        File pathElement = null;        if (fs instanceof ZipFileSet) pathElement = ((ZipFileSet) fs)            .getSrc(getProject());        else pathElement = fs.getDir(getProject());        getClasspath().setLocation(pathElement);        this.libs.add(fs);        log("Tests under " + pathElement.getAbsolutePath()            + " added to classpath and libs", Project.MSG_VERBOSE);      }    }  }  /**   * Adds implicit test if specified to set of tests.   */  private void addImplicitTest()  {    if (this.implicitTest != null)    {      if (this.pattern != null) this.implicitTest.setPattern(this.pattern);      this.implicitTest.setOnlyTests(this.onlyTests);      this.tests.add(this.implicitTest);      log("Implicit test added.", Project.MSG_VERBOSE);    }  }  /**   * Compiles source java classes if there are some specified.   */  private void compile()  {    Set srcs = new HashSet();    for (Iterator i = this.tests.iterator(); i.hasNext();)    {      TestElement test = (TestElement) i.next();      if (test.shouldUse(this) && !test.containsClasses()) srcs.add(test          .getFileSet());    }    if (srcs.size() > 0)    {      Compiler compiler = getCompiler();      if (compiler.getDestdir() == null)      {        log("compiler destination directory not specified.",            Project.MSG_VERBOSE);        File binDir = new File(this.appDir, "bin");        if (!binDir.exists() && !binDir.mkdir()) throw new BuildException(            "Error creating directory " + binDir.getAbsolutePath());        compiler.setDestdir(binDir);        log(            "compiler destination directory set to " + binDir.getAbsolutePath(),            Project.MSG_VERBOSE);        if (!compiler.wasDelOnExitSet()) compiler.setDelOnExit(true);      } else if (!compiler.wasDelOnExitSet()) compiler.setDelOnExit(false);      compiler.init(srcs, getClasspath());      compiler.execute();      this.libs.add(createFileSet(compiler.getDestdir()));      getClasspath().setLocation(compiler.getDestdir());      log("Compiled classes directory "          + compiler.getDestdir().getAbsolutePath()          + " added to classpath and libs.", Project.MSG_VERBOSE);      if (compiler.isDelOnExit()) removeDirTree(compiler.getDestdir());    }  }  /**   * Starts emulator.   *    * @param jad   *          jad descriptor file of app.   * @param jar   *          jar file of app.   */  private void executeEmulator(File jad, File jar)  {    try    {      Set fs = new HashSet();      TestErrorIndicator errorIndicator = null;      if (this.runnerType.supportsFormatters())      {        fs.addAll(getAndStartFormatters());        errorIndicator = new TestErrorIndicator(this, this.printSummary            .asBoolean(), this.printSummary.isWithOutAndErr());        fs.add(errorIndicator);      } else if (this.formatters.size() > 0 || this.errorProperty != null          || this.failureProperty != null || this.haltOnError.asBoolean()          || this.haltOnFailure.asBoolean() || this.printSummary.asBoolean()) log(          "\""              + this.runnerType.getValue()              + "\" runner type doesn't support <formatter> nested element "              + "errorproperty,failureproperty,haltonerror,haltonfailure,printsummary attributes"              + "\nContents of these elements are ignored.", Project.MSG_WARN);      Path emulClasspath = getEmulatorElement().getClasspath();      if (emulClasspath != null && emulClasspath.size() > 0) emulClasspath          .setLocation(this.appJar);      log("Starting emulator", Project.MSG_VERBOSE);      if (this.jad.getAppProperty(MOMEUNIT_TIMEOUT_KEY) != null) log(          "Executing tests with timeout="              + this.jad.getAppProperty(MOMEUNIT_TIMEOUT_KEY) + " checking.",          Project.MSG_VERBOSE);      Process p = getEmulator().execute(this.runnerType.getRunnerClassName(),          jad, jar);      OutputToString systemOut = attachOutputProcessors(p.getInputStream(),          this.listenOnOut ? fs : null, Project.MSG_INFO);      OutputToString systemErr = attachOutputProcessors(p.getErrorStream(),          this.listenOnErr ? fs : null, Project.MSG_ERR);      int exitCode = p.waitFor();      endTests(errorIndicator, fs, systemOut, systemErr);      if (exitCode != 0) log("Emulator returned with error " + exitCode,          Project.MSG_ERR);      else log("Emulator returned normally", Project.MSG_VERBOSE);    } catch (InterruptedException e)    {      log("build interrupted while executing emulator.", Project.MSG_ERR);    }  }  /**   * Creates FormatterElement for nested <code>&lt;formatter&gt;</code> tag.   *    * @return created FormatterElement.   * @since 1.1   */  public FormatterElement createFormatter()  {    FormatterElement res = new FormatterElement();    res.setTask(this);    this.formatters.add(res);    return res;  }  /**   * Returns set of momeunit results formatters configured via &lt;formatter&gt;   * tags.   *    * @return set of momeunit results formatters.   */  private Set getAndStartFormatters()  {    Set res = new HashSet();    for (Iterator i = this.formatters.iterator(); i.hasNext();)    {      FormatterElement fElement = (FormatterElement) i.next();      if (fElement.shouldUse(this))      {        UnitResultFormatter formatter = fElement.createFormatter(            getReportDir(), getReportFile(), this, this.loader);        formatter.startTestSuite(this.testsName);        res.add(formatter);      }    }    return res;  }  /**   * Sets test suite name.   *    * @param name   *          test suite name to set.   * @since 1.1   */  public void setName(String name)  {    Utility.assertNotEmpty(name, "name", getTaskType());    this.testsName = name;  }  /**   * Sets name of application to build. <code>&lt;momeunit&gt;</code> will use   * It as the basename of midlet jar and jad descriptor files. Defaults to   * <code>name</code> attribute.   *    * @param name   *          the name of application to build..   * @since 1.1   */  public void setAppName(String name)  {    Utility.assertNotEmpty(name, "appname", getTaskType());    this.appName = name;  }  /**   * Sets directory where report files should be created.   *    * @param reportDir   *          directory where report files should be created.   * @since 1.1   */  public void setReportDir(File reportDir)  {    Utility.assertDirectory(reportDir, "reportdir");    this.reportDir = reportDir;  }  /**   * Sets basename of report files to create.   *    *    * @param reportFile   *          basename of report files to create.   * @since 1.1   */  public void setReportFile(String reportFile)  {    Utility.assertNotEmpty(reportFile, "reportfile", getTaskType());    this.reportFile = reportFile;  }  /**   * Return basename of report files to create.   *    * @return basename of report files to create.   */  private String getReportFile()  {    return (this.reportFile != null) ? this.reportFile : "tests-"        + this.testsName;  }  /**   * Returns directory where report files should be created.   *    * @return directory where report files should be created.   */  private File getReportDir()  {    if (this.reportDir == null)    {      String dir = this.getProject().getProperty("basedir");      this.reportDir = dir != null ? new File(dir) : new File("./");    }    return this.reportDir;  }  /**   * Sets whether to direct output to ant's log.   *    * @param showOutput   *          <code>true</code> if output should be directed to ant's log,   *          <code>false</code> otherwise.   * @since 1.1   */  public void setShowOutput(boolean showOutput)  {    this.showOutput = showOutput;  }  /**   * Sets name of the property to set on the event of an error.   *    * @param errorProperty   *          the name of property to set on the event of an error.   * @since 1.1   */  public void setErrorProperty(String errorProperty)  {    Utility.assertNotEmpty(errorProperty, "errorproperty", getTaskType());    this.errorProperty = errorProperty;  }  /**   * Sets name of the property to set on the event of a failure (errors are   * considered failures as well).   *    * @param failureProperty   *          the name of property to set on the event of a failure (errors are   *          considered failures as well).   * @since 1.1   */  public void setFailureProperty(String failureProperty)  {    Utility.assertNotEmpty(failureProperty, "failureproperty", getTaskType());    this.failureProperty = failureProperty;  }  /**   * Sets whether to stop the build process if an error occurs during the tests   * run. Can take the values <code>on</code>, <code>off</code>, and   * <code>withCease</code>. If set to   * </p>   * <ul>   * <li><code>on</code> - stop build process, but not cease tests execution   * (all test are executed).</li>   * <li><code>off</code> - don't stop build process.</li>   * <li><code>withCease</code> - stop build process and cease tests   * execution.</li>   * </ul>   *    * @param haltOnError   *          <code>haltonerror</code> attribute to set.   *    * @since 1.1.2   */  public void setHaltOnError(String haltOnError)  {    Utility.assertNotEmpty(haltOnError, "haltonerror", getTaskName());    this.haltOnError.setValue(haltOnError);  }  /**   * Sets whether to stop the build process if some test fails (errors are   * considered failures as well). Can take the values <code>on</code>,   * <code>off</code>, and <code>withCease</code>. If set to   * </p>   * <ul>   * <li><code>on</code> - stop build process, but not cease tests execution   * (all test are executed).</li>   * <li><code>off</code> - don't stop build process.</li>   * <li><code>withCease</code> - stop build process and cease tests   * execution.</li>   * </ul>   *    * @param haltOnFailure   *          <code>haltonfailure</code> attribute to set.   * @since 1.1.2   */  public void setHaltOnFailure(String haltOnFailure)  {    Utility.assertNotEmpty(haltOnFailure, "haltonfailure", getTaskName());    this.haltOnFailure.setValue(haltOnFailure);  }  /**   * Sets whether to filter out <code>momeunit</code> and <code>mome</code>   * stack frames from error and failure stack traces.   *    * @param filter   *          flag to set.   * @since 1.1   */  public void setFilterTrace(boolean filter)  {    for (Iterator i = this.formatters.iterator(); i.hasNext();)      ((FormatterElement) i.next()).setFilterTrace(filter);  }  /**   * Notifies formatters given ErrorIndicator of end of tests run. Stops build   * on error or failure (depends on configuration) and sets error-property   * and/or failure-property (depends on configuration).   *    * @param indicator   *          ErrorIndicator to notify.   * @param formatters   *          Formatters to notify.   * @param out   * @param err   */  private void endTests(TestErrorIndicator indicator, Set formatters,      OutputToString out, OutputToString err)  {    if (formatters != null)    {      for (Iterator i = formatters.iterator(); i.hasNext();)      {        UnitResultFormatter formatter = (UnitResultFormatter) i.next();        formatter.setSystemOutput(out.getOutputString());        formatter.setSystemError(err.getOutputString());        formatter.endTestSuite();      }    }    if (indicator != null)    {      if (this.haltOnError.asBoolean() && indicator.hasErrors()) throw new BuildException(          indicator.getErrorMessage());      if (this.haltOnFailure.asBoolean())      {        if (indicator.hasFailures()) throw new BuildException(indicator            .getFailureMessage());        if (indicator.hasErrors()) throw new BuildException(indicator            .getErrorMessage());      }      if (this.errorProperty != null && indicator.hasErrors()) this          .getProject().setNewProperty(this.errorProperty, "true");      if (this.failureProperty != null          && (indicator.hasFailures() || indicator.hasErrors())) this          .getProject().setNewProperty(this.failureProperty, "true");    }  }  /**   * Attaches test event filters to process.   *    * @param output   * @param formatters   * @param msgPriority   * @param indicator   * @return   */  private OutputToString attachOutputProcessors(InputStream output,      Set formatters, int msgPriority)  {    OutputToString sysOut = null;    try    {

⌨️ 快捷键说明

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