view src/ReportGenerator.java @ 4:730c5549c0f9

2012-01-10 Pavel Tisnovsky <ptisnovs@redhat.com> * src/FileUtils.java: Added new helper class. * src/ReportGenerator.java: Updated to use HTML templates for test coverage report. * Makefile: Updated
author Pavel Tisnovsky <ptisnovs@redhat.com>
date Tue, 10 Jan 2012 14:08:47 +0100
parents 29318fe8d6d0
children 5849d5bfbee0
line wrap: on
line source

/*
  Test coverage tool.

   Copyright (C) 2012 Red Hat

This tool is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

This tool is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this tool; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.
*/

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;



/**
 * Report generator which process .txt files generated by PrintPublicMethods and
 * PrintTestCoverage classes.
 * 
 * @author Pavel Tisnovsky
 */
public class ReportGenerator
{
    /**
     * Read all classes from a file containing its list.
     * 
     * @param allClassListFileName
     * @return
     */
    private static Set<String> readAllClasses(String allClassListFileName)
    {
        // read file content
        List<String> fileContent = FileUtils.readTextFile(allClassListFileName);
        // set of classes should be sorted
        Set<String> allClasses = new TreeSet<String>();
        allClasses.addAll(fileContent);
        return allClasses;
    }

    /**
     * Creates file "all_packages.html" which contains link to all checked
     * packages. Structure of this file is based on template stored in
     * "templates/all_packages_template.html".
     * 
     * @param reportDirectory
     *            directory where report is generated
     * @param allClasses
     *            set of all classes
     * @param packageNames
     *            set of package names
     */
    private static void printPackageListToFile(String reportDirectory, Set<String> allClasses, Set<String> packageNames)
    {
        List<String> template = FileUtils.readTextFile("templates/all_packages_template.html");
        List<String> out = new LinkedList<String>();
        for (String templateLine : template)
        {
            // replace text in template where needed
            if ("${PACKAGE_LIST}".equals(templateLine))
            {
                addPackageList(packageNames, out);
            }
            else
            {
                out.add(templateLine);
            }
        }
        FileUtils.writeTextFile(reportDirectory, "all_packages.html", out);
    }

    /**
     * Create file containing test coverage report for given package. Structure
     * of this file is based on template stored in
     * "templates/all_packages_template.html".
     * 
     * @param reportDirectory
     *            directory where report is generated
     * @param packageName
     *            package for which the report is generated
     * @param testedClasses
     *            set of tested classes
     */
    private static void printReportForPackageToFile(String reportDirectory, String packageName, Set<String> testedClasses)
    {
        List<String> template = FileUtils.readTextFile("templates/package_template.html");
        List<String> out = new LinkedList<String>();
        for (String templateLine : template)
        {
            // replace text in template where needed
            if ("${CLASS_LIST}".equals(templateLine))
            {
                addClassList(packageName, testedClasses, out);
            }
            else
            {
                out.add(templateLine);
            }
        }
        FileUtils.writeTextFile(reportDirectory, packageName + ".html", out);
    }

    /**
     * Create file containing test coverage report for all classes. Structure of
     * this file is based on template stored in
     * "templates/all_classes_template.html".
     * 
     * @param reportDirectory
     *            directory where report is generated
     * @param usedPackageNames
     *            all checked package names
     * @param testedClasses
     *            set of tested classes
     */
    private static void printReportForAllClassesInOneFile(String reportDirectory, Set<String> usedPackageNames,
                    Set<String> testedClasses)
    {
        List<String> template = FileUtils.readTextFile("templates/all_classes_template.html");
        List<String> out = new LinkedList<String>();
        for (String templateLine : template)
        {
            // replace text in template where needed
            if ("${PACKAGE_AND_CLASS_LIST}".equals(templateLine))
            {
                addPackageAndClassList(usedPackageNames, testedClasses, out);
            }
            else
            {
                out.add(templateLine);
            }
        }
        FileUtils.writeTextFile(reportDirectory, "all_classes.html", out);
    }

    /**
     * Add list of all packages to a list of string which represents generated
     * report.
     * 
     * @param packageNames
     *            set of package names
     * @param out
     *            list of string which represents generated report
     */
    private static void addPackageList(Set<String> packageNames, List<String> out)
    {
        for (String packageName : packageNames)
        {
            out.add("<a target='ClassesListFrame' href='" + packageName + ".html'>" + packageName + "</a><br />");
        }
    }

    /**
     * Add list of all classes to a list of string which represents generated
     * report.
     * 
     * @param packageName
     *            package for which the report is generated
     * @param testedClasses
     *            set of tested classes
     * @param out
     *            list of string which represents generated report
     */
    private static void addClassList(String packageName, Set<String> testedClasses, List<String> out)
    {
        for (String className : testedClasses)
        {
            // list only classes from given package
            if (className.startsWith(packageName))
            {
                out.add("<a target='ResultsFrame' href='" + className + ".html'>" + className + "</a><br>");
            }
        }
    }

    /**
     * Add list of all packages and all its classes to a list of string which
     * represents generated report.
     * 
     * @param usedPackageNames
     *            all checked package names
     * @param testedClasses
     *            set of tested classes
     * @param out
     *            list of string which represents generated report
     */
    private static void addPackageAndClassList(Set<String> usedPackageNames, Set<String> testedClasses, List<String> out)
    {
        for (String packageName : usedPackageNames)
        {
            out.add("<h2>Package " + packageName + "</h2>");
            for (String className : testedClasses)
            {
                if (className.startsWith(packageName))
                {
                    out.add("<a target='ResultsFrame' href='" + className + ".html'>" + className + "</a><br />");
                }
            }
            out.add("<br />");
        }
    }

    private static void createFileForClass(String reportDirectory, String testClass, Set<String> allMethods, Set<String> apiMethods, Set<String> testedMethods)
    {
        BufferedWriter fout = null;
        try
        {
            fout = new BufferedWriter(new FileWriter(new File(reportDirectory, testClass + ".html")));
            fout.write("<html>\n");
            fout.write("<head>\n");
            fout.write("<title>" + testClass + "</title>\n");
            fout.write("</head>\n");
            fout.write("<body>\n");
            fout.write("<h1>Class " + testClass + "</h1>\n");
            fout.write("<table>\n");
            fout.write("<tr><th>Method</th><th><a href='"+testClass+"_api.txt'>API</a></th><th><a href='"+testClass+"_test.txt'>Tested</a></th></tr>\n");
            for (String methodName : allMethods)
            {
                fout.write("<tr><td>" + constructPrintedMethodName(methodName) + "</td>");
                fout.write(printMethodCoverage(methodName, apiMethods));
                fout.write(printMethodCoverage(methodName, testedMethods));
                fout.write("</tr>\n");
            }
            fout.write("</table>\n");
            fout.write("</body>\n");
            fout.write("</html>\n");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (fout != null)
                {
                    fout.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static Set<String> preparePackageNames(Set<String> allClasses)
    {
        Set<String> packages = new TreeSet<String>();
        for (String className : allClasses)
        {
            String packageName = className.substring(0, className.lastIndexOf('.'));
            if (!packageName.startsWith("com.") && !packageName.startsWith("sun"))
            {
                packages.add(packageName);
            }
        }
        return packages;
    }

    private static String constructPrintedMethodName(String methodName)
    {
        String printedMethodName = methodName.replace("<", "&lt;").replace(">", "&gt;");
        int returnTypeEnds = printedMethodName.indexOf(' ');
        int parametersBegin = printedMethodName.indexOf('(');
        String returnType = printedMethodName.substring(0, printedMethodName.indexOf(' '));
        String name = printedMethodName.substring(returnTypeEnds, parametersBegin);
        String params = printedMethodName.substring(parametersBegin);

        return String.format(
            "<span style='color:#000080'>%s</span>" +
            "<span style='color:#008000'>%s</span>" +
            "<span style='color:#804000'>%s</span>", returnType, name, params);
    }

    private static String printMethodCoverage(String methodName, Set<String> methodSet)
    {
        if (methodSet.contains(methodName))
        {
            return "<td style='background:#80ff80'>present</td>";
        }
        return "<td style='background:#ff8080'>absent</td>";
    }

    private static Set<String> prepareUsedPackageNames(Set<String> allPackageNames, Set<String> testedClasses)
    {
        Set<String> out = new TreeSet<String>();
        for (String packageName : allPackageNames)
        {
            for (String testClass : testedClasses)
            {
                if (testClass.startsWith(packageName))
                {
                    out.add(packageName);
                    break;
                }
            }
        }
        return out;
    }

    private static void printReportForAllPackages(String reportDirectory, Set<String> usedPackageNames,
                    Set<String> testedClasses)
    {
        for (String packageName : usedPackageNames)
        {
            printReportForPackageToFile(reportDirectory, packageName, testedClasses);
        }
    }

    private static void printReportForAllClasses(String reportDirectory, Set<String> testedClasses)
    {
        for (String testedClass : testedClasses)
        {
            Set<String> apiMethods = readApiMethods(reportDirectory, testedClass);
            Set<String> testedMethods = readTestedMethods(reportDirectory, testedClass);
            Set<String> allMethods = new TreeSet<String>();
            allMethods.addAll(apiMethods);
            allMethods.addAll(testedMethods);
            createFileForClass(reportDirectory, testedClass, allMethods, apiMethods, testedMethods);
        }
    }

    private static Set<String> readApiMethods(String reportDirectory, String testedClass)
    {
        File fileName = new File(reportDirectory, testedClass + "_api.txt");
        return readMethods(fileName);
    }

    private static Set<String> readTestedMethods(String reportDirectory, String testedClass)
    {
        File fileName = new File(reportDirectory, testedClass + "_test.txt");
        return readMethods(fileName);
    }

    private static Set<String> readMethods(File fileName)
    {
        BufferedReader reader = null;
        Set<String> allMethods = new TreeSet<String>();
        try
        {
            reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = reader.readLine()) != null)
            {
                allMethods.add(line);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (reader != null)
                {
                    reader.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return allMethods;
    }

    private static void prepareReport(String allClassListFileName, String testedClassListFileName,
                    String reportDirectory)
    {
        Set<String> allClasses = readAllClasses(allClassListFileName);
        Set<String> testedClasses = readAllClasses(testedClassListFileName);
        Set<String> allPackageNames = preparePackageNames(allClasses);
        Set<String> usedPackageNames = prepareUsedPackageNames(allPackageNames, testedClasses);

        System.out.println("All class list:    " + allClassListFileName);
        System.out.println("Read " + allClasses.size() + " class names");

        System.out.println("Tested class list: " + testedClassListFileName);
        System.out.println("Read " + testedClasses.size() + " class names");

        System.out.println("Setting list of " + allPackageNames.size() + " all package names");
        System.out.println("Setting list of " + usedPackageNames.size() + " used package names");

        System.out.println("Report directory:  " + reportDirectory);

        printPackageListToFile(reportDirectory, allClasses, usedPackageNames);
        printReportForAllClassesInOneFile(reportDirectory, usedPackageNames, testedClasses);
        printReportForAllPackages(reportDirectory, usedPackageNames, testedClasses);
        printReportForAllClasses(reportDirectory, testedClasses);
    }

    public static void main(String[] args)
    {
        if (args.length != 3)
        {
            System.err.println("Usage allClassListFileName classListFileName reportDirectory");
            System.exit(1);
        }
        String allClassListFileName = args[0];
        String testedClassListFileName = args[1];
        String reportDirectory = args[2];
        prepareReport(allClassListFileName, testedClassListFileName, reportDirectory);
    }
}