IdentityHashMapTest.java revision 89c1feb0a69a7707b271086e749975b3f7acacf7
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package tests.api.java.util;
19
20import dalvik.annotation.TestTarget;
21import dalvik.annotation.TestInfo;
22import dalvik.annotation.TestLevel;
23import dalvik.annotation.TestTargetClass;
24
25import java.io.Serializable;
26import java.util.AbstractMap;
27import java.util.ArrayList;
28import java.util.Arrays;
29import java.util.Collection;
30import java.util.HashMap;
31import java.util.IdentityHashMap;
32import java.util.Iterator;
33import java.util.Map;
34import java.util.Set;
35import java.util.TreeMap;
36
37import tests.support.Support_MapTest2;
38
39import org.apache.harmony.testframework.serialization.SerializationTest;
40
41@TestTargetClass(IdentityHashMap.class)
42public class IdentityHashMapTest extends junit.framework.TestCase {
43    private static final String ID = "hello";
44
45    class MockMap extends AbstractMap {
46        public Set entrySet() {
47            return null;
48        }
49        public int size(){
50            return 0;
51        }
52    }
53    /*
54     * TODO: change all the statements testing the keys and values with equals()
55     * method to check for reference equality instead
56     */
57
58    IdentityHashMap hm;
59
60    final static int hmSize = 1000;
61
62    static Object[] objArray;
63
64    static Object[] objArray2;
65    {
66        objArray = new Object[hmSize];
67        objArray2 = new Object[hmSize];
68        for (int i = 0; i < objArray.length; i++) {
69            objArray[i] = new Integer(i);
70            objArray2[i] = objArray[i].toString();
71        }
72    }
73
74    /**
75     * @tests java.util.IdentityHashMap#IdentityHashMap()
76     */
77    @TestInfo(
78      level = TestLevel.COMPLETE,
79      purpose = "",
80      targets = {
81        @TestTarget(
82          methodName = "IdentityHashMap",
83          methodArgs = {}
84        )
85    })
86    public void test_Constructor() {
87        // Test for method java.util.IdentityHashMap()
88        new Support_MapTest2(new IdentityHashMap()).runTest();
89
90        IdentityHashMap hm2 = new IdentityHashMap();
91        assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
92    }
93
94    /**
95     * @tests java.util.IdentityHashMap#IdentityHashMap(int)
96     */
97    @TestInfo(
98      level = TestLevel.TODO,
99      purpose = "Need to improve code.",
100      targets = {
101        @TestTarget(
102          methodName = "IdentityHashMap",
103          methodArgs = {int.class}
104        )
105    })
106    public void test_ConstructorI() {
107        // Test for method java.util.IdentityHashMap(int)
108        IdentityHashMap hm2 = new IdentityHashMap(5);
109        assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
110        try {
111            new IdentityHashMap(-1);
112        } catch (IllegalArgumentException e) {
113            return;
114        }
115        fail(
116                "Failed to throw IllegalArgumentException for initial capacity < 0");
117
118        IdentityHashMap empty = new IdentityHashMap(0);
119        assertNull("Empty IdentityHashMap access", empty.get("nothing"));
120        empty.put("something", "here");
121        assertTrue("cannot get element", empty.get("something") == "here");
122    }
123
124    /**
125     * @tests java.util.IdentityHashMap#IdentityHashMap(java.util.Map)
126     */
127    @TestInfo(
128      level = TestLevel.PARTIAL,
129      purpose = "Doesn't verify NullPointerException.",
130      targets = {
131        @TestTarget(
132          methodName = "IdentityHashMap",
133          methodArgs = {java.util.Map.class}
134        )
135    })
136    public void test_ConstructorLjava_util_Map() {
137        // Test for method java.util.IdentityHashMap(java.util.Map)
138        Map myMap = new TreeMap();
139        for (int counter = 0; counter < hmSize; counter++)
140            myMap.put(objArray2[counter], objArray[counter]);
141        IdentityHashMap hm2 = new IdentityHashMap(myMap);
142        for (int counter = 0; counter < hmSize; counter++)
143            assertTrue("Failed to construct correct IdentityHashMap", hm
144                    .get(objArray2[counter]) == hm2.get(objArray2[counter]));
145
146        Map mockMap = new MockMap();
147        hm2 = new IdentityHashMap(mockMap);
148        assertEquals("Size should be 0", 0, hm2.size());
149    }
150
151    /**
152     * @tests java.util.IdentityHashMap#clear()
153     */
154    @TestInfo(
155      level = TestLevel.COMPLETE,
156      purpose = "",
157      targets = {
158        @TestTarget(
159          methodName = "clear",
160          methodArgs = {}
161        )
162    })
163    public void test_clear() {
164        // Test for method void java.util.IdentityHashMap.clear()
165        hm.clear();
166        assertEquals("Clear failed to reset size", 0, hm.size());
167        for (int i = 0; i < hmSize; i++)
168            assertNull("Failed to clear all elements",
169                    hm.get(objArray2[i]));
170
171    }
172
173    /**
174     * @tests java.util.IdentityHashMap#clone()
175     */
176    @TestInfo(
177      level = TestLevel.COMPLETE,
178      purpose = "",
179      targets = {
180        @TestTarget(
181          methodName = "clone",
182          methodArgs = {}
183        )
184    })
185    public void test_clone() {
186        // Test for method java.lang.Object java.util.IdentityHashMap.clone()
187        IdentityHashMap hm2 = (IdentityHashMap) hm.clone();
188        assertTrue("Clone answered equivalent IdentityHashMap", hm2 != hm);
189        for (int counter = 0; counter < hmSize; counter++)
190            assertTrue("Clone answered unequal IdentityHashMap", hm
191                    .get(objArray2[counter]) == hm2.get(objArray2[counter]));
192
193        IdentityHashMap map = new IdentityHashMap();
194        map.put("key", "value");
195        // get the keySet() and values() on the original Map
196        Set keys = map.keySet();
197        Collection values = map.values();
198        assertEquals("values() does not work",
199                "value", values.iterator().next());
200        assertEquals("keySet() does not work",
201                "key", keys.iterator().next());
202        AbstractMap map2 = (AbstractMap) map.clone();
203        map2.put("key", "value2");
204        Collection values2 = map2.values();
205        assertTrue("values() is identical", values2 != values);
206        // values() and keySet() on the cloned() map should be different
207        assertEquals("values() was not cloned",
208                "value2", values2.iterator().next());
209        map2.clear();
210        map2.put("key2", "value3");
211        Set key2 = map2.keySet();
212        assertTrue("keySet() is identical", key2 != keys);
213        assertEquals("keySet() was not cloned",
214                "key2", key2.iterator().next());
215    }
216
217    /**
218     * @tests java.util.IdentityHashMap#containsKey(java.lang.Object)
219     */
220    @TestInfo(
221      level = TestLevel.COMPLETE,
222      purpose = "",
223      targets = {
224        @TestTarget(
225          methodName = "containsKey",
226          methodArgs = {java.lang.Object.class}
227        )
228    })
229    public void test_containsKeyLjava_lang_Object() {
230        // Test for method boolean
231        // java.util.IdentityHashMap.containsKey(java.lang.Object)
232        assertTrue("Returned false for valid key", hm
233                .containsKey(objArray2[23]));
234        assertTrue("Returned true for copy of valid key", !hm
235                .containsKey(new Integer(23).toString()));
236        assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
237
238        IdentityHashMap m = new IdentityHashMap();
239        m.put(null, "test");
240        assertTrue("Failed with null key", m.containsKey(null));
241        assertTrue("Failed with missing key matching null hash", !m
242                .containsKey(new Integer(0)));
243    }
244
245    /**
246     * @tests java.util.IdentityHashMap#containsValue(java.lang.Object)
247     */
248    @TestInfo(
249      level = TestLevel.COMPLETE,
250      purpose = "",
251      targets = {
252        @TestTarget(
253          methodName = "containsValue",
254          methodArgs = {java.lang.Object.class}
255        )
256    })
257    public void test_containsValueLjava_lang_Object() {
258        // Test for method boolean
259        // java.util.IdentityHashMap.containsValue(java.lang.Object)
260        assertTrue("Returned false for valid value", hm
261                .containsValue(objArray[19]));
262        assertTrue("Returned true for invalid valie", !hm
263                .containsValue(new Integer(-9)));
264    }
265
266    /**
267     * @tests java.util.IdentityHashMap#entrySet()
268     */
269    @TestInfo(
270      level = TestLevel.COMPLETE,
271      purpose = "",
272      targets = {
273        @TestTarget(
274          methodName = "entrySet",
275          methodArgs = {}
276        )
277    })
278    public void test_entrySet() {
279        // Test for method java.util.Set java.util.IdentityHashMap.entrySet()
280        Set s = hm.entrySet();
281        Iterator i = s.iterator();
282        assertTrue("Returned set of incorrect size", hm.size() == s.size());
283        while (i.hasNext()) {
284            Map.Entry m = (Map.Entry) i.next();
285            assertTrue("Returned incorrect entry set", hm.containsKey(m
286                    .getKey())
287                    && hm.containsValue(m.getValue()));
288        }
289    }
290
291    /**
292     * @tests java.util.IdentityHashMap#get(java.lang.Object)
293     */
294    @TestInfo(
295      level = TestLevel.COMPLETE,
296      purpose = "",
297      targets = {
298        @TestTarget(
299          methodName = "get",
300          methodArgs = {java.lang.Object.class}
301        )
302    })
303    public void test_getLjava_lang_Object() {
304        // Test for method java.lang.Object
305        // java.util.IdentityHashMap.get(java.lang.Object)
306        assertNull("Get returned non-null for non existent key",
307                hm.get("T"));
308        hm.put("T", "HELLO");
309        assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
310                );
311
312        IdentityHashMap m = new IdentityHashMap();
313        m.put(null, "test");
314        assertEquals("Failed with null key", "test", m.get(null));
315        assertNull("Failed with missing key matching null hash", m
316                .get(new Integer(0)));
317    }
318
319    /**
320     * @tests java.util.IdentityHashMap#isEmpty()
321     */
322    @TestInfo(
323      level = TestLevel.COMPLETE,
324      purpose = "",
325      targets = {
326        @TestTarget(
327          methodName = "isEmpty",
328          methodArgs = {}
329        )
330    })
331    public void test_isEmpty() {
332        // Test for method boolean java.util.IdentityHashMap.isEmpty()
333        assertTrue("Returned false for new map", new IdentityHashMap()
334                .isEmpty());
335        assertTrue("Returned true for non-empty", !hm.isEmpty());
336    }
337
338    /**
339     * @tests java.util.IdentityHashMap#keySet()
340     */
341    @TestInfo(
342      level = TestLevel.COMPLETE,
343      purpose = "",
344      targets = {
345        @TestTarget(
346          methodName = "keySet",
347          methodArgs = {}
348        )
349    })
350    public void test_keySet() {
351        // Test for method java.util.Set java.util.IdentityHashMap.keySet()
352        Set s = hm.keySet();
353        assertTrue("Returned set of incorrect size()", s.size() == hm.size());
354        for (int i = 0; i < objArray.length; i++) {
355            assertTrue("Returned set does not contain all keys", s
356                    .contains(objArray2[i]));
357        }
358
359        IdentityHashMap m = new IdentityHashMap();
360        m.put(null, "test");
361        assertTrue("Failed with null key", m.keySet().contains(null));
362        assertNull("Failed with null key", m.keySet().iterator().next());
363
364        Map map = new IdentityHashMap(101);
365        map.put(new Integer(1), "1");
366        map.put(new Integer(102), "102");
367        map.put(new Integer(203), "203");
368        Iterator it = map.keySet().iterator();
369        Integer remove1 = (Integer) it.next();
370        it.hasNext();
371        it.remove();
372        Integer remove2 = (Integer) it.next();
373        it.remove();
374        ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
375                new Integer(1), new Integer(102), new Integer(203) }));
376        list.remove(remove1);
377        list.remove(remove2);
378        assertTrue("Wrong result", it.next().equals(list.get(0)));
379        assertEquals("Wrong size", 1, map.size());
380        assertTrue("Wrong contents", map.keySet().iterator().next().equals(
381                list.get(0)));
382
383        Map map2 = new IdentityHashMap(101);
384        map2.put(new Integer(1), "1");
385        map2.put(new Integer(4), "4");
386        Iterator it2 = map2.keySet().iterator();
387        Integer remove3 = (Integer) it2.next();
388        Integer next;
389        if (remove3.intValue() == 1)
390            next = new Integer(4);
391        else
392            next = new Integer(1);
393        it2.hasNext();
394        it2.remove();
395        assertTrue("Wrong result 2", it2.next().equals(next));
396        assertEquals("Wrong size 2", 1, map2.size());
397        assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
398                next));
399    }
400
401    /**
402     * @tests java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
403     */
404    @TestInfo(
405      level = TestLevel.COMPLETE,
406      purpose = "",
407      targets = {
408        @TestTarget(
409          methodName = "put",
410          methodArgs = {Object.class, Object.class}
411        )
412    })
413    public void test_putLjava_lang_ObjectLjava_lang_Object() {
414        // Test for method java.lang.Object
415        // java.util.IdentityHashMap.put(java.lang.Object, java.lang.Object)
416        hm.put("KEY", "VALUE");
417        assertEquals("Failed to install key/value pair",
418                "VALUE", hm.get("KEY"));
419
420        IdentityHashMap m = new IdentityHashMap();
421        Short s0 = new Short((short) 0);
422        m.put(s0, "short");
423        m.put(null, "test");
424        Integer i0 = new Integer(0);
425        m.put(i0, "int");
426        assertEquals("Failed adding to bucket containing null",
427                "short", m.get(s0));
428        assertEquals("Failed adding to bucket containing null2", "int", m.get(i0)
429                );
430    }
431
432    /**
433     * @tests java.util.IdentityHashMap#putAll(java.util.Map)
434     */
435    @TestInfo(
436      level = TestLevel.PARTIAL,
437      purpose = "Doesn't verify NullPointerException.",
438      targets = {
439        @TestTarget(
440          methodName = "putAll",
441          methodArgs = {java.util.Map.class}
442        )
443    })
444    public void test_putAllLjava_util_Map() {
445        // Test for method void java.util.IdentityHashMap.putAll(java.util.Map)
446        IdentityHashMap hm2 = new IdentityHashMap();
447        hm2.putAll(hm);
448        for (int i = 0; i < 1000; i++)
449            assertTrue("Failed to clear all elements", hm2.get(objArray2[i])
450                    .equals((new Integer(i))));
451
452        hm2 = new IdentityHashMap();
453        Map mockMap = new MockMap();
454        hm2.putAll(mockMap);
455        assertEquals("Size should be 0", 0, hm2.size());
456    }
457
458    /**
459     * @tests java.util.IdentityHashMap#remove(java.lang.Object)
460     */
461    @TestInfo(
462      level = TestLevel.COMPLETE,
463      purpose = "",
464      targets = {
465        @TestTarget(
466          methodName = "remove",
467          methodArgs = {java.lang.Object.class}
468        )
469    })
470    public void test_removeLjava_lang_Object() {
471        // Test for method java.lang.Object
472        // java.util.IdentityHashMap.remove(java.lang.Object)
473        int size = hm.size();
474        Integer x = ((Integer) hm.remove(objArray2[9]));
475        assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
476        assertNull("Failed to remove given key", hm.get(objArray2[9]));
477        assertTrue("Failed to decrement size", hm.size() == (size - 1));
478        assertNull("Remove of non-existent key returned non-null", hm
479                .remove("LCLCLC"));
480
481        IdentityHashMap m = new IdentityHashMap();
482        m.put(null, "test");
483        assertNull("Failed with same hash as null",
484                m.remove(objArray[0]));
485        assertEquals("Failed with null key", "test", m.remove(null));
486    }
487
488    /**
489     * @tests java.util.IdentityHashMap#size()
490     */
491    @TestInfo(
492      level = TestLevel.COMPLETE,
493      purpose = "",
494      targets = {
495        @TestTarget(
496          methodName = "size",
497          methodArgs = {}
498        )
499    })
500    public void test_size() {
501        // Test for method int java.util.IdentityHashMap.size()
502        assertEquals("Returned incorrect size, ", (objArray.length + 2), hm
503                .size());
504    }
505
506    /**
507     * @tests java.util.IdentityHashMap#equals(java.lang.Object)
508     */
509    @TestInfo(
510      level = TestLevel.COMPLETE,
511      purpose = "",
512      targets = {
513        @TestTarget(
514          methodName = "equals",
515          methodArgs = {java.lang.Object.class}
516        )
517    })
518    public void test_equalsLjava_lang_Object() {
519        IdentityHashMap mapOne = new IdentityHashMap();
520        IdentityHashMap mapTwo = new IdentityHashMap();
521        IdentityHashMap mapThree = new IdentityHashMap();
522        IdentityHashMap mapFour = new IdentityHashMap();
523
524        String one = "one";
525        String alsoOne = new String(one); // use the new operator to ensure a
526        // new reference is constructed
527        String two = "two";
528        String alsoTwo = new String(two); // use the new operator to ensure a
529        // new reference is constructed
530
531        mapOne.put(one, two);
532        mapFour.put(one, two);
533
534        // these two are not equal to the above two
535        mapTwo.put(alsoOne, two);
536        mapThree.put(one, alsoTwo);
537
538        assertEquals("failure of equality of IdentityHashMaps", mapOne, mapFour);
539        assertTrue("failure of non-equality of IdentityHashMaps one and two",
540                !mapOne.equals(mapTwo));
541        assertTrue("failure of non-equality of IdentityHashMaps one and three",
542                !mapOne.equals(mapThree));
543        assertTrue("failure of non-equality of IdentityHashMaps two and three",
544                !mapTwo.equals(mapThree));
545
546        HashMap hashMapTwo = new HashMap();
547        HashMap hashMapThree = new HashMap();
548        hashMapTwo.put(alsoOne, two);
549        hashMapThree.put(one, alsoTwo);
550
551        assertTrue(
552                "failure of non-equality of IdentityHashMaps one and Hashmap two",
553                !mapOne.equals(hashMapTwo));
554        assertTrue(
555                "failure of non-equality of IdentityHashMaps one and Hashmap three",
556                !mapOne.equals(hashMapThree));
557    }
558
559    /**
560     * @tests java.util.IdentityHashMap#values()
561     */
562    @TestInfo(
563      level = TestLevel.COMPLETE,
564      purpose = "",
565      targets = {
566        @TestTarget(
567          methodName = "values",
568          methodArgs = {}
569        )
570    })
571    public void test_values() {
572        // Test for method java.util.Collection
573        // java.util.IdentityHashMap.values()
574        Collection c = hm.values();
575        assertTrue("Returned collection of incorrect size()", c.size() == hm
576                .size());
577        for (int i = 0; i < objArray.length; i++)
578            assertTrue("Returned collection does not contain all keys", c
579                    .contains(objArray[i]));
580
581        IdentityHashMap myIdentityHashMap = new IdentityHashMap();
582        for (int i = 0; i < 100; i++)
583            myIdentityHashMap.put(objArray2[i], objArray[i]);
584        Collection values = myIdentityHashMap.values();
585        values.remove(objArray[0]);
586        assertTrue(
587                "Removing from the values collection should remove from the original map",
588                !myIdentityHashMap.containsValue(objArray2[0]));
589
590    }
591
592    /**
593     * @tests java.util.IdentityHashMap#Serialization()
594     */
595    @TestInfo(
596      level = TestLevel.COMPLETE,
597      purpose = "Verifies serialization/deserialization compatibility.",
598      targets = {
599        @TestTarget(
600          methodName = "!SerializationSelf",
601          methodArgs = {}
602        ),
603        @TestTarget(
604          methodName = "!SerializationGolden",
605          methodArgs = {}
606        )
607    })
608    public void test_Serialization() throws Exception {
609        IdentityHashMap<String, String> map = new IdentityHashMap<String, String>();
610        map.put(ID, "world");
611        // BEGIN android-added
612        // Regression test for null key in serialized IdentityHashMap (1178549)
613        // Together with this change the IdentityHashMap.golden.ser resource
614        // was replaced by a version that contains a map with a null key.
615        map.put(null, "null");
616        // END android-added
617        SerializationTest.verifySelf(map, comparator);
618        SerializationTest.verifyGolden(this, map, comparator);
619    }
620
621    /**
622     * Sets up the fixture, for example, open a network connection. This method
623     * is called before a test is executed.
624     */
625    protected void setUp() {
626        hm = new IdentityHashMap();
627        for (int i = 0; i < objArray.length; i++)
628            hm.put(objArray2[i], objArray[i]);
629        hm.put("test", null);
630        hm.put(null, "test");
631    }
632
633    /**
634     * Tears down the fixture, for example, close a network connection. This
635     * method is called after a test is executed.
636     */
637    protected void tearDown() {
638    }
639
640    private static final SerializationTest.SerializableAssert comparator = new
641                             SerializationTest.SerializableAssert() {
642
643        public void assertDeserialized(Serializable initial, Serializable deserialized) {
644            IdentityHashMap<String, String> initialMap = (IdentityHashMap<String, String>) initial;
645            IdentityHashMap<String, String> deseriaMap = (IdentityHashMap<String, String>) deserialized;
646            assertEquals("should be equal", initialMap.size(), deseriaMap.size());
647        }
648
649    };
650}
651