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

📄 junittask.java

📁 java ant的源码!非常值得看的源码
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
            "JUnitTaskMirrorImpl",            "JUnitTestRunner",            "JUnitVersionHelper",            "OutErrSummaryJUnitResultFormatter",            "PlainJUnitResultFormatter",            "SummaryJUnitResultFormatter",            "XMLJUnitResultFormatter",        };        private boolean isSplit(String classname) {            String simplename = classname.substring(classname.lastIndexOf('.') + 1);            for (int i = 0; i < splitClasses.length; i++) {                if (simplename.equals(splitClasses[i])                        || simplename.startsWith(splitClasses[i] + '$')) {                    return true;                }            }            return false;        }    }    /**     * Runs the testcase.     *     * @throws BuildException in case of test failures or errors     * @since Ant 1.2     */    public void execute() throws BuildException {        ClassLoader myLoader = JUnitTask.class.getClassLoader();        ClassLoader mirrorLoader;        if (splitJunit) {            Path path = new Path(getProject());            path.add(antRuntimeClasses);            path.add(getCommandline().getClasspath());            mirrorLoader = new SplitLoader(myLoader, path);        } else {            mirrorLoader = myLoader;        }        delegate = createMirror(this, mirrorLoader);        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 {            deleteClassLoader();            if (mirrorLoader instanceof SplitLoader) {                ((SplitLoader) mirrorLoader).cleanup();            }            delegate = null;        }    }    /**     * 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 tests the list of tests to execute.     * @throws BuildException on error.     */    protected void execute(List tests) 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 = tests.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.     * @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 = null;        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());        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);        }        if (summary) {            String prefix = "";            if ("withoutanderr".equalsIgnoreCase(summaryValue)) {                prefix = "OutErr";            }            cmd.createArgument()                .setValue(Constants.FORMATTER                          + "org.apache.tools.ant.taskdefs.optional.junit."                          + prefix + "SummaryJUnitResultFormatter");        }        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);        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 {                br = new BufferedReader(new FileReader(vmWatcher));                vmCrashString = br.readLine();            } catch (Exception e) {                e.printStackTrace();                // ignored.            } finally {                FileUtils.close(br);            }            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);            }            vmWatcher.delete();            if (!propsFile.delete()) {                throw new BuildException("Could not delete temporary "                                         + "properties file.");            }        }        return result;    }    /**     * Create a temporary file to pass the properties to a new process.     * Will auto-delete on (graceful) exit.     * The file will be in the project basedir unless tmpDir declares     * something else.     * @param prefix     * @return created file     */    private File createTempPropertiesFile(String prefix) {        File propsFile =            FILE_UTILS.createTempFile(prefix, ".properties",                tmpDir != null ? tmpDir : getProject().getBaseDir(), true);        return propsFile;    }    /**     * Pass output sent to System.out to the TestRunner so it can     * collect ot for the formatters.     *     * @param output output coming from System.out     * @since Ant 1.5     */    protected void handleOutput(String output) {

⌨️ 快捷键说明

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