aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java
blob: 474479f87c0f6c43ef49b0fc2d2289615a4e97cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.utils;

import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.isUtilsClassHasPrivateConstructor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Optional;

import org.junit.Test;

import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;

public class TokenUtilsTest {

    @Test
    public void testIsProperUtilsClass() throws ReflectiveOperationException {
        assertTrue("Constructor is not private",
                isUtilsClassHasPrivateConstructor(TokenUtils.class, true));
    }

    @Test
    public void testGetIntFromAccessibleField() throws NoSuchFieldException {
        final Field field = Integer.class.getField("MAX_VALUE");

        assertEquals("Invalid getIntFromField result",
                Integer.MAX_VALUE, TokenUtils.getIntFromField(field, 0));
    }

    @Test
    public void testGetIntFromInaccessibleField() throws NoSuchFieldException {
        final Field field = Integer.class.getDeclaredField("value");

        try {
            TokenUtils.getIntFromField(field, 0);
            fail("IllegalStateException is expected");
        }
        catch (IllegalStateException expected) {
            assertTrue("Invalid exception message: " + expected.getMessage(),
                    expected.getMessage().startsWith("java.lang.IllegalAccessException: Class"
                + " com.puppycrawl.tools.checkstyle.utils.TokenUtils"
                + " can not access a member of class java.lang.Integer with modifiers "));
        }
    }

    @Test
    public void testTokenValueIncorrect() throws IllegalAccessException {
        int maxId = 0;
        final Field[] fields = TokenTypes.class.getDeclaredFields();
        for (final Field field : fields) {
            // Only process the int declarations.
            if (field.getType() != Integer.TYPE) {
                continue;
            }

            final String name = field.getName();
            final int id = field.getInt(name);
            if (id > maxId) {
                maxId = id;
            }
        }

        final int nextAfterMaxId = maxId + 1;
        try {
            TokenUtils.getTokenName(nextAfterMaxId);
            fail("IllegalArgumentException is expected");
        }
        catch (IllegalArgumentException expected) {
            assertEquals("Invalid exception message",
                    "given id " + nextAfterMaxId, expected.getMessage());
        }
    }

    @Test
    public void testTokenValueCorrect() throws IllegalAccessException {
        final Field[] fields = TokenTypes.class.getDeclaredFields();
        for (final Field field : fields) {
            // Only process the int declarations.
            if (field.getType() != Integer.TYPE) {
                continue;
            }

            final String name = field.getName();
            final int id = field.getInt(name);

            assertEquals("Invalid token name", name, TokenUtils.getTokenName(id));
        }
    }

    @Test
    public void testTokenValueIncorrect2() throws Exception {
        final Integer id = 0;
        String[] originalValue = null;
        Field fieldToken = null;
        try {
            // overwrite static field with new value
            final Field[] fields = TokenUtils.class.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if ("TOKEN_VALUE_TO_NAME".equals(field.getName())) {
                    fieldToken = field;
                    final Field modifiersField = Field.class.getDeclaredField("modifiers");
                    modifiersField.setAccessible(true);
                    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
                    originalValue = (String[]) field.get(null);
                    field.set(null, new String[] {null});
                }
            }

            TokenUtils.getTokenName(id);
            fail("IllegalArgumentException is expected");
        }
        catch (IllegalArgumentException expected) {
            // restoring original value, to let other tests pass
            fieldToken.set(null, originalValue);

            assertEquals("Invalid exception message",
                    "given id " + id, expected.getMessage());

        }
    }

    @Test
    public void testTokenIdIncorrect() {
        final String id = "NON_EXISTENT_VALUE";
        try {
            TokenUtils.getTokenId(id);
            fail("IllegalArgumentException is expected");
        }
        catch (IllegalArgumentException expected) {
            assertEquals("Invalid exception message",
                    "given name " + id, expected.getMessage());
        }
    }

    @Test
    public void testShortDescriptionIncorrect() {
        final String id = "NON_EXISTENT_VALUE";
        try {
            TokenUtils.getShortDescription(id);
            fail("IllegalArgumentException is expected");
        }
        catch (IllegalArgumentException expected) {
            assertEquals("Invalid exception message",
                    "given name " + id, expected.getMessage());
        }
    }

    @Test
    public void testIsCommentType() {
        assertTrue("Should return true when valid type passed",
                TokenUtils.isCommentType(TokenTypes.SINGLE_LINE_COMMENT));
        assertTrue("Should return true when valid type passed",
                TokenUtils.isCommentType(TokenTypes.BLOCK_COMMENT_BEGIN));
        assertTrue("Should return true when valid type passed",
                TokenUtils.isCommentType(TokenTypes.BLOCK_COMMENT_END));
        assertTrue("Should return true when valid type passed",
                TokenUtils.isCommentType(TokenTypes.COMMENT_CONTENT));
        assertTrue("Should return true when valid type passed",
                TokenUtils.isCommentType("COMMENT_CONTENT"));
    }

    @Test
    public void testGetTokenTypesTotalNumber() {
        final int tokenTypesTotalNumber = TokenUtils.getTokenTypesTotalNumber();

        assertEquals("Invalid token total number", 169, tokenTypesTotalNumber);
    }

    @Test
    public void testGetAllTokenIds() {
        final int[] allTokenIds = TokenUtils.getAllTokenIds();
        final int sum = Arrays.stream(allTokenIds).sum();

        assertEquals("Invalid token length", 169, allTokenIds.length);
        assertEquals("invalid sum", 15662, sum);
    }

    @Test
    public void testGetTokenNameWithGreatestPossibleId() {
        final Integer id = TokenTypes.COMMENT_CONTENT;
        final String tokenName = TokenUtils.getTokenName(id);

        assertEquals("Invalid token name", "COMMENT_CONTENT", tokenName);
    }

    @Test
    public void testCorrectBehaviourOfGetTokenId() {
        final String id = "EOF";

        assertEquals("Invalid token id", TokenTypes.EOF, TokenUtils.getTokenId(id));

    }

    @Test
    public void testCorrectBehaviourOfShortDescription() {
        final String id = "EOF";
        final String shortDescription = TokenUtils.getShortDescription(id);

        assertEquals("Invalid short description", "The end of file token.", shortDescription);
    }

    @Test
    public void testFindFirstTokenByPredicate() {
        final DetailAST astForTest = new DetailAST();
        final DetailAST child = new DetailAST();
        final DetailAST firstSibling = new DetailAST();
        final DetailAST secondSibling = new DetailAST();
        final DetailAST thirdSibling = new DetailAST();
        firstSibling.setText("first");
        secondSibling.setText("second");
        thirdSibling.setText("third");
        secondSibling.setNextSibling(thirdSibling);
        firstSibling.setNextSibling(secondSibling);
        child.setNextSibling(firstSibling);
        astForTest.setFirstChild(child);
        final Optional<DetailAST> result = TokenUtils.findFirstTokenByPredicate(astForTest,
            ast -> "second".equals(ast.getText()));

        assertEquals("Invalid second sibling", secondSibling, result.get());
    }
}