From e01cedb62d1f24b6452f6fe4fda90d3b0db2bf27 Mon Sep 17 00:00:00 2001 From: Luolc Date: Mon, 21 Aug 2017 15:57:45 +0800 Subject: [PATCH] Issue #78: extract: grab property info --- config/findbugs-exclude.xml | 5 + config/import-control.xml | 5 + config/pmd.xml | 6 +- config/sevntu_suppressions.xml | 2 +- config/suppressions.xml | 2 +- pom.xml | 5 + .../regression/data/ModuleExtractInfo.java | 37 +++ .../regression/module/UnitTestProcessor.java | 115 ++++++++++ .../module/UnitTestProcessorCheck.java | 211 ++++++++++++++++++ .../extract/ExtractInfoGeneratorTest.java | 172 +++++++++++++- .../extract/ExtractInfoProcessorTest.java | 9 + .../module/ModuleInfoCollectorTest.java | 9 + .../module/UnitTestProcessorTest.java | 71 ++++++ src/test/resources/checkstyle_modules.json | 13 ++ .../module/ReturnCountCheckTest.java | 149 +++++++++++++ 15 files changed, 804 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/github/checkstyle/regression/module/UnitTestProcessor.java create mode 100644 src/main/java/com/github/checkstyle/regression/module/UnitTestProcessorCheck.java create mode 100644 src/test/java/com/github/checkstyle/regression/module/UnitTestProcessorTest.java create mode 100644 src/test/resources/com/github/checkstyle/regression/module/ReturnCountCheckTest.java diff --git a/config/findbugs-exclude.xml b/config/findbugs-exclude.xml index 0f14231..7040fb5 100644 --- a/config/findbugs-exclude.xml +++ b/config/findbugs-exclude.xml @@ -27,4 +27,9 @@ + + + + + diff --git a/config/import-control.xml b/config/import-control.xml index b2e1110..0940597 100644 --- a/config/import-control.xml +++ b/config/import-control.xml @@ -51,4 +51,9 @@ + + + + + diff --git a/config/pmd.xml b/config/pmd.xml index 6ab7c5e..2512506 100644 --- a/config/pmd.xml +++ b/config/pmd.xml @@ -34,7 +34,11 @@ - + + + + + diff --git a/config/sevntu_suppressions.xml b/config/sevntu_suppressions.xml index 96c88d8..13a051b 100644 --- a/config/sevntu_suppressions.xml +++ b/config/sevntu_suppressions.xml @@ -4,5 +4,5 @@ "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> - + diff --git a/config/suppressions.xml b/config/suppressions.xml index fc75af3..523ae74 100644 --- a/config/suppressions.xml +++ b/config/suppressions.xml @@ -13,7 +13,7 @@ - + diff --git a/pom.xml b/pom.xml index c355d15..8daeb05 100644 --- a/pom.xml +++ b/pom.xml @@ -393,6 +393,11 @@ 0 0 + + com.github.checkstyle.regression.module.UnitTestProcessorCheck + 76 + 92 + com.github.checkstyle.regression.report.ReportGenerator 0 diff --git a/src/main/java/com/github/checkstyle/regression/data/ModuleExtractInfo.java b/src/main/java/com/github/checkstyle/regression/data/ModuleExtractInfo.java index 22566cf..aa7d429 100644 --- a/src/main/java/com/github/checkstyle/regression/data/ModuleExtractInfo.java +++ b/src/main/java/com/github/checkstyle/regression/data/ModuleExtractInfo.java @@ -19,6 +19,8 @@ package com.github.checkstyle.regression.data; +import java.util.List; + import org.immutables.gson.Gson; import org.immutables.value.Value; @@ -48,6 +50,12 @@ public abstract class ModuleExtractInfo { */ public abstract String parent(); + /** + * The properties of this module. + * @return the properties of this module + */ + public abstract List properties(); + /** * The full qualified name of this module. * @return the full qualified name of this module @@ -55,4 +63,33 @@ public abstract class ModuleExtractInfo { public String fullName() { return packageName() + "." + name(); } + + /** Represents a property of checkstyle module. */ + @Gson.TypeAdapters + @Value.Immutable + public interface ModuleProperty { + /** + * The name of this property. + * @return the name of this property + */ + String name(); + + /** + * The type of this property. + * The value should be one of the followings: + * - Pattern + * - SeverityLevel + * - boolean + * - Scope + * - double[] + * - int[] + * - String[] + * - String + * - URI + * - AccessModifier[] + * - int + * @return the type of this property + */ + String type(); + } } diff --git a/src/main/java/com/github/checkstyle/regression/module/UnitTestProcessor.java b/src/main/java/com/github/checkstyle/regression/module/UnitTestProcessor.java new file mode 100644 index 0000000..c99c0b4 --- /dev/null +++ b/src/main/java/com/github/checkstyle/regression/module/UnitTestProcessor.java @@ -0,0 +1,115 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2017 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.checkstyle.regression.module; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.github.checkstyle.regression.data.ModuleInfo; +import com.puppycrawl.tools.checkstyle.Checker; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.TreeWalker; +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; +import com.puppycrawl.tools.checkstyle.api.Configuration; +import com.puppycrawl.tools.checkstyle.api.FileSetCheck; + +/** + * Processes the unit test class of a checkstyle module. + * This utility class would run {@link UnitTestProcessorCheck} on the file with + * the given path and return the collected property info. + * @author LuoLiangchen + */ +public final class UnitTestProcessor { + /** Prevents instantiation. */ + private UnitTestProcessor() { + } + + /** + * Processes the unit test class with the given path. + * @param path the path of the unit test class + * @return the unit test method name to properties map + * @throws CheckstyleException failure when running the check + * @throws ReflectiveOperationException failure of reflection on checker and tree walker + */ + public static Map> process(String path) + throws CheckstyleException, ReflectiveOperationException { + final DefaultConfiguration moduleConfig = createModuleConfig(UnitTestProcessorCheck.class); + final Configuration dc = createTreeWalkerConfig(moduleConfig); + final Checker checker = new Checker(); + checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); + checker.configure(dc); + final List processedFiles = Collections.singletonList(new File(path)); + checker.process(processedFiles); + + final UnitTestProcessorCheck check = getCheckInstance(checker); + return check.getUnitTestToPropertiesMap(); + } + + /** + * Gets the instance of {@link UnitTestProcessorCheck} from the checker. + * @param checker the checker which run the check + * @return the instance of {@link UnitTestProcessorCheck} + * @throws ReflectiveOperationException failure of reflection + */ + @SuppressWarnings("unchecked") + private static UnitTestProcessorCheck getCheckInstance(Checker checker) + throws ReflectiveOperationException { + final Field fileSetChecks = checker.getClass().getDeclaredField("fileSetChecks"); + fileSetChecks.setAccessible(true); + final TreeWalker treeWalker = + (TreeWalker) ((List) fileSetChecks.get(checker)).get(0); + final Field ordinaryChecks = treeWalker.getClass().getDeclaredField("ordinaryChecks"); + ordinaryChecks.setAccessible(true); + final Set checks = (Set) ordinaryChecks.get(treeWalker); + return (UnitTestProcessorCheck) checks.iterator().next(); + } + + /** + * Creates {@link DefaultConfiguration} for the {@link TreeWalker} + * based on the given {@link Configuration} instance. + * @param config {@link Configuration} instance. + * @return {@link DefaultConfiguration} for the {@link TreeWalker} + * based on the given {@link Configuration} instance. + */ + private static DefaultConfiguration createTreeWalkerConfig(Configuration config) { + final DefaultConfiguration dc = + new DefaultConfiguration("configuration"); + final DefaultConfiguration twConf = createModuleConfig(TreeWalker.class); + // make sure that the tests always run with this charset + dc.addAttribute("charset", "UTF-8"); + dc.addChild(twConf); + twConf.addChild(config); + return dc; + } + + /** + * Creates {@link DefaultConfiguration} for the given class. + * @param clazz the class of module + * @return the {@link DefaultConfiguration} of the module class + */ + private static DefaultConfiguration createModuleConfig(Class clazz) { + return new DefaultConfiguration(clazz.getName()); + } +} diff --git a/src/main/java/com/github/checkstyle/regression/module/UnitTestProcessorCheck.java b/src/main/java/com/github/checkstyle/regression/module/UnitTestProcessorCheck.java new file mode 100644 index 0000000..add1101 --- /dev/null +++ b/src/main/java/com/github/checkstyle/regression/module/UnitTestProcessorCheck.java @@ -0,0 +1,211 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2017 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.checkstyle.regression.module; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import com.github.checkstyle.regression.data.ImmutableProperty; +import com.github.checkstyle.regression.data.ModuleInfo; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; + +/** + * The custom check which processes the unit test class of a checkstyle module. + * This check would walk through the {@code @Test} annotation, find variable definition + * like {@code final DefaultConfiguration checkConfig = createModuleConfig(FooCheck.class)} + * and grab the property info from {@link DefaultConfiguration#addAttribute(String, String)} + * method call. + * @author LuoLiangchen + */ +public class UnitTestProcessorCheck extends AbstractCheck { + /** The map of unit test method name to properties. */ + private final Map> unitTestToProperties = + new LinkedHashMap<>(); + + @Override + public int[] getDefaultTokens() { + return new int[] { + TokenTypes.ANNOTATION, + }; + } + + @Override + public int[] getRequiredTokens() { + return new int[] { + TokenTypes.ANNOTATION, + }; + } + + @Override + public int[] getAcceptableTokens() { + return new int[] { + TokenTypes.ANNOTATION, + }; + } + + @Override + public void visitToken(DetailAST ast) { + if ("Test".equals(ast.findFirstToken(TokenTypes.IDENT).getText())) { + final DetailAST methodDef = ast.getParent().getParent(); + final DetailAST methodBlock = methodDef.findFirstToken(TokenTypes.SLIST); + final Optional configVariableName = + getModuleConfigVariableName(methodBlock); + if (configVariableName.isPresent()) { + final Set properties = new LinkedHashSet<>(); + + for (DetailAST expr : getAllChildrenWithToken(methodBlock, TokenTypes.EXPR)) { + if (isAddAttributeMethodCall(expr.getFirstChild(), configVariableName.get())) { + final DetailAST elist = + expr.getFirstChild().findFirstToken(TokenTypes.ELIST); + final String key = convertExprToText(elist.getFirstChild()); + final String value = convertExprToText(elist.getLastChild()); + properties.add(ImmutableProperty.builder().name(key).value(value).build()); + } + } + + if (!unitTestToProperties.containsValue(properties)) { + final String methodName = methodDef.findFirstToken(TokenTypes.IDENT).getText(); + unitTestToProperties.put(methodName, properties); + } + } + } + } + + /** + * Gets the map of unit test method name to properties. + * @return the map of unit test method name to properties + */ + public Map> getUnitTestToPropertiesMap() { + return Collections.unmodifiableMap(unitTestToProperties); + } + + /** + * Gets the module config variable name, if it exists. + * @param methodBlock the UT method block ast, which should have a type {@link TokenTypes#SLIST} + * @return the optional variable name, if it exists + */ + private static Optional getModuleConfigVariableName(DetailAST methodBlock) { + Optional returnValue = Optional.empty(); + + for (DetailAST ast = methodBlock.getFirstChild(); ast != null; ast = ast.getNextSibling()) { + if (ast.getType() == TokenTypes.VARIABLE_DEF) { + final DetailAST type = ast.findFirstToken(TokenTypes.TYPE); + final DetailAST assign = ast.findFirstToken(TokenTypes.ASSIGN); + if (isDefaultConfigurationType(type) && isCreateModuleConfigAssign(assign)) { + returnValue = Optional.of(type.getNextSibling().getText()); + break; + } + } + } + + return returnValue; + } + + /** + * Checks whether this {@link TokenTypes#TYPE} ast is {@link DefaultConfiguration}. + * @param ast the {@link TokenTypes#TYPE} ast + * @return true if the type is {@link DefaultConfiguration} + */ + private static boolean isDefaultConfigurationType(DetailAST ast) { + return "DefaultConfiguration".equals(ast.getFirstChild().getText()); + } + + /** + * Checks whether this {@link TokenTypes#ASSIGN} ast contains + * a {@code createModuleConfig} method call. + * @param ast the {@link TokenTypes#ASSIGN} ast + * @return true if the assignment contains a {@code createModuleConfig} method call + */ + private static boolean isCreateModuleConfigAssign(DetailAST ast) { + final boolean result; + + if (ast == null) { + result = false; + } + else { + final DetailAST exprChild = ast.getFirstChild().getFirstChild(); + result = exprChild.getType() == TokenTypes.METHOD_CALL + && exprChild.getFirstChild().getType() == TokenTypes.IDENT + && "createModuleConfig".equals(exprChild.getFirstChild().getText()); + } + + return result; + } + + /** + * Gets all children of a ast with the given tokens type. + * @param parent the parent ast + * @param type the given tokens type + * @return the children with the given tokens type + */ + private static List getAllChildrenWithToken(DetailAST parent, int type) { + final List returnValue = new LinkedList<>(); + + for (DetailAST ast = parent.getFirstChild(); ast != null; ast = ast.getNextSibling()) { + if (ast.getType() == type) { + returnValue.add(ast); + } + } + + return returnValue; + } + + /** + * Checks whether this expression is an {@code addAttribute} method call on an instance with + * the given variable name. + * @param ast the ast to check + * @param variableName the given variable name of the module config instance + * @return true if the expression is a valid {@code addAttribute} method call + */ + private static boolean isAddAttributeMethodCall(DetailAST ast, String variableName) { + final boolean result; + + if (ast.getType() == TokenTypes.METHOD_CALL + && ast.getFirstChild().getType() == TokenTypes.DOT) { + final DetailAST dot = ast.getFirstChild(); + result = variableName.equals(dot.getFirstChild().getText()) + && "addAttribute".equals(dot.getLastChild().getText()); + } + else { + result = false; + } + + return result; + } + + /** + * Converts an expression to raw text. + * @param ast the expression ast to convert + * @return the converted raw text + */ + private static String convertExprToText(DetailAST ast) { + final String original = ast.getFirstChild().getText(); + return original.substring(1, original.length() - 1); + } +} diff --git a/src/main/resources/com/github/checkstyle/regression/extract/ExtractInfoGeneratorTest.java b/src/main/resources/com/github/checkstyle/regression/extract/ExtractInfoGeneratorTest.java index f7f2790..f135592 100644 --- a/src/main/resources/com/github/checkstyle/regression/extract/ExtractInfoGeneratorTest.java +++ b/src/main/resources/com/github/checkstyle/regression/extract/ExtractInfoGeneratorTest.java @@ -19,8 +19,8 @@ package com.puppycrawl.tools.checkstyle; +import java.beans.PropertyDescriptor; import java.io.File; -import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardOpenOption; @@ -28,10 +28,17 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import org.apache.commons.beanutils.PropertyUtils; import org.junit.Test; +import com.puppycrawl.tools.checkstyle.api.AbstractCheck; +import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; +import com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck; import com.puppycrawl.tools.checkstyle.internal.CheckUtil; +import com.puppycrawl.tools.checkstyle.internal.TestUtils; import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtils; /** @@ -40,12 +47,57 @@ * @author LuoLiangchen */ public class ExtractInfoGeneratorTest { + /** Modules which do not have global properties to drop. */ + private static final List XML_FILESET_LIST = Arrays.asList( + "TreeWalker", + "Checker", + "Header", + "Translation", + "SeverityMatchFilter", + "SuppressionFilter", + "SuppressWarningsFilter", + "BeforeExecutionExclusionFileFilter", + "RegexpHeader", + "RegexpOnFilename", + "RegexpSingleline", + "RegexpMultiline", + "JavadocPackage", + "NewlineAtEndOfFile", + "UniqueProperties", + "FileLength", + "FileTabCharacter" + ); + + /** Properties of abstract check. */ + private static final Set CHECK_PROPERTIES = getProperties(AbstractCheck.class); + + /** Properties of abstract Javadoc check. */ + private static final Set JAVADOC_CHECK_PROPERTIES = + getProperties(AbstractJavadocCheck.class); + + /** Properties of abstract file-set check. */ + private static final Set FILESET_PROPERTIES = getProperties(AbstractFileSetCheck.class); + + /** Properties without document. */ + private static final List UNDOCUMENTED_PROPERTIES = Arrays.asList( + "Checker.classLoader", + "Checker.classloader", + "Checker.moduleClassLoader", + "Checker.moduleFactory", + "TreeWalker.classLoader", + "TreeWalker.moduleFactory", + "TreeWalker.cacheFile", + "TreeWalker.upChild", + "SuppressWithNearbyCommentFilter.fileContents", + "SuppressionCommentFilter.fileContents" + ); + /** * Generates the extract info file named as "checkstyle_modules.json". - * @throws IOException failure when generating the file + * @throws Exception failure when generating the file */ @Test - public void generateExtractInfoFile() throws IOException { + public void generateExtractInfoFile() throws Exception { final List> modules = new ArrayList<>(CheckUtil.getCheckstyleModules()); modules.sort(Comparator.comparing(Class::getSimpleName)); final JsonUtil.JsonArray moduleJsonArray = new JsonUtil.JsonArray(); @@ -62,8 +114,10 @@ public void generateExtractInfoFile() throws IOException { * Creates Json object for a module from the module class. * @param clazz the given module class * @return the Json object describing the extract info of the module + * @throws Exception failure when creating Json object */ - private static JsonUtil.JsonObject createJsonObjectFromModuleClass(Class clazz) { + private static JsonUtil.JsonObject createJsonObjectFromModuleClass(Class clazz) + throws Exception { final JsonUtil.JsonObject object = new JsonUtil.JsonObject(); final String name = clazz.getSimpleName(); @@ -94,6 +148,116 @@ else if (ModuleReflectionUtils.isRootModule(clazz)) { object.add("interfaces", interfaces); object.add("hierarchies", hierarchies); + final JsonUtil.JsonArray properties = new JsonUtil.JsonArray(); + for (String propertyName : getNecessaryProperties(clazz)) { + final JsonUtil.JsonObject property = new JsonUtil.JsonObject(); + property.addProperty("name", propertyName); + Arrays.stream(PropertyUtils.getPropertyDescriptors(clazz)) + .filter(p -> p.getName().equals(propertyName)) + .map(PropertyDescriptor::getPropertyType) + .map(Class::getSimpleName) + .findAny() + .ifPresent(type -> property.addProperty("type", type)); + properties.add(property); + } + object.add("properties", properties); + return object; } + + /** + * Gets the necessary properties of a checkstyle module. + * Global properties and undocumented properties are not necessary for us. + * @param clazz the class instance of the given module + * @return a set of the necessary properties of the module + * @throws Exception failure when getting properties + */ + // -@cs[CyclomaticComplexity] many different kinds of module + private static Set getNecessaryProperties(Class clazz) + throws Exception { + final Set properties = getProperties(clazz); + if (hasParentModule(clazz.getSimpleName())) { + if (AbstractJavadocCheck.class.isAssignableFrom(clazz)) { + properties.removeAll(JAVADOC_CHECK_PROPERTIES); + } + else if (ModuleReflectionUtils.isCheckstyleCheck(clazz)) { + properties.removeAll(CHECK_PROPERTIES); + } + } + if (ModuleReflectionUtils.isFileSetModule(clazz)) { + properties.removeAll(FILESET_PROPERTIES); + + // override + properties.add("fileExtensions"); + } + + // undocumented properties are not necessary + properties.removeIf(prop -> UNDOCUMENTED_PROPERTIES.contains( + clazz.getSimpleName() + "." + prop)); + + final PackageObjectFactory factory = TestUtils.getPackageObjectFactory(); + final Object instance = factory.createModule(clazz.getSimpleName()); + + if (ModuleReflectionUtils.isCheckstyleCheck(clazz)) { + final AbstractCheck check = (AbstractCheck) instance; + + final int[] acceptableTokens = check.getAcceptableTokens(); + Arrays.sort(acceptableTokens); + final int[] defaultTokens = check.getDefaultTokens(); + Arrays.sort(defaultTokens); + final int[] requiredTokens = check.getRequiredTokens(); + Arrays.sort(requiredTokens); + + if (!Arrays.equals(acceptableTokens, defaultTokens) + || !Arrays.equals(acceptableTokens, requiredTokens)) { + properties.add("tokens"); + } + } + + if (AbstractJavadocCheck.class.isAssignableFrom(clazz)) { + final AbstractJavadocCheck check = (AbstractJavadocCheck) instance; + + final int[] acceptableJavadocTokens = check.getAcceptableJavadocTokens(); + Arrays.sort(acceptableJavadocTokens); + final int[] defaultJavadocTokens = check.getDefaultJavadocTokens(); + Arrays.sort(defaultJavadocTokens); + final int[] requiredJavadocTokens = check.getRequiredJavadocTokens(); + Arrays.sort(requiredJavadocTokens); + + if (!Arrays.equals(acceptableJavadocTokens, defaultJavadocTokens) + || !Arrays.equals(acceptableJavadocTokens, requiredJavadocTokens)) { + properties.add("javadocTokens"); + } + } + + return properties; + } + + /** + * Gets the properties of a checkstyle module. + * @param clazz the class instance of the given module + * @return a set of the properties of the module + */ + private static Set getProperties(Class clazz) { + final Set result = new TreeSet<>(); + final PropertyDescriptor[] map = PropertyUtils.getPropertyDescriptors(clazz); + + for (PropertyDescriptor p : map) { + if (p.getWriteMethod() != null) { + result.add(p.getName()); + } + } + + return result; + } + + /** + * Checks whether a module has a parent that may contains global properties. + * @param className the class name of given module + * @return true if the module has a parent + */ + private static boolean hasParentModule(String className) { + return !XML_FILESET_LIST.contains(className) && XML_FILESET_LIST.stream() + .map(name -> name + "Check").noneMatch(name -> name.equals(className)); + } } diff --git a/src/test/java/com/github/checkstyle/regression/extract/ExtractInfoProcessorTest.java b/src/test/java/com/github/checkstyle/regression/extract/ExtractInfoProcessorTest.java index 6f8262a..146c83a 100644 --- a/src/test/java/com/github/checkstyle/regression/extract/ExtractInfoProcessorTest.java +++ b/src/test/java/com/github/checkstyle/regression/extract/ExtractInfoProcessorTest.java @@ -38,6 +38,7 @@ import org.junit.Test; import com.github.checkstyle.regression.data.ImmutableModuleExtractInfo; +import com.github.checkstyle.regression.data.ImmutableModuleProperty; import com.github.checkstyle.regression.data.ModuleExtractInfo; public class ExtractInfoProcessorTest { @@ -69,6 +70,14 @@ public void testGetModuleExtractInfosFromReader() throws Exception { .name(module1) .packageName(BASE_PACKAGE + ".checks") .parent("Checker") + .addProperties(ImmutableModuleProperty.builder() + .name("fileExtensions") + .type("String[]") + .build()) + .addProperties(ImmutableModuleProperty.builder() + .name("lineSeparator") + .type("String") + .build()) .build(); final String module2 = "EmptyStatementCheck"; final ModuleExtractInfo extractInfo2 = ImmutableModuleExtractInfo.builder() diff --git a/src/test/java/com/github/checkstyle/regression/module/ModuleInfoCollectorTest.java b/src/test/java/com/github/checkstyle/regression/module/ModuleInfoCollectorTest.java index ce3466d..a5603e3 100644 --- a/src/test/java/com/github/checkstyle/regression/module/ModuleInfoCollectorTest.java +++ b/src/test/java/com/github/checkstyle/regression/module/ModuleInfoCollectorTest.java @@ -39,6 +39,7 @@ import com.github.checkstyle.regression.data.ImmutableGitChange; import com.github.checkstyle.regression.data.ImmutableModuleExtractInfo; import com.github.checkstyle.regression.data.ImmutableModuleInfo; +import com.github.checkstyle.regression.data.ImmutableModuleProperty; import com.github.checkstyle.regression.data.ModuleExtractInfo; import com.github.checkstyle.regression.data.ModuleInfo; import com.github.checkstyle.regression.extract.ExtractInfoProcessor; @@ -117,6 +118,14 @@ public void testGenerateConfigNodesForValidChanges2() { .name("NewlineAtEndOfFileCheck") .packageName(BASE_PACKAGE + ".checks") .parent("Checker") + .addProperties(ImmutableModuleProperty.builder() + .name("fileExtensions") + .type("String[]") + .build()) + .addProperties(ImmutableModuleProperty.builder() + .name("lineSeparator") + .type("String") + .build()) .build(); final List moduleInfos = ModuleCollector.generate(changes); diff --git a/src/test/java/com/github/checkstyle/regression/module/UnitTestProcessorTest.java b/src/test/java/com/github/checkstyle/regression/module/UnitTestProcessorTest.java new file mode 100644 index 0000000..f8c915c --- /dev/null +++ b/src/test/java/com/github/checkstyle/regression/module/UnitTestProcessorTest.java @@ -0,0 +1,71 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2017 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.checkstyle.regression.module; + +import static com.github.checkstyle.regression.internal.TestUtils.assertUtilsClassHasPrivateConstructor; +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.junit.Test; + +import com.github.checkstyle.regression.data.ImmutableProperty; +import com.github.checkstyle.regression.data.ModuleInfo; + +public class UnitTestProcessorTest { + @Test + public void testIsProperUtilsClass() throws Exception { + assertUtilsClassHasPrivateConstructor(UnitTestProcessor.class); + } + + private static String getInputPath(String name) { + return "src/test/resources/com/github/checkstyle/regression/module/" + name; + } + + @Test + public void testProcess() throws Exception { + final Map> map = + UnitTestProcessor.process(getInputPath("ReturnCountCheckTest.java")); + assertEquals("The size of UTs is wrong", 7, map.size()); + assertPropertiesEquals(map, "testDefault"); + assertPropertiesEquals(map, "testFormat", + ImmutableProperty.builder().name("format").value("^$").build()); + assertPropertiesEquals(map, "testMethodsAndLambdas", + ImmutableProperty.builder().name("max").value("1").build()); + assertPropertiesEquals(map, "testLambdasOnly", + ImmutableProperty.builder().name("tokens").value("LAMBDA").build()); + assertPropertiesEquals(map, "testMethodsOnly", + ImmutableProperty.builder().name("tokens").value("METHOD_DEF").build()); + assertPropertiesEquals(map, "testWithReturnOnlyAsTokens", + ImmutableProperty.builder().name("tokens").value("LITERAL_RETURN").build()); + assertPropertiesEquals(map, "testMaxForVoid", + ImmutableProperty.builder().name("max").value("2").build(), + ImmutableProperty.builder().name("maxForVoid").value("0").build()); + } + + private static void assertPropertiesEquals(Map> map, + String key, ModuleInfo.Property... properties) { + assertEquals("properties is wrong from UT:" + key, + Arrays.stream(properties).collect(Collectors.toSet()), map.get(key)); + } +} diff --git a/src/test/resources/checkstyle_modules.json b/src/test/resources/checkstyle_modules.json index 8a28051..6864da0 100644 --- a/src/test/resources/checkstyle_modules.json +++ b/src/test/resources/checkstyle_modules.json @@ -12,6 +12,16 @@ "com.puppycrawl.tools.checkstyle.api.FileSetCheck", "com.puppycrawl.tools.checkstyle.api.Configurable", "com.puppycrawl.tools.checkstyle.api.Contextualizable" + ], + "properties": [ + { + "name": "fileExtensions", + "type": "String[]" + }, + { + "name": "lineSeparator", + "type": "String" + } ] }, { @@ -26,6 +36,9 @@ "interfaces": [ "com.puppycrawl.tools.checkstyle.api.Configurable", "com.puppycrawl.tools.checkstyle.api.Contextualizable" + ], + "properties": [ + ] } ] diff --git a/src/test/resources/com/github/checkstyle/regression/module/ReturnCountCheckTest.java b/src/test/resources/com/github/checkstyle/regression/module/ReturnCountCheckTest.java new file mode 100644 index 0000000..ebc1625 --- /dev/null +++ b/src/test/resources/com/github/checkstyle/regression/module/ReturnCountCheckTest.java @@ -0,0 +1,149 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2017 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.github.checkstyle.regression.module; + +import static com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck.MSG_KEY; + +import org.junit.Assert; +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; + +public class ReturnCountCheckTest extends AbstractModuleTestSupport { + @Override + protected String getPackageLocation() { + return "com/puppycrawl/tools/checkstyle/checks/coding/returncount"; + } + + @Test + public void testDefault() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountCheck.class); + final String[] expected = { + "18:5: " + getCheckMessage(MSG_KEY, 7, 1), + "30:5: " + getCheckMessage(MSG_KEY, 2, 1), + "35:17: " + getCheckMessage(MSG_KEY, 6, 1), + "49:5: " + getCheckMessage(MSG_KEY, 7, 2), + }; + verify(checkConfig, getPath("InputReturnCountSwitches.java"), expected); + } + + @Test + public void testFormat() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ReturnCountCheck.class); + checkConfig.addAttribute("format", "^$"); + final String[] expected = { + "5:5: " + getCheckMessage(MSG_KEY, 7, 2), + "18:5: " + getCheckMessage(MSG_KEY, 7, 1), + "30:5: " + getCheckMessage(MSG_KEY, 2, 1), + "35:17: " + getCheckMessage(MSG_KEY, 6, 1), + "49:5: " + getCheckMessage(MSG_KEY, 7, 2), + }; + verify(checkConfig, getPath("InputReturnCountSwitches.java"), expected); + } + + @Test + public void testMethodsAndLambdas() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ReturnCountCheck.class); + checkConfig.addAttribute("max", "1"); + final String[] expected = { + "15:55: " + getCheckMessage(MSG_KEY, 2, 1), + "27:49: " + getCheckMessage(MSG_KEY, 2, 1), + "34:42: " + getCheckMessage(MSG_KEY, 3, 1), + "41:5: " + getCheckMessage(MSG_KEY, 2, 1), + "49:57: " + getCheckMessage(MSG_KEY, 2, 1), + }; + verify(checkConfig, getPath("InputReturnCountLambda.java"), expected); + } + + @Test + public void testLambdasOnly() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ReturnCountCheck.class); + checkConfig.addAttribute("tokens", "LAMBDA"); + final String[] expected = { + "34:42: " + getCheckMessage(MSG_KEY, 3, 2), + }; + verify(checkConfig, getPath("InputReturnCountLambda.java"), expected); + } + + @Test + public void testMethodsOnly() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ReturnCountCheck.class); + checkConfig.addAttribute("tokens", "METHOD_DEF"); + final String[] expected = { + "26:5: " + getCheckMessage(MSG_KEY, 3, 2), + "33:5: " + getCheckMessage(MSG_KEY, 4, 2), + "41:5: " + getCheckMessage(MSG_KEY, 4, 2), + "56:5: " + getCheckMessage(MSG_KEY, 3, 2), + }; + verify(checkConfig, getPath("InputReturnCountLambda.java"), expected); + } + + @Test + public void testWithReturnOnlyAsTokens() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ReturnCountCheck.class); + checkConfig.addAttribute("tokens", "LITERAL_RETURN"); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(checkConfig, getPath("InputReturnCountLambda.java"), expected); + } + + @Test + public void testImproperToken() { + final ReturnCountCheck check = new ReturnCountCheck(); + + final DetailAST classDefAst = new DetailAST(); + classDefAst.setType(TokenTypes.CLASS_DEF); + + try { + check.visitToken(classDefAst); + Assert.fail("IllegalStateException is expected"); + } + catch (IllegalStateException ex) { + // it is OK + } + + try { + check.leaveToken(classDefAst); + Assert.fail("IllegalStateException is expected"); + } + catch (IllegalStateException ex) { + // it is OK + } + } + + @Test + public void testMaxForVoid() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(ReturnCountCheck.class); + checkConfig.addAttribute("max", "2"); + checkConfig.addAttribute("maxForVoid", "0"); + final String[] expected = { + "4:5: " + getCheckMessage(MSG_KEY, 1, 0), + "8:5: " + getCheckMessage(MSG_KEY, 1, 0), + "14:5: " + getCheckMessage(MSG_KEY, 2, 0), + "30:5: " + getCheckMessage(MSG_KEY, 3, 2), + }; + verify(checkConfig, getPath("InputReturnCountVoid.java"), expected); + } +}