View Javadoc
1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2018 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.internal;
21  
22  import java.lang.reflect.Field;
23  import java.lang.reflect.Modifier;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.HashMap;
27  import java.util.HashSet;
28  import java.util.List;
29  import java.util.Locale;
30  import java.util.Map;
31  import java.util.Map.Entry;
32  import java.util.Properties;
33  import java.util.Set;
34  import java.util.TreeMap;
35  import java.util.stream.Collectors;
36  import java.util.stream.Stream;
37  
38  import org.junit.Assert;
39  import org.junit.Test;
40  
41  import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
42  import com.puppycrawl.tools.checkstyle.Checker;
43  import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
44  import com.puppycrawl.tools.checkstyle.ModuleFactory;
45  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
46  import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
47  import com.puppycrawl.tools.checkstyle.api.Configuration;
48  import com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck;
49  import com.puppycrawl.tools.checkstyle.internal.utils.CheckUtil;
50  import com.puppycrawl.tools.checkstyle.internal.utils.ConfigurationUtil;
51  import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
52  import com.puppycrawl.tools.checkstyle.internal.utils.XdocUtil;
53  import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
54  import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtils;
55  
56  public class AllChecksTest extends AbstractModuleTestSupport {
57  
58      private static final Locale[] ALL_LOCALES = {
59          Locale.GERMAN,
60          new Locale("es"),
61          new Locale("fi"),
62          Locale.FRENCH,
63          Locale.JAPANESE,
64          new Locale("pt"),
65          new Locale("tr"),
66          Locale.CHINESE,
67          Locale.ENGLISH,
68      };
69  
70      private static final Map<String, Set<String>> CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE =
71              new HashMap<>();
72      private static final Map<String, Set<String>> GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE =
73              new HashMap<>();
74  
75      static {
76          // checkstyle
77  
78          CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("NoWhitespaceBefore", Stream.of(
79                  // we use GenericWhitespace for this behavior
80                  "GENERIC_START", "GENERIC_END").collect(Collectors.toSet()));
81          CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("AbbreviationAsWordInName", Stream.of(
82                  // enum values should be uppercase, we use EnumValueNameCheck instead
83                  "ENUM_CONSTANT_DEF").collect(Collectors.toSet()));
84          CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("FinalLocalVariable", Stream.of(
85                  // we prefer all parameters be effectively final as to not damage readability
86                  // we use ParameterAssignmentCheck to enforce this
87                  "PARAMETER_DEF").collect(Collectors.toSet()));
88          // we have no need to block these specific tokens
89          CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("IllegalToken",
90                  Stream.of("LITERAL_SUPER", "LITERAL_ASSERT", "ENUM_CONSTANT_DEF",
91                          "TYPE_PARAMETERS", "TYPE_UPPER_BOUNDS", "NUM_DOUBLE", "LITERAL_SWITCH",
92                          "ANNOTATIONS", "LITERAL_SHORT", "LITERAL_PROTECTED", "FOR_CONDITION",
93                          "FOR_INIT", "LITERAL_LONG", "MINUS", "OBJBLOCK", "LITERAL_NULL",
94                          "ANNOTATION", "LITERAL_TRUE", "COMMENT_CONTENT", "LITERAL_CHAR",
95                          "PARAMETER_DEF", "POST_DEC", "ANNOTATION_FIELD_DEF", "BLOCK_COMMENT_END",
96                          "TYPE", "LITERAL_INT", "BSR", "ENUM", "ANNOTATION_MEMBER_VALUE_PAIR",
97                          "TYPECAST", "LITERAL_SYNCHRONIZED", "PLUS_ASSIGN", "DOT", "LPAREN",
98                          "LITERAL_IF", "LITERAL_CATCH", "BAND", "INTERFACE_DEF", "LOR", "BNOT",
99                          "METHOD_CALL", "AT", "ELLIPSIS", "ARRAY_INIT", "FOR_EACH_CLAUSE",
100                         "LITERAL_THROWS", "CHAR_LITERAL", "CASE_GROUP", "POST_INC", "SEMI",
101                         "LITERAL_FINALLY", "ASSIGN", "RESOURCE_SPECIFICATION", "STATIC_IMPORT",
102                         "GENERIC_START", "IMPORT", "SL", "VARIABLE_DEF", "LITERAL_DOUBLE",
103                         "RCURLY", "RESOURCE", "SR", "COMMA", "BAND_ASSIGN", "METHOD_DEF",
104                         "LITERAL_VOID", "NUM_LONG", "LITERAL_TRANSIENT", "LITERAL_THIS", "LCURLY",
105                         "MINUS_ASSIGN", "TYPE_LOWER_BOUNDS", "TYPE_ARGUMENT", "LITERAL_CLASS",
106                         "INSTANCE_INIT", "DIV", "STAR", "UNARY_MINUS", "FOR_ITERATOR", "NOT_EQUAL",
107                         "LE", "LITERAL_INTERFACE", "LITERAL_FLOAT", "LITERAL_INSTANCEOF",
108                         "BOR_ASSIGN", "LT", "SL_ASSIGN", "ELIST", "ANNOTATION_ARRAY_INIT",
109                         "MODIFIERS", "LITERAL_BREAK", "EXTENDS_CLAUSE", "TYPE_PARAMETER",
110                         "LITERAL_DEFAULT", "STATIC_INIT", "BSR_ASSIGN", "TYPE_EXTENSION_AND",
111                         "BOR", "LITERAL_PRIVATE", "LITERAL_THROW", "LITERAL_BYTE", "BXOR",
112                         "WILDCARD_TYPE", "FINAL", "PARAMETERS", "RPAREN", "SR_ASSIGN",
113                         "UNARY_PLUS", "EMPTY_STAT", "LITERAL_STATIC", "LITERAL_CONTINUE",
114                         "STAR_ASSIGN", "LAMBDA", "RBRACK", "BXOR_ASSIGN", "CTOR_CALL",
115                         "LITERAL_FALSE", "DO_WHILE", "LITERAL_PUBLIC", "LITERAL_WHILE", "PLUS",
116                         "INC", "CTOR_DEF", "GENERIC_END", "DIV_ASSIGN", "SLIST", "LNOT", "LAND",
117                         "LITERAL_ELSE", "ABSTRACT", "STRICTFP", "QUESTION", "LITERAL_NEW",
118                         "LITERAL_RETURN", "SINGLE_LINE_COMMENT", "INDEX_OP", "EXPR",
119                         "BLOCK_COMMENT_BEGIN", "PACKAGE_DEF", "IMPLEMENTS_CLAUSE", "NUM_FLOAT",
120                         "LITERAL_DO", "EOF", "GE", "RESOURCES", "MOD", "DEC", "EQUAL",
121                         "LITERAL_BOOLEAN", "CLASS_DEF", "COLON", "LITERAL_TRY", "ENUM_DEF", "GT",
122                         "NUM_INT", "ANNOTATION_DEF", "METHOD_REF", "TYPE_ARGUMENTS",
123                         "DOUBLE_COLON", "IDENT", "MOD_ASSIGN", "LITERAL_FOR", "SUPER_CTOR_CALL",
124                         "STRING_LITERAL", "ARRAY_DECLARATOR", "LITERAL_CASE").collect(
125                         Collectors.toSet()));
126         // we have no need to block specific token text
127         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("IllegalTokenText",
128                 Stream.of("NUM_DOUBLE", "NUM_FLOAT", "NUM_INT", "NUM_LONG", "IDENT",
129                     "COMMENT_CONTENT", "STRING_LITERAL", "CHAR_LITERAL")
130                     .collect(Collectors.toSet()));
131         // we do not use this check as it is deprecated
132         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("WriteTag",
133                 Stream.of("ENUM_CONSTANT_DEF", "METHOD_DEF", "CTOR_DEF", "ANNOTATION_FIELD_DEF")
134                         .collect(Collectors.toSet()));
135         // state of the configuration when test was made until reason found in
136         // https://github.com/checkstyle/checkstyle/issues/3730
137         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("AnnotationLocation",
138                 Stream.of("TYPECAST", "DOT", "TYPE_ARGUMENT", "LITERAL_NEW", "LITERAL_THROWS",
139                         "IMPLEMENTS_CLAUSE", "CLASS_DEF", "CTOR_DEF", "ENUM_DEF", "INTERFACE_DEF",
140                         "METHOD_DEF", "VARIABLE_DEF").collect(Collectors.toSet()));
141         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("NoLineWrap", Stream.of(
142                 // method declaration could be long due to "parameters/exceptions", it is ok to
143                 // be not strict there
144                 "METHOD_DEF", "CTOR_DEF",
145                 // type declaration could be long due to "extends/implements", it is ok to
146                 // be not strict there
147                 "CLASS_DEF", "ENUM_DEF", "INTERFACE_DEF")
148                 .collect(Collectors.toSet()));
149         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("NoWhitespaceAfter", Stream.of(
150                 // whitespace after is preferred
151                 "TYPECAST", "LITERAL_SYNCHRONIZED").collect(Collectors.toSet()));
152         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("SeparatorWrap", Stream.of(
153                 // needs context to decide what type of parentheses should be separated or not
154                 // which this check does not provide
155                 "LPAREN", "RPAREN").collect(Collectors.toSet()));
156         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("NeedBraces", Stream.of(
157                 // we prefer no braces here as it looks unusual even though they help avoid sharing
158                 // scope of variables
159                 "LITERAL_DEFAULT", "LITERAL_CASE").collect(Collectors.toSet()));
160         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("FinalParameters", Stream.of(
161                 // we prefer these to be effectively final as to not damage readability
162                 "FOR_EACH_CLAUSE", "LITERAL_CATCH").collect(Collectors.toSet()));
163         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("WhitespaceAround", Stream.of(
164                 // we prefer no spaces on one side or both for these tokens
165                 "ARRAY_INIT",
166                 "ELLIPSIS",
167                 // these are covered by GenericWhitespaceCheck
168                 "WILDCARD_TYPE", "GENERIC_END", "GENERIC_START").collect(Collectors.toSet()));
169         CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE.put("RightCurly", Stream.of(
170                 // Until https://github.com/checkstyle/checkstyle/issues/4177
171                 "LAMBDA").collect(Collectors.toSet()));
172 
173         // google
174         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("AnnotationLocation", Stream.of(
175                 // state of the configuration when test was made until reason found in
176                 // https://github.com/checkstyle/checkstyle/issues/3730
177                 "TYPECAST", "DOT", "TYPE_ARGUMENT", "ANNOTATION_DEF", "LITERAL_NEW",
178                 "LITERAL_THROWS", "PARAMETER_DEF", "IMPLEMENTS_CLAUSE", "ANNOTATION_FIELD_DEF")
179                 .collect(Collectors.toSet()));
180         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("AbbreviationAsWordInName", Stream.of(
181                 // enum values should be uppercase
182                 "ENUM_CONSTANT_DEF").collect(Collectors.toSet()));
183         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("NoLineWrap", Stream.of(
184                 // method declaration could be long due to "parameters/exceptions", it is ok to
185                 // be not strict there
186                 "METHOD_DEF", "CTOR_DEF", "CLASS_DEF", "ENUM_DEF", "INTERFACE_DEF")
187                 .collect(Collectors.toSet()));
188         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("SeparatorWrap", Stream.of(
189                 // location could be any to allow writing expressions for indexes evaluation
190                 // on new line, see https://github.com/checkstyle/checkstyle/issues/3752
191                 "RBRACK",
192                 // for some targets annotations can be used without wrapping, as described
193                 // in https://google.github.io/styleguide/javaguide.html#s4.8.5-annotations
194                 "AT",
195                 // location could be any to allow using for line separation in enum values,
196                 // see https://github.com/checkstyle/checkstyle/issues/3752
197                 "SEMI",
198                 // needs context to decide what type of parentheses should be separated or not
199                 // which this check does not provide
200                 "LPAREN", "RPAREN").collect(Collectors.toSet()));
201         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("NeedBraces", Stream.of(
202                 // google doesn't require or prevent braces on these
203                 "LAMBDA", "LITERAL_DEFAULT", "LITERAL_CASE").collect(Collectors.toSet()));
204         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("EmptyBlock", Stream.of(
205                 // google doesn't specifically mention empty braces at the start of a case/default
206                 "LITERAL_DEFAULT", "LITERAL_CASE",
207                 // can be empty for special cases via '6.2 Caught exceptions: not ignored'
208                 "LITERAL_CATCH",
209                 // specifically allowed via '5.2.4 Constant names'
210                 "ARRAY_INIT",
211                 // state of the configuration when test was made until
212                 // https://github.com/checkstyle/checkstyle/issues/4121
213                 "INSTANCE_INIT", "LITERAL_DO", "LITERAL_FOR", "LITERAL_SYNCHRONIZED",
214                 "LITERAL_WHILE", "STATIC_INIT").collect(Collectors.toSet()));
215         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("WhitespaceAround", Stream.of(
216                 //  allowed via '4.8.3 Arrays'
217                 "ARRAY_INIT",
218                 //  '...' is almost same as '[]' by meaning
219                 "ELLIPSIS",
220                 // google prefers no spaces on one side or both for these tokens
221                 "GENERIC_START", "GENERIC_END", "WILDCARD_TYPE")
222                 .collect(Collectors.toSet()));
223         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("IllegalTokenText", Stream.of(
224                 // all other java tokens and text are allowed
225                 "NUM_DOUBLE", "NUM_FLOAT", "NUM_INT", "NUM_LONG", "IDENT",
226                 "COMMENT_CONTENT", "STRING_LITERAL", "CHAR_LITERAL")
227                 .collect(Collectors.toSet()));
228         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("OperatorWrap", Stream.of(
229                 // specifically allowed via '4.5.1 Where to break' because the following are
230                 // assignment operators and they are allowed to break before or after the symbol
231                 "DIV_ASSIGN", "BOR_ASSIGN", "SL_ASSIGN", "ASSIGN", "BSR_ASSIGN", "BAND_ASSIGN",
232                 "PLUS_ASSIGN", "MINUS_ASSIGN", "SR_ASSIGN", "STAR_ASSIGN", "BXOR_ASSIGN",
233                 "MOD_ASSIGN",
234                 // state of the configuration when test was made until
235                 // https://github.com/checkstyle/checkstyle/issues/4122
236                 "COLON", "TYPE_EXTENSION_AND").collect(Collectors.toSet()));
237         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("RightCurly", Stream.of(
238                 // Until https://github.com/checkstyle/checkstyle/issues/4178
239                 "LAMBDA").collect(Collectors.toSet()));
240         GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE.put("NoWhitespaceBefore", Stream.of(
241                 // google uses GenericWhitespace for this behavior
242                 "GENERIC_START", "GENERIC_END").collect(Collectors.toSet()));
243     }
244 
245     @Override
246     protected String getPackageLocation() {
247         return "com/puppycrawl/tools/checkstyle/internal/allchecks";
248     }
249 
250     @Test
251     public void testAllModulesWithDefaultConfiguration() throws Exception {
252         final String inputFilePath = getPath("InputAllChecksDefaultConfig.java");
253         final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
254 
255         for (Class<?> module : CheckUtil.getCheckstyleModules()) {
256             if (ModuleReflectionUtils.isRootModule(module)) {
257                 continue;
258             }
259 
260             final DefaultConfiguration moduleConfig = createModuleConfig(module);
261             final Checker checker;
262             if (module.equals(ImportControlCheck.class)) {
263                 // ImportControlCheck must have the import control configuration file to avoid
264                 // violation.
265                 moduleConfig.addAttribute("file", getPath(
266                         "InputAllChecksImportControl.xml"));
267             }
268             checker = createChecker(moduleConfig);
269             verify(checker, inputFilePath, expected);
270         }
271     }
272 
273     @Test
274     public void testDefaultTokensAreSubsetOfAcceptableTokens() throws Exception {
275         for (Class<?> check : CheckUtil.getCheckstyleChecks()) {
276             if (AbstractCheck.class.isAssignableFrom(check)) {
277                 final AbstractCheck testedCheck = (AbstractCheck) check.getDeclaredConstructor()
278                         .newInstance();
279                 final int[] defaultTokens = testedCheck.getDefaultTokens();
280                 final int[] acceptableTokens = testedCheck.getAcceptableTokens();
281 
282                 if (!isSubset(defaultTokens, acceptableTokens)) {
283                     final String errorMessage = String.format(Locale.ROOT,
284                             "%s's default tokens must be a subset"
285                             + " of acceptable tokens.", check.getName());
286                     Assert.fail(errorMessage);
287                 }
288             }
289         }
290     }
291 
292     @Test
293     public void testRequiredTokensAreSubsetOfAcceptableTokens() throws Exception {
294         for (Class<?> check : CheckUtil.getCheckstyleChecks()) {
295             if (AbstractCheck.class.isAssignableFrom(check)) {
296                 final AbstractCheck testedCheck = (AbstractCheck) check.getDeclaredConstructor()
297                         .newInstance();
298                 final int[] requiredTokens = testedCheck.getRequiredTokens();
299                 final int[] acceptableTokens = testedCheck.getAcceptableTokens();
300 
301                 if (!isSubset(requiredTokens, acceptableTokens)) {
302                     final String errorMessage = String.format(Locale.ROOT,
303                             "%s's required tokens must be a subset"
304                             + " of acceptable tokens.", check.getName());
305                     Assert.fail(errorMessage);
306                 }
307             }
308         }
309     }
310 
311     @Test
312     public void testRequiredTokensAreSubsetOfDefaultTokens() throws Exception {
313         for (Class<?> check : CheckUtil.getCheckstyleChecks()) {
314             if (AbstractCheck.class.isAssignableFrom(check)) {
315                 final AbstractCheck testedCheck = (AbstractCheck) check.getDeclaredConstructor()
316                         .newInstance();
317                 final int[] defaultTokens = testedCheck.getDefaultTokens();
318                 final int[] requiredTokens = testedCheck.getRequiredTokens();
319 
320                 if (!isSubset(requiredTokens, defaultTokens)) {
321                     final String errorMessage = String.format(Locale.ROOT,
322                             "%s's required tokens must be a subset"
323                             + " of default tokens.", check.getName());
324                     Assert.fail(errorMessage);
325                 }
326             }
327         }
328     }
329 
330     @Test
331     public void testAllModulesAreReferencedInConfigFile() throws Exception {
332         final Set<String> modulesReferencedInConfig = CheckUtil.getConfigCheckStyleModules();
333         final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules());
334 
335         moduleNames.stream().filter(check -> !modulesReferencedInConfig.contains(check))
336             .forEach(check -> {
337                 final String errorMessage = String.format(Locale.ROOT,
338                     "%s is not referenced in checkstyle_checks.xml", check);
339                 Assert.fail(errorMessage);
340             });
341     }
342 
343     @Test
344     public void testAllCheckTokensAreReferencedInCheckstyleConfigFile() throws Exception {
345         final Configuration configuration = ConfigurationUtil
346                 .loadConfiguration("config/checkstyle_checks.xml");
347 
348         validateAllCheckTokensAreReferencedInConfigFile("checkstyle", configuration,
349                 CHECKSTYLE_TOKENS_IN_CONFIG_TO_IGNORE);
350     }
351 
352     @Test
353     public void testAllCheckTokensAreReferencedInGoogleConfigFile() throws Exception {
354         final Configuration configuration = ConfigurationUtil
355                 .loadConfiguration("src/main/resources/google_checks.xml");
356 
357         validateAllCheckTokensAreReferencedInConfigFile("google", configuration,
358                 GOOGLE_TOKENS_IN_CONFIG_TO_IGNORE);
359     }
360 
361     private static void validateAllCheckTokensAreReferencedInConfigFile(String configName,
362             Configuration configuration, Map<String, Set<String>> tokensToIgnore) throws Exception {
363         final ModuleFactory moduleFactory = TestUtil.getPackageObjectFactory();
364         final Set<Configuration> configChecks = ConfigurationUtil.getChecks(configuration);
365 
366         final Map<String, Set<String>> configCheckTokens = new HashMap<>();
367         final Map<String, Set<String>> checkTokens = new HashMap<>();
368 
369         for (Configuration checkConfig : configChecks) {
370             final String checkName = checkConfig.getName();
371             final Object instance;
372 
373             try {
374                 instance = moduleFactory.createModule(checkName);
375             }
376             catch (CheckstyleException ex) {
377                 throw new CheckstyleException("Couldn't find check: " + checkName, ex);
378             }
379 
380             if (instance instanceof AbstractCheck) {
381                 final AbstractCheck check = (AbstractCheck) instance;
382 
383                 Set<String> configTokens = configCheckTokens.get(checkName);
384 
385                 if (configTokens == null) {
386                     configTokens = new HashSet<>();
387 
388                     configCheckTokens.put(checkName, configTokens);
389 
390                     // add all overridden tokens
391                     final Set<String> overrideTokens = tokensToIgnore.get(checkName);
392 
393                     if (overrideTokens != null) {
394                         configTokens.addAll(overrideTokens);
395                     }
396 
397                     configTokens.addAll(CheckUtil.getTokenNameSet(check.getRequiredTokens()));
398                     checkTokens.put(checkName,
399                             CheckUtil.getTokenNameSet(check.getAcceptableTokens()));
400                 }
401 
402                 try {
403                     configTokens.addAll(Arrays.asList(checkConfig.getAttribute("tokens").trim()
404                             .split(",\\s*")));
405                 }
406                 catch (CheckstyleException ex) {
407                     // no tokens defined, so it is using default
408                     configTokens.addAll(CheckUtil.getTokenNameSet(check.getDefaultTokens()));
409                 }
410             }
411         }
412 
413         for (Entry<String, Set<String>> entry : checkTokens.entrySet()) {
414             Assert.assertEquals("'" + entry.getKey()
415                     + "' should have all acceptable tokens from check in " + configName
416                     + " config or specify an override to ignore the specific tokens",
417                     entry.getValue(), configCheckTokens.get(entry.getKey()));
418         }
419     }
420 
421     @Test
422     public void testAllCheckstyleModulesHaveXdocDocumentation() throws Exception {
423         final Set<String> checkstyleModulesNames = CheckUtil.getSimpleNames(CheckUtil
424                 .getCheckstyleModules());
425         final Set<String> modulesNamesWhichHaveXdocs = XdocUtil.getModulesNamesWhichHaveXdoc();
426 
427         // these are documented on non-'config_' pages
428         checkstyleModulesNames.remove("TreeWalker");
429         checkstyleModulesNames.remove("Checker");
430 
431         checkstyleModulesNames.stream()
432             .filter(moduleName -> !modulesNamesWhichHaveXdocs.contains(moduleName))
433             .forEach(moduleName -> {
434                 final String missingModuleMessage = String.format(Locale.ROOT,
435                     "Module %s does not have xdoc documentation.",
436                     moduleName);
437                 Assert.fail(missingModuleMessage);
438             });
439     }
440 
441     @Test
442     public void testAllCheckstyleModulesInCheckstyleConfig() throws Exception {
443         final Set<String> configChecks = CheckUtil.getConfigCheckStyleModules();
444         final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules());
445 
446         for (String moduleName : moduleNames) {
447             Assert.assertTrue("checkstyle_checks.xml is missing module: " + moduleName,
448                     configChecks.contains(moduleName));
449         }
450     }
451 
452     @Test
453     public void testAllCheckstyleChecksHaveMessage() throws Exception {
454         for (Class<?> module : CheckUtil.getCheckstyleChecks()) {
455             final String name = module.getSimpleName();
456 
457             Assert.assertFalse(name
458                     + " should have at least one 'MSG_*' field for error messages", CheckUtil
459                     .getCheckMessages(module).isEmpty());
460         }
461     }
462 
463     @Test
464     public void testAllCheckstyleMessages() throws Exception {
465         final Map<String, List<String>> usedMessages = new TreeMap<>();
466 
467         // test validity of messages from modules
468         for (Class<?> module : CheckUtil.getCheckstyleModules()) {
469             for (Field message : CheckUtil.getCheckMessages(module)) {
470                 Assert.assertEquals(module.getSimpleName() + "." + message.getName()
471                         + " should be 'public static final'", Modifier.PUBLIC | Modifier.STATIC
472                         | Modifier.FINAL, message.getModifiers());
473 
474                 // below is required for package/private classes
475                 if (!message.isAccessible()) {
476                     message.setAccessible(true);
477                 }
478 
479                 verifyCheckstyleMessage(usedMessages, module, message);
480             }
481         }
482 
483         // test properties for messages not used by checks
484         for (Entry<String, List<String>> entry : usedMessages.entrySet()) {
485             final Properties pr = new Properties();
486             pr.load(AllChecksTest.class.getResourceAsStream(
487                     "/" + entry.getKey().replace('.', '/') + "/messages.properties"));
488 
489             for (Object key : pr.keySet()) {
490                 // hidden exception messages
491                 if ("translation.wrongLanguageCode".equals(key)) {
492                     continue;
493                 }
494 
495                 Assert.assertTrue("property '" + key + "' isn't used by any check in package '"
496                         + entry.getKey() + "'", entry.getValue().contains(key.toString()));
497             }
498         }
499     }
500 
501     private static void verifyCheckstyleMessage(Map<String, List<String>> usedMessages,
502             Class<?> module, Field message) throws Exception {
503         final String messageString = message.get(null).toString();
504         final String packageName = module.getPackage().getName();
505         List<String> packageMessages = usedMessages.get(packageName);
506 
507         if (packageMessages == null) {
508             packageMessages = new ArrayList<>();
509             usedMessages.put(packageName, packageMessages);
510         }
511 
512         packageMessages.add(messageString);
513 
514         for (Locale locale : ALL_LOCALES) {
515             String result = null;
516 
517             try {
518                 result = CheckUtil.getCheckMessage(module, locale, messageString);
519             }
520             catch (IllegalArgumentException ex) {
521                 Assert.fail(module.getSimpleName() + " with the message '" + messageString
522                         + "' in locale '" + locale.getLanguage() + "' failed with: "
523                         + ex.getClass().getSimpleName() + " - " + ex.getMessage());
524             }
525 
526             Assert.assertNotNull(
527                     module.getSimpleName() + " should have text for the message '"
528                             + messageString + "' in locale " + locale.getLanguage() + "'",
529                     result);
530             Assert.assertFalse(
531                     module.getSimpleName() + " should have non-empty text for the message '"
532                             + messageString + "' in locale '" + locale.getLanguage() + "'",
533                     result.trim().isEmpty());
534             Assert.assertFalse(
535                     module.getSimpleName() + " should have non-TODO text for the message '"
536                             + messageString + "' in locale " + locale.getLanguage() + "'",
537                     !"todo.match".equals(messageString)
538                             && result.trim().startsWith("TODO"));
539         }
540     }
541 
542     /**
543      * Checks that an array is a subset of other array.
544      * @param array to check whether it is a subset.
545      * @param arrayToCheckIn array to check in.
546      * @return {@code true} if all elements in {@code array} are in {@code arrayToCheckIn}.
547      */
548     private static boolean isSubset(int[] array, int... arrayToCheckIn) {
549         Arrays.sort(arrayToCheckIn);
550         boolean result = true;
551         for (final int element : array) {
552             if (Arrays.binarySearch(arrayToCheckIn, element) < 0) {
553                 result = false;
554                 break;
555             }
556         }
557         return result;
558     }
559 
560 }