View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.checkstyle;
6   
7   import com.google.common.base.Joiner;
8   import com.qulice.spi.Environment;
9   import com.qulice.spi.Violation;
10  import java.io.File;
11  import java.io.IOException;
12  import java.util.Collection;
13  import org.cactoos.io.ResourceOf;
14  import org.cactoos.text.FormattedText;
15  import org.cactoos.text.IoCheckedText;
16  import org.cactoos.text.TextOf;
17  import org.hamcrest.MatcherAssert;
18  import org.hamcrest.Matchers;
19  import org.junit.jupiter.api.Assertions;
20  import org.junit.jupiter.api.Assumptions;
21  import org.junit.jupiter.api.Test;
22  
23  /**
24   * Test case for general {@link CheckstyleValidator} behavior that
25   * is not tied to a single check: method references, record/default
26   * methods, lambda and generics at end of line, chained lambdas
27   * passed as arguments, literal comparisons, and the imports-only
28   * regression guard. Per-check coverage lives in the dedicated
29   * {@code *CheckTest.java} and {@code Checkstyle*Test.java} files
30   * in this package.
31   * @since 0.3
32   */
33  final class CheckstyleValidatorTest {
34  
35      @Test
36      void acceptsInstanceMethodReferences() throws Exception {
37          Assertions.assertDoesNotThrow(
38              () -> this.runValidation("InstanceMethodRef.java", true)
39          );
40      }
41  
42      @Test
43      void acceptsIdAsMethodName() throws Exception {
44          Assertions.assertDoesNotThrow(
45              () -> this.runValidation("IdMethodName.java", true)
46          );
47      }
48  
49      @Test
50      void acceptsDefaultMethodsWithFinalModifiers() throws Exception {
51          Assertions.assertDoesNotThrow(
52              () -> this.runValidation("DefaultMethods.java", true)
53          );
54      }
55  
56      @Test
57      void supportsRecordTypes() throws Exception {
58          Assertions.assertDoesNotThrow(
59              () -> this.runValidation("ValidRecord.java", true)
60          );
61      }
62  
63      @Test
64      void acceptsLambdaAndGenericsAtEndOfLine() throws Exception {
65          Assertions.assertDoesNotThrow(
66              () -> this.runValidation("ValidLambdaAndGenericsAtEndOfLine.java", true)
67          );
68      }
69  
70      @Test
71      void acceptsChainedLambdaAsArgument() throws Exception {
72          Assertions.assertDoesNotThrow(
73              () -> this.runValidation("ValidLambdaIndentation.java", true)
74          );
75      }
76  
77      @Test
78      void allowsStringLiteralsOnBothSideInComparisons() throws Exception {
79          Assertions.assertDoesNotThrow(
80              () -> this.runValidation("ValidLiteralComparisonCheck.java", true)
81          );
82      }
83  
84      @Test
85      void failsClearlyWhenCacheParentIsNotWritable() throws Exception {
86          final Environment.Mock mock = new Environment.Mock();
87          final File parent = new File(mock.tempdir(), "checkstyle");
88          Assumptions.assumeTrue(
89              parent.mkdirs() || parent.isDirectory(),
90              "Parent directory must exist for the regression scenario"
91          );
92          try {
93              Assumptions.assumeTrue(
94                  parent.setReadOnly(),
95                  "Filesystem does not support marking a directory read-only"
96              );
97              Assumptions.assumeFalse(
98                  parent.canWrite(),
99                  "Skipped: current user can write despite read-only attribute"
100             );
101             final Environment env = mock.withFile(
102                 "src/main/java/foo/Foo.java",
103                 "package foo; class Foo {}"
104             );
105             MatcherAssert.assertThat(
106                 "Validation must fail fast with a clear writability error",
107                 Assertions.assertThrows(
108                     IllegalStateException.class,
109                     () -> new CheckstyleValidator(env).validate(env.files("Foo.java"))
110                 ).getMessage(),
111                 Matchers.allOf(
112                     Matchers.containsString("write"),
113                     Matchers.containsString(parent.getAbsolutePath())
114                 )
115             );
116         } finally {
117             parent.setWritable(true, false);
118         }
119     }
120 
121     @Test
122     void doesNotThrowExceptionIfImportsOnly() throws Exception {
123         final Environment.Mock mock = new Environment.Mock();
124         final String crlf = String.valueOf('\r').concat(String.valueOf('\n'));
125         final String name = "Foo.java";
126         final Environment env = mock.withParam(
127             "license",
128             String.format(
129                 "file:%s",
130                 new License().savePackageInfo(
131                     new File(mock.basedir(), "src/main/java/foo")
132                 ).withLines("License-1.", "", "License-2.")
133                     .withEol(String.valueOf('\n'))
134                     .file()
135             )
136         ).withFile(
137             String.format("src/main/java/foo/%s", name),
138             Joiner.on(crlf).join(
139                 "package com.google;",
140                 crlf,
141                 "import java.util.*;"
142             )
143         );
144         MatcherAssert.assertThat(
145             "Validation error should exist",
146             new CheckstyleValidator(env).validate(env.files(name)),
147             Matchers.not(Matchers.<Violation>empty())
148         );
149     }
150 
151     private Collection<Violation> runValidation(final String file,
152         final boolean passes) throws IOException {
153         final Environment.Mock mock = new Environment.Mock();
154         final Environment env = mock.withParam(
155             "license",
156             String.format(
157                 "file:%s",
158                 new License().savePackageInfo(
159                     new File(mock.basedir(), "src/main/java/foo")
160                 ).withLines("Hello.")
161                     .withEol(String.valueOf('\n')).file()
162             )
163         ).withFile(
164             String.format("src/main/java/foo/%s", file),
165             new IoCheckedText(
166                 new TextOf(
167                     new ResourceOf(
168                         new FormattedText("com/qulice/checkstyle/%s", file)
169                     )
170                 )
171             ).asString()
172         );
173         final Collection<Violation> results =
174             new CheckstyleValidator(env).validate(env.files(file));
175         MatcherAssert.assertThat(
176             "validation result should match expected state",
177             results.isEmpty(),
178             Matchers.is(passes)
179         );
180         return results;
181     }
182 }