View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 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  
24  import java.io.IOException;
25  import java.io.PrintWriter;
26  import java.util.List;
27  
28  import org.junit.jupiter.api.Test;
29  
30  import com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions;
31  import com.puppycrawl.tools.checkstyle.api.AuditEvent;
32  import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
33  import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
34  import com.puppycrawl.tools.checkstyle.api.Violation;
35  import com.puppycrawl.tools.checkstyle.internal.utils.CloseAndFlushTestByteArrayOutputStream;
36  import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
37  
38  /**
39   * Enter a description of class XMLLoggerTest.java.
40   */
41  // -@cs[AbbreviationAsWordInName] Test should be named as its main class.
42  public class XMLLoggerTest extends AbstractXmlTestSupport {
43  
44      /**
45       * Output stream to hold the test results. The IntelliJ IDEA issues the AutoCloseableResource
46       * warning here, so it needs to be suppressed. The {@code ByteArrayOutputStream} does not hold
47       * any resources that need to be released.
48       */
49      private final CloseAndFlushTestByteArrayOutputStream outStream =
50          new CloseAndFlushTestByteArrayOutputStream();
51  
52      @Override
53      protected String getPackageLocation() {
54          return "com/puppycrawl/tools/checkstyle/xmllogger";
55      }
56  
57      @Test
58      public void testEncode()
59              throws IOException {
60          final XMLLogger test = new XMLLogger(outStream, OutputStreamOptions.NONE);
61          assertWithMessage("should be able to create XMLLogger without issue")
62              .that(test)
63              .isNotNull();
64          final String[][] encodings = {
65              {"<", "&lt;"},
66              {">", "&gt;"},
67              {"'", "&apos;"},
68              {"\"", "&quot;"},
69              {"&", "&amp;"},
70              {"&lt;", "&amp;lt;"},
71              {"abc;", "abc;"},
72              {"&#0;", "&amp;#0;"},
73              {"&#0", "&amp;#0"},
74              {"&#X0;", "&amp;#X0;"},
75              {"\u0001", "#x1;"},
76              {"\u0080", "#x80;"},
77          };
78          for (String[] encoding : encodings) {
79              final String encoded = XMLLogger.encode(encoding[0]);
80              assertWithMessage("\"" + encoding[0] + "\"")
81                  .that(encoded)
82                  .isEqualTo(encoding[1]);
83          }
84          outStream.close();
85      }
86  
87      @Test
88      public void testIsReference()
89              throws IOException {
90          final XMLLogger test = new XMLLogger(outStream, OutputStreamOptions.NONE);
91          assertWithMessage("should be able to create XMLLogger without issue")
92              .that(test)
93              .isNotNull();
94          final String[] references = {
95              "&#0;",
96              "&#x0;",
97              "&lt;",
98              "&gt;",
99              "&apos;",
100             "&quot;",
101             "&amp;",
102         };
103         for (String reference : references) {
104             assertWithMessage("reference: " + reference)
105                     .that(XMLLogger.isReference(reference))
106                     .isTrue();
107         }
108         final String[] noReferences = {
109             "&",
110             "&;",
111             "&#;",
112             "&#a;",
113             "&#X0;",
114             "&#x;",
115             "&#xg;",
116             "ramp;",
117             "ref",
118         };
119         for (String noReference : noReferences) {
120             assertWithMessage("no reference: " + noReference)
121                     .that(XMLLogger.isReference(noReference))
122                     .isFalse();
123         }
124 
125         outStream.close();
126     }
127 
128     @Test
129     public void testCloseStream()
130             throws Exception {
131         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
132         logger.auditStarted(null);
133         logger.auditFinished(null);
134 
135         assertWithMessage("Invalid close count")
136             .that(outStream.getCloseCount())
137             .isEqualTo(1);
138 
139         verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream);
140     }
141 
142     @Test
143     public void testNoCloseStream()
144             throws Exception {
145         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.NONE);
146         logger.auditStarted(null);
147         logger.auditFinished(null);
148 
149         assertWithMessage("Invalid close count")
150             .that(outStream.getCloseCount())
151             .isEqualTo(0);
152 
153         outStream.close();
154         verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream);
155     }
156 
157     @Test
158     public void testFileStarted()
159             throws Exception {
160         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
161         logger.auditStarted(null);
162         final AuditEvent ev = new AuditEvent(this, "Test.java");
163         logger.fileStarted(ev);
164         logger.fileFinished(ev);
165         logger.auditFinished(null);
166         verifyXml(getPath("ExpectedXMLLogger.xml"), outStream);
167     }
168 
169     @Test
170     public void testFileFinished()
171             throws Exception {
172         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
173         logger.auditStarted(null);
174         final AuditEvent ev = new AuditEvent(this, "Test.java");
175         logger.fileFinished(ev);
176         logger.auditFinished(null);
177         verifyXml(getPath("ExpectedXMLLogger.xml"), outStream);
178     }
179 
180     @Test
181     public void testAddError() throws Exception {
182         verifyWithInlineConfigParserAndXmlLogger("InputXMLLoggerAddError.java",
183                 "ExpectedXMLLoggerAddError.xml");
184     }
185 
186     @Test
187     public void testAddErrorWithNullFileName() throws Exception {
188         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
189         logger.auditStarted(null);
190         final Violation violation =
191                 new Violation(1, 1,
192                         "messages.properties", "key", null, SeverityLevel.ERROR, null,
193                         getClass(), null);
194         final AuditEvent ev = new AuditEvent(this, null, violation);
195         logger.addError(ev);
196         logger.auditFinished(null);
197         verifyXml(getPath("ExpectedXMLLoggerErrorNullFileName.xml"), outStream,
198                 violation.getViolation());
199     }
200 
201     @Test
202     public void testAddErrorModuleId() throws Exception {
203         final String inputFile = "InputXMLLoggerErrorModuleId.java";
204         final String expectedXmlReport = "ExpectedXMLLoggerErrorModuleId.xml";
205         verifyWithInlineConfigParserAndXmlLogger(inputFile, expectedXmlReport);
206     }
207 
208     @Test
209     public void testAddErrorWithEncodedMessage() throws Exception {
210         final String inputFileWithConfig = "InputXMLLoggerEncodedMessage.java";
211         final String expectedXmlReport = "ExpectedXMLLoggerEncodedMessage.xml";
212         verifyWithInlineConfigParserAndXmlLogger(inputFileWithConfig, expectedXmlReport);
213     }
214 
215     @Test
216     public void testAddErrorOnZeroColumns() throws Exception {
217         verifyWithInlineConfigParserAndXmlLogger("InputXMLLoggerErrorOnZeroColumn.java",
218                 "ExpectedXMLLoggerErrorZeroColumn.xml");
219     }
220 
221     @Test
222     public void testAddIgnored() throws Exception {
223         final String inputFile = "InputXMLLoggerIgnored.java";
224         final String expectedXmlReport = "ExpectedXMLLoggerIgnored.xml";
225         verifyWithInlineConfigParserAndXmlLogger(inputFile, expectedXmlReport);
226     }
227 
228     @Test
229     public void testAddException()
230             throws Exception {
231         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
232         logger.auditStarted(null);
233         final Violation violation =
234             new Violation(1, 1,
235                 "messages.properties", null, null, null, getClass(), null);
236         final AuditEvent ev = new AuditEvent(this, "Test.java", violation);
237         logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
238         logger.auditFinished(null);
239         verifyXml(getPath("ExpectedXMLLoggerException.xml"), outStream);
240         assertWithMessage("Invalid close count")
241             .that(outStream.getCloseCount())
242             .isEqualTo(1);
243     }
244 
245     @Test
246     public void testAddExceptionWithNullFileName()
247             throws Exception {
248         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
249         logger.auditStarted(null);
250         final Violation violation =
251                 new Violation(1, 1,
252                         "messages.properties", null, null, null, getClass(), null);
253         final AuditEvent ev = new AuditEvent(this, null, violation);
254         logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
255         logger.auditFinished(null);
256         verifyXml(getPath("ExpectedXMLLoggerExceptionNullFileName.xml"), outStream);
257         assertWithMessage("Invalid close count")
258             .that(outStream.getCloseCount())
259             .isEqualTo(1);
260     }
261 
262     @Test
263     public void testAddExceptionAfterFileStarted()
264             throws Exception {
265         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
266         logger.auditStarted(null);
267 
268         final AuditEvent fileStartedEvent = new AuditEvent(this, "Test.java");
269         logger.fileStarted(fileStartedEvent);
270 
271         final Violation violation =
272                 new Violation(1, 1,
273                         "messages.properties", null, null, null, getClass(), null);
274         final AuditEvent ev = new AuditEvent(this, "Test.java", violation);
275         logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
276 
277         logger.fileFinished(ev);
278         logger.auditFinished(null);
279         verifyXml(getPath("ExpectedXMLLoggerException2.xml"), outStream);
280         assertWithMessage("Invalid close count")
281             .that(outStream.getCloseCount())
282             .isEqualTo(1);
283     }
284 
285     @Test
286     public void testAddExceptionBeforeFileFinished()
287             throws Exception {
288         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
289         logger.auditStarted(null);
290         final Violation violation =
291                 new Violation(1, 1,
292                         "messages.properties", null, null, null, getClass(), null);
293         final AuditEvent ev = new AuditEvent(this, "Test.java", violation);
294         logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
295         final AuditEvent fileFinishedEvent = new AuditEvent(this, "Test.java");
296         logger.fileFinished(fileFinishedEvent);
297         logger.auditFinished(null);
298         verifyXml(getPath("ExpectedXMLLoggerException3.xml"), outStream);
299         assertWithMessage("Invalid close count")
300             .that(outStream.getCloseCount())
301             .isEqualTo(1);
302     }
303 
304     @Test
305     public void testAddExceptionBetweenFileStartedAndFinished()
306             throws Exception {
307         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
308         logger.auditStarted(null);
309         final Violation violation =
310                 new Violation(1, 1,
311                         "messages.properties", null, null, null, getClass(), null);
312         final AuditEvent fileStartedEvent = new AuditEvent(this, "Test.java");
313         logger.fileStarted(fileStartedEvent);
314         final AuditEvent ev = new AuditEvent(this, "Test.java", violation);
315         logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
316         final AuditEvent fileFinishedEvent = new AuditEvent(this, "Test.java");
317         logger.fileFinished(fileFinishedEvent);
318         logger.auditFinished(null);
319         verifyXml(getPath("ExpectedXMLLoggerException2.xml"), outStream);
320         assertWithMessage("Invalid close count")
321             .that(outStream.getCloseCount())
322             .isEqualTo(1);
323     }
324 
325     @Test
326     public void testAuditFinishedWithoutFileFinished() throws Exception {
327         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
328         logger.auditStarted(null);
329         final AuditEvent fileStartedEvent = new AuditEvent(this, "Test.java");
330         logger.fileStarted(fileStartedEvent);
331 
332         final Violation violation =
333                 new Violation(1, 1,
334                         "messages.properties", "key", null, SeverityLevel.ERROR, null,
335                         getClass(), null);
336         final AuditEvent errorEvent = new AuditEvent(this, "Test.java", violation);
337         logger.addError(errorEvent);
338 
339         logger.fileFinished(errorEvent);
340         logger.auditFinished(null);
341         verifyXml(getPath("ExpectedXMLLoggerError.xml"), outStream, violation.getViolation());
342     }
343 
344     @Test
345     public void testFileOpenTag()
346             throws Exception {
347         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
348         logger.auditStarted(null);
349         final AuditEvent ev = new AuditEvent(this, "Test&.java");
350         logger.fileFinished(ev);
351         logger.auditFinished(null);
352         verifyXml(getPath("ExpectedXMLLoggerSpecialName.xml"),
353                 outStream, "<file name=" + "Test&amp;.java" + ">");
354 
355     }
356 
357     @Test
358     public void testVerifyLogger()
359             throws Exception {
360         final String inputFileWithConfig = "InputXMLLogger.java";
361         final String xmlReport = "ExpectedXMLLoggerWithChecker.xml";
362         verifyWithInlineConfigParserAndXmlLogger(inputFileWithConfig, xmlReport);
363     }
364 
365     @Test
366     public void testVerifyLoggerWithMultipleInput()
367             throws Exception {
368         final String inputFileWithConfig = "InputXMLLogger.java";
369         final String expectedXmlReport = "ExpectedXMLLoggerDuplicatedFile.xml";
370         verifyWithInlineConfigParserAndXmlLogger(
371                 inputFileWithConfig,
372                 expectedXmlReport,
373                 List.of(inputFileWithConfig, inputFileWithConfig));
374     }
375 
376     @Test
377     public void testNullOutputStreamOptions() {
378         try {
379             final XMLLogger logger = new XMLLogger(outStream,
380                     (OutputStreamOptions) null);
381             // assert required to calm down eclipse's 'The allocated object is never used' violation
382             assertWithMessage("Null instance")
383                 .that(logger)
384                 .isNotNull();
385             assertWithMessage("Exception was expected").fail();
386         }
387         catch (IllegalArgumentException exception) {
388             assertWithMessage("Invalid error message")
389                 .that(exception.getMessage())
390                 .isEqualTo("Parameter outputStreamOptions can not be null");
391         }
392     }
393 
394     @Test
395     public void testFinishLocalSetup() {
396         final XMLLogger logger = new XMLLogger(outStream, OutputStreamOptions.CLOSE);
397         logger.finishLocalSetup();
398         logger.auditStarted(null);
399         logger.auditFinished(null);
400         assertWithMessage("instance should not be null")
401             .that(logger)
402             .isNotNull();
403     }
404 
405     /**
406      * We keep this test for 100% coverage. Until #12873.
407      */
408     @Test
409     public void testCtorWithTwoParametersCloseStreamOptions() {
410         final XMLLogger logger = new XMLLogger(outStream, AutomaticBean.OutputStreamOptions.CLOSE);
411         final boolean closeStream = TestUtil.getInternalState(logger, "closeStream");
412 
413         assertWithMessage("closeStream should be true")
414                 .that(closeStream)
415                 .isTrue();
416     }
417 
418     /**
419      * We keep this test for 100% coverage. Until #12873.
420      */
421     @Test
422     public void testCtorWithTwoParametersNoneStreamOptions() {
423         final XMLLogger logger = new XMLLogger(outStream, AutomaticBean.OutputStreamOptions.NONE);
424         final boolean closeStream = TestUtil.getInternalState(logger, "closeStream");
425 
426         assertWithMessage("closeStream should be false")
427                 .that(closeStream)
428                 .isFalse();
429     }
430 
431     private static final class TestException extends RuntimeException {
432 
433         private static final long serialVersionUID = 1L;
434 
435         private TestException(String msg, Throwable cause) {
436             super(msg, cause);
437         }
438 
439         @Override
440         public void printStackTrace(PrintWriter printWriter) {
441             printWriter.print("stackTrace\r\nexample");
442         }
443 
444     }
445 
446 }