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