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