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.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          final URI uri = new URI("aaa://" + getPath("InputImportControlLoaderComplete.xml"));
64          try {
65              ImportControlLoader.load(uri);
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.getMessage())
74                  .isEqualTo("syntax error in url " + uri);
75              assertWithMessage("Invalid exception message")
76                  .that(exc)
77                  .hasCauseThat()
78                  .hasMessageThat()
79                  .isEqualTo("unknown protocol: aaa");
80          }
81      }
82  
83      @Test
84      public void testExtraElementInConfig() throws Exception {
85          final AbstractImportControl root =
86                  ImportControlLoader.load(
87                      new File(getPath("InputImportControlLoaderWithNewElement.xml")).toURI());
88          assertWithMessage("Import root should not be null")
89              .that(root)
90              .isNotNull();
91      }
92  
93      @Test
94      // UT uses Reflection to avoid removing null-validation from static method
95      public void testSafeGetThrowsException() {
96          final AttributesImpl attr = new AttributesImpl() {
97              @Override
98              public String getValue(int index) {
99                  return null;
100                 }
101             };
102         try {
103             final Class<?> clazz = ImportControlLoader.class;
104             TestUtil.invokeVoidStaticMethod(clazz, "safeGet", attr, "you_cannot_find_me");
105             assertWithMessage("exception expected").fail();
106         }
107         catch (ReflectiveOperationException exc) {
108             assertWithMessage("Invalid exception class")
109                 .that(exc.getCause())
110                 .isInstanceOf(SAXException.class);
111             assertWithMessage("Invalid exception message")
112                 .that(exc)
113                 .hasCauseThat()
114                 .hasMessageThat()
115                 .isEqualTo("missing attribute you_cannot_find_me");
116         }
117     }
118 
119     @Test
120     // UT uses Reflection to cover IOException from 'loader.parseInputSource(source);'
121     // because this is possible situation (though highly unlikely), which depends on hardware
122     // and is difficult to emulate
123     public void testLoadThrowsException() {
124         final InputSource source = new InputSource();
125         final URI uri = new File(getPath("InputImportControlLoaderComplete.xml")).toURI();
126         try {
127             final Class<?> clazz = ImportControlLoader.class;
128             TestUtil.invokeVoidStaticMethod(clazz, "load", source,
129                     uri);
130             assertWithMessage("exception expected").fail();
131         }
132         catch (ReflectiveOperationException exc) {
133             assertWithMessage("Invalid exception class")
134                 .that(exc.getCause())
135                 .isInstanceOf(CheckstyleException.class);
136             assertWithMessage("Invalid exception message: %s", exc.getCause().getMessage())
137                     .that(exc)
138                     .hasCauseThat()
139                     .hasMessageThat()
140                     .isEqualTo("unable to read " + uri);
141         }
142     }
143 
144     @Test
145     public void testInputStreamFailsOnRead() throws Exception {
146         try (InputStream inputStream = mock()) {
147             final int available = doThrow(IOException.class).when(inputStream).available();
148             final URL url = mock();
149             when(url.openStream()).thenReturn(inputStream);
150             final URI uri = mock();
151             when(uri.toURL()).thenReturn(url);
152 
153             final CheckstyleException ex = getExpectedThrowable(CheckstyleException.class, () -> {
154                 ImportControlLoader.load(uri);
155             });
156             assertWithMessage("Invalid exception class")
157                     .that(ex)
158                     .hasCauseThat()
159                             .isInstanceOf(SAXParseException.class);
160             // Workaround for warning "Result of InputStream.available() is ignored"
161             assertWithMessage("")
162                     .that(available)
163                     .isEqualTo(0);
164         }
165     }
166 
167 }