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;
21  
22  import static com.google.common.truth.Truth.assertWithMessage;
23  import static com.puppycrawl.tools.checkstyle.AbstractPathTestSupport.addEndOfLine;
24  import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.getExpectedThrowable;
25  import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.isUtilsClassHasPrivateConstructor;
26  import static org.junit.jupiter.api.Assumptions.assumeTrue;
27  import static org.mockito.Mockito.mock;
28  import static org.mockito.Mockito.mockStatic;
29  import static org.mockito.Mockito.verify;
30  
31  import java.io.BufferedReader;
32  import java.io.ByteArrayOutputStream;
33  import java.io.File;
34  import java.io.IOException;
35  import java.io.PrintStream;
36  import java.io.Serial;
37  import java.nio.charset.StandardCharsets;
38  import java.nio.file.Files;
39  import java.nio.file.Path;
40  import java.util.ArrayList;
41  import java.util.Arrays;
42  import java.util.List;
43  import java.util.Objects;
44  import java.util.logging.Handler;
45  import java.util.logging.Level;
46  import java.util.logging.Logger;
47  import java.util.regex.Matcher;
48  import java.util.regex.Pattern;
49  import java.util.stream.Collectors;
50  
51  import org.itsallcode.io.Capturable;
52  import org.itsallcode.junit.sysextensions.SystemErrGuard;
53  import org.itsallcode.junit.sysextensions.SystemErrGuard.SysErr;
54  import org.itsallcode.junit.sysextensions.SystemOutGuard;
55  import org.itsallcode.junit.sysextensions.SystemOutGuard.SysOut;
56  import org.junit.jupiter.api.BeforeEach;
57  import org.junit.jupiter.api.Test;
58  import org.junit.jupiter.api.extension.ExtendWith;
59  import org.junit.jupiter.api.io.TempDir;
60  import org.junitpioneer.jupiter.DefaultLocale;
61  import org.junitpioneer.jupiter.SetSystemProperty;
62  import org.mockito.MockedStatic;
63  import org.mockito.Mockito;
64  
65  import com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions;
66  import com.puppycrawl.tools.checkstyle.api.AuditListener;
67  import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
68  import com.puppycrawl.tools.checkstyle.api.Violation;
69  import com.puppycrawl.tools.checkstyle.internal.testmodules.TestRootModuleChecker;
70  import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
71  import com.puppycrawl.tools.checkstyle.utils.ChainedPropertyUtil;
72  
73  @DefaultLocale("en")
74  @ExtendWith({SystemErrGuard.class, SystemOutGuard.class})
75  @SetSystemProperty(key = "picocli.ansi", value = "false")
76  public class MainTest {
77  
78      private static final String EOL = System.lineSeparator();
79  
80      private static final String SHORT_USAGE = denormalizeLineEnding(
81              """
82              Usage: checkstyle [OPTIONS]... file(s) or folder(s) ...
83              Try 'checkstyle --help' for more information.
84              """);
85  
86      private static final String USAGE = denormalizeLineEnding(
87              """
88              Usage: checkstyle [-dEgGhjJtTV] [-b=<xpath>] [-c=<configurationFile>] \
89              [-f=<format>]
90                                [-o=<outputPath>] [-p=<propertiesFile>] \
91              [-s=<suppressionLineColumnNumber>]
92                                [-w=<tabWidth>] [-e=<exclude>]... [-x=<excludeRegex>]... \
93              <files or folders>...
94              Checkstyle verifies that the specified source code files adhere to the\
95               specified rules. By default,
96              violations are reported to standard out in plain format. Checkstyle requires\
97               a configuration XML
98              file that configures the checks to apply.
99                    <files or folders>... One or more source files to verify
100               -b, --branch-matching-xpath=<xpath>
101                                         Shows Abstract Syntax Tree(AST) branches that\
102              match given XPath query.
103               -c=<configurationFile>    Specifies the location of the file that defines\
104              the configuration
105                                           modules. The location can either be a\
106              filesystem location, or a name
107                                           passed to the ClassLoader.getResource()\
108              method.
109               -d, --debug               Prints all debug logging of CheckStyle utility.
110               -e, --exclude=<exclude>   Directory/file to exclude from CheckStyle. The\
111              path can be the full,
112                                           absolute path, or relative to the current\
113              path. Multiple excludes are
114                                           allowed.
115               -E, --executeIgnoredModules
116                                         Allows ignored modules to be run.
117               -f=<format>               Specifies the output format. Valid values: \
118             xml, sarif, plain for
119                                           XMLLogger, SarifLogger, and \
120             DefaultLogger respectively. Defaults to
121                                           plain.
122               -g, --generate-xpath-suppression
123                                         Generates an output xpath suppression XML to use\
124              to suppress all
125                                           violations from user's config. Instead of\
126              printing every violation,
127                                           all violations will be caught and single\
128              suppressions xml file will
129                                           be printed out. Used only with -c option. Output\
130              location can be
131                                           specified with -o option.
132               -G, --generate-checks-and-files-suppression
133                                         Generates an output suppression XML that will\
134              have suppress elements
135                                           with "checks" and "files" attributes only to\
136              use to suppress all
137                                           violations from user's config. Instead of\
138              printing every violation,
139                                           all violations will be caught and single\
140              suppressions xml file will
141                                           be printed out. Used only with -c option. Output\
142              location can be
143                                           specified with -o option.
144               -h, --help                Show this help message and exit.
145               -j, --javadocTree         This option is used to print the Parse Tree of\
146              the Javadoc comment. The
147                                           file has to contain only Javadoc comment\
148              content excluding '/**' and
149                                           '*/' at the beginning and at the end\
150              respectively. It can only be
151                                           used on a single file and cannot be\
152              combined with other options.
153               -J, --treeWithJavadoc     This option is used to display the Abstract\
154              Syntax Tree (AST) with
155                                           Javadoc nodes of the specified file. It can\
156              only be used on a single
157                                           file and cannot be combined\
158              with other options.
159               -o=<outputPath>           Sets the output file. Defaults to stdout.
160               -p=<propertiesFile>       Sets the property files to load.
161               -s=<suppressionLineColumnNumber>
162                                         Prints xpath suppressions at the file's line and\
163              column position.
164                                           Argument is the line and column number\
165              (separated by a : ) in the
166                                           file that the suppression should be generated\
167              for. The option cannot
168                                           be used with other options and requires exactly\
169              one file to run on to
170                                           be specified. Note that the generated result\
171              will have few queries,
172                                           joined by pipe(|). Together they will match all\
173              AST nodes on
174                                           specified line and column. You need to choose\
175              only one and recheck
176                                           that it works. Usage of all of them is also ok,\
177              but might result in
178                                           undesirable matching and suppress other\
179              issues.
180               -t, --tree                This option is used to display the Abstract\
181              Syntax Tree (AST) without
182                                           any comments of the specified file. It can\
183              only be used on a single
184                                           file and cannot be combined with\
185              other options.
186               -T, --treeWithComments    This option is used to display the Abstract\
187              Syntax Tree (AST) with
188                                           comment nodes excluding Javadoc of the\
189              specified file. It can only be
190                                           used on a single file and cannot be combined\
191              with other options.
192               -V, --version             Print version information and exit.
193               -w, --tabWidth=<tabWidth> Sets the length of the tab character. Used only\
194              with -s option. Default
195                                           value is 8.
196               -x, --exclude-regexp=<excludeRegex>
197                                         Directory/file pattern to exclude from CheckStyle.\
198              Multiple excludes
199                                           are allowed.
200             """);
201 
202     private static final Logger LOG = Logger.getLogger(MainTest.class.getName()).getParent();
203     private static final Handler[] HANDLERS = LOG.getHandlers();
204     private static final Level ORIGINAL_LOG_LEVEL = LOG.getLevel();
205 
206     @TempDir
207     public File temporaryFolder;
208 
209     private final LocalizedMessage auditStartMessage = new LocalizedMessage(
210             Definitions.CHECKSTYLE_BUNDLE, getClass(),
211             "DefaultLogger.auditStarted");
212 
213     private final LocalizedMessage auditFinishMessage = new LocalizedMessage(
214             Definitions.CHECKSTYLE_BUNDLE, getClass(),
215             "DefaultLogger.auditFinished");
216 
217     private final String noViolationsOutput = auditStartMessage.getMessage() + EOL
218                     + auditFinishMessage.getMessage() + EOL;
219 
220     private static String getPath(String filename) {
221         return "src/test/resources/com/puppycrawl/tools/checkstyle/main/" + filename;
222     }
223 
224     private static String getNonCompilablePath(String filename) {
225         return "src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/main/" + filename;
226     }
227 
228     private static String getFilePath(String filename) throws IOException {
229         return new File(getPath(filename)).getCanonicalPath();
230     }
231 
232     /**
233      * Configures the environment for each test.
234      * <ul>
235      * <li>Restore original logging level and HANDLERS to prevent bleeding into other tests;</li>
236      * <li>Turn off colors for picocli to not conflict with tests if they are auto turned on.</li>
237      * <li>Start output capture for {@link System#err} and {@link System#out}</li>
238      * </ul>
239      *
240      * @param systemErr wrapper for {@code System.err}
241      * @param systemOut wrapper for {@code System.out}
242      */
243     @BeforeEach
244     public void setUp(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
245         systemErr.captureMuted();
246         systemOut.captureMuted();
247 
248         LOG.setLevel(ORIGINAL_LOG_LEVEL);
249 
250         for (Handler handler : LOG.getHandlers()) {
251             boolean found = false;
252 
253             for (Handler savedHandler : HANDLERS) {
254                 if (Objects.equals(handler, savedHandler)) {
255                     found = true;
256                     break;
257                 }
258             }
259 
260             if (!found) {
261                 LOG.removeHandler(handler);
262             }
263         }
264     }
265 
266     @Test
267     public void testIsProperUtilsClass() throws ReflectiveOperationException {
268         assertWithMessage("Constructor is not private")
269                 .that(isUtilsClassHasPrivateConstructor(Main.class))
270                 .isTrue();
271     }
272 
273     @Test
274     public void testVersionPrint(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
275         assertMainReturnCode(0, "-V");
276         assertWithMessage("Unexpected output log")
277             .that(systemOut.getCapturedData())
278             .isEqualTo("Checkstyle version: null" + System.lineSeparator());
279         assertWithMessage("Unexpected system error log")
280             .that(systemErr.getCapturedData())
281             .isEqualTo("");
282     }
283 
284     @Test
285     public void testUsageHelpPrint(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
286         assertMainReturnCode(0, "-h");
287         assertWithMessage("Unexpected output log")
288             .that(systemOut.getCapturedData())
289             .isEqualTo(USAGE);
290         assertWithMessage("Unexpected system error log")
291             .that(systemErr.getCapturedData())
292             .isEqualTo("");
293     }
294 
295     @Test
296     public void testWrongArgument(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
297         // need to specify a file:
298         // <files> is defined as a required positional param;
299         // picocli verifies required parameters before checking unknown options
300         assertMainReturnCode(-1, "-q", "file");
301         final String usage = "Unknown option: '-q'" + EOL + SHORT_USAGE;
302         assertWithMessage("Unexpected output log")
303             .that(systemOut.getCapturedData())
304             .isEqualTo("");
305         assertWithMessage("Unexpected system error log")
306             .that(systemErr.getCapturedData())
307             .isEqualTo(usage);
308     }
309 
310     @Test
311     public void testWrongArgumentMissingFiles(@SysErr Capturable systemErr,
312             @SysOut Capturable systemOut) {
313         assertMainReturnCode(-1, "-q");
314         // files is defined as a required positional param;
315         // picocli verifies required parameters before checking unknown options
316         final String usage = "Missing required parameter: '<files or folders>'" + EOL + SHORT_USAGE;
317         assertWithMessage("Unexpected output log")
318             .that(systemOut.getCapturedData())
319             .isEqualTo("");
320         assertWithMessage("Unexpected system error log")
321             .that(systemErr.getCapturedData())
322             .isEqualTo(usage);
323     }
324 
325     @Test
326     public void testNoConfigSpecified(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
327         assertMainReturnCode(-1, getPath("InputMain.java"));
328         assertWithMessage("Unexpected output log")
329             .that(systemOut.getCapturedData())
330             .isEqualTo("Must specify a config XML file." + System.lineSeparator());
331         assertWithMessage("Unexpected system error log")
332             .that(systemErr.getCapturedData())
333             .isEqualTo("");
334     }
335 
336     @Test
337     public void testNonExistentTargetFile(@SysErr Capturable systemErr,
338             @SysOut Capturable systemOut) {
339         assertMainReturnCode(-1, "-c", "/google_checks.xml", "NonExistentFile.java");
340         assertWithMessage("Unexpected output log")
341             .that(systemOut.getCapturedData())
342             .isEqualTo("Files to process must be specified, found 0." + System.lineSeparator());
343         assertWithMessage("Unexpected system error log")
344             .that(systemErr.getCapturedData())
345             .isEqualTo("");
346     }
347 
348     @Test
349     public void testExistingTargetFileButWithoutReadAccess(
350             @SysErr Capturable systemErr, @SysOut Capturable systemOut)
351                     throws IOException {
352         final File file = Files.createTempFile(temporaryFolder.toPath(),
353                 "testExistingTargetFileButWithoutReadAccess", null).toFile();
354         // skip execution if file is still readable, it is possible on some Windows machines
355         // see https://github.com/checkstyle/checkstyle/issues/7032 for details
356         assumeTrue(file.setReadable(false), "file is still readable");
357 
358         final String canonicalPath = file.getCanonicalPath();
359         assertMainReturnCode(-1, "-c", "/google_checks.xml", canonicalPath);
360         assertWithMessage("Unexpected output log")
361             .that(systemOut.getCapturedData())
362             .isEqualTo("Files to process must be specified, found 0." + System.lineSeparator());
363         assertWithMessage("Unexpected system error log")
364             .that(systemErr.getCapturedData())
365             .isEqualTo("");
366     }
367 
368     @Test
369     public void testCustomSeverityVariableForGoogleConfig(@SysOut Capturable systemOut) {
370         assertMainReturnCode(1, "-c", "/google_checks.xml",
371                 "-p", getPath("InputMainCustomSeverityForGoogleConfig.properties"),
372                 getPath("InputMainCustomSeverityForGoogleConfig.java"));
373 
374         final String expectedOutputStart = addEndOfLine(auditStartMessage.getMessage())
375             + "[ERROR] ";
376         final String expectedOutputEnd = addEndOfLine(
377                 "InputMainCustomSeverityForGoogleConfig.java:3:1:"
378                     + " Missing a Javadoc comment for 'InputMainCustomSeverityForGoogleConfig'."
379                     + " [MissingJavadocType]",
380                 auditFinishMessage.getMessage());
381         assertWithMessage("Unexpected output log")
382             .that(systemOut.getCapturedData())
383             .startsWith(expectedOutputStart);
384         assertWithMessage("Unexpected output log")
385             .that(systemOut.getCapturedData())
386             .endsWith(expectedOutputEnd);
387     }
388 
389     @Test
390     public void testDefaultSeverityVariableForGoogleConfig(@SysOut Capturable systemOut) {
391         assertMainReturnCode(0, "-c", "/google_checks.xml",
392                 getPath("InputMainCustomSeverityForGoogleConfig.java"));
393 
394         final String expectedOutputStart = addEndOfLine(auditStartMessage.getMessage())
395                 + "[WARN] ";
396         final String expectedOutputEnd = addEndOfLine(
397                 "InputMainCustomSeverityForGoogleConfig.java:3:1:"
398                         + " Missing a Javadoc comment for"
399                         + " 'InputMainCustomSeverityForGoogleConfig'. [MissingJavadocType]",
400                 auditFinishMessage.getMessage());
401         assertWithMessage("Unexpected output log")
402                 .that(systemOut.getCapturedData())
403                 .startsWith(expectedOutputStart);
404         assertWithMessage("Unexpected output log")
405                 .that(systemOut.getCapturedData())
406                 .endsWith(expectedOutputEnd);
407     }
408 
409     @Test
410     public void testNonExistentConfigFile(@SysErr Capturable systemErr,
411             @SysOut Capturable systemOut) {
412         assertMainReturnCode(-1, "-c", "src/main/resources/non_existent_config.xml",
413                     getPath("InputMain.java"));
414         assertWithMessage("Unexpected output log")
415             .that(systemOut.getCapturedData())
416             .isEqualTo(addEndOfLine("Could not find config XML file "
417                     + "'src/main/resources/non_existent_config.xml'."));
418         assertWithMessage("Unexpected system error log")
419             .that(systemErr.getCapturedData())
420             .isEqualTo("");
421     }
422 
423     @Test
424     public void testNonExistentOutputFormat(@SysErr Capturable systemErr,
425             @SysOut Capturable systemOut) {
426         assertMainReturnCode(-1, "-c", "/google_checks.xml", "-f", "xmlp",
427                 getPath("InputMain.java"));
428         assertWithMessage("Unexpected output log")
429             .that(systemOut.getCapturedData())
430             .isEqualTo("");
431         assertWithMessage("Unexpected system error log")
432             .that(systemErr.getCapturedData())
433             .isEqualTo("Invalid value for option '-f': expected one of [XML, SARIF, PLAIN]"
434                     + " (case-insensitive) but was 'xmlp'" + EOL + SHORT_USAGE);
435     }
436 
437     @Test
438     public void testNonExistentClass(@SysErr Capturable systemErr) {
439         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-non-existent-classname.xml"),
440                     getPath("InputMain.java"));
441         final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:"
442                 + " cannot initialize module TreeWalker" + EOL;
443         final String nestedCause = "Caused by: com.puppycrawl.tools.checkstyle.api."
444                 + "CheckstyleException: cannot initialize module NonExistentClass" + EOL;
445         assertWithMessage("Unexpected system error log")
446                 .that(systemErr.getCapturedData())
447                 .startsWith(cause);
448         assertWithMessage("Unexpected system error log")
449                 .that(systemErr.getCapturedData())
450                 .contains(nestedCause);
451     }
452 
453     @Test
454     public void testExistingTargetFile(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
455         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname.xml"),
456                 getPath("InputMain.java"));
457         assertWithMessage("Unexpected output log")
458             .that(systemOut.getCapturedData())
459             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
460                 auditFinishMessage.getMessage()));
461         assertWithMessage("Unexpected system error log")
462             .that(systemErr.getCapturedData())
463             .isEqualTo("");
464     }
465 
466     @Test
467     public void testExistingTargetFileXmlOutput(@SysErr Capturable systemErr,
468             @SysOut Capturable systemOut)
469                     throws IOException {
470         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname.xml"), "-f", "xml",
471                 getPath("InputMain.java"));
472         final String expectedPath = getFilePath("InputMain.java");
473         final String version = Main.class.getPackage().getImplementationVersion();
474         assertWithMessage("Unexpected output log")
475             .that(systemOut.getCapturedData())
476             .isEqualTo(addEndOfLine(
477             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
478                 "<checkstyle version=\"" + version + "\">",
479                 "<file name=\"" + expectedPath + "\">",
480                 "</file>",
481                 "</checkstyle>"));
482         assertWithMessage("Unexpected system error log")
483             .that(systemErr.getCapturedData())
484             .isEqualTo("");
485     }
486 
487     /**
488      * This test method is created only to cover
489      * pitest mutation survival at {@code Main#getOutputStreamOptions}.
490      * Parameters {@code systemErr} and {@code systemOut} are used to restore
491      * the original system streams.
492      *
493      * @param systemErr the system error stream
494      * @param systemOut the system output stream
495      */
496     @Test
497     public void testNonClosedSystemStreams(@SysErr Capturable systemErr,
498            @SysOut Capturable systemOut) {
499         try (ShouldNotBeClosedStream stream = new ShouldNotBeClosedStream()) {
500             System.setOut(stream);
501             System.setErr(stream);
502             assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname.xml"), "-f", "xml",
503                     getPath("InputMain.java"));
504             assertWithMessage("stream should not be closed")
505                 .that(stream.isClosed)
506                 .isFalse();
507             assertWithMessage("System.err should be not used")
508                 .that(systemErr.getCapturedData())
509                 .isEmpty();
510             assertWithMessage("System.out should be not used")
511                 .that(systemOut.getCapturedData())
512                 .isEmpty();
513         }
514     }
515 
516     /**
517      * This test method is created only to cover
518      * pitest mutation survival at Main#getOutputStreamOptions.
519      * No ability to test it by out general tests.
520      * It is hard test that inner stream is closed, so pure UT is created to validate result
521      * of private method Main.getOutputStreamOptions
522      *
523      * @throws Exception if there is an error.
524      */
525     @Test
526     public void testGetOutputStreamOptionsMethod() throws Exception {
527         final Path path = new File(getPath("InputMain.java")).toPath();
528         final OutputStreamOptions option =
529                 TestUtil.invokeStaticMethod(Main.class, "getOutputStreamOptions",
530                         OutputStreamOptions.class, path);
531         assertWithMessage("Main.getOutputStreamOptions return CLOSE on not null Path")
532                 .that(option)
533                 .isEqualTo(OutputStreamOptions.CLOSE);
534     }
535 
536     @Test
537     public void testExistingTargetFilePlainOutput(@SysErr Capturable systemErr,
538             @SysOut Capturable systemOut) {
539         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname.xml"), "-f", "plain",
540                 getPath("InputMain.java"));
541         assertWithMessage("Unexpected output log")
542             .that(systemOut.getCapturedData())
543             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
544                 auditFinishMessage.getMessage()));
545         assertWithMessage("Unexpected system error log")
546             .that(systemErr.getCapturedData())
547             .isEqualTo("");
548     }
549 
550     @Test
551     public void testExistingTargetFileWithViolations(@SysErr Capturable systemErr,
552             @SysOut Capturable systemOut)
553                     throws IOException {
554         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname2.xml"),
555                 getPath("InputMain.java"));
556         final Violation invalidPatternMessageMain = new Violation(1,
557                 "com.puppycrawl.tools.checkstyle.checks.naming.messages",
558                 "name.invalidPattern", new String[] {"InputMain", "^[a-z0-9]*$"},
559                 null, getClass(), null);
560         final Violation invalidPatternMessageMainInner = new Violation(1,
561                 "com.puppycrawl.tools.checkstyle.checks.naming.messages",
562                 "name.invalidPattern", new String[] {"InputMainInner", "^[a-z0-9]*$"},
563                 null, getClass(), null);
564         final String expectedPath = getFilePath("InputMain.java");
565         assertWithMessage("Unexpected output log")
566             .that(systemOut.getCapturedData())
567             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
568                     "[WARN] " + expectedPath + ":3:14: "
569                         + invalidPatternMessageMain.getViolation()
570                         + " [TypeName]",
571                     "[WARN] " + expectedPath + ":5:7: "
572                         + invalidPatternMessageMainInner.getViolation()
573                         + " [TypeName]",
574                     auditFinishMessage.getMessage()));
575         assertWithMessage("Unexpected system error log")
576             .that(systemErr.getCapturedData())
577             .isEqualTo("");
578     }
579 
580     @Test
581     public void testViolationsByGoogleAndXpathSuppressions(@SysErr Capturable systemErr,
582             @SysOut Capturable systemOut) {
583         assertMainReturnCode(0, "-c", "/google_checks.xml",
584                 "-p", getPath("InputMainViolationsForGoogleXpathSuppressions.properties"),
585                 getPath("InputMainViolationsForGoogle.java"));
586         assertWithMessage("Unexpected output log")
587             .that(systemOut.getCapturedData())
588             .isEqualTo(noViolationsOutput);
589         assertWithMessage("Unexpected system error log")
590             .that(systemErr.getCapturedData())
591             .isEqualTo("");
592     }
593 
594     @Test
595     public void testViolationsByGoogleAndSuppressions(@SysErr Capturable systemErr,
596             @SysOut Capturable systemOut) {
597         assertMainReturnCode(0, "-c", "/google_checks.xml",
598                 "-p", getPath("InputMainViolationsForGoogleSuppressions.properties"),
599                 getPath("InputMainViolationsForGoogle.java"));
600         assertWithMessage("Unexpected output log")
601             .that(systemOut.getCapturedData())
602             .isEqualTo(noViolationsOutput);
603         assertWithMessage("Unexpected system error log")
604             .that(systemErr.getCapturedData())
605             .isEqualTo("");
606     }
607 
608     @Test
609     public void testExistingTargetFileWithError(@SysErr Capturable systemErr,
610             @SysOut Capturable systemOut)
611                     throws Exception {
612         assertMainReturnCode(2, "-c", getPath("InputMainConfig-classname2-error.xml"),
613                     getPath("InputMain.java"));
614         final Violation errorCounterTwoMessage = new Violation(1,
615                 Definitions.CHECKSTYLE_BUNDLE, Main.ERROR_COUNTER,
616                 new String[] {String.valueOf(2)}, null, getClass(), null);
617         final Violation invalidPatternMessageMain = new Violation(1,
618                 "com.puppycrawl.tools.checkstyle.checks.naming.messages",
619                 "name.invalidPattern", new String[] {"InputMain", "^[a-z0-9]*$"},
620                 null, getClass(), null);
621         final Violation invalidPatternMessageMainInner = new Violation(1,
622                 "com.puppycrawl.tools.checkstyle.checks.naming.messages",
623                 "name.invalidPattern", new String[] {"InputMainInner", "^[a-z0-9]*$"},
624                 null, getClass(), null);
625         final String expectedPath = getFilePath("InputMain.java");
626         assertWithMessage("Unexpected output log")
627             .that(systemOut.getCapturedData())
628             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
629                     "[ERROR] " + expectedPath + ":3:14: "
630                         + invalidPatternMessageMain.getViolation() + " [TypeName]",
631                     "[ERROR] " + expectedPath + ":5:7: "
632                         + invalidPatternMessageMainInner.getViolation() + " [TypeName]",
633                     auditFinishMessage.getMessage()));
634         assertWithMessage("Unexpected system error log")
635             .that(systemErr.getCapturedData())
636             .isEqualTo(addEndOfLine(errorCounterTwoMessage.getViolation()));
637     }
638 
639     /**
640      * Similar test to {@link #testExistingTargetFileWithError}, but for PIT mutation tests:
641      * this test fails if the boundary condition is changed from {@code if (exitStatus > 0)}
642      * to {@code if (exitStatus > 1)}.
643      *
644      * @throws Exception should not throw anything
645      */
646     @Test
647     public void testExistingTargetFileWithOneError(@SysErr Capturable systemErr,
648             @SysOut Capturable systemOut)
649                     throws Exception {
650         assertMainReturnCode(1, "-c", getPath("InputMainConfig-classname2-error.xml"),
651                     getPath("InputMain1.java"));
652         final Violation errorCounterTwoMessage = new Violation(1,
653                 Definitions.CHECKSTYLE_BUNDLE, Main.ERROR_COUNTER,
654                 new String[] {String.valueOf(1)}, null, getClass(), null);
655         final Violation invalidPatternMessageMain = new Violation(1,
656                 "com.puppycrawl.tools.checkstyle.checks.naming.messages",
657                 "name.invalidPattern", new String[] {"InputMain1", "^[a-z0-9]*$"},
658                 null, getClass(), null);
659         final String expectedPath = getFilePath("InputMain1.java");
660         assertWithMessage("Unexpected output log")
661             .that(systemOut.getCapturedData())
662             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
663                     "[ERROR] " + expectedPath + ":3:14: "
664                         + invalidPatternMessageMain.getViolation() + " [TypeName]",
665                     auditFinishMessage.getMessage()));
666         assertWithMessage("Unexpected system error log")
667             .that(systemErr.getCapturedData())
668             .isEqualTo(addEndOfLine(errorCounterTwoMessage.getViolation()));
669     }
670 
671     @Test
672     public void testMainExitCodeOn256Errors(@SysErr Capturable systemErr) {
673         assertMainReturnCode(255, "-c", getPath("InputMainConfig-magicnumber.xml"),
674                 getPath("InputMainMagicNumber256Errors.java"));
675         final Violation errorCounterMessage = new Violation(1,
676                 Definitions.CHECKSTYLE_BUNDLE, Main.ERROR_COUNTER,
677                 new String[] {String.valueOf(256)}, null, getClass(), null);
678         assertWithMessage("Unexpected system error log")
679             .that(systemErr.getCapturedData())
680             .isEqualTo(addEndOfLine(errorCounterMessage.getViolation()));
681     }
682 
683     @Test
684     public void testMainExitCodeOn300Errors(@SysErr Capturable systemErr) {
685         assertMainReturnCode(255, "-c", getPath("InputMainConfig-magicnumber.xml"),
686                 getPath("InputMainMagicNumber300Errors.java"));
687         final Violation errorCounterMessage = new Violation(1,
688                 Definitions.CHECKSTYLE_BUNDLE, Main.ERROR_COUNTER,
689                 new String[] {String.valueOf(300)}, null, getClass(), null);
690         assertWithMessage("Unexpected system error log")
691             .that(systemErr.getCapturedData())
692             .isEqualTo(addEndOfLine(errorCounterMessage.getViolation()));
693     }
694 
695     @Test
696     public void testExistingTargetFileWithOneErrorAgainstSunCheck(@SysErr Capturable systemErr,
697             @SysOut Capturable systemOut)
698                     throws Exception {
699         assertMainReturnCode(1, "-c", "/sun_checks.xml", getPath("InputMain1.java"));
700         final Violation errorCounterTwoMessage = new Violation(1,
701                 Definitions.CHECKSTYLE_BUNDLE, Main.ERROR_COUNTER,
702                 new String[] {String.valueOf(1)}, null, getClass(), null);
703         final Violation message = new Violation(1,
704                 "com.puppycrawl.tools.checkstyle.checks.javadoc.messages",
705                 "javadoc.packageInfo", new String[] {},
706                 null, getClass(), null);
707         final String expectedPath = getFilePath("InputMain1.java");
708         assertWithMessage("Unexpected output log")
709             .that(systemOut.getCapturedData())
710             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
711                 "[ERROR] " + expectedPath + ":1: " + message.getViolation() + " [JavadocPackage]",
712                 auditFinishMessage.getMessage()));
713         assertWithMessage("Unexpected system error log")
714             .that(systemErr.getCapturedData())
715             .isEqualTo(addEndOfLine(errorCounterTwoMessage.getViolation()));
716     }
717 
718     @Test
719     public void testExistentTargetFilePlainOutputToNonExistentFile(@SysErr Capturable systemErr,
720             @SysOut Capturable systemOut) {
721         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname.xml"), "-f", "plain",
722                 "-o", temporaryFolder + "/output.txt", getPath("InputMain.java"));
723         assertWithMessage("Unexpected output log")
724             .that(systemOut.getCapturedData())
725             .isEqualTo("");
726         assertWithMessage("Unexpected system error log")
727             .that(systemErr.getCapturedData())
728             .isEqualTo("");
729     }
730 
731     @Test
732     public void testExistingTargetFilePlainOutputToFile(@SysErr Capturable systemErr,
733             @SysOut Capturable systemOut)
734                     throws Exception {
735         final String outputFile =
736                 Files.createTempFile(temporaryFolder.toPath(), "file", ".output").toFile()
737                     .getCanonicalPath();
738         assertWithMessage("File must exist")
739                 .that(new File(outputFile).exists())
740                 .isTrue();
741         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname.xml"), "-f", "plain",
742                 "-o", outputFile, getPath("InputMain.java"));
743         assertWithMessage("Unexpected output log")
744             .that(systemOut.getCapturedData())
745             .isEqualTo("");
746         assertWithMessage("Unexpected system error log")
747             .that(systemErr.getCapturedData())
748             .isEqualTo("");
749     }
750 
751     @Test
752     public void testCreateNonExistentOutputFile() throws IOException {
753         final String outputFile = new File(temporaryFolder, "nonexistent.out").getCanonicalPath();
754         assertWithMessage("File must not exist")
755                 .that(new File(outputFile).exists())
756                 .isFalse();
757         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname.xml"), "-f", "plain",
758                 "-o", outputFile, getPath("InputMain.java"));
759         assertWithMessage("File must exist")
760                 .that(new File(outputFile).exists())
761                 .isTrue();
762     }
763 
764     @Test
765     public void testExistingTargetFilePlainOutputProperties(@SysErr Capturable systemErr,
766             @SysOut Capturable systemOut) {
767         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname-prop.xml"),
768                 "-p", getPath("InputMainMycheckstyle.properties"), getPath("InputMain.java"));
769         assertWithMessage("Unexpected output log")
770             .that(systemOut.getCapturedData())
771             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
772                 auditFinishMessage.getMessage()));
773         assertWithMessage("Unexpected system error log")
774             .that(systemErr.getCapturedData())
775             .isEqualTo("");
776     }
777 
778     @Test
779     public void testPropertyFileWithPropertyChaining(@SysErr Capturable systemErr,
780             @SysOut Capturable systemOut) {
781         assertMainReturnCode(0, "-c", getPath("InputMainConfig-classname-prop.xml"),
782             "-p", getPath("InputMainPropertyChaining.properties"), getPath("InputMain.java"));
783 
784         assertWithMessage("Unexpected output log")
785             .that(systemOut.getCapturedData())
786             .isEqualTo(addEndOfLine(auditStartMessage.getMessage(),
787                 auditFinishMessage.getMessage()));
788         assertWithMessage("Unexpected system error log")
789             .that(systemErr.getCapturedData())
790             .isEqualTo("");
791     }
792 
793     @Test
794     public void testPropertyFileWithPropertyChainingUndefinedProperty(@SysErr Capturable systemErr,
795             @SysOut Capturable systemOut) {
796         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-classname-prop.xml"),
797                 "-p", getPath("InputMainPropertyChainingUndefinedProperty.properties"),
798                 getPath("InputMain.java"));
799 
800         assertWithMessage("Invalid error message")
801             .that(systemErr.getCapturedData())
802             .contains(ChainedPropertyUtil.UNDEFINED_PROPERTY_MESSAGE);
803         assertWithMessage("Unexpected output log")
804             .that(systemOut.getCapturedData())
805             .isEqualTo("");
806     }
807 
808     @Test
809     public void testExistingTargetFilePlainOutputNonexistentProperties(@SysErr Capturable systemErr,
810             @SysOut Capturable systemOut) {
811         assertMainReturnCode(-1, "-c", getPath("InputMainConfig-classname-prop.xml"),
812                     "-p", "nonexistent.properties", getPath("InputMain.java"));
813         assertWithMessage("Unexpected output log")
814             .that(systemOut.getCapturedData())
815             .isEqualTo("Could not find file 'nonexistent.properties'."
816                 + System.lineSeparator());
817         assertWithMessage("Unexpected system error log")
818             .that(systemErr.getCapturedData())
819             .isEqualTo("");
820     }
821 
822     @Test
823     public void testExistingIncorrectConfigFile(@SysErr Capturable systemErr) {
824         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-Incorrect.xml"),
825                 getPath("InputMain.java"));
826         final String errorOutput = "com.puppycrawl.tools.checkstyle.api."
827             + "CheckstyleException: unable to parse configuration stream - ";
828         assertWithMessage("Unexpected system error log")
829                 .that(systemErr.getCapturedData())
830                 .startsWith(errorOutput);
831     }
832 
833     @Test
834     public void testExistingIncorrectChildrenInConfigFile(@SysErr Capturable systemErr) {
835         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-incorrectChildren.xml"),
836                     getPath("InputMain.java"));
837         final String errorOutput = "com.puppycrawl.tools.checkstyle.api."
838                 + "CheckstyleException: cannot initialize module RegexpSingleline" + EOL;
839         final String causeOutput = "Caused by: com.puppycrawl.tools.checkstyle.api."
840                 + "CheckstyleException: RegexpSingleline is not allowed as a child in "
841                 + "RegexpSingleline";
842         assertWithMessage("Unexpected system error log")
843                 .that(systemErr.getCapturedData())
844                 .startsWith(errorOutput);
845         assertWithMessage("Unexpected system error log")
846                 .that(systemErr.getCapturedData())
847                 .contains(causeOutput);
848     }
849 
850     @Test
851     public void testExistingIncorrectChildrenInConfigFile2(@SysErr Capturable systemErr) {
852         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-incorrectChildren2.xml"),
853                     getPath("InputMain.java"));
854         final String errorOutput = "com.puppycrawl.tools.checkstyle.api."
855                 + "CheckstyleException: cannot initialize module TreeWalker" + EOL;
856         final String causeOutput = "Caused by: com.puppycrawl.tools.checkstyle.api."
857                 + "CheckstyleException: cannot initialize module JavadocMethod" + EOL;
858         assertWithMessage("Unexpected system error log")
859                 .that(systemErr.getCapturedData())
860                 .startsWith(errorOutput);
861         assertWithMessage("Unexpected system error log")
862                 .that(systemErr.getCapturedData())
863                 .contains(causeOutput);
864     }
865 
866     @Test
867     public void testLoadPropertiesIoException() throws Exception {
868         final Class<?> cliOptionsClass = Class.forName(Main.class.getName());
869         final ReflectiveOperationException exc =
870                 getExpectedThrowable(ReflectiveOperationException.class, () -> {
871                     TestUtil.invokeVoidStaticMethod(cliOptionsClass,
872                             "loadProperties", new File("."));
873                 }, "Exception was expected");
874         assertWithMessage("Invalid error cause")
875                 .that(exc)
876                 .hasCauseThat()
877                 .isInstanceOf(CheckstyleException.class);
878         // We do separate validation for message as in Windows
879         // disk drive letter appear in message,
880         // so we skip that drive letter for compatibility issues
881         final Violation loadPropertiesMessage = new Violation(1,
882                 Definitions.CHECKSTYLE_BUNDLE, Main.LOAD_PROPERTIES_EXCEPTION,
883                 new String[] {""}, null, getClass(), null);
884         final String causeMessage = exc.getCause().getLocalizedMessage();
885         final String violation = loadPropertiesMessage.getViolation();
886         final boolean samePrefix = causeMessage.substring(0, causeMessage.indexOf(' '))
887                 .equals(violation
888                         .substring(0, violation.indexOf(' ')));
889         final boolean sameSuffix =
890                 causeMessage.substring(causeMessage.lastIndexOf(' '))
891                 .equals(violation
892                         .substring(violation.lastIndexOf(' ')));
893         assertWithMessage("Invalid violation")
894                 .that(samePrefix || sameSuffix)
895                 .isTrue();
896         assertWithMessage("Invalid violation")
897                 .that(causeMessage)
898                 .contains(".'");
899     }
900 
901     @Test
902     public void testExistingDirectoryWithViolations(@SysErr Capturable systemErr,
903             @SysOut Capturable systemOut)
904                     throws IOException {
905         // we just reference there all violations
906         final String[][] outputValues = {
907                 {"InputMainComplexityOverflow", "1", "108"},
908         };
909 
910         final int allowedLength = 106;
911         final String msgKey = "maxLen.file";
912         final String bundle = "com.puppycrawl.tools.checkstyle.checks.sizes.messages";
913 
914         assertMainReturnCode(0, "-c", getPath("InputMainConfig-filelength.xml"),
915                 getPath(""));
916         final String expectedPath = getFilePath("") + File.separator;
917         final StringBuilder sb = new StringBuilder(28);
918         sb.append(auditStartMessage.getMessage())
919                 .append(EOL);
920         final String format = "[WARN] " + expectedPath + outputValues[0][0] + ".java:"
921                 + outputValues[0][1] + ": ";
922         for (String[] outputValue : outputValues) {
923             final String violation = new Violation(1, bundle,
924                     msgKey, new Integer[] {Integer.valueOf(outputValue[2]), allowedLength},
925                     null, getClass(), null).getViolation();
926             final String line = format + violation + " [FileLength]";
927             sb.append(line).append(EOL);
928         }
929         sb.append(auditFinishMessage.getMessage())
930                 .append(EOL);
931         assertWithMessage("Unexpected output log")
932             .that(systemOut.getCapturedData())
933             .isEqualTo(sb.toString());
934         assertWithMessage("Unexpected system error log")
935             .that(systemErr.getCapturedData())
936             .isEqualTo("");
937     }
938 
939     /**
940      * Test doesn't need to be serialized.
941      *
942      * @noinspection SerializableInnerClassWithNonSerializableOuterClass
943      * @noinspectionreason SerializableInnerClassWithNonSerializableOuterClass - mocked file
944      *      for test does not require serialization
945      */
946     @Test
947     public void testListFilesNotFile() throws Exception {
948         final File fileMock = new File("") {
949             @Serial
950             private static final long serialVersionUID = 1L;
951 
952             @Override
953             public boolean canRead() {
954                 return true;
955             }
956 
957             @Override
958             public boolean isDirectory() {
959                 return false;
960             }
961 
962             @Override
963             public boolean isFile() {
964                 return false;
965             }
966         };
967 
968         final List<File> result = TestUtil.invokeStaticMethodList(Main.class, "listFiles",
969                 fileMock, new ArrayList<>());
970         assertWithMessage("Invalid result size")
971             .that(result)
972             .isEmpty();
973     }
974 
975     /**
976      * Test doesn't need to be serialized.
977      *
978      * @noinspection SerializableInnerClassWithNonSerializableOuterClass
979      * @noinspectionreason SerializableInnerClassWithNonSerializableOuterClass - mocked file
980      *      for test does not require serialization
981      */
982     @Test
983     public void testListFilesDirectoryWithNull() throws Exception {
984         final File[] nullResult = null;
985         final File fileMock = new File("") {
986             @Serial
987             private static final long serialVersionUID = 1L;
988 
989             @Override
990             public boolean canRead() {
991                 return true;
992             }
993 
994             @Override
995             public boolean isDirectory() {
996                 return true;
997             }
998 
999             @Override
1000             public File[] listFiles() {
1001                 return nullResult;
1002             }
1003         };
1004 
1005         final List<File> result = TestUtil.invokeStaticMethodList(Main.class, "listFiles",
1006                 fileMock, new ArrayList<>());
1007         assertWithMessage("Invalid result size")
1008             .that(result)
1009             .isEmpty();
1010     }
1011 
1012     @Test
1013     public void testFileReferenceDuringException(@SysErr Capturable systemErr) {
1014         // We put xml as source to cause parse exception
1015         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-classname.xml"),
1016                     getNonCompilablePath("InputMainIncorrectClass.java"));
1017         final String exceptionMessage = addEndOfLine("com.puppycrawl.tools.checkstyle.api."
1018                 + "CheckstyleException: Exception was thrown while processing "
1019                 + new File(getNonCompilablePath("InputMainIncorrectClass.java")).getPath());
1020         assertWithMessage("Unexpected system error log")
1021                 .that(systemErr.getCapturedData())
1022                 .contains(exceptionMessage);
1023     }
1024 
1025     @Test
1026     public void testRemoveLexerDefaultErrorListener(@SysErr Capturable systemErr) {
1027         assertMainReturnCode(-2, "-t", getNonCompilablePath("InputMainIncorrectClass.java"));
1028 
1029         assertWithMessage("First line of exception message should not contain lexer error.")
1030             .that(systemErr.getCapturedData().startsWith("line 2:2 token recognition error"))
1031                 .isFalse();
1032     }
1033 
1034     @Test
1035     public void testRemoveParserDefaultErrorListener(@SysErr Capturable systemErr) {
1036         assertMainReturnCode(-2, "-t", getNonCompilablePath("InputMainIncorrectClass.java"));
1037         final String capturedData = systemErr.getCapturedData();
1038 
1039         assertWithMessage("First line of exception message should not contain parser error.")
1040             .that(capturedData.startsWith("line 2:0 no viable alternative"))
1041                 .isFalse();
1042         assertWithMessage("Second line of exception message should not contain parser error.")
1043             .that(capturedData.startsWith("line 2:0 no viable alternative",
1044                     capturedData.indexOf('\n') + 1))
1045                 .isFalse();
1046     }
1047 
1048     @Test
1049     public void testPrintTreeOnMoreThanOneFile(@SysErr Capturable systemErr,
1050             @SysOut Capturable systemOut) {
1051         assertMainReturnCode(-1, "-t", getPath(""));
1052         assertWithMessage("Unexpected output log")
1053             .that(systemOut.getCapturedData())
1054             .isEqualTo("Printing AST is allowed for only one file." + System.lineSeparator());
1055         assertWithMessage("Unexpected system error log")
1056             .that(systemErr.getCapturedData())
1057             .isEqualTo("");
1058     }
1059 
1060     @Test
1061     public void testPrintTreeOption(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1062         final String expected = addEndOfLine(
1063             "COMPILATION_UNIT -> COMPILATION_UNIT [1:1]",
1064             "|--PACKAGE_DEF -> package [1:1]",
1065             "|   |--ANNOTATIONS -> ANNOTATIONS [1:40]",
1066             "|   |--DOT -> . [1:40]",
1067             "|   |   |--DOT -> . [1:29]",
1068             "|   |   |   |--DOT -> . [1:23]",
1069             "|   |   |   |   |--DOT -> . [1:12]",
1070             "|   |   |   |   |   |--IDENT -> com [1:9]",
1071             "|   |   |   |   |   `--IDENT -> puppycrawl [1:13]",
1072             "|   |   |   |   `--IDENT -> tools [1:24]",
1073             "|   |   |   `--IDENT -> checkstyle [1:30]",
1074             "|   |   `--IDENT -> main [1:41]",
1075             "|   `--SEMI -> ; [1:45]",
1076             "|--CLASS_DEF -> CLASS_DEF [3:1]",
1077             "|   |--MODIFIERS -> MODIFIERS [3:1]",
1078             "|   |   `--LITERAL_PUBLIC -> public [3:1]",
1079             "|   |--LITERAL_CLASS -> class [3:8]",
1080             "|   |--IDENT -> InputMain [3:14]",
1081             "|   `--OBJBLOCK -> OBJBLOCK [3:24]",
1082             "|       |--LCURLY -> { [3:24]",
1083             "|       `--RCURLY -> } [4:1]",
1084             "`--CLASS_DEF -> CLASS_DEF [5:1]",
1085             "    |--MODIFIERS -> MODIFIERS [5:1]",
1086             "    |--LITERAL_CLASS -> class [5:1]",
1087             "    |--IDENT -> InputMainInner [5:7]",
1088             "    `--OBJBLOCK -> OBJBLOCK [5:22]",
1089             "        |--LCURLY -> { [5:22]",
1090             "        `--RCURLY -> } [6:1]");
1091 
1092         assertMainReturnCode(0, "-t", getPath("InputMain.java"));
1093         assertWithMessage("Unexpected output log")
1094             .that(systemOut.getCapturedData())
1095             .isEqualTo(expected);
1096         assertWithMessage("Unexpected system error log")
1097             .that(systemErr.getCapturedData())
1098             .isEqualTo("");
1099     }
1100 
1101     @Test
1102     public void testPrintXpathOption(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1103         final String expected = addEndOfLine(
1104             "COMPILATION_UNIT -> COMPILATION_UNIT [1:1]",
1105             "|--CLASS_DEF -> CLASS_DEF [3:1]",
1106             "|   `--OBJBLOCK -> OBJBLOCK [3:29]",
1107             "|       |--METHOD_DEF -> METHOD_DEF [4:5]",
1108             "|       |   `--SLIST -> { [4:21]",
1109             "|       |       |--VARIABLE_DEF -> VARIABLE_DEF [5:9]",
1110             "|       |       |   |--IDENT -> a [5:13]");
1111         assertMainReturnCode(0, "-b",
1112                 "/COMPILATION_UNIT/CLASS_DEF//METHOD_DEF[./IDENT[@text='methodOne']]"
1113                         + "//VARIABLE_DEF/IDENT",
1114                 getPath("InputMainXPath.java"));
1115         assertWithMessage("Unexpected output log")
1116             .that(systemOut.getCapturedData())
1117             .isEqualTo(expected);
1118         assertWithMessage("Unexpected system error log")
1119             .that(systemErr.getCapturedData())
1120             .isEqualTo("");
1121     }
1122 
1123     @Test
1124     public void testCliTreeAndSuppressionConsistency(@SysOut Capturable systemOut) {
1125         final String filePath = getPath("InputMain.java");
1126 
1127         assertMainReturnCode(0, "-t", filePath);
1128 
1129         final String treeOutput = systemOut.getCapturedData();
1130 
1131         final Pattern pattern = Pattern.compile("(\\w+) -> .*?\\[(\\d+:\\d+)]");
1132         final Matcher matcher = pattern.matcher(treeOutput);
1133 
1134         boolean foundAtLeastOne = false;
1135         while (matcher.find()) {
1136             foundAtLeastOne = true;
1137             final String tokenName = matcher.group(1);
1138 
1139             if (!"COMPILATION_UNIT".equals(tokenName)) {
1140                 final String coordinates = matcher.group(2);
1141 
1142                 final int previousLength = systemOut.getCapturedData().length();
1143 
1144                 assertMainReturnCode(0, "-s", coordinates, filePath);
1145 
1146                 final String allOutput = systemOut.getCapturedData();
1147                 final String newOutput = allOutput.substring(previousLength);
1148 
1149                 assertWithMessage("CLI -s should return XPath ending in /%s for coordinates %s",
1150                         tokenName, coordinates)
1151                         .that(newOutput)
1152                         .contains("/" + tokenName);
1153             }
1154         }
1155 
1156         assertWithMessage("Should have found at least one token in -t output")
1157                 .that(foundAtLeastOne)
1158                 .isTrue();
1159     }
1160 
1161     @Test
1162     public void testPrintXpathCommentNode(@SysErr Capturable systemErr,
1163             @SysOut Capturable systemOut) {
1164         final String expected = addEndOfLine(
1165             "COMPILATION_UNIT -> COMPILATION_UNIT [1:1]",
1166             "`--CLASS_DEF -> CLASS_DEF [17:1]",
1167             "    `--OBJBLOCK -> OBJBLOCK [17:20]",
1168             "        |--CTOR_DEF -> CTOR_DEF [19:5]",
1169             "        |   |--BLOCK_COMMENT_BEGIN -> /* [18:5]");
1170         assertMainReturnCode(0, "-b", "/COMPILATION_UNIT/CLASS_DEF//BLOCK_COMMENT_BEGIN",
1171                 getPath("InputMainXPath.java"));
1172         assertWithMessage("Unexpected output log")
1173             .that(systemOut.getCapturedData())
1174             .isEqualTo(expected);
1175         assertWithMessage("Unexpected system error log")
1176             .that(systemErr.getCapturedData())
1177             .isEqualTo("");
1178     }
1179 
1180     @Test
1181     public void testPrintXpathNodeParentNull(@SysErr Capturable systemErr,
1182             @SysOut Capturable systemOut) {
1183         final String expected = addEndOfLine("COMPILATION_UNIT -> COMPILATION_UNIT [1:1]");
1184         assertMainReturnCode(0, "-b", "/COMPILATION_UNIT", getPath("InputMainXPath.java"));
1185         assertWithMessage("Unexpected output log")
1186             .that(systemOut.getCapturedData())
1187             .isEqualTo(expected);
1188         assertWithMessage("Unexpected system error log")
1189             .that(systemErr.getCapturedData())
1190             .isEqualTo("");
1191     }
1192 
1193     @Test
1194     public void testPrintXpathFullOption(
1195             @SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1196         final String expected = addEndOfLine(
1197             "COMPILATION_UNIT -> COMPILATION_UNIT [1:1]",
1198             "|--CLASS_DEF -> CLASS_DEF [3:1]",
1199             "|   `--OBJBLOCK -> OBJBLOCK [3:29]",
1200             "|       |--METHOD_DEF -> METHOD_DEF [8:5]",
1201             "|       |   `--SLIST -> { [8:27]",
1202             "|       |       |--VARIABLE_DEF -> VARIABLE_DEF [9:9]",
1203             "|       |       |   |--IDENT -> a [9:13]");
1204         final String xpath = "/COMPILATION_UNIT/CLASS_DEF//METHOD_DEF[./IDENT[@text='method']]"
1205                 + "//VARIABLE_DEF/IDENT";
1206         assertMainReturnCode(0, "--branch-matching-xpath", xpath, getPath("InputMainXPath.java"));
1207         assertWithMessage("Unexpected output log")
1208             .that(systemOut.getCapturedData())
1209             .isEqualTo(expected);
1210         assertWithMessage("Unexpected system error log")
1211             .that(systemErr.getCapturedData())
1212             .isEqualTo("");
1213     }
1214 
1215     @Test
1216     public void testPrintXpathTwoResults(
1217             @SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1218         final String expected = addEndOfLine(
1219             "COMPILATION_UNIT -> COMPILATION_UNIT [1:1]",
1220             "|--CLASS_DEF -> CLASS_DEF [12:1]",
1221             "|   `--OBJBLOCK -> OBJBLOCK [12:11]",
1222             "|       |--METHOD_DEF -> METHOD_DEF [13:5]",
1223             "---------",
1224             "COMPILATION_UNIT -> COMPILATION_UNIT [1:1]",
1225             "|--CLASS_DEF -> CLASS_DEF [12:1]",
1226             "|   `--OBJBLOCK -> OBJBLOCK [12:11]",
1227             "|       |--METHOD_DEF -> METHOD_DEF [14:5]");
1228         assertMainReturnCode(0, "--branch-matching-xpath",
1229                 "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Two']]//METHOD_DEF",
1230                 getPath("InputMainXPath.java"));
1231         assertWithMessage("Unexpected output log")
1232             .that(systemOut.getCapturedData())
1233             .isEqualTo(expected);
1234         assertWithMessage("Unexpected system error log")
1235             .that(systemErr.getCapturedData())
1236             .isEqualTo("");
1237     }
1238 
1239     @Test
1240     public void testPrintXpathInvalidXpath(@SysErr Capturable systemErr) throws Exception {
1241         final String invalidXpath = "\\/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Two']]"
1242                 + "//METHOD_DEF";
1243         final String filePath = getFilePath("InputMainXPath.java");
1244         assertMainReturnCode(-2, "--branch-matching-xpath", invalidXpath, filePath);
1245         final String exceptionFirstLine = addEndOfLine("com.puppycrawl.tools.checkstyle.api."
1246             + "CheckstyleException: Error during evaluation for xpath: " + invalidXpath
1247             + ", file: " + filePath);
1248         assertWithMessage("Unexpected system error log")
1249             .that(systemErr.getCapturedData())
1250             .startsWith(exceptionFirstLine);
1251     }
1252 
1253     @Test
1254     public void testPrintTreeCommentsOption(@SysErr Capturable systemErr,
1255             @SysOut Capturable systemOut) {
1256         final String expected = addEndOfLine(
1257             "COMPILATION_UNIT -> COMPILATION_UNIT [1:1]",
1258             "|--PACKAGE_DEF -> package [1:1]",
1259             "|   |--ANNOTATIONS -> ANNOTATIONS [1:40]",
1260             "|   |--DOT -> . [1:40]",
1261             "|   |   |--DOT -> . [1:29]",
1262             "|   |   |   |--DOT -> . [1:23]",
1263             "|   |   |   |   |--DOT -> . [1:12]",
1264             "|   |   |   |   |   |--IDENT -> com [1:9]",
1265             "|   |   |   |   |   `--IDENT -> puppycrawl [1:13]",
1266             "|   |   |   |   `--IDENT -> tools [1:24]",
1267             "|   |   |   `--IDENT -> checkstyle [1:30]",
1268             "|   |   `--IDENT -> main [1:41]",
1269             "|   `--SEMI -> ; [1:45]",
1270             "|--CLASS_DEF -> CLASS_DEF [3:1]",
1271             "|   |--MODIFIERS -> MODIFIERS [3:1]",
1272             "|   |   |--BLOCK_COMMENT_BEGIN -> /* [2:1]",
1273             "|   |   |   |--COMMENT_CONTENT -> comment [2:3]",
1274             "|   |   |   `--BLOCK_COMMENT_END -> */ [2:9]",
1275             "|   |   `--LITERAL_PUBLIC -> public [3:1]",
1276             "|   |--LITERAL_CLASS -> class [3:8]",
1277             "|   |--IDENT -> InputMain [3:14]",
1278             "|   `--OBJBLOCK -> OBJBLOCK [3:24]",
1279             "|       |--LCURLY -> { [3:24]",
1280             "|       `--RCURLY -> } [4:1]",
1281             "`--CLASS_DEF -> CLASS_DEF [5:1]",
1282             "    |--MODIFIERS -> MODIFIERS [5:1]",
1283             "    |--LITERAL_CLASS -> class [5:1]",
1284             "    |--IDENT -> InputMainInner [5:7]",
1285             "    `--OBJBLOCK -> OBJBLOCK [5:22]",
1286             "        |--LCURLY -> { [5:22]",
1287             "        `--RCURLY -> } [6:1]");
1288 
1289         assertMainReturnCode(0, "-T", getPath("InputMain.java"));
1290         assertWithMessage("Unexpected output log")
1291             .that(systemOut.getCapturedData())
1292             .isEqualTo(expected);
1293         assertWithMessage("Unexpected system error log")
1294             .that(systemErr.getCapturedData())
1295             .isEqualTo("");
1296     }
1297 
1298     /**
1299      * Verifies the output of the command line parameter "-j".
1300      *
1301      * @param systemErr wrapper for {@code System.err}
1302      * @param systemOut wrapper for {@code System.out}
1303      * @throws IOException if I/O exception occurs while reading the test input.
1304      * @noinspection RedundantThrows
1305      * @noinspectionreason RedundantThrows - false positive
1306      */
1307     @Test
1308     public void testPrintTreeJavadocOption(@SysErr Capturable systemErr,
1309             @SysOut Capturable systemOut)
1310                     throws IOException {
1311         final String expected = Files.readString(Path.of(
1312             getPath("InputMainExpectedInputJavadocComment.txt")))
1313             .replace("\\\\r\\\\n", "\\\\n").replace("\r\n", "\n");
1314 
1315         assertMainReturnCode(0, "-j", getPath("InputMainJavadocComment.javadoc"));
1316         assertWithMessage("Unexpected output log")
1317             .that(systemOut.getCapturedData().replaceAll("\\\\r\\\\n", "\\\\n")
1318                         .replace("\r\n", "\n"))
1319             .isEqualTo(expected);
1320         assertWithMessage("Unexpected system error log")
1321             .that(systemErr.getCapturedData())
1322             .isEqualTo("");
1323     }
1324 
1325     @Test
1326     public void testPrintSuppressionOption(@SysErr Capturable systemErr,
1327             @SysOut Capturable systemOut) {
1328         final String expected = addEndOfLine(
1329             "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputMainSuppressionsStringPrinter']]",
1330                 "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputMainSuppressionsStringPrinter']]"
1331                         + "/MODIFIERS",
1332                 "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputMainSuppressionsStringPrinter']"
1333                         + "]/LITERAL_CLASS");
1334 
1335         assertMainReturnCode(0, getPath("InputMainSuppressionsStringPrinter.java"), "-s", "3:1");
1336         assertWithMessage("Unexpected output log")
1337             .that(systemOut.getCapturedData())
1338             .isEqualTo(expected);
1339         assertWithMessage("Unexpected system error log")
1340             .that(systemErr.getCapturedData())
1341             .isEqualTo("");
1342     }
1343 
1344     @Test
1345     public void testPrintSuppressionAndTabWidthOption(@SysErr Capturable systemErr,
1346             @SysOut Capturable systemOut) {
1347         final String expected = addEndOfLine(
1348             "/COMPILATION_UNIT/CLASS_DEF"
1349                     + "[./IDENT[@text='InputMainSuppressionsStringPrinter']]/OBJBLOCK"
1350                     + "/METHOD_DEF[./IDENT[@text='getName']]"
1351                     + "/SLIST/VARIABLE_DEF[./IDENT[@text='var']]",
1352                 "/COMPILATION_UNIT/CLASS_DEF"
1353                     + "[./IDENT[@text='InputMainSuppressionsStringPrinter']]/OBJBLOCK"
1354                     + "/METHOD_DEF[./IDENT[@text='getName']]/SLIST"
1355                     + "/VARIABLE_DEF[./IDENT[@text='var']]/MODIFIERS",
1356                 "/COMPILATION_UNIT/CLASS_DEF"
1357                     + "[./IDENT[@text='InputMainSuppressionsStringPrinter']]/OBJBLOCK"
1358                     + "/METHOD_DEF[./IDENT[@text='getName']]/SLIST"
1359                     + "/VARIABLE_DEF[./IDENT[@text='var']]/TYPE",
1360                 "/COMPILATION_UNIT/CLASS_DEF"
1361                     + "[./IDENT[@text='InputMainSuppressionsStringPrinter']]/OBJBLOCK"
1362                     + "/METHOD_DEF[./IDENT[@text='getName']]/SLIST"
1363                     + "/VARIABLE_DEF[./IDENT[@text='var']]/TYPE/LITERAL_INT");
1364 
1365         assertMainReturnCode(0, getPath("InputMainSuppressionsStringPrinter.java"),
1366                 "-s", "7:9", "--tabWidth", "2");
1367         assertWithMessage("Unexpected output log")
1368             .that(systemOut.getCapturedData())
1369             .isEqualTo(expected);
1370         assertWithMessage("Unexpected system error log")
1371             .that(systemErr.getCapturedData())
1372             .isEqualTo("");
1373     }
1374 
1375     @Test
1376     public void testPrintSuppressionConflictingOptionsTvsC(@SysErr Capturable systemErr,
1377             @SysOut Capturable systemOut) {
1378         assertMainReturnCode(-1, "-c", "/google_checks.xml", getPath(""), "-s", "2:4");
1379         assertWithMessage("Unexpected output log")
1380             .that(systemOut.getCapturedData())
1381             .isEqualTo("Option '-s' cannot be used with other options."
1382                 + System.lineSeparator());
1383         assertWithMessage("Unexpected system error log")
1384             .that(systemErr.getCapturedData())
1385             .isEqualTo("");
1386     }
1387 
1388     @Test
1389     public void testPrintSuppressionConflictingOptionsTvsP(@SysErr Capturable systemErr,
1390             @SysOut Capturable systemOut) {
1391         assertMainReturnCode(-1, "-p", getPath("InputMainMycheckstyle.properties"), "-s", "2:4",
1392                 getPath(""));
1393         assertWithMessage("Unexpected output log")
1394             .that(systemOut.getCapturedData())
1395             .isEqualTo("Option '-s' cannot be used with other options."
1396                 + System.lineSeparator());
1397         assertWithMessage("Unexpected system error log")
1398             .that(systemErr.getCapturedData())
1399             .isEqualTo("");
1400     }
1401 
1402     @Test
1403     public void testPrintSuppressionConflictingOptionsTvsF(@SysErr Capturable systemErr,
1404             @SysOut Capturable systemOut) {
1405         assertMainReturnCode(-1, "-f", "plain", "-s", "2:4", getPath(""));
1406         assertWithMessage("Unexpected output log")
1407             .that(systemOut.getCapturedData())
1408             .isEqualTo("Option '-s' cannot be used with other options."
1409                 + System.lineSeparator());
1410         assertWithMessage("Unexpected system error log")
1411             .that(systemErr.getCapturedData())
1412             .isEqualTo("");
1413     }
1414 
1415     @Test
1416     public void testPrintSuppressionConflictingOptionsTvsO(@SysErr Capturable systemErr,
1417             @SysOut Capturable systemOut)
1418                     throws IOException {
1419         final String outputPath = new File(temporaryFolder, "file.output").getCanonicalPath();
1420 
1421         assertMainReturnCode(-1, "-o", outputPath, "-s", "2:4", getPath(""));
1422         assertWithMessage("Unexpected output log")
1423             .that(systemOut.getCapturedData())
1424             .isEqualTo("Option '-s' cannot be used with other options."
1425                 + System.lineSeparator());
1426         assertWithMessage("Unexpected system error log")
1427             .that(systemErr.getCapturedData())
1428             .isEqualTo("");
1429     }
1430 
1431     @Test
1432     public void testPrintSuppressionOnMoreThanOneFile(@SysErr Capturable systemErr,
1433             @SysOut Capturable systemOut) {
1434         assertMainReturnCode(-1, "-s", "2:4", getPath(""), getPath(""));
1435         assertWithMessage("Unexpected output log")
1436             .that(systemOut.getCapturedData())
1437             .isEqualTo("Printing xpath suppressions is allowed for only one file."
1438                 + System.lineSeparator());
1439         assertWithMessage("Unexpected system error log")
1440             .that(systemErr.getCapturedData())
1441             .isEqualTo("");
1442     }
1443 
1444     @Test
1445     public void testGenerateXpathSuppressionOptionOne(@SysErr Capturable systemErr,
1446             @SysOut Capturable systemOut) {
1447         final String expected =
1448                 """
1449                 <?xml version="1.0" encoding="UTF-8"?>
1450                 <!DOCTYPE suppressions PUBLIC
1451                     "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
1452                     "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
1453                 <suppressions>
1454                   <suppress-xpath
1455                        files="InputMainComplexityOverflow.java"
1456                        checks="MissingJavadocMethodCheck"
1457                        query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
1458                 [@text='InputMainComplexityOverflow']]/OBJBLOCK/METHOD_DEF[./IDENT\
1459                 [@text='provokeNpathIntegerOverflow']]"/>
1460                   <suppress-xpath
1461                        files="InputMainComplexityOverflow.java"
1462                        id="LeftCurlyEol"
1463                        query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
1464                 [@text='InputMainComplexityOverflow']]/OBJBLOCK/METHOD_DEF[./IDENT\
1465                 [@text='provokeNpathIntegerOverflow']]/SLIST"/>
1466                 </suppressions>
1467                 """.replace("\n", EOL);
1468 
1469         assertMainReturnCode(0, "-c", "/google_checks.xml", "--generate-xpath-suppression",
1470                 getPath("InputMainComplexityOverflow.java"));
1471         assertWithMessage("Unexpected output log")
1472             .that(systemOut.getCapturedData())
1473             .isEqualTo(expected);
1474         assertWithMessage("Unexpected system error log")
1475             .that(systemErr.getCapturedData())
1476             .isEqualTo("");
1477     }
1478 
1479     @Test
1480     public void testGenerateXpathSuppressionOptionTwo(@SysErr Capturable systemErr,
1481             @SysOut Capturable systemOut) {
1482         final String expected =
1483                 """
1484                 <?xml version="1.0" encoding="UTF-8"?>
1485                 <!DOCTYPE suppressions PUBLIC
1486                     "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
1487                     "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
1488                 <suppressions>
1489                   <suppress-xpath
1490                        files="InputMainGenerateXpathSuppressions.java"
1491                        checks="ExplicitInitializationCheck"
1492                        query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
1493                 [@text='InputMainGenerateXpathSuppressions']]/OBJBLOCK/VARIABLE_DEF/IDENT\
1494                 [@text='low']"/>
1495                   <suppress-xpath
1496                        files="InputMainGenerateXpathSuppressions.java"
1497                        checks="IllegalThrowsCheck"
1498                        query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
1499                 [@text='InputMainGenerateXpathSuppressions']]/OBJBLOCK/METHOD_DEF[./IDENT\
1500                 [@text='test']]/LITERAL_THROWS/IDENT[@text='RuntimeException']"/>
1501                   <suppress-xpath
1502                        files="InputMainGenerateXpathSuppressions.java"
1503                        checks="NestedForDepthCheck"
1504                        query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
1505                 [@text='InputMainGenerateXpathSuppressions']]/OBJBLOCK/METHOD_DEF[./IDENT\
1506                 [@text='test']]/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR"/>
1507                 </suppressions>
1508                 """.replace("\n", EOL);
1509 
1510         assertMainReturnCode(0, "-c", getPath("InputMainConfig-xpath-suppressions.xml"),
1511                 "--generate-xpath-suppression",
1512                 getPath("InputMainGenerateXpathSuppressions.java"));
1513         assertWithMessage("Unexpected output log")
1514             .that(systemOut.getCapturedData())
1515             .isEqualTo(expected);
1516         assertWithMessage("Unexpected system error log")
1517             .that(systemErr.getCapturedData())
1518             .isEqualTo("");
1519     }
1520 
1521     @Test
1522     public void testGenerateXpathSuppressionOptionEmptyConfig(@SysErr Capturable systemErr,
1523             @SysOut Capturable systemOut) {
1524         final String expected = "";
1525 
1526         assertMainReturnCode(0, "-c", getPath("InputMainConfig-empty.xml"),
1527                 "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java"));
1528         assertWithMessage("Unexpected output log")
1529             .that(systemOut.getCapturedData())
1530             .isEqualTo(expected);
1531         assertWithMessage("Unexpected system error log")
1532             .that(systemErr.getCapturedData())
1533             .isEqualTo("");
1534     }
1535 
1536     @Test
1537     public void testGenerateXpathSuppressionOptionCustomOutput(@SysErr Capturable systemErr)
1538             throws IOException {
1539         final String expected =
1540                 """
1541                 <?xml version="1.0" encoding="UTF-8"?>
1542                 <!DOCTYPE suppressions PUBLIC
1543                     "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
1544                     "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
1545                 <suppressions>
1546                   <suppress-xpath
1547                        files="InputMainGenerateXpathSuppressionsTabWidth.java"
1548                        checks="ExplicitInitializationCheck"
1549                        query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
1550                 [@text='InputMainGenerateXpathSuppressionsTabWidth']]\
1551                 /OBJBLOCK/VARIABLE_DEF/IDENT[@text='low']"/>
1552                 </suppressions>
1553                 """.replace("\n", EOL);
1554         final File file = new File(temporaryFolder, "file.output");
1555         assertMainReturnCode(0, "-c", getPath("InputMainConfig-xpath-suppressions.xml"), "-o",
1556                 file.getPath(), "--generate-xpath-suppression",
1557                 getPath("InputMainGenerateXpathSuppressionsTabWidth.java"));
1558         try (BufferedReader br = Files.newBufferedReader(file.toPath())) {
1559             final String fileContent = br.lines().collect(Collectors.joining(EOL, "", EOL));
1560             assertWithMessage("Unexpected output log")
1561                 .that(fileContent)
1562                 .isEqualTo(expected);
1563             assertWithMessage("Unexpected system error log")
1564                 .that(systemErr.getCapturedData())
1565                 .isEqualTo("");
1566         }
1567     }
1568 
1569     @Test
1570     public void testGenerateXpathSuppressionOptionDefaultTabWidth(@SysErr Capturable systemErr,
1571             @SysOut Capturable systemOut) {
1572         final String expected =
1573                 """
1574                 <?xml version="1.0" encoding="UTF-8"?>
1575                 <!DOCTYPE suppressions PUBLIC
1576                     "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
1577                     "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
1578                 <suppressions>
1579                   <suppress-xpath
1580                        files="InputMainGenerateXpathSuppressionsTabWidth.java"
1581                        checks="ExplicitInitializationCheck"
1582                        query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
1583                 [@text='InputMainGenerateXpathSuppressionsTabWidth']]\
1584                 /OBJBLOCK/VARIABLE_DEF/IDENT[@text='low']"/>
1585                 </suppressions>
1586                 """.replace("\n", EOL);
1587 
1588         assertMainReturnCode(0, "-c", getPath("InputMainConfig-xpath-suppressions.xml"),
1589                 "--generate-xpath-suppression",
1590                 getPath("InputMainGenerateXpathSuppressionsTabWidth.java"));
1591         assertWithMessage("Unexpected output log")
1592             .that(systemOut.getCapturedData())
1593             .isEqualTo(expected);
1594         assertWithMessage("Unexpected system error log")
1595             .that(systemErr.getCapturedData())
1596             .isEqualTo("");
1597     }
1598 
1599     @Test
1600     public void testGenerateXpathSuppressionOptionCustomTabWidth(@SysErr Capturable systemErr,
1601             @SysOut Capturable systemOut) {
1602         final String expected = "";
1603 
1604         assertMainReturnCode(0, "-c", getPath("InputMainConfig-xpath-suppressions.xml"),
1605                 "--generate-xpath-suppression", "--tabWidth", "20",
1606                 getPath("InputMainGenerateXpathSuppressionsTabWidth.java"));
1607         assertWithMessage("Unexpected output log")
1608             .that(systemOut.getCapturedData())
1609             .isEqualTo(expected);
1610         assertWithMessage("Unexpected system error log")
1611             .that(systemErr.getCapturedData())
1612             .isEqualTo("");
1613     }
1614 
1615     @Test
1616     public void testGenerateChecksAndFilesSuppressionOptionOne(@SysErr Capturable systemErr,
1617             @SysOut Capturable systemOut) {
1618         final String expected =
1619                 """
1620                 <?xml version="1.0" encoding="UTF-8"?>
1621                 <!DOCTYPE suppressions PUBLIC
1622                     "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
1623                     "https://checkstyle.org/dtds/suppressions_1_2.dtd">
1624                 <suppressions>
1625                   <suppress
1626                       files="InputMainComplexityOverflow.java"
1627                       checks="MissingJavadocMethodCheck"/>
1628                   <suppress
1629                       files="InputMainComplexityOverflow.java"
1630                       id="LeftCurlyEol"/>
1631                 </suppressions>
1632                 """.replace("\n", EOL);
1633 
1634         assertMainReturnCode(0, "-c", "/google_checks.xml",
1635                 "--generate-checks-and-files-suppression",
1636                 getPath("InputMainComplexityOverflow.java"));
1637         assertWithMessage("Unexpected output log")
1638             .that(systemOut.getCapturedData())
1639             .isEqualTo(expected);
1640         assertWithMessage("Unexpected system error log")
1641             .that(systemErr.getCapturedData())
1642             .isEqualTo("");
1643     }
1644 
1645     @Test
1646     public void testGenerateChecksAndFilesSuppressionOptionTwo(@SysErr Capturable systemErr,
1647             @SysOut Capturable systemOut) {
1648         final String expected =
1649                 """
1650                 <?xml version="1.0" encoding="UTF-8"?>
1651                 <!DOCTYPE suppressions PUBLIC
1652                     "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
1653                     "https://checkstyle.org/dtds/suppressions_1_2.dtd">
1654                 <suppressions>
1655                   <suppress
1656                       files="InputMainGenerateChecksAndFilesSuppressions.java"
1657                       id="InitializeViolation"/>
1658                   <suppress
1659                       files="InputMainGenerateChecksAndFilesSuppressions.java"
1660                       checks="IllegalThrowsCheck"/>
1661                   <suppress
1662                       files="InputMainGenerateChecksAndFilesSuppressions.java"
1663                       checks="NestedForDepthCheck"/>
1664                   <suppress
1665                       files="InputMainGenerateChecksAndFilesSuppressions.java"
1666                       id="MethodNaming"/>
1667                 </suppressions>
1668                 """.replace("\n", EOL);
1669 
1670         assertMainReturnCode(0, "-c", getPath("InputMainConfig-Checks-And-Files-suppressions.xml"),
1671                 "--generate-checks-and-files-suppression",
1672                 getPath("InputMainGenerateChecksAndFilesSuppressions.java"));
1673         assertWithMessage("Unexpected output log")
1674             .that(systemOut.getCapturedData())
1675             .isEqualTo(expected);
1676         assertWithMessage("Unexpected system error log")
1677             .that(systemErr.getCapturedData())
1678             .isEqualTo("");
1679     }
1680 
1681     @Test
1682     public void testGenerateChecksAndFilesSuppressionOptionEmptyConfig(@SysErr Capturable systemErr,
1683             @SysOut Capturable systemOut) {
1684         final String expected = "";
1685 
1686         assertMainReturnCode(0, "-c", getPath("InputMainConfig-empty.xml"),
1687                 "--generate-checks-and-files-suppression",
1688                 getPath("InputMainComplexityOverflow.java"));
1689         assertWithMessage("Unexpected output log")
1690             .that(systemOut.getCapturedData())
1691             .isEqualTo(expected);
1692         assertWithMessage("Unexpected system error log")
1693             .that(systemErr.getCapturedData())
1694             .isEqualTo("");
1695     }
1696 
1697     @Test
1698     public void testGenerateChecksAndFilesSuppressionOptionCustomOutput(
1699             @SysErr Capturable systemErr)
1700                     throws IOException {
1701         final String expected =
1702                 """
1703                 <?xml version="1.0" encoding="UTF-8"?>
1704                 <!DOCTYPE suppressions PUBLIC
1705                     "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
1706                     "https://checkstyle.org/dtds/suppressions_1_2.dtd">
1707                 <suppressions>
1708                   <suppress
1709                       files="InputMainGenerateChecksAndFilesSuppressionsTabWidth.java"
1710                       id="InitializeViolation"/>
1711                 </suppressions>
1712                 """.replace("\n", EOL);
1713         final File file = new File(temporaryFolder, "file.output");
1714         assertMainReturnCode(0, "-c", getPath("InputMainConfig-Checks-And-Files-suppressions.xml"),
1715                 "-o", file.getPath(), "--generate-checks-and-files-suppression",
1716                 getPath("InputMainGenerateChecksAndFilesSuppressionsTabWidth.java"));
1717         try (BufferedReader br = Files.newBufferedReader(file.toPath())) {
1718             final String fileContent = br.lines().collect(Collectors.joining(EOL, "", EOL));
1719             assertWithMessage("Unexpected output log")
1720                 .that(fileContent)
1721                 .isEqualTo(expected);
1722             assertWithMessage("Unexpected system error log")
1723                 .that(systemErr.getCapturedData())
1724                 .isEqualTo("");
1725         }
1726     }
1727 
1728     @Test
1729     public void testGenerateChecksAndFilesSuppressionOptionDefaultTabWidth(
1730             @SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1731         final String expected =
1732                 """
1733                 <?xml version="1.0" encoding="UTF-8"?>
1734                 <!DOCTYPE suppressions PUBLIC
1735                     "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
1736                     "https://checkstyle.org/dtds/suppressions_1_2.dtd">
1737                 <suppressions>
1738                   <suppress
1739                       files="InputMainGenerateChecksAndFilesSuppressionsTabWidth.java"
1740                       id="InitializeViolation"/>
1741                 </suppressions>
1742                 """.replace("\n", EOL);
1743 
1744         assertMainReturnCode(0, "-c", getPath("InputMainConfig-Checks-And-Files-suppressions.xml"),
1745                 "--generate-checks-and-files-suppression",
1746                 getPath("InputMainGenerateChecksAndFilesSuppressionsTabWidth.java"));
1747         assertWithMessage("Unexpected output log")
1748             .that(systemOut.getCapturedData())
1749             .isEqualTo(expected);
1750         assertWithMessage("Unexpected system error log")
1751             .that(systemErr.getCapturedData())
1752             .isEqualTo("");
1753     }
1754 
1755     @Test
1756     public void testGenerateChecksAndFilesSuppressionOptionCustomTabWidth(
1757             @SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1758         final String expected =
1759                 """
1760                 <?xml version="1.0" encoding="UTF-8"?>
1761                 <!DOCTYPE suppressions PUBLIC
1762                     "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
1763                     "https://checkstyle.org/dtds/suppressions_1_2.dtd">
1764                 <suppressions>
1765                   <suppress
1766                       files="InputMainGenerateChecksAndFilesSuppressionsTabWidth.java"
1767                       id="InitializeViolation"/>
1768                 </suppressions>
1769                 """.replace("\n", EOL);
1770 
1771         assertMainReturnCode(0, "-c", getPath("InputMainConfig-Checks-And-Files-suppressions.xml"),
1772                 "--generate-checks-and-files-suppression", "--tabWidth", "20",
1773                 getPath("InputMainGenerateChecksAndFilesSuppressionsTabWidth.java"));
1774         assertWithMessage("Unexpected output log")
1775             .that(systemOut.getCapturedData())
1776             .isEqualTo(expected);
1777         assertWithMessage("Unexpected system error log")
1778             .that(systemErr.getCapturedData())
1779             .isEqualTo("");
1780     }
1781 
1782     /**
1783      * Verifies the output of the command line parameter "-J".
1784      *
1785      * @param systemErr wrapper for {@code System.err}
1786      * @param systemOut wrapper for {@code System.out}
1787      * @throws IOException if I/O exception occurs while reading the test input.
1788      * @noinspection RedundantThrows
1789      * @noinspectionreason RedundantThrows - false positive
1790      */
1791     @Test
1792     public void testPrintFullTreeOption(@SysErr Capturable systemErr, @SysOut Capturable systemOut)
1793             throws IOException {
1794         final String expected = Files.readString(Path.of(
1795             getPath("InputMainExpectedInputAstTreeStringPrinterJavadoc.txt")))
1796                 .replaceAll("\\\\r\\\\n", "\\\\n")
1797                 .replace("\r\n", "\n");
1798 
1799         assertMainReturnCode(0, "-J", getPath("InputMainAstTreeStringPrinterJavadoc.java"));
1800         assertWithMessage("Unexpected output log")
1801             .that(systemOut.getCapturedData().replaceAll("\\\\r\\\\n", "\\\\n")
1802                         .replace("\r\n", "\n"))
1803             .isEqualTo(expected);
1804         assertWithMessage("Unexpected system error log")
1805             .that(systemErr.getCapturedData())
1806             .isEqualTo("");
1807     }
1808 
1809     @Test
1810     public void testConflictingOptionsTvsC(@SysErr Capturable systemErr,
1811             @SysOut Capturable systemOut) {
1812         assertMainReturnCode(-1, "-c", "/google_checks.xml", "-t", getPath(""));
1813         assertWithMessage("Unexpected output log")
1814             .that(systemOut.getCapturedData())
1815             .isEqualTo("Option '-t' cannot be used with other options." + System.lineSeparator());
1816         assertWithMessage("Unexpected system error log")
1817             .that(systemErr.getCapturedData())
1818             .isEqualTo("");
1819     }
1820 
1821     @Test
1822     public void testConflictingOptionsTvsP(@SysErr Capturable systemErr,
1823             @SysOut Capturable systemOut) {
1824         assertMainReturnCode(-1, "-p", getPath("InputMainMycheckstyle.properties"), "-t",
1825                 getPath(""));
1826         assertWithMessage("Unexpected output log")
1827             .that(systemOut.getCapturedData())
1828             .isEqualTo("Option '-t' cannot be used with other options." + System.lineSeparator());
1829         assertWithMessage("Unexpected system error log")
1830             .that(systemErr.getCapturedData())
1831             .isEqualTo("");
1832     }
1833 
1834     @Test
1835     public void testConflictingOptionsTvsF(@SysErr Capturable systemErr,
1836             @SysOut Capturable systemOut) {
1837         assertMainReturnCode(-1, "-f", "plain", "-t", getPath(""));
1838         assertWithMessage("Unexpected output log")
1839             .that(systemOut.getCapturedData())
1840             .isEqualTo("Option '-t' cannot be used with other options." + System.lineSeparator());
1841         assertWithMessage("Unexpected system error log")
1842             .that(systemErr.getCapturedData())
1843             .isEqualTo("");
1844     }
1845 
1846     @Test
1847     public void testConflictingOptionsTvsS(@SysErr Capturable systemErr,
1848             @SysOut Capturable systemOut)
1849                     throws IOException {
1850         final String outputPath = new File(temporaryFolder, "file.output").getCanonicalPath();
1851 
1852         assertMainReturnCode(-1, "-s", outputPath, "-t", getPath(""));
1853         assertWithMessage("Unexpected output log")
1854             .that(systemOut.getCapturedData())
1855             .isEqualTo("Option '-t' cannot be used with other options." + System.lineSeparator());
1856         assertWithMessage("Unexpected system error log")
1857             .that(systemErr.getCapturedData())
1858             .isEqualTo("");
1859     }
1860 
1861     @Test
1862     public void testConflictingOptionsTvsO(@SysErr Capturable systemErr,
1863             @SysOut Capturable systemOut)
1864                     throws IOException {
1865         final String outputPath = new File(temporaryFolder, "file.output").getCanonicalPath();
1866 
1867         assertMainReturnCode(-1, "-o", outputPath, "-t", getPath(""));
1868         assertWithMessage("Unexpected output log")
1869             .that(systemOut.getCapturedData())
1870             .isEqualTo("Option '-t' cannot be used with other options." + System.lineSeparator());
1871         assertWithMessage("Unexpected system error log")
1872             .that(systemErr.getCapturedData())
1873             .isEqualTo("");
1874     }
1875 
1876     @Test
1877     public void testDebugOption(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1878         assertMainReturnCode(0, "-c", "/google_checks.xml", getPath("InputMain.java"), "-d");
1879         assertWithMessage("Unexpected system error log")
1880             .that(systemErr.getCapturedData())
1881             .contains("FINE: Checkstyle debug logging enabled");
1882         assertWithMessage("Unexpected system error log")
1883             .that(systemOut.getCapturedData())
1884             .contains("Audit done.");
1885 
1886     }
1887 
1888     @Test
1889     public void testExcludeOption(@SysErr Capturable systemErr, @SysOut Capturable systemOut)
1890             throws IOException {
1891         final String filePath = getFilePath("");
1892         assertMainReturnCode(-1, "-c", "/google_checks.xml", filePath, "-e", filePath);
1893         assertWithMessage("Unexpected output log")
1894             .that(systemOut.getCapturedData())
1895             .isEqualTo("Files to process must be specified, found 0." + System.lineSeparator());
1896         assertWithMessage("Unexpected system error log")
1897             .that(systemErr.getCapturedData())
1898             .isEqualTo("");
1899     }
1900 
1901     @Test
1902     public void testExcludeOptionFile(@SysErr Capturable systemErr, @SysOut Capturable systemOut)
1903             throws IOException {
1904         final String filePath = getFilePath("InputMain.java");
1905         assertMainReturnCode(-1, "-c", "/google_checks.xml", filePath, "-e", filePath);
1906         assertWithMessage("Unexpected output log")
1907             .that(systemOut.getCapturedData())
1908             .isEqualTo("Files to process must be specified, found 0." + System.lineSeparator());
1909         assertWithMessage("Unexpected system error log")
1910             .that(systemErr.getCapturedData())
1911             .isEqualTo("");
1912     }
1913 
1914     @Test
1915     public void testExcludeRegexpOption(@SysErr Capturable systemErr, @SysOut Capturable systemOut)
1916             throws IOException {
1917         final String filePath = getFilePath("");
1918         assertMainReturnCode(-1, "-c", "/google_checks.xml", filePath, "-x", ".");
1919         assertWithMessage("Unexpected output log")
1920             .that(systemOut.getCapturedData())
1921             .isEqualTo("Files to process must be specified, found 0." + System.lineSeparator());
1922         assertWithMessage("Unexpected output log")
1923             .that(systemErr.getCapturedData())
1924             .isEqualTo("");
1925     }
1926 
1927     @Test
1928     public void testExcludeRegexpOptionFile(@SysErr Capturable systemErr,
1929             @SysOut Capturable systemOut)
1930                     throws IOException {
1931         final String filePath = getFilePath("InputMain.java");
1932         assertMainReturnCode(-1, "-c", "/google_checks.xml", filePath, "-x", ".");
1933         assertWithMessage("Unexpected output log")
1934             .that(systemOut.getCapturedData())
1935             .isEqualTo("Files to process must be specified, found 0." + System.lineSeparator());
1936         assertWithMessage("Unexpected output log")
1937             .that(systemErr.getCapturedData())
1938             .isEqualTo("");
1939     }
1940 
1941     @Test
1942     public void testExcludeDirectoryNotMatch() throws Exception {
1943         final Class<?> optionsClass = Class.forName(Main.class.getName());
1944         final List<Pattern> list = new ArrayList<>();
1945         list.add(Pattern.compile("BAD_PATH"));
1946 
1947         final List<File> result = TestUtil.invokeStaticMethodList(
1948                 optionsClass, "listFiles", new File(getFilePath("")), list);
1949         assertWithMessage("Invalid result size")
1950             .that(result)
1951             .isNotEmpty();
1952     }
1953 
1954     @Test
1955     public void testCustomRootModule(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
1956         TestRootModuleChecker.reset();
1957 
1958         assertMainReturnCode(0, "-c", getPath("InputMainConfig-custom-root-module.xml"),
1959                 getPath("InputMain.java"));
1960         assertWithMessage("Unexpected output log")
1961             .that(systemOut.getCapturedData())
1962             .isEqualTo("");
1963         assertWithMessage("Unexpected system error log")
1964             .that(systemErr.getCapturedData())
1965             .isEqualTo("");
1966         assertWithMessage("Invalid Checker state")
1967                 .that(TestRootModuleChecker.isProcessed())
1968                 .isTrue();
1969         assertWithMessage("RootModule should be destroyed")
1970                 .that(TestRootModuleChecker.isDestroyed())
1971                 .isTrue();
1972     }
1973 
1974     @Test
1975     public void testCustomSimpleRootModule(@SysErr Capturable systemErr) {
1976         TestRootModuleChecker.reset();
1977         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-custom-simple-root-module.xml"),
1978                 getPath("InputMain.java"));
1979         final String checkstylePackage = "com.puppycrawl.tools.checkstyle.";
1980         final LocalizedMessage unableToInstantiateExceptionMessage = new LocalizedMessage(
1981                 Definitions.CHECKSTYLE_BUNDLE,
1982                 getClass(),
1983                 "PackageObjectFactory.unableToInstantiateExceptionMessage",
1984                 "TestRootModuleChecker",
1985                 checkstylePackage
1986                         + "TestRootModuleChecker, "
1987                         + "TestRootModuleCheckerCheck, " + checkstylePackage
1988                         + "TestRootModuleCheckerCheck");
1989         assertWithMessage(
1990                 "Unexpected system error log")
1991                         .that(systemErr.getCapturedData())
1992                         .startsWith(checkstylePackage + "api.CheckstyleException: "
1993                                 + unableToInstantiateExceptionMessage.getMessage());
1994         assertWithMessage("Invalid checker state")
1995                 .that(TestRootModuleChecker.isProcessed())
1996                 .isFalse();
1997     }
1998 
1999     @Test
2000     public void testExceptionOnExecuteIgnoredModuleWithUnknownModuleName(
2001             @SysErr Capturable systemErr) {
2002         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-non-existent-classname-ignore.xml"),
2003                     "--executeIgnoredModules", getPath("InputMain.java"));
2004         final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:"
2005                 + " cannot initialize module TreeWalker" + EOL;
2006         final String nestedCause = "Caused by: com.puppycrawl.tools.checkstyle.api."
2007                 + "CheckstyleException: cannot initialize module NonExistentClass" + EOL;
2008         assertWithMessage("Unexpected system error log")
2009                 .that(systemErr.getCapturedData())
2010                 .startsWith(cause);
2011         assertWithMessage("Unexpected system error log")
2012                 .that(systemErr.getCapturedData())
2013                 .contains(nestedCause);
2014     }
2015 
2016     @Test
2017     public void testExceptionOnExecuteIgnoredModuleWithBadPropertyValue(
2018             @SysErr Capturable systemErr) {
2019         assertMainReturnCode(-2, "-c", getPath("InputMainConfig-TypeName-bad-value.xml"),
2020                     "--executeIgnoredModules", getPath("InputMain.java"));
2021         final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:"
2022                 + " cannot initialize module TreeWalker" + EOL;
2023         final String nestedCause = "Caused by: com.puppycrawl.tools.checkstyle.api."
2024                 + "CheckstyleException: cannot initialize module TypeName" + EOL;
2025         final String causeDetail = "it is not a boolean";
2026         assertWithMessage("Unexpected system error log")
2027                 .that(systemErr.getCapturedData())
2028                 .startsWith(cause);
2029         assertWithMessage("Unexpected system error log")
2030                 .that(systemErr.getCapturedData())
2031                 .contains(nestedCause);
2032         assertWithMessage("Unexpected system error log")
2033                 .that(systemErr.getCapturedData())
2034                 .contains(causeDetail);
2035     }
2036 
2037     @Test
2038     public void testNoProblemOnExecuteIgnoredModuleWithBadPropertyValue(
2039             @SysErr Capturable systemErr) {
2040         assertMainReturnCode(0, "-c", getPath("InputMainConfig-TypeName-bad-value.xml"),
2041                     "", getPath("InputMain.java"));
2042         assertWithMessage("Unexpected system error log")
2043             .that(systemErr.getCapturedData())
2044                 .isEmpty();
2045     }
2046 
2047     @Test
2048     public void testMissingFiles(@SysErr Capturable systemErr, @SysOut Capturable systemOut) {
2049         assertMainReturnCode(-1);
2050         final String usage = "Missing required parameter: '<files or folders>'" + EOL + SHORT_USAGE;
2051         assertWithMessage("Unexpected output log")
2052             .that(systemOut.getCapturedData())
2053             .isEqualTo("");
2054         assertWithMessage("Unexpected system error log")
2055             .that(systemErr.getCapturedData())
2056             .isEqualTo(usage);
2057     }
2058 
2059     @Test
2060     public void testOutputFormatToStringLowercase() {
2061         assertWithMessage("expected xml")
2062             .that(Main.OutputFormat.XML.toString())
2063             .isEqualTo("xml");
2064         assertWithMessage("expected plain")
2065             .that(Main.OutputFormat.PLAIN.toString())
2066             .isEqualTo("plain");
2067     }
2068 
2069     @Test
2070     public void testXmlOutputFormatCreateListener() throws IOException {
2071         final ByteArrayOutputStream out = new ByteArrayOutputStream();
2072         final AuditListener listener = Main.OutputFormat.XML.createListener(out,
2073                 OutputStreamOptions.CLOSE);
2074         assertWithMessage("listener is XMLLogger")
2075                 .that(listener)
2076                 .isInstanceOf(XMLLogger.class);
2077     }
2078 
2079     @Test
2080     public void testSarifOutputFormatCreateListener() throws IOException {
2081         final ByteArrayOutputStream out = new ByteArrayOutputStream();
2082         final AuditListener listener = Main.OutputFormat.SARIF.createListener(out,
2083                 OutputStreamOptions.CLOSE);
2084         assertWithMessage("listener is SarifLogger")
2085                 .that(listener)
2086                 .isInstanceOf(SarifLogger.class);
2087     }
2088 
2089     @Test
2090     public void testPlainOutputFormatCreateListener() throws IOException {
2091         final ByteArrayOutputStream out = new ByteArrayOutputStream();
2092         final AuditListener listener = Main.OutputFormat.PLAIN.createListener(out,
2093                 OutputStreamOptions.CLOSE);
2094         assertWithMessage("listener is DefaultLogger")
2095                 .that(listener)
2096                 .isInstanceOf(DefaultLogger.class);
2097     }
2098 
2099     @Test
2100     public void testExcludeOptionDirectoryWithPlusInName(@SysErr Capturable systemErr,
2101                                                          @SysOut Capturable systemOut)
2102             throws IOException {
2103 
2104         final File specialDir = new File(temporaryFolder, "dir+name");
2105         assertWithMessage("Directory must be created")
2106                 .that(specialDir.mkdirs())
2107                 .isTrue();
2108 
2109         final File inputFile = new File(specialDir, "InputMainExclude.java");
2110         Files.writeString(inputFile.toPath(),
2111                 "public class InputMainExclude { }" + System.lineSeparator());
2112 
2113         final String dirPath = specialDir.getCanonicalPath();
2114 
2115         assertMainReturnCode(-1, "-c", "/google_checks.xml", dirPath,
2116                 "-e", dirPath);
2117 
2118         assertWithMessage("Unexpected output log")
2119                 .that(systemOut.getCapturedData())
2120                 .isEqualTo("Files to process must be specified, found 0."
2121                         + System.lineSeparator());
2122         assertWithMessage("Unexpected system error log")
2123                 .that(systemErr.getCapturedData())
2124                 .isEqualTo("");
2125     }
2126 
2127     /**
2128      * Helper method to run {@link Main#main(String...)} and verify the exit code.
2129      * Uses {@link Mockito#mockStatic(Class)} to mock method {@link Runtime#exit(int)}
2130      * to avoid VM termination.
2131      *
2132      * @param expectedExitCode the expected exit code to verify
2133      * @param arguments the command line arguments
2134      * @noinspection CallToSystemExit, ResultOfMethodCallIgnored
2135      * @noinspectionreason CallToSystemExit - test helper method requires workaround to
2136      *      verify exit code
2137      * @noinspectionreason ResultOfMethodCallIgnored - Setup for mockito to only
2138      *                     mock getRuntime to avoid VM termination.
2139      */
2140     private static void assertMainReturnCode(int expectedExitCode,
2141             String... arguments) {
2142         final Runtime mock = mock();
2143         try (MockedStatic<Runtime> runtime = mockStatic(Runtime.class)) {
2144             runtime.when(Runtime::getRuntime)
2145                     .thenReturn(mock);
2146             Main.main(arguments);
2147         }
2148         catch (IOException exception) {
2149             throw new IllegalStateException("Unexpected IOException for "
2150                     + Arrays.toString(arguments), exception);
2151         }
2152         verify(mock).exit(expectedExitCode);
2153     }
2154 
2155     /**
2156      * Replaces LF line endings with the platform-specific line separator.
2157      * Java text blocks normalize their line terminators to LF, including on Windows
2158      * (<a href="https://docs.oracle.com/en/java/javase/21/text-blocks/index.html">
2159      * Java text-block guide</a>, "Normalization Of Line Terminators").
2160      *
2161      * @param text the text with normalized LF line endings
2162      * @return the text with platform-specific line endings
2163      */
2164     private static String denormalizeLineEnding(String text) {
2165         return text.replace("\n", EOL);
2166     }
2167 
2168     /**
2169      * Print stream that shouldn't be closed. The purpose of this class is to ensure that
2170      * {@code System.out} and {@code System.err} are not closed by Checkstyle.
2171      */
2172     private static final class ShouldNotBeClosedStream extends PrintStream {
2173 
2174         private boolean isClosed;
2175 
2176         private ShouldNotBeClosedStream() {
2177             super(new ByteArrayOutputStream(), false, StandardCharsets.UTF_8);
2178         }
2179 
2180         @Override
2181         public void close() {
2182             isClosed = true;
2183             super.close();
2184         }
2185 
2186     }
2187 
2188 }