Search in sources :

Example 1 with AbstractCheck

use of com.puppycrawl.tools.checkstyle.api.AbstractCheck in project sevntu.checkstyle by sevntu-checkstyle.

the class AllChecksTest method testRequiredTokensAreSubsetOfAcceptableTokens.

@Test
public void testRequiredTokensAreSubsetOfAcceptableTokens() throws Exception {
    for (Class<?> check : CheckUtil.getCheckstyleChecks()) {
        if (AbstractCheck.class.isAssignableFrom(check)) {
            final AbstractCheck testedCheck = (AbstractCheck) check.getDeclaredConstructor().newInstance();
            final int[] requiredTokens = testedCheck.getRequiredTokens();
            final int[] acceptableTokens = testedCheck.getAcceptableTokens();
            if (!isSubset(requiredTokens, acceptableTokens)) {
                final String errorMessage = String.format(Locale.ROOT, "%s's required tokens must be a subset" + " of acceptable tokens.", check.getName());
                Assert.fail(errorMessage);
            }
        }
    }
}
Also used : AbstractCheck(com.puppycrawl.tools.checkstyle.api.AbstractCheck) Test(org.junit.Test)

Example 2 with AbstractCheck

use of com.puppycrawl.tools.checkstyle.api.AbstractCheck in project checkstyle by checkstyle.

the class TreeWalker method setupChild.

/**
 * {@inheritDoc} Creates child module.
 *
 * @noinspection ChainOfInstanceofChecks
 */
@Override
public void setupChild(Configuration childConf) throws CheckstyleException {
    final String name = childConf.getName();
    final Object module;
    try {
        module = moduleFactory.createModule(name);
        if (module instanceof AutomaticBean) {
            final AutomaticBean bean = (AutomaticBean) module;
            bean.contextualize(childContext);
            bean.configure(childConf);
        }
    } catch (final CheckstyleException ex) {
        throw new CheckstyleException("cannot initialize module " + name + " - " + ex.getMessage(), ex);
    }
    if (module instanceof AbstractCheck) {
        final AbstractCheck check = (AbstractCheck) module;
        check.init();
        registerCheck(check);
    } else if (module instanceof TreeWalkerFilter) {
        final TreeWalkerFilter filter = (TreeWalkerFilter) module;
        filters.add(filter);
    } else {
        throw new CheckstyleException("TreeWalker is not allowed as a parent of " + name + " Please review 'Parent Module' section for this Check in web" + " documentation if Check is standard.");
    }
}
Also used : AbstractCheck(com.puppycrawl.tools.checkstyle.api.AbstractCheck) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) AutomaticBean(com.puppycrawl.tools.checkstyle.api.AutomaticBean)

Example 3 with AbstractCheck

use of com.puppycrawl.tools.checkstyle.api.AbstractCheck in project checkstyle by checkstyle.

the class XdocsPagesTest method fixCapturedProperties.

private static void fixCapturedProperties(String sectionName, Object instance, Class<?> clss, Set<String> properties) {
    // remove global properties that don't need documentation
    if (hasParentModule(sectionName)) {
        if (AbstractJavadocCheck.class.isAssignableFrom(clss)) {
            properties.removeAll(JAVADOC_CHECK_PROPERTIES);
            // override
            properties.add("violateExecutionOnNonTightHtml");
        } else if (AbstractCheck.class.isAssignableFrom(clss)) {
            properties.removeAll(CHECK_PROPERTIES);
        }
    }
    if (AbstractFileSetCheck.class.isAssignableFrom(clss)) {
        properties.removeAll(FILESET_PROPERTIES);
        // override
        properties.add("fileExtensions");
    }
    // remove undocumented properties
    new HashSet<>(properties).stream().filter(prop -> UNDOCUMENTED_PROPERTIES.contains(clss.getSimpleName() + "." + prop)).forEach(properties::remove);
    if (AbstractCheck.class.isAssignableFrom(clss)) {
        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(clss)) {
        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");
        }
    }
}
Also used : Arrays(java.util.Arrays) Array(java.lang.reflect.Array) PropertyUtils(org.apache.commons.beanutils.PropertyUtils) CheckUtil(com.puppycrawl.tools.checkstyle.internal.utils.CheckUtil) AbstractJavadocCheck(com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck) Matcher(java.util.regex.Matcher) Locale(java.util.Locale) Document(org.w3c.dom.Document) Map(java.util.Map) TokenUtil(com.puppycrawl.tools.checkstyle.utils.TokenUtil) URI(java.net.URI) ConfigurationLoader(com.puppycrawl.tools.checkstyle.ConfigurationLoader) Path(java.nio.file.Path) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) AbstractCheck(com.puppycrawl.tools.checkstyle.api.AbstractCheck) Collection(java.util.Collection) AbstractFileSetCheck(com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck) Set(java.util.Set) Collectors(java.util.stream.Collectors) IgnoredModulesOptions(com.puppycrawl.tools.checkstyle.ConfigurationLoader.IgnoredModulesOptions) Test(org.junit.jupiter.api.Test) List(java.util.List) Stream(java.util.stream.Stream) XdocUtil(com.puppycrawl.tools.checkstyle.internal.utils.XdocUtil) PropertyDescriptor(java.beans.PropertyDescriptor) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) IntStream(java.util.stream.IntStream) TestUtil(com.puppycrawl.tools.checkstyle.internal.utils.TestUtil) AccessModifierOption(com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption) XdocsPropertyType(com.puppycrawl.tools.checkstyle.XdocsPropertyType) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Node(org.w3c.dom.Node) NoSuchElementException(java.util.NoSuchElementException) XmlUtil(com.puppycrawl.tools.checkstyle.internal.utils.XmlUtil) InputSource(org.xml.sax.InputSource) Properties(java.util.Properties) NodeList(org.w3c.dom.NodeList) PropertiesExpander(com.puppycrawl.tools.checkstyle.PropertiesExpander) Iterator(java.util.Iterator) Files(java.nio.file.Files) ModuleFactory(com.puppycrawl.tools.checkstyle.ModuleFactory) IOException(java.io.IOException) Field(java.lang.reflect.Field) Integer.parseInt(java.lang.Integer.parseInt) File(java.io.File) Configuration(com.puppycrawl.tools.checkstyle.api.Configuration) StringReader(java.io.StringReader) ParameterizedType(java.lang.reflect.ParameterizedType) PropertyType(com.puppycrawl.tools.checkstyle.PropertyType) Paths(java.nio.file.Paths) Checker(com.puppycrawl.tools.checkstyle.Checker) BitSet(java.util.BitSet) Collections(java.util.Collections) AbstractJavadocCheck(com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck) AbstractCheck(com.puppycrawl.tools.checkstyle.api.AbstractCheck)

Example 4 with AbstractCheck

use of com.puppycrawl.tools.checkstyle.api.AbstractCheck in project checkstyle by checkstyle.

the class XdocsPagesTest method validatePropertySectionProperties.

private static void validatePropertySectionProperties(String fileName, String sectionName, Node table, Object instance, Set<String> properties) throws Exception {
    boolean skip = true;
    boolean didJavadocTokens = false;
    boolean didTokens = false;
    for (Node row : XmlUtil.getChildrenElements(table)) {
        final List<Node> columns = new ArrayList<>(XmlUtil.getChildrenElements(row));
        assertWithMessage(fileName + " section '" + sectionName + "' should have the requested columns").that(columns).hasSize(5);
        if (skip) {
            assertWithMessage(fileName + " section '" + sectionName + "' should have the specific title").that(columns.get(0).getTextContent()).isEqualTo("name");
            assertWithMessage(fileName + " section '" + sectionName + "' should have the specific title").that(columns.get(1).getTextContent()).isEqualTo("description");
            assertWithMessage(fileName + " section '" + sectionName + "' should have the specific title").that(columns.get(2).getTextContent()).isEqualTo("type");
            assertWithMessage(fileName + " section '" + sectionName + "' should have the specific title").that(columns.get(3).getTextContent()).isEqualTo("default value");
            assertWithMessage(fileName + " section '" + sectionName + "' should have the specific title").that(columns.get(4).getTextContent()).isEqualTo("since");
            skip = false;
            continue;
        }
        assertWithMessage(fileName + " section '" + sectionName + "' should have token properties last").that(didTokens).isFalse();
        final String propertyName = columns.get(0).getTextContent();
        assertWithMessage(fileName + " section '" + sectionName + "' should not contain the property: " + propertyName).that(properties.remove(propertyName)).isTrue();
        if ("tokens".equals(propertyName)) {
            final AbstractCheck check = (AbstractCheck) instance;
            validatePropertySectionPropertyTokens(fileName, sectionName, check, columns);
            didTokens = true;
        } else if ("javadocTokens".equals(propertyName)) {
            final AbstractJavadocCheck check = (AbstractJavadocCheck) instance;
            validatePropertySectionPropertyJavadocTokens(fileName, sectionName, check, columns);
            didJavadocTokens = true;
        } else {
            assertWithMessage(fileName + " section '" + sectionName + "' should have javadoc token properties next to last, before tokens").that(didJavadocTokens).isFalse();
            validatePropertySectionPropertyEx(fileName, sectionName, instance, columns, propertyName);
        }
        assertWithMessage("%s section '%s' should have a version for %s", fileName, sectionName, propertyName).that(columns.get(4).getTextContent().trim()).isNotEmpty();
        assertWithMessage("%s section '%s' should have a valid version for %s", fileName, sectionName, propertyName).that(columns.get(4).getTextContent().trim()).matches(VERSION);
    }
}
Also used : AbstractJavadocCheck(com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck) AbstractCheck(com.puppycrawl.tools.checkstyle.api.AbstractCheck) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList)

Example 5 with AbstractCheck

use of com.puppycrawl.tools.checkstyle.api.AbstractCheck in project checkstyle by checkstyle.

the class AllChecksTest method validateAllCheckTokensAreReferencedInConfigFile.

private static void validateAllCheckTokensAreReferencedInConfigFile(String configName, Configuration configuration, Map<String, Set<String>> tokensToIgnore, boolean defaultTokensMustBeExplicit) throws Exception {
    final ModuleFactory moduleFactory = TestUtil.getPackageObjectFactory();
    final Set<Configuration> configChecks = ConfigurationUtil.getChecks(configuration);
    final Map<String, Set<String>> configCheckTokens = new HashMap<>();
    final Map<String, Set<String>> checkTokens = new HashMap<>();
    for (Configuration checkConfig : configChecks) {
        final String checkName = checkConfig.getName();
        final Object instance;
        try {
            instance = moduleFactory.createModule(checkName);
        } catch (CheckstyleException ex) {
            throw new CheckstyleException("Couldn't find check: " + checkName, ex);
        }
        final AbstractCheck check;
        if (instance instanceof AbstractCheck && !isAllTokensAcceptable((AbstractCheck) instance)) {
            check = (AbstractCheck) instance;
        } else {
            // we can not have in our config test for all tokens
            continue;
        }
        Set<String> configTokens = configCheckTokens.get(checkName);
        if (configTokens == null) {
            configTokens = new HashSet<>();
            configCheckTokens.put(checkName, configTokens);
            // add all overridden tokens
            final Set<String> overrideTokens = tokensToIgnore.get(checkName);
            if (overrideTokens != null) {
                configTokens.addAll(overrideTokens);
            }
            configTokens.addAll(CheckUtil.getTokenNameSet(check.getRequiredTokens()));
            checkTokens.put(checkName, CheckUtil.getTokenNameSet(check.getAcceptableTokens()));
        }
        try {
            configTokens.addAll(Arrays.asList(checkConfig.getProperty("tokens").trim().split(",\\s*")));
        } catch (CheckstyleException ex) {
            // no tokens defined, so it is using default
            if (defaultTokensMustBeExplicit) {
                validateDefaultTokens(checkConfig, check, configTokens);
            } else {
                configTokens.addAll(CheckUtil.getTokenNameSet(check.getDefaultTokens()));
            }
        }
    }
    for (Entry<String, Set<String>> entry : checkTokens.entrySet()) {
        final Set<String> actual = configCheckTokens.get(entry.getKey());
        assertWithMessage("'" + entry.getKey() + "' should have all acceptable tokens from check in " + configName + " config or specify an override to ignore the specific tokens").that(actual).isEqualTo(entry.getValue());
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Configuration(com.puppycrawl.tools.checkstyle.api.Configuration) DefaultConfiguration(com.puppycrawl.tools.checkstyle.DefaultConfiguration) HashMap(java.util.HashMap) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) ModuleFactory(com.puppycrawl.tools.checkstyle.ModuleFactory) AbstractCheck(com.puppycrawl.tools.checkstyle.api.AbstractCheck)

Aggregations

AbstractCheck (com.puppycrawl.tools.checkstyle.api.AbstractCheck)13 CheckstyleException (com.puppycrawl.tools.checkstyle.api.CheckstyleException)4 Test (org.junit.jupiter.api.Test)4 ModuleFactory (com.puppycrawl.tools.checkstyle.ModuleFactory)3 Configuration (com.puppycrawl.tools.checkstyle.api.Configuration)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Set (java.util.Set)3 DefaultConfiguration (com.puppycrawl.tools.checkstyle.DefaultConfiguration)2 AbstractJavadocCheck (com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck)2 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 Node (org.w3c.dom.Node)2 Truth.assertWithMessage (com.google.common.truth.Truth.assertWithMessage)1 Checker (com.puppycrawl.tools.checkstyle.Checker)1 ConfigurationLoader (com.puppycrawl.tools.checkstyle.ConfigurationLoader)1 IgnoredModulesOptions (com.puppycrawl.tools.checkstyle.ConfigurationLoader.IgnoredModulesOptions)1 PropertiesExpander (com.puppycrawl.tools.checkstyle.PropertiesExpander)1 PropertyType (com.puppycrawl.tools.checkstyle.PropertyType)1 XdocsPropertyType (com.puppycrawl.tools.checkstyle.XdocsPropertyType)1