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.assertTrue;
25  import static org.junit.Assert.fail;
26  
27  import java.lang.reflect.Field;
28  import java.lang.reflect.Modifier;
29  import java.util.Arrays;
30  import java.util.Optional;
31  
32  import org.junit.Test;
33  
34  import com.puppycrawl.tools.checkstyle.api.DetailAST;
35  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
36  
37  public class TokenUtilsTest {
38  
39      @Test
40      public void testIsProperUtilsClass() throws ReflectiveOperationException {
41          assertTrue("Constructor is not private",
42                  isUtilsClassHasPrivateConstructor(TokenUtils.class, true));
43      }
44  
45      @Test
46      public void testGetIntFromAccessibleField() throws NoSuchFieldException {
47          final Field field = Integer.class.getField("MAX_VALUE");
48  
49          assertEquals("Invalid getIntFromField result",
50                  Integer.MAX_VALUE, TokenUtils.getIntFromField(field, 0));
51      }
52  
53      @Test
54      public void testGetIntFromInaccessibleField() throws NoSuchFieldException {
55          final Field field = Integer.class.getDeclaredField("value");
56  
57          try {
58              TokenUtils.getIntFromField(field, 0);
59              fail("IllegalStateException is expected");
60          }
61          catch (IllegalStateException expected) {
62              assertTrue("Invalid exception message: " + expected.getMessage(),
63                      expected.getMessage().startsWith("java.lang.IllegalAccessException: Class"
64                  + " com.puppycrawl.tools.checkstyle.utils.TokenUtils"
65                  + " can not access a member of class java.lang.Integer with modifiers "));
66          }
67      }
68  
69      @Test
70      public void testTokenValueIncorrect() throws IllegalAccessException {
71          int maxId = 0;
72          final Field[] fields = TokenTypes.class.getDeclaredFields();
73          for (final Field field : fields) {
74              // Only process the int declarations.
75              if (field.getType() != Integer.TYPE) {
76                  continue;
77              }
78  
79              final String name = field.getName();
80              final int id = field.getInt(name);
81              if (id > maxId) {
82                  maxId = id;
83              }
84          }
85  
86          final int nextAfterMaxId = maxId + 1;
87          try {
88              TokenUtils.getTokenName(nextAfterMaxId);
89              fail("IllegalArgumentException is expected");
90          }
91          catch (IllegalArgumentException expected) {
92              assertEquals("Invalid exception message",
93                      "given id " + nextAfterMaxId, expected.getMessage());
94          }
95      }
96  
97      @Test
98      public void testTokenValueCorrect() throws IllegalAccessException {
99          final Field[] fields = TokenTypes.class.getDeclaredFields();
100         for (final Field field : fields) {
101             // Only process the int declarations.
102             if (field.getType() != Integer.TYPE) {
103                 continue;
104             }
105 
106             final String name = field.getName();
107             final int id = field.getInt(name);
108 
109             assertEquals("Invalid token name", name, TokenUtils.getTokenName(id));
110         }
111     }
112 
113     @Test
114     public void testTokenValueIncorrect2() throws Exception {
115         final Integer id = 0;
116         String[] originalValue = null;
117         Field fieldToken = null;
118         try {
119             // overwrite static field with new value
120             final Field[] fields = TokenUtils.class.getDeclaredFields();
121             for (Field field : fields) {
122                 field.setAccessible(true);
123                 if ("TOKEN_VALUE_TO_NAME".equals(field.getName())) {
124                     fieldToken = field;
125                     final Field modifiersField = Field.class.getDeclaredField("modifiers");
126                     modifiersField.setAccessible(true);
127                     modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
128                     originalValue = (String[]) field.get(null);
129                     field.set(null, new String[] {null});
130                 }
131             }
132 
133             TokenUtils.getTokenName(id);
134             fail("IllegalArgumentException is expected");
135         }
136         catch (IllegalArgumentException expected) {
137             // restoring original value, to let other tests pass
138             fieldToken.set(null, originalValue);
139 
140             assertEquals("Invalid exception message",
141                     "given id " + id, expected.getMessage());
142 
143         }
144     }
145 
146     @Test
147     public void testTokenIdIncorrect() {
148         final String id = "NON_EXISTENT_VALUE";
149         try {
150             TokenUtils.getTokenId(id);
151             fail("IllegalArgumentException is expected");
152         }
153         catch (IllegalArgumentException expected) {
154             assertEquals("Invalid exception message",
155                     "given name " + id, expected.getMessage());
156         }
157     }
158 
159     @Test
160     public void testShortDescriptionIncorrect() {
161         final String id = "NON_EXISTENT_VALUE";
162         try {
163             TokenUtils.getShortDescription(id);
164             fail("IllegalArgumentException is expected");
165         }
166         catch (IllegalArgumentException expected) {
167             assertEquals("Invalid exception message",
168                     "given name " + id, expected.getMessage());
169         }
170     }
171 
172     @Test
173     public void testIsCommentType() {
174         assertTrue("Should return true when valid type passed",
175                 TokenUtils.isCommentType(TokenTypes.SINGLE_LINE_COMMENT));
176         assertTrue("Should return true when valid type passed",
177                 TokenUtils.isCommentType(TokenTypes.BLOCK_COMMENT_BEGIN));
178         assertTrue("Should return true when valid type passed",
179                 TokenUtils.isCommentType(TokenTypes.BLOCK_COMMENT_END));
180         assertTrue("Should return true when valid type passed",
181                 TokenUtils.isCommentType(TokenTypes.COMMENT_CONTENT));
182         assertTrue("Should return true when valid type passed",
183                 TokenUtils.isCommentType("COMMENT_CONTENT"));
184     }
185 
186     @Test
187     public void testGetTokenTypesTotalNumber() {
188         final int tokenTypesTotalNumber = TokenUtils.getTokenTypesTotalNumber();
189 
190         assertEquals("Invalid token total number", 169, tokenTypesTotalNumber);
191     }
192 
193     @Test
194     public void testGetAllTokenIds() {
195         final int[] allTokenIds = TokenUtils.getAllTokenIds();
196         final int sum = Arrays.stream(allTokenIds).sum();
197 
198         assertEquals("Invalid token length", 169, allTokenIds.length);
199         assertEquals("invalid sum", 15662, sum);
200     }
201 
202     @Test
203     public void testGetTokenNameWithGreatestPossibleId() {
204         final Integer id = TokenTypes.COMMENT_CONTENT;
205         final String tokenName = TokenUtils.getTokenName(id);
206 
207         assertEquals("Invalid token name", "COMMENT_CONTENT", tokenName);
208     }
209 
210     @Test
211     public void testCorrectBehaviourOfGetTokenId() {
212         final String id = "EOF";
213 
214         assertEquals("Invalid token id", TokenTypes.EOF, TokenUtils.getTokenId(id));
215 
216     }
217 
218     @Test
219     public void testCorrectBehaviourOfShortDescription() {
220         final String id = "EOF";
221         final String shortDescription = TokenUtils.getShortDescription(id);
222 
223         assertEquals("Invalid short description", "The end of file token.", shortDescription);
224     }
225 
226     @Test
227     public void testFindFirstTokenByPredicate() {
228         final DetailAST astForTest = new DetailAST();
229         final DetailAST child = new DetailAST();
230         final DetailAST firstSibling = new DetailAST();
231         final DetailAST secondSibling = new DetailAST();
232         final DetailAST thirdSibling = new DetailAST();
233         firstSibling.setText("first");
234         secondSibling.setText("second");
235         thirdSibling.setText("third");
236         secondSibling.setNextSibling(thirdSibling);
237         firstSibling.setNextSibling(secondSibling);
238         child.setNextSibling(firstSibling);
239         astForTest.setFirstChild(child);
240         final Optional<DetailAST> result = TokenUtils.findFirstTokenByPredicate(astForTest,
241             ast -> "second".equals(ast.getText()));
242 
243         assertEquals("Invalid second sibling", secondSibling, result.get());
244     }
245 }