1 /*
2  * Copyright (C) 2009 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.escape;
18 
19 import com.google.common.annotations.GwtCompatible;
20 import com.google.common.collect.ImmutableMap;
21 import java.util.Map;
22 import junit.framework.TestCase;
23 
24 /** @author David Beaumont */
25 @GwtCompatible
26 public class ArrayBasedEscaperMapTest extends TestCase {
testNullMap()27   public void testNullMap() {
28     try {
29       ArrayBasedEscaperMap.create(null);
30       fail("expected exception did not occur");
31     } catch (NullPointerException e) {
32       // pass
33     }
34   }
35 
testEmptyMap()36   public void testEmptyMap() {
37     Map<Character, String> map = ImmutableMap.of();
38     ArrayBasedEscaperMap fem = ArrayBasedEscaperMap.create(map);
39     // Non-null array of zero length.
40     assertEquals(0, fem.getReplacementArray().length);
41   }
42 
testMapLength()43   public void testMapLength() {
44     Map<Character, String> map =
45         ImmutableMap.of(
46             'a', "first",
47             'z', "last");
48     ArrayBasedEscaperMap fem = ArrayBasedEscaperMap.create(map);
49     // Array length is highest character value + 1
50     assertEquals('z' + 1, fem.getReplacementArray().length);
51   }
52 
testMapping()53   public void testMapping() {
54     Map<Character, String> map =
55         ImmutableMap.of(
56             '\0', "zero",
57             'a', "first",
58             'b', "second",
59             'z', "last",
60             '\uFFFF', "biggest");
61     ArrayBasedEscaperMap fem = ArrayBasedEscaperMap.create(map);
62     char[][] replacementArray = fem.getReplacementArray();
63     // Array length is highest character value + 1
64     assertEquals(65536, replacementArray.length);
65     // The final element should always be non null.
66     assertNotNull(replacementArray[replacementArray.length - 1]);
67     // Exhaustively check all mappings (an int index avoids wrapping).
68     for (int n = 0; n < replacementArray.length; ++n) {
69       char c = (char) n;
70       if (replacementArray[n] != null) {
71         assertEquals(map.get(c), new String(replacementArray[n]));
72       } else {
73         assertFalse(map.containsKey(c));
74       }
75     }
76   }
77 }
78