1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.internal.utils.TestUtil.getExpectedThrowable;
24
25 import java.io.ByteArrayOutputStream;
26 import java.io.File;
27 import java.io.OutputStream;
28 import java.nio.charset.StandardCharsets;
29
30 import org.junit.jupiter.api.Test;
31
32 import com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions;
33 import com.puppycrawl.tools.checkstyle.api.AuditEvent;
34 import com.puppycrawl.tools.checkstyle.api.DetailAST;
35 import com.puppycrawl.tools.checkstyle.api.FileContents;
36 import com.puppycrawl.tools.checkstyle.api.FileText;
37 import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
38 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
39 import com.puppycrawl.tools.checkstyle.api.Violation;
40 import com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyCheck;
41 import com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck;
42 import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck;
43 import com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck;
44 import com.puppycrawl.tools.checkstyle.internal.utils.CloseAndFlushTestByteArrayOutputStream;
45 import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
46
47 public class XpathFileGeneratorAuditListenerTest {
48
49
50 private static final String EOL = System.lineSeparator();
51
52 private static final Violation FIRST_MESSAGE = createViolation(3, 51,
53 TokenTypes.LCURLY, null, LeftCurlyCheck.class);
54
55 private static final Violation SECOND_MESSAGE = createViolation(15, 5,
56 TokenTypes.METHOD_DEF, "MyModule", MethodParamPadCheck.class);
57
58 private static final Violation THIRD_MESSAGE = createViolation(17, 13,
59 TokenTypes.LITERAL_FOR, null, NestedForDepthCheck.class);
60
61 private static final Violation FOURTH_MESSAGE = createViolation(5, 5,
62 TokenTypes.VARIABLE_DEF, "JavadocModuleId", JavadocVariableCheck.class);
63
64 private final CloseAndFlushTestByteArrayOutputStream outStream =
65 new CloseAndFlushTestByteArrayOutputStream();
66
67 static {
68 try {
69 constructEvents();
70 }
71 catch (Exception exc) {
72 throw new IllegalStateException("Failed to construct events for "
73 + FOURTH_MESSAGE.getSourceName(), exc);
74 }
75 }
76
77 private static void constructEvents() throws Exception {
78 final TreeWalkerAuditEvent event1 = createTreeWalkerAuditEvent(
79 "InputXpathFileGeneratorAuditListener.java", FIRST_MESSAGE);
80
81 final TreeWalkerAuditEvent event2 = createTreeWalkerAuditEvent(
82 "InputXpathFileGeneratorAuditListener.java", SECOND_MESSAGE);
83
84 final TreeWalkerAuditEvent event3 = createTreeWalkerAuditEvent(
85 "InputXpathFileGeneratorAuditListener.java", THIRD_MESSAGE);
86
87 final TreeWalkerAuditEvent event4 = createTreeWalkerAuditEvent(
88 "InputXpathFileGeneratorAuditListener.java", FOURTH_MESSAGE);
89
90 final XpathFileGeneratorAstFilter astFilter = new XpathFileGeneratorAstFilter();
91 astFilter.accept(event1);
92 astFilter.accept(event2);
93 astFilter.accept(event3);
94 astFilter.accept(event4);
95 }
96
97 @Test
98 public void testFinishLocalSetup() {
99 final OutputStream out = new ByteArrayOutputStream();
100 final XpathFileGeneratorAuditListener listener =
101 new XpathFileGeneratorAuditListener(out, OutputStreamOptions.CLOSE);
102
103 listener.finishLocalSetup();
104 listener.auditStarted(null);
105 listener.auditFinished(null);
106 final String actual = out.toString();
107 assertWithMessage("Output should be empty")
108 .that(actual)
109 .isEmpty();
110 }
111
112 @Test
113 public void testFileStarted() {
114 final OutputStream out = new ByteArrayOutputStream();
115 final XpathFileGeneratorAuditListener listener =
116 new XpathFileGeneratorAuditListener(out, OutputStreamOptions.CLOSE);
117 final AuditEvent ev = new AuditEvent(this, "Test.java", null);
118 listener.fileStarted(ev);
119 listener.auditFinished(null);
120 final String actual = out.toString();
121 assertWithMessage("Output should be empty")
122 .that(actual)
123 .isEmpty();
124 }
125
126 @Test
127 public void testFileFinished() {
128 final OutputStream out = new ByteArrayOutputStream();
129 final XpathFileGeneratorAuditListener listener =
130 new XpathFileGeneratorAuditListener(out, OutputStreamOptions.CLOSE);
131 final AuditEvent ev = new AuditEvent(this, "Test.java", null);
132 listener.fileFinished(ev);
133 listener.auditFinished(null);
134 final String actual = out.toString();
135 assertWithMessage("Output should be empty")
136 .that(actual)
137 .isEmpty();
138 }
139
140 @Test
141 public void testAddException() {
142 final OutputStream out = new ByteArrayOutputStream();
143 final XpathFileGeneratorAuditListener logger =
144 new XpathFileGeneratorAuditListener(out, OutputStreamOptions.CLOSE);
145 logger.auditStarted(null);
146 final Violation violation =
147 new Violation(1, 1,
148 "messages.properties", null, null, null, getClass(), null);
149 final AuditEvent ev = new AuditEvent(this, "Test.java", violation);
150
151 final UnsupportedOperationException exception =
152 getExpectedThrowable(UnsupportedOperationException.class,
153 () -> logger.addException(ev, null));
154 assertWithMessage("Invalid exception message")
155 .that(exception.getMessage())
156 .isEqualTo("Operation is not supported");
157 }
158
159 @Test
160 public void testCorrectOne() {
161 final AuditEvent event = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
162 FIRST_MESSAGE);
163
164 final String expected =
165 """
166 <?xml version="1.0" encoding="UTF-8"?>
167 <!DOCTYPE suppressions PUBLIC
168 "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
169 "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
170 <suppressions>
171 <suppress-xpath
172 files="InputXpathFileGeneratorAuditListener.java"
173 checks="LeftCurlyCheck"
174 query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
175 [@text='InputXpathFileGeneratorAuditListener']]/OBJBLOCK/LCURLY"/>
176 </suppressions>
177 """.replace("\n", EOL);
178
179 verifyOutput(expected, event);
180 }
181
182 @Test
183 public void testCorrectTwo() {
184 final AuditEvent event1 = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
185 SECOND_MESSAGE);
186
187 final AuditEvent event2 = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
188 THIRD_MESSAGE);
189
190 final String expected =
191 """
192 <?xml version="1.0" encoding="UTF-8"?>
193 <!DOCTYPE suppressions PUBLIC
194 "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
195 "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
196 <suppressions>
197 <suppress-xpath
198 files="InputXpathFileGeneratorAuditListener.java"
199 id="MyModule"
200 query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
201 [@text='InputXpathFileGeneratorAuditListener']]/OBJBLOCK/METHOD_DEF[./IDENT\
202 [@text='sort']]"/>
203 <suppress-xpath
204 files="InputXpathFileGeneratorAuditListener.java"
205 checks="NestedForDepthCheck"
206 query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
207 [@text='InputXpathFileGeneratorAuditListener']]/OBJBLOCK/METHOD_DEF[./IDENT\
208 [@text='sort']]/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR"/>
209 </suppressions>
210 """.replace("\n", EOL);
211
212 verifyOutput(expected, event1, event2);
213 }
214
215 @Test
216 public void testOnlyOneMatching() {
217 final AuditEvent event1 = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
218 10, 5, MethodParamPadCheck.class);
219
220 final AuditEvent event2 = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
221 5, 5, JavadocVariableCheck.class);
222
223 final AuditEvent event3 = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
224 FOURTH_MESSAGE);
225
226 final String expected =
227 """
228 <?xml version="1.0" encoding="UTF-8"?>
229 <!DOCTYPE suppressions PUBLIC
230 "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
231 "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
232 <suppressions>
233 <suppress-xpath
234 files="InputXpathFileGeneratorAuditListener.java"
235 id="JavadocModuleId"
236 query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
237 [@text='InputXpathFileGeneratorAuditListener']]/OBJBLOCK/VARIABLE_DEF[./IDENT\
238 [@text='isValid']]"/>
239 </suppressions>
240 """.replace("\n", EOL);
241
242 verifyOutput(expected, event1, event2, event3);
243 }
244
245 @Test
246 public void testFileNameWithXmlSpecialCharacter() {
247 final AuditEvent event = createAuditEvent("Input&XpathFileGenerator.java",
248 FIRST_MESSAGE);
249
250 final String expected =
251 """
252 <?xml version="1.0" encoding="UTF-8"?>
253 <!DOCTYPE suppressions PUBLIC
254 "-//Checkstyle//DTD SuppressionXpathFilter Configuration 1.2//EN"
255 "https://checkstyle.org/dtds/suppressions_1_2_xpath.dtd">
256 <suppressions>
257 <suppress-xpath
258 files="Input&XpathFileGenerator.java"
259 checks="LeftCurlyCheck"
260 query="/COMPILATION_UNIT/CLASS_DEF[./IDENT\
261 [@text='InputXpathFileGeneratorAuditListener']]/OBJBLOCK/LCURLY"/>
262 </suppressions>
263 """.replace("\n", EOL);
264
265 verifyOutput(expected, event);
266 }
267
268 @Test
269 public void testCloseStream() {
270 final XpathFileGeneratorAuditListener listener =
271 new XpathFileGeneratorAuditListener(outStream, OutputStreamOptions.CLOSE);
272 listener.finishLocalSetup();
273 listener.auditStarted(null);
274 listener.auditFinished(null);
275
276 assertWithMessage("Invalid close count")
277 .that(outStream.getCloseCount())
278 .isEqualTo(1);
279 }
280
281 @Test
282 public void testNoCloseStream() {
283 final XpathFileGeneratorAuditListener listener =
284 new XpathFileGeneratorAuditListener(outStream, OutputStreamOptions.NONE);
285 listener.finishLocalSetup();
286 listener.auditStarted(null);
287 listener.auditFinished(null);
288
289 assertWithMessage("Invalid close count")
290 .that(outStream.getCloseCount())
291 .isEqualTo(0);
292 }
293
294 @Test
295 public void testNullOutputStreamOptions() {
296 final OutputStream out = new ByteArrayOutputStream();
297 final IllegalArgumentException exception =
298 getExpectedThrowable(IllegalArgumentException.class,
299 () -> new XpathFileGeneratorAuditListener(out, null));
300 assertWithMessage("Invalid error message")
301 .that(exception.getMessage())
302 .isEqualTo("Parameter outputStreamOptions can not be null");
303 }
304
305 private AuditEvent createAuditEvent(String fileName, Violation violation) {
306 return new AuditEvent(this,
307 getPath(fileName), violation);
308 }
309
310 private AuditEvent createAuditEvent(String fileName, int lineNumber, int columnNumber,
311 Class<?> sourceClass) {
312 final Violation violation =
313 new Violation(lineNumber, columnNumber, "messages.properties", null,
314 null, null, sourceClass, null);
315
316 return new AuditEvent(this,
317 getPath(fileName), violation);
318 }
319
320 private static Violation createViolation(int lineNumber,
321 int columnNumber, int tokenType,
322 String moduleId,
323 Class<?> sourceClass) {
324 return new Violation(lineNumber, columnNumber, tokenType,
325 "messages.properties", null, null,
326 SeverityLevel.ERROR, moduleId, sourceClass, null);
327 }
328
329 private static TreeWalkerAuditEvent createTreeWalkerAuditEvent(String fileName,
330 Violation violation)
331 throws Exception {
332 final File file = new File(getPath(fileName));
333 final FileText fileText = new FileText(
334 file.getAbsoluteFile(),
335 System.getProperty("file.encoding", StandardCharsets.UTF_8.name()));
336 final FileContents fileContents = new FileContents(fileText);
337 final DetailAST rootAst = JavaParser.parseFile(file, JavaParser.Options.WITHOUT_COMMENTS);
338
339 return new TreeWalkerAuditEvent(fileContents, fileName,
340 violation, rootAst);
341 }
342
343 private static String getPath(String filename) {
344 return "src/test/resources/com/puppycrawl/tools/checkstyle/xpathfilegeneratorauditlistener/"
345 + filename;
346 }
347
348 private static void verifyOutput(String expected, AuditEvent... events) {
349 final TestByteArrayOutputStream out = new TestByteArrayOutputStream();
350
351 final XpathFileGeneratorAuditListener listener =
352 new XpathFileGeneratorAuditListener(out, OutputStreamOptions.CLOSE);
353
354 for (AuditEvent event : events) {
355 listener.addError(event);
356 }
357
358 listener.auditFinished(null);
359
360 assertWithMessage("Output stream flush count")
361 .that(out.flushCount)
362 .isEqualTo(TestUtil.adjustFlushCountForOutputStreamClose(1));
363 assertWithMessage("Output stream close count")
364 .that(out.closeCount)
365 .isEqualTo(1);
366
367 final String actual = out.toString(StandardCharsets.UTF_8);
368 assertWithMessage("Invalid suppressions file content")
369 .that(actual)
370 .isEqualTo(expected);
371 }
372
373 private static final class TestByteArrayOutputStream extends ByteArrayOutputStream {
374
375 private int closeCount;
376 private int flushCount;
377
378 @Override
379 public void close() {
380 closeCount++;
381 }
382
383 @Override
384 public void flush() {
385 flushCount++;
386 }
387
388 }
389
390 }