⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 junittask.java

📁 Use the links below to download a source distribution of Ant from one of our mirrors. It is good pra
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
     *     * @since Ant 1.7.1     */    protected void setupJUnitDelegate() {        ClassLoader myLoader = JUnitTask.class.getClassLoader();        if (splitJunit) {            Path path = new Path(getProject());            path.add(antRuntimeClasses);            Path extra = getCommandline().getClasspath();            if (extra != null) {                path.add(extra);            }            mirrorLoader = new SplitLoader(myLoader, path);        } else {            mirrorLoader = myLoader;        }        delegate = createMirror(this, mirrorLoader);    }    /**     * Runs the testcase.     *     * @throws BuildException in case of test failures or errors     * @since Ant 1.2     */    public void execute() throws BuildException {        setupJUnitDelegate();        List testLists = new ArrayList();        boolean forkPerTest = forkMode.getValue().equals(ForkMode.PER_TEST);        if (forkPerTest || forkMode.getValue().equals(ForkMode.ONCE)) {            testLists.addAll(executeOrQueue(getIndividualTests(),                                            forkPerTest));        } else { /* forkMode.getValue().equals(ForkMode.PER_BATCH) */            final int count = batchTests.size();            for (int i = 0; i < count; i++) {                BatchTest batchtest = (BatchTest) batchTests.elementAt(i);                testLists.addAll(executeOrQueue(batchtest.elements(), false));            }            testLists.addAll(executeOrQueue(tests.elements(), forkPerTest));        }        try {            Iterator iter = testLists.iterator();            while (iter.hasNext()) {                List l = (List) iter.next();                if (l.size() == 1) {                    execute((JUnitTest) l.get(0));                } else {                    execute(l);                }            }        } finally {            cleanup();        }    }    /**     * Run the tests.     * @param arg one JunitTest     * @throws BuildException in case of test failures or errors     */    protected void execute(JUnitTest arg) throws BuildException {        JUnitTest test = (JUnitTest) arg.clone();        // set the default values if not specified        //@todo should be moved to the test class instead.        if (test.getTodir() == null) {            test.setTodir(getProject().resolveFile("."));        }        if (test.getOutfile() == null) {            test.setOutfile("TEST-" + test.getName());        }        // execute the test and get the return code        TestResultHolder result = null;        if (!test.getFork()) {            result = executeInVM(test);        } else {            ExecuteWatchdog watchdog = createWatchdog();            result = executeAsForked(test, watchdog, null);            // null watchdog means no timeout, you'd better not check with null        }        actOnTestResult(result, test, "Test " + test.getName());    }    /**     * Execute a list of tests in a single forked Java VM.     * @param testList the list of tests to execute.     * @throws BuildException on error.     */    protected void execute(List testList) throws BuildException {        JUnitTest test = null;        // Create a temporary file to pass the test cases to run to        // the runner (one test case per line)        File casesFile = createTempPropertiesFile("junittestcases");        PrintWriter writer = null;        try {            writer =                new PrintWriter(new BufferedWriter(new FileWriter(casesFile)));            Iterator iter = testList.iterator();            while (iter.hasNext()) {                test = (JUnitTest) iter.next();                writer.print(test.getName());                if (test.getTodir() == null) {                    writer.print("," + getProject().resolveFile("."));                } else {                    writer.print("," + test.getTodir());                }                if (test.getOutfile() == null) {                    writer.println("," + "TEST-" + test.getName());                } else {                    writer.println("," + test.getOutfile());                }            }            writer.flush();            writer.close();            writer = null;            // execute the test and get the return code            ExecuteWatchdog watchdog = createWatchdog();            TestResultHolder result =                executeAsForked(test, watchdog, casesFile);            actOnTestResult(result, test, "Tests");        } catch (IOException e) {            log(e.toString(), Project.MSG_ERR);            throw new BuildException(e);        } finally {            if (writer != null) {                writer.close();            }            try {                casesFile.delete();            } catch (Exception e) {                log(e.toString(), Project.MSG_ERR);            }        }    }    /**     * Execute a testcase by forking a new JVM. The command will block     * until it finishes. To know if the process was destroyed or not     * or whether the forked Java VM exited abnormally, use the     * attributes of the returned holder object.     * @param  test       the testcase to execute.     * @param  watchdog   the watchdog in charge of cancelling the test if it     * exceeds a certain amount of time. Can be <tt>null</tt>, in this case     * the test could probably hang forever.     * @param casesFile list of test cases to execute. Can be <tt>null</tt>,     * in this case only one test is executed.     * @return the test results from the JVM itself.     * @throws BuildException in case of error creating a temporary property file,     * or if the junit process can not be forked     */    private TestResultHolder executeAsForked(JUnitTest test,                                             ExecuteWatchdog watchdog,                                             File casesFile)        throws BuildException {        if (perm != null) {            log("Permissions ignored when running in forked mode!",                Project.MSG_WARN);        }        CommandlineJava cmd;        try {            cmd = (CommandlineJava) (getCommandline().clone());        } catch (CloneNotSupportedException e) {            throw new BuildException("This shouldn't happen", e, getLocation());        }        cmd.setClassname("org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner");        if (casesFile == null) {            cmd.createArgument().setValue(test.getName());        } else {            log("Running multiple tests in the same VM", Project.MSG_VERBOSE);            cmd.createArgument().setValue(Constants.TESTSFILE + casesFile);        }        cmd.createArgument().setValue(Constants.FILTERTRACE + test.getFiltertrace());        cmd.createArgument().setValue(Constants.HALT_ON_ERROR + test.getHaltonerror());        cmd.createArgument().setValue(Constants.HALT_ON_FAILURE                                      + test.getHaltonfailure());        checkIncludeAntRuntime(cmd);        checkIncludeSummary(cmd);        cmd.createArgument().setValue(Constants.SHOWOUTPUT                                      + String.valueOf(showOutput));        cmd.createArgument().setValue(Constants.OUTPUT_TO_FORMATTERS                                      + String.valueOf(outputToFormatters));        cmd.createArgument().setValue(            Constants.LOGTESTLISTENEREVENTS + "true"); // #31885        StringBuffer formatterArg = new StringBuffer(STRING_BUFFER_SIZE);        final FormatterElement[] feArray = mergeFormatters(test);        for (int i = 0; i < feArray.length; i++) {            FormatterElement fe = feArray[i];            if (fe.shouldUse(this)) {                formatterArg.append(Constants.FORMATTER);                formatterArg.append(fe.getClassname());                File outFile = getOutput(fe, test);                if (outFile != null) {                    formatterArg.append(",");                    formatterArg.append(outFile);                }                cmd.createArgument().setValue(formatterArg.toString());                formatterArg = new StringBuffer();            }        }        File vmWatcher = createTempPropertiesFile("junitvmwatcher");        cmd.createArgument().setValue(Constants.CRASHFILE                                      + vmWatcher.getAbsolutePath());        File propsFile = createTempPropertiesFile("junit");        cmd.createArgument().setValue(Constants.PROPSFILE                                      + propsFile.getAbsolutePath());        Hashtable p = getProject().getProperties();        Properties props = new Properties();        for (Enumeration e = p.keys(); e.hasMoreElements();) {            Object key = e.nextElement();            props.put(key, p.get(key));        }        try {            FileOutputStream outstream = new FileOutputStream(propsFile);            props.store(outstream, "Ant JUnitTask generated properties file");            outstream.close();        } catch (java.io.IOException e) {            propsFile.delete();            throw new BuildException("Error creating temporary properties "                                     + "file.", e, getLocation());        }        Execute execute = new Execute(            new JUnitLogStreamHandler(                this,                Project.MSG_INFO,                Project.MSG_WARN),            watchdog);        execute.setCommandline(cmd.getCommandline());        execute.setAntRun(getProject());        if (dir != null) {            execute.setWorkingDirectory(dir);        }        String[] environment = env.getVariables();        if (environment != null) {            for (int i = 0; i < environment.length; i++) {                log("Setting environment variable: " + environment[i],                    Project.MSG_VERBOSE);            }        }        execute.setNewenvironment(newEnvironment);        execute.setEnvironment(environment);        log(cmd.describeCommand(), Project.MSG_VERBOSE);        checkForkedPath(cmd);        TestResultHolder result = new TestResultHolder();        try {            result.exitCode = execute.execute();        } catch (IOException e) {            throw new BuildException("Process fork failed.", e, getLocation());        } finally {            String vmCrashString = "unknown";            BufferedReader br = null;            try {                if (vmWatcher.exists()) {                    br = new BufferedReader(new FileReader(vmWatcher));                    vmCrashString = br.readLine();                } else {                    vmCrashString = "Monitor file ("                            + vmWatcher.getAbsolutePath()                            + ") missing, location not writable,"                            + " testcase not started or mixing ant versions?";                }            } catch (Exception e) {                e.printStackTrace();                // ignored.            } finally {                FileUtils.close(br);                if (vmWatcher.exists()) {                    vmWatcher.delete();                }            }            if (watchdog != null && watchdog.killedProcess()) {                result.timedOut = true;                logTimeout(feArray, test, vmCrashString);            } else if (!Constants.TERMINATED_SUCCESSFULLY.equals(vmCrashString)) {                result.crashed = true;                logVmCrash(feArray, test, vmCrashString);            }            if (!propsFile.delete()) {                throw new BuildException("Could not delete temporary "                                         + "properties file.");            }        }        return result;    }    /**     * Adding ant runtime.     * @param cmd command to run     */    private void checkIncludeAntRuntime(CommandlineJava cmd) {        if (includeAntRuntime) {            Vector v = Execute.getProcEnvironment();            Enumeration e = v.elements();            while (e.hasMoreElements()) {                String s = (String) e.nextElement();                if (s.startsWith(CLASSPATH)) {                    cmd.createClasspath(getProject()).createPath()                        .append(new Path(getProject(),                                         s.substring(CLASSPATH.length()                                                     )));                }            }            log("Implicitly adding " + antRuntimeClasses + " to CLASSPATH",                Project.MSG_VERBOSE);            cmd.createClasspath(getProject()).createPath()                .append(antRuntimeClasses);        }    }    /**     * check for the parameter being "withoutanderr" in a locale-independent way.     * @param summaryOption the summary option -can be null     * @return true if the run should be withoutput and error     */    private boolean equalsWithOutAndErr(String summaryOption) {        return summaryOption != null && "withoutanderr".equals(            summaryOption.toLowerCase(Locale.ENGLISH));    }    private void checkIncludeSummary(CommandlineJava cmd) {        if (summary) {            String prefix = "";            if (equalsWithOutAndErr(summaryValue)) {                prefix = "OutErr";            }            cmd.createArgument()                .setValue(Constants.FORMATTER                          + "org.apache.tools.ant.taskdefs.optional.junit."                          + prefix + "SummaryJUnitResultFormatter");        }    }    /**     * Check the path for multiple different versions of     * ant.     * @param cmd command to execute     */    private void checkForkedPath(CommandlineJava cmd) {        if (forkedPathChecked) {            return;        }        forkedPathChecked = true;        if (!cmd.haveClasspath()) {            return;        }        AntClassLoader loader = new AntClassLoader(            getProject(), cmd.createClasspath(getProject()));        String projectResourceName = LoaderUtils.classNameToResource(            Project.class.getName());        URL previous = null;        try {            for (Enumeration e = loader.getResources(projectResourceName);                 e.hasMoreElements();) {                URL current = (URL) e.nextElement();

⌨️ 快捷键说明

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