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.checks.imports;
21  
22  import static com.google.common.truth.Truth.assertWithMessage;
23  import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.getExpectedThrowable;
24  import static org.mockito.Mockito.doThrow;
25  import static org.mockito.Mockito.mock;
26  import static org.mockito.Mockito.when;
27  
28  import java.io.File;
29  import java.io.IOException;
30  import java.io.InputStream;
31  import java.net.MalformedURLException;
32  import java.net.URI;
33  import java.net.URL;
34  
35  import org.junit.jupiter.api.Test;
36  import org.xml.sax.InputSource;
37  import org.xml.sax.SAXException;
38  import org.xml.sax.SAXParseException;
39  import org.xml.sax.helpers.AttributesImpl;
40  
41  import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
42  import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
43  
44  public class ImportControlLoaderTest {
45  
46      private static String getPath(String filename) {
47          return "src/test/resources/com/puppycrawl/tools/"
48                  + "checkstyle/checks/imports/importcontrolloader/" + filename;
49      }
50  
51      @Test
52      public void testLoad() throws CheckstyleException {
53          final AbstractImportControl root =
54                  ImportControlLoader.load(
55                      new File(getPath("InputImportControlLoaderComplete.xml")).toURI());
56          assertWithMessage("Import root should not be null")
57              .that(root)
58              .isNotNull();
59      }
60  
61      @Test
62      public void testWrongFormatUri() throws Exception {
63          try {
64              ImportControlLoader.load(new URI("aaa://"
65                      + getPath("InputImportControlLoaderComplete.xml")));
66              assertWithMessage("exception expected").fail();
67          }
68          catch (CheckstyleException exc) {
69              assertWithMessage("Invalid exception class")
70                  .that(exc.getCause())
71                  .isInstanceOf(MalformedURLException.class);
72              assertWithMessage("Invalid exception message")
73                  .that(exc)
74                  .hasCauseThat()
75                  .hasMessageThat()
76                  .isEqualTo("unknown protocol: aaa");
77          }
78      }
79  
80      @Test
81      public void testExtraElementInConfig() throws Exception {
82          final AbstractImportControl root =
83                  ImportControlLoader.load(
84                      new File(getPath("InputImportControlLoaderWithNewElement.xml")).toURI());
85          assertWithMessage("Import root should not be null")
86              .that(root)
87              .isNotNull();
88      }
89  
90      @Test
91      // UT uses Reflection to avoid removing null-validation from static method
92      public void testSafeGetThrowsException() {
93          final AttributesImpl attr = new AttributesImpl() {
94              @Override
95              public String getValue(int index) {
96                  return null;
97                  }
98              };
99          try {
100             final Class<?> clazz = ImportControlLoader.class;
101             TestUtil.invokeStaticMethod(clazz, "safeGet", attr, "you_cannot_find_me");
102             assertWithMessage("exception expected").fail();
103         }
104         catch (ReflectiveOperationException exc) {
105             assertWithMessage("Invalid exception class")
106                 .that(exc.getCause())
107                 .isInstanceOf(SAXException.class);
108             assertWithMessage("Invalid exception message")
109                 .that(exc)
110                 .hasCauseThat()
111                 .hasMessageThat()
112                 .isEqualTo("missing attribute you_cannot_find_me");
113         }
114     }
115 
116     @Test
117     // UT uses Reflection to cover IOException from 'loader.parseInputSource(source);'
118     // because this is possible situation (though highly unlikely), which depends on hardware
119     // and is difficult to emulate
120     public void testLoadThrowsException() {
121         final InputSource source = new InputSource();
122         try {
123             final Class<?> clazz = ImportControlLoader.class;
124             TestUtil.invokeStaticMethod(clazz, "load", source,
125                     new File(getPath("InputImportControlLoaderComplete.xml")).toURI());
126             assertWithMessage("exception expected").fail();
127         }
128         catch (ReflectiveOperationException exc) {
129             assertWithMessage("Invalid exception class")
130                 .that(exc.getCause())
131                 .isInstanceOf(CheckstyleException.class);
132             assertWithMessage("Invalid exception message: " + exc.getCause().getMessage())
133                     .that(exc)
134                     .hasCauseThat()
135                     .hasMessageThat()
136                     .startsWith("unable to read");
137         }
138     }
139 
140     @Test
141     public void testInputStreamFailsOnRead() throws Exception {
142         try (InputStream inputStream = mock()) {
143             final int available = doThrow(IOException.class).when(inputStream).available();
144             final URL url = mock();
145             when(url.openStream()).thenReturn(inputStream);
146             final URI uri = mock();
147             when(uri.toURL()).thenReturn(url);
148 
149             final CheckstyleException ex = getExpectedThrowable(CheckstyleException.class, () -> {
150                 ImportControlLoader.load(uri);
151             });
152             assertWithMessage("Invalid exception class")
153                     .that(ex)
154                     .hasCauseThat()
155                             .isInstanceOf(SAXParseException.class);
156             // Workaround for warning "Result of InputStream.available() is ignored"
157             assertWithMessage("")
158                     .that(available)
159                     .isEqualTo(0);
160         }
161     }
162 
163 }