View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 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.meta;
21  
22  import static com.google.common.truth.Truth.assertThat;
23  import static com.google.common.truth.Truth.assertWithMessage;
24  
25  import java.io.InputStream;
26  import java.nio.charset.StandardCharsets;
27  import java.nio.file.Files;
28  import java.nio.file.Path;
29  import java.util.List;
30  import java.util.Set;
31  import java.util.TreeSet;
32  import java.util.stream.Collectors;
33  
34  import org.apache.commons.io.IOUtils;
35  import org.junit.jupiter.api.Test;
36  
37  import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport;
38  import com.puppycrawl.tools.checkstyle.internal.utils.CheckUtil;
39  
40  public class XmlMetaReaderTest extends AbstractPathTestSupport {
41  
42      /** Modules that intentionally ship no metadata file. */
43      private static final Set<String> MODULES_WITHOUT_METADATA = Set.of(
44              "com.puppycrawl.tools.checkstyle.Checker",
45              "com.puppycrawl.tools.checkstyle.TreeWalker"
46      );
47  
48      /** Plain scan result, shared to avoid repeating an expensive classpath scan. */
49      private static final List<ModuleDetails> ALL_MODULES =
50              XmlMetaReader.readAllModulesIncludingThirdPartyIfAny();
51  
52      @Override
53      public String getPackageLocation() {
54          return "com/puppycrawl/tools/checkstyle/meta/xmlmetareader";
55      }
56  
57      /**
58       * Verifies that metadata for every checkstyle module can be located on the classpath
59       * and parsed.
60       *
61       * <p>This is "contains at least", not "contains exactly", because this test's own input
62       * files live inside the scanned package and are therefore picked up by the scan. The
63       * reverse direction, metadata files with no matching module, is covered by
64       * {@code MetadataGeneratorUtilTest}.
65       *
66       * <p>When running this test directly from an IDE, run {@code ./mvnw process-classes}
67       * first to generate the metadata files under {@code target/classes}.
68       *
69       * @throws Exception if the attempt to read class path resources failed
70       */
71      @Test
72      public void testAllModulesHaveMetadata() throws Exception {
73          final Set<String> expected = CheckUtil.getCheckstyleModules().stream()
74                  .map(Class::getName)
75                  .filter(name -> !MODULES_WITHOUT_METADATA.contains(name))
76                  .collect(Collectors.toCollection(TreeSet::new));
77  
78          assertWithMessage("Metadata should be readable for every checkstyle module")
79                  .that(fullNames(ALL_MODULES))
80                  .containsAtLeastElementsIn(expected);
81      }
82  
83      @Test
84      public void testDuplicatePackage() {
85          final List<ModuleDetails> actual = XmlMetaReader
86                  .readAllModulesIncludingThirdPartyIfAny("com.puppycrawl.tools.checkstyle.meta");
87  
88          assertWithMessage("Rescanning a scanned package should not duplicate modules")
89                  .that(actual)
90                  .hasSize(ALL_MODULES.size());
91          assertWithMessage("Rescanning a scanned package should not change the modules")
92                  .that(fullNames(actual))
93                  .containsExactlyElementsIn(fullNames(ALL_MODULES));
94      }
95  
96      @Test
97      public void testBadPackage() {
98          final List<ModuleDetails> actual =
99                  XmlMetaReader.readAllModulesIncludingThirdPartyIfAny("DOES.NOT.EXIST");
100 
101         assertWithMessage("A nonexistent third party package should not add modules")
102                 .that(actual)
103                 .hasSize(ALL_MODULES.size());
104         assertWithMessage("A nonexistent third party package should not change the modules")
105                 .that(fullNames(actual))
106                 .containsExactlyElementsIn(fullNames(ALL_MODULES));
107     }
108 
109     @Test
110     public void testReadXmlMetaCheckWithProperties() throws Exception {
111         final String path = getPath("InputXmlMetaReaderCheckWithProps.xml");
112         try (InputStream is = Files.newInputStream(Path.of(path))) {
113             final ModuleDetails result = XmlMetaReader.read(is, ModuleType.CHECK);
114             checkModuleProps(result, ModuleType.CHECK, "Some description for check",
115                     "com.puppycrawl.tools.checkstyle.checks.misc.InputCheck",
116                     "com.puppycrawl.tools.checkstyle.TreeWalker");
117             assertThat(result.getName()).isEqualTo("InputCheck");
118             final List<String> violationMessageKeys = result.getViolationMessageKeys();
119             assertThat(violationMessageKeys).hasSize(1);
120             assertThat(violationMessageKeys.getFirst()).isEqualTo("test.key");
121             final List<ModulePropertyDetails> props = result.getProperties();
122             assertThat(props).hasSize(2);
123             final ModulePropertyDetails prop1 = props.getFirst();
124             checkProperty(prop1, "propertyOne", "java.lang.String",
125                     "propertyOneDefaultValue",
126                     "Property wrapped\n            description.");
127             assertThat(prop1.getValidationType()).isNull();
128 
129             final ModulePropertyDetails prop2 = props.get(1);
130             checkProperty(prop2, "propertyTwo", "java.lang.String[]",
131                     "", "Property two desc");
132             assertThat(prop2.getValidationType()).isEqualTo("tokenTypesSet");
133         }
134     }
135 
136     @Test
137     public void testReadXmlMetaCheckNoProperties() throws Exception {
138         final String path = getPath("InputXmlMetaReaderCheckNoProps.xml");
139         try (InputStream is = Files.newInputStream(Path.of(path))) {
140             final ModuleDetails result = XmlMetaReader.read(is, ModuleType.CHECK);
141             checkModuleProps(result, ModuleType.CHECK,
142                     "Some description for check with no properties",
143                     "com.puppycrawl.tools.checkstyle.checks.misc.InputCheckNoProps",
144                     "com.puppycrawl.tools.checkstyle.TreeWalker");
145             assertThat(result.getName()).isEqualTo("InputCheckNoProps");
146             final List<String> violationMessageKeys = result.getViolationMessageKeys();
147             assertThat(violationMessageKeys).hasSize(2);
148             assertThat(violationMessageKeys.getFirst()).isEqualTo("test.key1");
149             assertThat(violationMessageKeys.get(1)).isEqualTo("test.key2");
150             assertThat(result.getProperties()).isEmpty();
151         }
152     }
153 
154     @Test
155     public void testReadXmlMetaFilter() throws Exception {
156         final String path = getPath("InputXmlMetaReaderFilter.xml");
157         try (InputStream is = Files.newInputStream(Path.of(path))) {
158             final ModuleDetails result = XmlMetaReader.read(is, ModuleType.FILTER);
159             checkModuleProps(result, ModuleType.FILTER, "Description for filter",
160                     "com.puppycrawl.tools.checkstyle.filters.SomeFilter",
161                     "com.puppycrawl.tools.checkstyle.TreeWalker");
162             assertThat(result.getName()).isEqualTo("SomeFilter");
163             assertThat(result.getViolationMessageKeys()).isEmpty();
164             final List<ModulePropertyDetails> props = result.getProperties();
165             assertThat(props).hasSize(1);
166             final ModulePropertyDetails prop1 = props.getFirst();
167             checkProperty(prop1, "propertyOne", "java.util.regex.Pattern",
168                     "propertyDefaultValue", "Property description.");
169             assertThat(prop1.getValidationType()).isNull();
170         }
171     }
172 
173     @Test
174     public void testReadXmlMetaFileFilter() throws Exception {
175         final String path = getPath("InputXmlMetaReaderFileFilter.xml");
176         try (InputStream is = Files.newInputStream(Path.of(path))) {
177             final ModuleDetails result = XmlMetaReader.read(is, ModuleType.FILEFILTER);
178             checkModuleProps(result, ModuleType.FILEFILTER,
179                     "File filter description",
180                     "com.puppycrawl.tools.checkstyle.filefilters.FileFilter",
181                     "com.puppycrawl.tools.checkstyle.Checker");
182             assertThat(result.getName()).isEqualTo("FileFilter");
183             assertThat(result.getViolationMessageKeys()).isEmpty();
184             final List<ModulePropertyDetails> props = result.getProperties();
185             assertThat(props).hasSize(1);
186             final ModulePropertyDetails prop1 = props.getFirst();
187             assertThat(prop1.getName()).isEqualTo("fileNamePattern");
188             assertThat(prop1.getType()).isEqualTo("java.util.regex.Pattern");
189             assertThat(prop1.getDefaultValue()).isNull();
190             assertThat(prop1.getValidationType()).isNull();
191             assertThat(prop1.getDescription())
192                     .isEqualTo("Define regular expression to match the file name against.");
193         }
194     }
195 
196     @Test
197     public void testReadXmlMetaModuleTypeNull() throws Exception {
198         try (InputStream is = IOUtils.toInputStream("", StandardCharsets.UTF_8)) {
199             assertThat(XmlMetaReader.read(is, null)).isNull();
200         }
201     }
202 
203     private static Set<String> fullNames(List<ModuleDetails> modules) {
204         return modules.stream()
205                 .map(ModuleDetails::getFullQualifiedName)
206                 .collect(Collectors.toCollection(TreeSet::new));
207     }
208 
209     private static void checkModuleProps(ModuleDetails result, ModuleType moduleType,
210                                          String description,
211                                          String fullName, String parent) {
212         assertThat(result.getModuleType()).isEqualTo(moduleType);
213         assertThat(result.getDescription()).isEqualTo(description);
214         assertThat(result.getFullQualifiedName()).isEqualTo(fullName);
215         assertThat(result.getParent()).isEqualTo(parent);
216     }
217 
218     private static void checkProperty(ModulePropertyDetails prop, String name,
219                                       String type, String defaultValue, String description) {
220         assertThat(prop.getName()).isEqualTo(name);
221         assertThat(prop.getType()).isEqualTo(type);
222         assertThat(prop.getDefaultValue()).isEqualTo(defaultValue);
223         assertThat(prop.getDescription()).isEqualTo(description);
224     }
225 
226 }