View Javadoc
1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2017 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.utils;
21  
22  import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.isUtilsClassHasPrivateConstructor;
23  import static org.junit.Assert.assertEquals;
24  import static org.junit.Assert.assertFalse;
25  import static org.junit.Assert.assertSame;
26  import static org.junit.Assert.assertTrue;
27  import static org.junit.Assert.fail;
28  import static org.powermock.api.mockito.PowerMockito.mock;
29  import static org.powermock.api.mockito.PowerMockito.mockStatic;
30  import static org.powermock.api.mockito.PowerMockito.when;
31  
32  import java.io.Closeable;
33  import java.io.File;
34  import java.io.IOException;
35  import java.lang.reflect.Constructor;
36  import java.net.URISyntaxException;
37  import java.net.URL;
38  import java.util.Dictionary;
39  import java.util.regex.Pattern;
40  
41  import org.junit.Test;
42  import org.junit.runner.RunWith;
43  import org.mockito.Mockito;
44  import org.powermock.core.classloader.annotations.PrepareForTest;
45  import org.powermock.modules.junit4.PowerMockRunner;
46  
47  import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
48  import com.puppycrawl.tools.checkstyle.api.DetailAST;
49  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
50  
51  @RunWith(PowerMockRunner.class)
52  public class CommonUtilsTest {
53  
54      /** After appending to path produces equivalent, but denormalized path. */
55      private static final String PATH_DENORMALIZER = "/levelDown/.././";
56  
57      @Test
58      public void testIsProperUtilsClass() throws ReflectiveOperationException {
59          assertTrue("Constructor is not private",
60                  isUtilsClassHasPrivateConstructor(CommonUtils.class, true));
61      }
62  
63      /**
64       * Test CommonUtils.countCharInString.
65       */
66      @Test
67      public void testLengthExpandedTabs() {
68          final String s1 = "\t";
69          assertEquals("Invalid expanded tabs length", 8,
70              CommonUtils.lengthExpandedTabs(s1, s1.length(), 8));
71  
72          final String s2 = "  \t";
73          assertEquals("Invalid expanded tabs length", 8,
74              CommonUtils.lengthExpandedTabs(s2, s2.length(), 8));
75  
76          final String s3 = "\t\t";
77          assertEquals("Invalid expanded tabs length", 16,
78              CommonUtils.lengthExpandedTabs(s3, s3.length(), 8));
79  
80          final String s4 = " \t ";
81          assertEquals("Invalid expanded tabs length", 9,
82              CommonUtils.lengthExpandedTabs(s4, s4.length(), 8));
83  
84          assertEquals("Invalid expanded tabs length", 0,
85              CommonUtils.lengthMinusTrailingWhitespace(""));
86          assertEquals("Invalid expanded tabs length", 0,
87              CommonUtils.lengthMinusTrailingWhitespace(" \t "));
88          assertEquals("Invalid expanded tabs length", 3,
89              CommonUtils.lengthMinusTrailingWhitespace(" 23"));
90          assertEquals("Invalid expanded tabs length", 3,
91              CommonUtils.lengthMinusTrailingWhitespace(" 23 \t "));
92      }
93  
94      @Test
95      public void testCreatePattern() {
96          assertEquals("invalid pattern", "Test", CommonUtils.createPattern("Test").pattern());
97          assertEquals("invalid pattern", ".*Pattern.*", CommonUtils.createPattern(".*Pattern.*")
98                  .pattern());
99      }
100 
101     @Test
102     public void testBadRegex() {
103         try {
104             CommonUtils.createPattern("[");
105             fail("exception expected");
106         }
107         catch (IllegalArgumentException ex) {
108             assertEquals("Invalid exception message",
109                 "Failed to initialise regular expression [", ex.getMessage());
110         }
111     }
112 
113     @Test
114     public void testBadRegex2() {
115         try {
116             CommonUtils.createPattern("[", Pattern.MULTILINE);
117             fail("exception expected");
118         }
119         catch (IllegalArgumentException ex) {
120             assertEquals("Invalid exception message",
121                 "Failed to initialise regular expression [", ex.getMessage());
122         }
123     }
124 
125     @Test
126     public void testCreationOfFakeCommentBlock() {
127         final DetailAST testCommentBlock =
128                 CommonUtils.createBlockCommentNode("test_comment");
129         assertEquals("Invalid token type",
130                 TokenTypes.BLOCK_COMMENT_BEGIN, testCommentBlock.getType());
131         assertEquals("Invalid text", "/*", testCommentBlock.getText());
132         assertEquals("Invalid line number", 0, testCommentBlock.getLineNo());
133 
134         final DetailAST contentCommentBlock = testCommentBlock.getFirstChild();
135         assertEquals("Invalid token type",
136                 TokenTypes.COMMENT_CONTENT, contentCommentBlock.getType());
137         assertEquals("Invalid text", "*test_comment", contentCommentBlock.getText());
138         assertEquals("Invalid line number", 0, contentCommentBlock.getLineNo());
139         assertEquals("Invalid column number", -1, contentCommentBlock.getColumnNo());
140 
141         final DetailAST endCommentBlock = contentCommentBlock.getNextSibling();
142         assertEquals("Invalid token type", TokenTypes.BLOCK_COMMENT_END, endCommentBlock.getType());
143         assertEquals("Invalid text", "*/", endCommentBlock.getText());
144     }
145 
146     @Test
147     public void testFileExtensions() {
148         final String[] fileExtensions = {"java"};
149         final File pdfFile = new File("file.pdf");
150         assertFalse("Invalid file extension",
151             CommonUtils.matchesFileExtension(pdfFile, fileExtensions));
152         assertTrue("Invalid file extension",
153             CommonUtils.matchesFileExtension(pdfFile));
154         assertTrue("Invalid file extension",
155             CommonUtils.matchesFileExtension(pdfFile, (String[]) null));
156         final File javaFile = new File("file.java");
157         assertTrue("Invalid file extension",
158             CommonUtils.matchesFileExtension(javaFile, fileExtensions));
159         final File emptyExtensionFile = new File("file.");
160         assertTrue("Invalid file extension",
161             CommonUtils.matchesFileExtension(emptyExtensionFile, ""));
162         assertFalse("Invalid file extension",
163             CommonUtils.matchesFileExtension(pdfFile, ".noMatch"));
164         assertTrue("Invalid file extension",
165             CommonUtils.matchesFileExtension(pdfFile, ".pdf"));
166     }
167 
168     @Test
169     public void testHasWhitespaceBefore() {
170         assertTrue("Invalid result",
171             CommonUtils.hasWhitespaceBefore(0, "a"));
172         assertTrue("Invalid result",
173             CommonUtils.hasWhitespaceBefore(4, "    a"));
174         assertFalse("Invalid result",
175             CommonUtils.hasWhitespaceBefore(5, "    a"));
176     }
177 
178     @Test
179     public void testBaseClassNameForCanonicalName() {
180         assertEquals("Invalid base class name", "List",
181             CommonUtils.baseClassName("java.util.List"));
182     }
183 
184     @Test
185     public void testBaseClassNameForSimpleName() {
186 
187         assertEquals("Invalid base class name", "Set",
188             CommonUtils.baseClassName("Set"));
189     }
190 
191     @Test
192     public void testRelativeNormalizedPath() {
193         final String relativePath = CommonUtils.relativizeAndNormalizePath("/home", "/home/test");
194 
195         assertEquals("Invalid relative path", "test", relativePath);
196     }
197 
198     @Test
199     public void testRelativeNormalizedPathWithNullBaseDirectory() {
200         final String relativePath = CommonUtils.relativizeAndNormalizePath(null, "/tmp");
201 
202         assertEquals("Invalid relative path", "/tmp", relativePath);
203     }
204 
205     @Test
206     public void testRelativeNormalizedPathWithDenormalizedBaseDirectory() throws IOException {
207         final String sampleAbsolutePath = new File("src/main/java").getCanonicalPath();
208         final String absoluteFilePath = sampleAbsolutePath + "/SampleFile.java";
209         final String basePath = sampleAbsolutePath + PATH_DENORMALIZER;
210 
211         final String relativePath = CommonUtils.relativizeAndNormalizePath(basePath,
212             absoluteFilePath);
213 
214         assertEquals("Invalid relative path", "SampleFile.java", relativePath);
215     }
216 
217     @Test
218     public void testInvalidPattern() {
219         final boolean result = CommonUtils.isPatternValid("some[invalidPattern");
220         assertFalse("Should return false when pattern is invalid", result);
221     }
222 
223     @Test
224     public void testGetExistingConstructor() throws NoSuchMethodException {
225         final Constructor<?> constructor = CommonUtils.getConstructor(String.class, String.class);
226 
227         assertEquals("Invalid constructor",
228             String.class.getConstructor(String.class), constructor);
229     }
230 
231     @Test
232     public void testGetNonExistentConstructor() {
233         try {
234             CommonUtils.getConstructor(Math.class);
235             fail("IllegalStateException is expected");
236         }
237         catch (IllegalStateException expected) {
238             assertSame("Invalid exception cause",
239                 NoSuchMethodException.class, expected.getCause().getClass());
240         }
241     }
242 
243     @Test
244     public void testInvokeConstructor() throws NoSuchMethodException {
245         final Constructor<String> constructor = String.class.getConstructor(String.class);
246 
247         final String constructedString = CommonUtils.invokeConstructor(constructor, "string");
248 
249         assertEquals("Invalid construction result", "string", constructedString);
250     }
251 
252     @SuppressWarnings("rawtypes")
253     @Test
254     public void testInvokeConstructorThatFails() throws NoSuchMethodException {
255         final Constructor<Dictionary> constructor = Dictionary.class.getConstructor();
256 
257         try {
258             CommonUtils.invokeConstructor(constructor);
259             fail("IllegalStateException is expected");
260         }
261         catch (IllegalStateException expected) {
262             assertSame("Invalid exception cause", InstantiationException.class,
263                 expected.getCause().getClass());
264         }
265     }
266 
267     @Test
268     public void testClose() {
269         final TestCloseable closeable = new TestCloseable();
270 
271         CommonUtils.close(null);
272         CommonUtils.close(closeable);
273 
274         assertTrue("Should be closed", closeable.closed);
275     }
276 
277     @Test
278     public void testCloseWithException() {
279         try {
280             CommonUtils.close(() -> {
281                 throw new IOException("Test IOException");
282             });
283             fail("exception expected");
284         }
285         catch (IllegalStateException ex) {
286             assertEquals("Invalid exception message",
287                 "Cannot close the stream", ex.getMessage());
288         }
289     }
290 
291     @Test
292     public void testFillTemplateWithStringsByRegexp() {
293         assertEquals("invalid result", "template", CommonUtils.fillTemplateWithStringsByRegexp(
294                 "template", "lineToPlaceInTemplate", Pattern.compile("NO MATCH")));
295         assertEquals(
296                 "invalid result",
297                 "before word after",
298                 CommonUtils.fillTemplateWithStringsByRegexp("before $0 after", "word",
299                         Pattern.compile("\\w+")));
300         assertEquals("invalid result", "before word 123 after1 word after2 123 after3",
301                 CommonUtils.fillTemplateWithStringsByRegexp("before $0 after1 $1 after2 $2 after3",
302                         "word 123", Pattern.compile("(\\w+) (\\d+)")));
303     }
304 
305     @Test
306     public void testGetFileNameWithoutExtension() {
307         assertEquals("invalid result", "filename",
308                 CommonUtils.getFileNameWithoutExtension("filename"));
309         assertEquals("invalid result", "filename",
310                 CommonUtils.getFileNameWithoutExtension("filename.extension"));
311         assertEquals("invalid result", "filename.subext",
312                 CommonUtils.getFileNameWithoutExtension("filename.subext.extension"));
313     }
314 
315     @Test
316     public void testGetFileExtension() {
317         assertEquals("Invalid extension", "", CommonUtils.getFileExtension("filename"));
318         assertEquals("Invalid extension", "extension",
319                 CommonUtils.getFileExtension("filename.extension"));
320         assertEquals("Invalid extension", "extension",
321                 CommonUtils.getFileExtension("filename.subext.extension"));
322     }
323 
324     @Test
325     public void testIsIdentifier() {
326         assertTrue("Should return true when valid identifier is passed",
327             CommonUtils.isIdentifier("aValidIdentifier"));
328     }
329 
330     @Test
331     public void testIsIdentifierEmptyString() {
332         assertFalse("Should return false when empty string is passed",
333             CommonUtils.isIdentifier(""));
334     }
335 
336     @Test
337     public void testIsIdentifierInvalidFirstSymbol() {
338         assertFalse("Should return false when invalid identifier is passed",
339             CommonUtils.isIdentifier("1InvalidIdentifier"));
340     }
341 
342     @Test
343     public void testIsIdentifierInvalidSymbols() {
344         assertFalse("Should return false when invalid identifier is passed",
345             CommonUtils.isIdentifier("invalid#Identifier"));
346     }
347 
348     @Test
349     public void testIsName() {
350         assertTrue("Should return true when valid name is passed",
351             CommonUtils.isName("a.valid.Nam3"));
352     }
353 
354     @Test
355     public void testIsNameEmptyString() {
356         assertFalse("Should return false when empty string is passed",
357             CommonUtils.isName(""));
358     }
359 
360     @Test
361     public void testIsNameInvalidFirstSymbol() {
362         assertFalse("Should return false when invalid name is passed",
363             CommonUtils.isName("1.invalid.name"));
364     }
365 
366     @Test
367     public void testIsNameEmptyPart() {
368         assertFalse("Should return false when name has empty part",
369             CommonUtils.isName("invalid..name"));
370     }
371 
372     @Test
373     public void testIsNameEmptyLastPart() {
374         assertFalse("Should return false when name has empty part",
375             CommonUtils.isName("invalid.name."));
376     }
377 
378     @Test
379     public void testIsNameInvalidSymbol() {
380         assertFalse("Should return false when invalid name is passed",
381             CommonUtils.isName("invalid.name#42"));
382     }
383 
384     @Test
385     public void testIsBlank() {
386         assertFalse("Should return false when string is not empty",
387             CommonUtils.isBlank("string"));
388     }
389 
390     @Test
391     public void testIsBlankAheadWhitespace() {
392         assertFalse("Should return false when string is not empty",
393             CommonUtils.isBlank("  string"));
394     }
395 
396     @Test
397     public void testIsBlankBehindWhitespace() {
398         assertFalse("Should return false when string is not empty",
399             CommonUtils.isBlank("string    "));
400     }
401 
402     @Test
403     public void testIsBlankWithWhitespacesAround() {
404         assertFalse("Should return false when string is not empty",
405             CommonUtils.isBlank("    string    "));
406     }
407 
408     @Test
409     public void testIsBlankWhitespaceInside() {
410         assertFalse("Should return false when string is not empty",
411             CommonUtils.isBlank("str    ing"));
412     }
413 
414     @Test
415     public void testIsBlankNullString() {
416         assertTrue("Should return true when string is null",
417             CommonUtils.isBlank(null));
418     }
419 
420     @Test
421     public void testIsBlankWithEmptyString() {
422         assertTrue("Should return true when string is empty",
423             CommonUtils.isBlank(""));
424     }
425 
426     @Test
427     public void testIsBlankWithWhitespacesOnly() {
428         assertTrue("Should return true when string contains only spaces",
429             CommonUtils.isBlank("   "));
430     }
431 
432     @Test
433     @PrepareForTest({ CommonUtils.class, CommonUtilsTest.class })
434     @SuppressWarnings("unchecked")
435     public void testLoadSuppressionsUriSyntaxException() throws Exception {
436         final URL configUrl = mock(URL.class);
437 
438         when(configUrl.toURI()).thenThrow(URISyntaxException.class);
439         mockStatic(CommonUtils.class, Mockito.CALLS_REAL_METHODS);
440         final String fileName = "suppressions_none.xml";
441         when(CommonUtils.class.getResource(fileName)).thenReturn(configUrl);
442 
443         try {
444             CommonUtils.getUriByFilename(fileName);
445             fail("Exception is expected");
446         }
447         catch (CheckstyleException ex) {
448             assertTrue("Invalid exception cause", ex.getCause() instanceof URISyntaxException);
449             assertEquals("Invalid exception message",
450                 "Unable to find: " + fileName, ex.getMessage());
451         }
452     }
453 
454     @Test
455     public void testIsIntValidString() {
456         assertTrue("Should return true when string is null", CommonUtils.isInt("42"));
457     }
458 
459     @Test
460     public void testIsIntInvalidString() {
461         assertFalse("Should return false when object passed is not integer",
462             CommonUtils.isInt("foo"));
463     }
464 
465     @Test
466     public void testIsIntNull() {
467         assertFalse("Should return false when null is passed",
468             CommonUtils.isInt(null));
469     }
470 
471     private static class TestCloseable implements Closeable {
472         private boolean closed;
473 
474         @Override
475         public void close() {
476             closed = true;
477         }
478     }
479 }