All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.moe.gradle.utils.JUnitTestCollector Maven / Gradle / Ivy

/*
Copyright (C) 2016 Migeran

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.moe.gradle.utils;

import org.apache.commons.lang3.StringEscapeUtils;
import org.moe.gradle.anns.IgnoreUnused;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;

public class JUnitTestCollector {

    /**
     * JUnit test message IDs.
     */
    private class MessageIDs {

        /**
         * Test run start message ID.
         */
        private static final String TEST_RUN_START = "%TESTC  :";

        /**
         * Test definition message ID.
         */
        private static final String TEST_DEFINE = "%TESTD  :";

        /**
         * Test start message ID.
         */
        private static final String TEST_START = "%TESTS  :";

        /**
         * Test end message ID.
         */
        private static final String TEST_END = "%TESTE  :";

        /**
         * Test error message ID.
         */
        private static final String TEST_ERROR = "%ERROR  :";

        /**
         * Test failed message ID.
         */
        private static final String TEST_FAILED = "%FAILED :";

        /**
         * Test ignored message ID.
         */
        private static final String TEST_IGNORED = "%IGNORED:";

        /**
         * Test run end message ID.
         */
        private static final String TEST_RUN_END = "%RUNTIME:";
    }

    /**
     * Number of tests.
     */
    private int numTests;
    /**
     * Number of started tests.
     */
    private int numStarted;
    /**
     * Number of failed tests.
     */
    private int numFailures;
    /**
     * Number of tests with errors.
     */
    private int numErrors;
    /**
     * Number of ignored tests.
     */
    private int numIgnored;
    /**
     * Test received last message flag.
     */
    private boolean hasEnded;

    /**
     * Test suites.
     */
    private final HashMap suites = new HashMap<>();

    /**
     * Complete input.
     */
    private final StringBuilder completeInput = new StringBuilder();

    /**
     * Class representing a test suite.
     */
    private static class TestSuite {
        /**
         * Name of the suite.
         */
        String name;
        /**
         * Suite execution time.
         */
        long time;
        /**
         * Test cases in suite.
         */
        final HashMap cases = new HashMap<>();
    }

    /**
     * Class representing a test suite.
     */
    private static class TestCase {
        /**
         * Name of the case.
         */
        String name;
        /**
         * Case execution time.
         */
        long time;
        /**
         * Failure string or null.
         */
        StringBuilder failure;
        /**
         * Case test was started.
         */
        boolean wasStarted = false;
        /**
         * Case test was ignored.
         */
        boolean wasIgnored = false;
    }

    private TestCase currentTest;

    /**
     * Append a line to the test.
     *
     * @param line line to append
     */
    public void appendLine(String line) {
        if (line == null || line.length() == 0) {
            return;
        }

        completeInput.append(line).append('\n');

        if (line.startsWith(MessageIDs.TEST_RUN_START)) {

        } else if (line.startsWith(MessageIDs.TEST_DEFINE)) {
            getTestCase(line.substring(9));
            ++numTests;

        } else if (line.startsWith(MessageIDs.TEST_START)) {
            currentTest = getTestCase(line.substring(9));
            currentTest.time = new Date().getTime();
            currentTest.wasStarted = true;
            ++numStarted;

        } else if (line.startsWith(MessageIDs.TEST_END)) {
            currentTest.time = new Date().getTime() - currentTest.time;
            currentTest = null;

        } else if (line.startsWith(MessageIDs.TEST_ERROR)) {
            // JUnit 4+ simplifies errors to failures
            ++numErrors;

        } else if (line.startsWith(MessageIDs.TEST_FAILED)) {
            if (currentTest != null) {
                currentTest.failure = new StringBuilder(line.substring(9));
                ++numFailures;
            }

        } else if (line.startsWith(MessageIDs.TEST_IGNORED)) {
            final TestCase testCase = getTestCase(line.substring(9));
            testCase.wasIgnored = true;
            ++numIgnored;

        } else if (line.startsWith(MessageIDs.TEST_RUN_END)) {
            hasEnded = true;

            suites.forEach((_skey, tSuite) -> {
                tSuite.time = 0;
                tSuite.cases.forEach((_ckey, tCase) -> {
                    tSuite.time += tCase.time;
                });
            });
        } else {
            if (currentTest != null && currentTest.failure != null) {
                currentTest.failure.append("\n").append(line);
            }
        }
    }

    /**
     * Return the complete input
     *
     * @return complete input
     */
    public String getCompleteInput() {
        return completeInput.toString();
    }

    /**
     * Return a test case for the specified name
     *
     * @param testCase Test case name
     * @return test case object
     */
    private TestCase getTestCase(String testCase) {
        try {
            int idx = testCase.lastIndexOf('-');
            final String suiteName = testCase.substring(0, idx);
            final String caseName = testCase.substring(idx + 1);

            TestSuite tSuite = suites.get(suiteName);
            if (tSuite == null) {
                tSuite = new TestSuite();
                tSuite.name = suiteName;
                suites.put(suiteName, tSuite);
            }

            TestCase tCase = tSuite.cases.get(caseName);
            if (tCase == null) {
                tCase = new TestCase();
                tCase.name = caseName;
                tSuite.cases.put(caseName, tCase);
            }

            return tCase;
        } catch (Exception ex) {
            // Ignore
        }
        return new TestCase();
    }

    private static String getXMLString(String str) {
        return StringEscapeUtils.escapeXml10(str);
    }

    public String getXMLReport() {
        StringBuilder report = new StringBuilder(16 * 1024);

        report.append("\n");
        report.append("\n");

        suites.forEach((_skey, tSuite) -> {
            report.append("    ");
            report.append("\n");
            tSuite.cases.forEach((_ckey, tCase) -> {
                report.append("        ");
                report.append("\n");
                    report.append("            ");
                    report.append("");
                    report.append(getXMLString(tCase.failure.toString()));
                    report.append("\n            ");
                    report.append("\n");


                    report.append("        ");
                    report.append("\n");

                } else {
                    report.append("/>\n");
                }
            });
            report.append("    ");
            report.append("\n");
        });


        report.append("\n");
        return report.toString();
    }

    private static String getHTMLString(String str) {
        return StringEscapeUtils.escapeHtml4(str);
    }

    public String getHTMLReport(String targetName) {
        StringBuilder report = new StringBuilder(16 * 1024);

        report.append("\n" +
                "\n" +
                "\n" +
                "JUnit Test Results\n" +
                "\t\n" +
                "\t\n" +
                "\n" +
                "\n");
        report.append("

Test report for <").append(getHTMLString(targetName)).append(">

\n"); report.append("

Summary

\n" + "\n" + "\t\n" + "\t\t\n" + "\t\n" + "\t\n" + "\t\t" + "") .append("") .append(" 0 ? " class=\"color-fail\"" : "").append(">").append(numFailures).append("") .append("") .append("\n") .append("\t\n").append("
TestsStartedFailuresErrorsIgnored
").append(numTests).append("").append(numStarted).append("").append(numErrors).append("").append(numIgnored).append("
\n"); report.append("

Results

\n" + "\n" + "\t\n" + "\t\t\n" + "\t\n" + "\t\n"); final int[] suiteIndex = {0}; suites.forEach((_skey, tSuite) -> { suiteIndex[0]++; final int[] numSucc = {0}; final int[] numFailed = {0}; final int[] numIgnored = {0}; tSuite.cases.forEach((_ckey, tCase) -> { if (tCase.wasIgnored) { ++numIgnored[0]; } else if (tCase.failure != null) { ++numFailed[0]; } else { ++numSucc[0]; } }); int numSum = numSucc[0] + numFailed[0] + numIgnored[0]; String sumColor = "color-ok"; if (numSum == numIgnored[0]) { sumColor = "color-ignore"; } else if (numFailed[0] == numSum - numIgnored[0]) { sumColor = "color-fail"; } else if (numFailed[0] > 0) { sumColor = "color-warn"; } report.append("\t\t") .append("") .append("") .append("") .append("") .append("\n"); report.append("\t\t\n"); }); report.append("\t\n" + "
Suite NameTime (sec)Success/Failed/Ignored
").append(getHTMLString(tSuite.name)).append("").append(getAsSeconds(tSuite.time)).append("").append(numSucc[0]).append("/").append(numFailed[0]).append("/").append(numIgnored[0]).append("
\n" + "\t\t\t\n" + "\t\t\t\t\n" + "\t\t\t\t\t\n" + "\t\t\t\t\n" + "\t\t\t\t\n"); final int[] caseIndex = {0}; tSuite.cases.forEach((_ckey, tCase) -> { caseIndex[0]++; report.append("\t\t\t\t\t" + "" + ""); if (tCase.wasIgnored) { report.append(""); } else if (tCase.failure != null) { report.append(""); } else { report.append(""); } report.append("\n"); if (tCase.failure != null) { String message = tCase.failure.toString(); message = getHTMLString(message.trim()); message = message.replaceAll("\n", "
\n"); report.append("\t\t\t\t\t\n"); } }); report.append("\t\t\t\t\n" + "\t\t\t
NameTime (sec)Status
").append(getHTMLString(tCase.name)).append("").append(getAsSeconds(tCase.time)).append("IgnoredFailedOK
").append(message).append("
\n" + "\t\t
\n" + "\n" + "\n"); return report.toString(); } /** * Converts milliseconds to seconds. * * @param millis milliseconds * @return seconds */ private static double getAsSeconds(long millis) { final double t = ((double) millis) / (1000.0); return new BigDecimal(t).setScale(3, RoundingMode.HALF_UP).doubleValue(); } /** * Returns the number of tests. * * @return number of tests */ @IgnoreUnused public int getNumTests() { return numTests; } /** * Returns the number of started tests. * * @return number of started tests */ @IgnoreUnused public int getNumStarted() { return numStarted; } /** * Returns the number of failed tests. * * @return number of failed tests */ public int getNumFailures() { return numFailures; } /** * Returns the number of tests with error. * * @return number of tests with error */ public int getNumErrors() { return numErrors; } /** * Returns the number of ignored tests. * * @return number of ignored tests */ @IgnoreUnused public int getNumIgnored() { return numIgnored; } /** * Returns the has ended flag. * * @return has ended flag */ @IgnoreUnused public boolean getHasEnded() { return hasEnded; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy