forked from checkstyle/checkstyle
/
AbstractModuleTestSupport.java
561 lines (515 loc) · 23.9 KB
/
AbstractModuleTestSupport.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2021 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.puppycrawl.tools.checkstyle;
import static com.google.common.truth.Truth.assertWithMessage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import com.google.common.collect.Maps;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.Violation;
import com.puppycrawl.tools.checkstyle.bdd.InlineConfigParser;
import com.puppycrawl.tools.checkstyle.bdd.ModuleInputConfiguration;
import com.puppycrawl.tools.checkstyle.bdd.TestInputViolation;
import com.puppycrawl.tools.checkstyle.internal.utils.BriefUtLogger;
import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil;
public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport {
/**
* Enum to specify options for checker creation.
*/
public enum ModuleCreationOption {
/**
* Points that the module configurations
* has to be added under {@link TreeWalker}.
*/
IN_TREEWALKER,
/**
* Points that checker will be created as
* a root of default configuration.
*/
IN_CHECKER,
}
private static final String ROOT_MODULE_NAME = "root";
private final ByteArrayOutputStream stream = new ByteArrayOutputStream();
/**
* Returns log stream.
*
* @return stream with log
*/
public ByteArrayOutputStream getStream() {
return stream;
}
/**
* Returns test logger.
*
* @return logger for tests
*/
public final BriefUtLogger getBriefUtLogger() {
return new BriefUtLogger(stream);
}
protected static DefaultConfiguration createModuleConfig(Class<?> clazz) {
return new DefaultConfiguration(clazz.getName());
}
/**
* Creates {@link Checker} instance based on the given {@link Configuration} instance.
*
* @param moduleConfig {@link Configuration} instance.
* @return {@link Checker} instance based on the given {@link Configuration} instance.
* @throws Exception if an exception occurs during checker configuration.
*/
public final Checker createChecker(Configuration moduleConfig)
throws Exception {
ModuleCreationOption moduleCreationOption = ModuleCreationOption.IN_CHECKER;
final String moduleName = moduleConfig.getName();
if (!ROOT_MODULE_NAME.equals(moduleName)) {
try {
final Class<?> moduleClass = Class.forName(moduleName);
if (ModuleReflectionUtil.isCheckstyleTreeWalkerCheck(moduleClass)
|| ModuleReflectionUtil.isTreeWalkerFilterModule(moduleClass)) {
moduleCreationOption = ModuleCreationOption.IN_TREEWALKER;
}
}
catch (ClassNotFoundException ignore) {
// ignore exception, assume it is not part of TreeWalker
}
}
return createChecker(moduleConfig, moduleCreationOption);
}
/**
* Creates {@link Checker} instance based on the given {@link Configuration} instance.
*
* @param moduleConfig {@link Configuration} instance.
* @param moduleCreationOption {@code IN_TREEWALKER} if the {@code moduleConfig} should be added
* under {@link TreeWalker}.
* @return {@link Checker} instance based on the given {@link Configuration} instance.
* @throws Exception if an exception occurs during checker configuration.
*/
public final Checker createChecker(Configuration moduleConfig,
ModuleCreationOption moduleCreationOption)
throws Exception {
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
if (moduleCreationOption == ModuleCreationOption.IN_TREEWALKER) {
final Configuration dc = createTreeWalkerConfig(moduleConfig);
checker.configure(dc);
}
else if (ROOT_MODULE_NAME.equals(moduleConfig.getName())) {
checker.configure(moduleConfig);
}
else {
final Configuration dc = createRootConfig(moduleConfig);
checker.configure(dc);
}
checker.addListener(new BriefUtLogger(stream));
return checker;
}
/**
* 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.
*/
protected 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.addProperty("charset", StandardCharsets.UTF_8.name());
dc.addChild(twConf);
twConf.addChild(config);
return dc;
}
/**
* Creates {@link DefaultConfiguration} for the given {@link Configuration} instance.
*
* @param config {@link Configuration} instance.
* @return {@link DefaultConfiguration} for the given {@link Configuration} instance.
*/
protected static DefaultConfiguration createRootConfig(Configuration config) {
final DefaultConfiguration dc = new DefaultConfiguration(ROOT_MODULE_NAME);
if (config != null) {
dc.addChild(config);
}
return dc;
}
/**
* Returns canonical path for the file with the given file name.
* The path is formed base on the non-compilable resources location.
* This implementation uses 'src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/'
* as a non-compilable resource location.
*
* @param filename file name.
* @return canonical path for the file with the given file name.
* @throws IOException if I/O exception occurs while forming the path.
*/
protected final String getNonCompilablePath(String filename) throws IOException {
return new File("src/test/resources-noncompilable/" + getPackageLocation() + "/"
+ filename).getCanonicalPath();
}
/**
* Returns URI-representation of the path for the given file name.
* The path is formed base on the root location.
* This implementation uses 'src/test/resources/com/puppycrawl/tools/checkstyle/'
* as a root location.
*
* @param filename file name.
* @return URI-representation of the path for the file with the given file name.
*/
protected final String getUriString(String filename) {
return new File("src/test/resources/" + getPackageLocation() + "/" + filename).toURI()
.toString();
}
protected final void verifyFilterWithInlineConfigParser(Configuration aConfig,
Configuration filterConfig,
String filePath, String[] expectedUnfiltered,
String... expectedFiltered)
throws Exception {
final ModuleInputConfiguration checkModuleInputConfiguration =
InlineConfigParser.parseWithFilteredViolations(filePath);
final Configuration parsedCheckConfig = checkModuleInputConfiguration.createConfiguration();
verifyConfig(aConfig, parsedCheckConfig, checkModuleInputConfiguration);
verifyViolations(parsedCheckConfig, filePath, checkModuleInputConfiguration);
verify(parsedCheckConfig, filePath, expectedUnfiltered);
final ModuleInputConfiguration filterModuleInputConfiguration =
InlineConfigParser.parseFilter(filePath);
final Configuration parsedFilterConfig = filterModuleInputConfiguration.createConfiguration();
verifyConfig(filterConfig, parsedFilterConfig, filterModuleInputConfiguration);
final DefaultConfiguration rootConfig = createRootConfig(parsedCheckConfig);
rootConfig.addChild(parsedFilterConfig);
verifyViolations(rootConfig, filePath, filterModuleInputConfiguration);
verify(rootConfig, filePath, expectedFiltered);
}
/**
* Performs verification of the file with the given file path using specified configuration
* and the array expected messages. Also performs verification of the config specified in
* input file.
*
* @param aConfig configuration.
* @param filePath file path to verify.
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
protected final void verifyWithInlineConfigParser(Configuration aConfig,
String filePath, String... expected)
throws Exception {
final ModuleInputConfiguration moduleInputConfiguration =
InlineConfigParser.parse(filePath);
final Configuration parsedConfig = moduleInputConfiguration.createConfiguration();
verifyConfig(aConfig, parsedConfig, moduleInputConfiguration);
verifyViolations(parsedConfig, filePath, moduleInputConfiguration);
verify(parsedConfig, filePath, expected);
}
/**
* Performs verification of the file with the given file name. Uses specified configuration.
* Expected messages are represented by the array of strings.
* This implementation uses overloaded
* {@link AbstractModuleTestSupport#verify(Checker, File[], String, String...)} method inside.
*
* @param aConfig configuration.
* @param fileName file name to verify.
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
protected final void verify(Configuration aConfig, String fileName, String... expected)
throws Exception {
verify(createChecker(aConfig), fileName, fileName, expected);
}
/**
* Performs verification of the file with the given file name.
* Uses provided {@link Checker} instance.
* Expected messages are represented by the array of strings.
* This implementation uses overloaded
* {@link AbstractModuleTestSupport#verify(Checker, String, String, String...)} method inside.
*
* @param checker {@link Checker} instance.
* @param fileName file name to verify.
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
protected void verify(Checker checker, String fileName, String... expected)
throws Exception {
verify(checker, fileName, fileName, expected);
}
/**
* Performs verification of the file with the given file name.
* Uses provided {@link Checker} instance.
* Expected messages are represented by the array of strings.
* This implementation uses overloaded
* {@link AbstractModuleTestSupport#verify(Checker, File[], String, String...)} method inside.
*
* @param checker {@link Checker} instance.
* @param processedFilename file name to verify.
* @param messageFileName message file name.
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
protected final void verify(Checker checker,
String processedFilename,
String messageFileName,
String... expected)
throws Exception {
verify(checker,
new File[] {new File(processedFilename)},
messageFileName, expected);
}
/**
* Performs verification of the given files against the array of
* expected messages using the provided {@link Checker} instance.
*
* @param checker {@link Checker} instance.
* @param processedFiles list of files to verify.
* @param messageFileName message file name.
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
protected void verify(Checker checker,
File[] processedFiles,
String messageFileName,
String... expected)
throws Exception {
final Map<String, List<String>> expectedViolations = new HashMap<>();
expectedViolations.put(messageFileName, Arrays.asList(expected));
verify(checker, processedFiles, expectedViolations);
}
/**
* Performs verification of the given files.
*
* @param checker {@link Checker} instance
* @param processedFiles files to process.
* @param expectedViolations a map of expected violations per files.
* @throws Exception if exception occurs during verification process.
*/
protected final void verify(Checker checker,
File[] processedFiles,
Map<String, List<String>> expectedViolations)
throws Exception {
stream.flush();
stream.reset();
final List<File> theFiles = new ArrayList<>();
Collections.addAll(theFiles, processedFiles);
final int errs = checker.process(theFiles);
// process each of the lines
final Map<String, List<String>> actualViolations = getActualViolations(errs);
final Map<String, List<String>> realExpectedViolations =
Maps.filterValues(expectedViolations, input -> !input.isEmpty());
assertWithMessage("Files with expected violations and actual violations differ.")
.that(actualViolations.keySet())
.isEqualTo(realExpectedViolations.keySet());
realExpectedViolations.forEach((fileName, violationList) -> {
assertWithMessage("Violations for %s differ.", fileName)
.that(actualViolations.get(fileName))
.containsExactlyElementsIn(violationList);
});
checker.destroy();
}
/**
* Runs 'verifyWithInlineConfigParser' with limited stack size and time duration.
*
* @param aConfig configuration.
* @param fileName file name to verify.
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
protected final void verifyWithLimitedResources(Configuration aConfig,
String fileName, String... expected)
throws Exception {
// We return null here, which gives us a result to make an assertion about
final Void result = TestUtil.getResultWithLimitedResources(() -> {
verifyWithInlineConfigParser(aConfig, fileName, expected);
return null;
});
assertWithMessage("Verify should complete successfully.")
.that(result)
.isNull();
}
/**
* Performs verification of the config read from input file.
*
* @param testConfig hardcoded test config.
* @param parsedConfig parsed config from input file.
* @param moduleInputConfiguration ModuleInputConfiguration object.
* @throws CheckstyleException if property keys not found.
*/
private static void verifyConfig(Configuration testConfig,
Configuration parsedConfig,
ModuleInputConfiguration moduleInputConfiguration)
throws CheckstyleException {
assertWithMessage("Check name differs from expected.")
.that(testConfig.getName())
.isEqualTo(parsedConfig.getName());
for (String property : parsedConfig.getPropertyNames()) {
assertWithMessage("Property value for key %s differs from expected.", property)
.that(testConfig.getProperty(property))
.isEqualTo(parsedConfig.getProperty(property));
}
final List<String> testProperties =
new LinkedList<>(Arrays.asList(testConfig.getPropertyNames()));
testProperties.removeAll(Arrays.asList(parsedConfig.getPropertyNames()));
for (String property : testProperties) {
assertWithMessage("Property value for key %s differs from expected.", property)
.that(moduleInputConfiguration.getDefaultPropertyValue(property))
.isEqualTo(testConfig.getProperty(property));
}
}
/**
* Performs verification of violation lines.
*
* @param config parsed config.
* @param file file path.
* @param moduleInputConfiguration ModuleInputConfiguration object.
* @throws Exception if exception occurs during verification process.
*/
private void verifyViolations(Configuration config,
String file,
ModuleInputConfiguration moduleInputConfiguration) throws Exception {
final List<String> actualViolations = getActualViolationsForFile(config, file);
final List<TestInputViolation> testInputViolations = moduleInputConfiguration.getViolations();
assertWithMessage("Number of actual and expected violations differ.")
.that(actualViolations)
.hasSize(testInputViolations.size());
for (int index = 0; index < actualViolations.size(); index++) {
assertWithMessage("Actual and expected violations differ.")
.that(actualViolations.get(index))
.matches(testInputViolations.get(index).toRegex());
}
}
/**
* Tests the file with the check config.
*
* @param config check configuration.
* @param file input file path.
* @return list of actual violations.
* @throws Exception if exception occurs during verification process.
*/
private List<String> getActualViolationsForFile(Configuration config,
String file) throws Exception {
stream.flush();
stream.reset();
final List<File> files = Collections.singletonList(new File(file));
final Checker checker = createChecker(config);
final Map<String, List<String>> actualViolations =
getActualViolations(checker.process(files));
checker.destroy();
return actualViolations.getOrDefault(file, new ArrayList<>());
}
private Map<String, List<String>> getActualViolations(int errorCount) throws IOException {
// process each of the lines
try (ByteArrayInputStream inputStream =
new ByteArrayInputStream(stream.toByteArray());
LineNumberReader lnr = new LineNumberReader(
new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
final Map<String, List<String>> actualViolations = new HashMap<>();
for (String line = lnr.readLine(); line != null && lnr.getLineNumber() <= errorCount;
line = lnr.readLine()) {
// have at least 2 characters before the splitting colon,
// to not split after the drive letter on windows
final String[] actualViolation = line.split("(?<=.{2}):", 2);
final String actualViolationFileName = actualViolation[0];
final String actualViolationMessage = actualViolation[1];
List<String> actualViolationsPerFile =
actualViolations.get(actualViolationFileName);
if (actualViolationsPerFile == null) {
actualViolationsPerFile = new ArrayList<>();
actualViolations.put(actualViolationFileName, actualViolationsPerFile);
}
actualViolationsPerFile.add(actualViolationMessage);
}
return actualViolations;
}
}
/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
* @return The message of the check with the arguments applied.
*/
protected final String getCheckMessage(String messageKey, Object... arguments) {
return internalGetCheckMessage(getMessageBundle(), messageKey, arguments);
}
/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param clazz the related check class.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
* @return The message of the check with the arguments applied.
*/
protected static String getCheckMessage(
Class<?> clazz, String messageKey, Object... arguments) {
return internalGetCheckMessage(getMessageBundle(clazz.getName()), messageKey, arguments);
}
/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param messageBundle the bundle name.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
* @return The message of the check with the arguments applied.
*/
private static String internalGetCheckMessage(
String messageBundle, String messageKey, Object... arguments) {
final ResourceBundle resourceBundle = ResourceBundle.getBundle(
messageBundle,
Locale.getDefault(),
Thread.currentThread().getContextClassLoader(),
new Violation.Utf8Control());
final String pattern = resourceBundle.getString(messageKey);
final MessageFormat formatter = new MessageFormat(pattern, Locale.ROOT);
return formatter.format(arguments);
}
private String getMessageBundle() {
final String className = getClass().getName();
return getMessageBundle(className);
}
private static String getMessageBundle(String className) {
final String messageBundle;
final String messages = "messages";
final int endIndex = className.lastIndexOf('.');
if (endIndex < 0) {
messageBundle = messages;
}
else {
final String packageName = className.substring(0, endIndex);
messageBundle = packageName + "." + messages;
}
return messageBundle;
}
}