KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > collections > list > AbstractTestList


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation
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 package org.apache.commons.collections.list;
17
18 import java.io.IOException JavaDoc;
19 import java.io.Serializable JavaDoc;
20 import java.lang.reflect.InvocationTargetException JavaDoc;
21 import java.lang.reflect.Method JavaDoc;
22 import java.util.AbstractCollection JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Arrays JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.ConcurrentModificationException JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.ListIterator JavaDoc;
31 import java.util.NoSuchElementException JavaDoc;
32
33 import org.apache.commons.collections.BulkTest;
34 import org.apache.commons.collections.collection.AbstractTestCollection;
35 import org.apache.commons.collections.iterators.AbstractTestListIterator;
36
37 /**
38  * Abstract test class for {@link java.util.List} methods and contracts.
39  * <p>
40  * To use, simply extend this class, and implement
41  * the {@link #makeEmptyList} method.
42  * <p>
43  * If your {@link List} fails one of these tests by design,
44  * you may still use this base set of cases. Simply override the
45  * test case (method) your {@link List} fails or override one of the
46  * protected methods from AbstractTestCollection.
47  *
48  * @version $Revision: 1.9 $ $Date: 2004/05/31 22:39:20 $
49  *
50  * @author Rodney Waldhoff
51  * @author Paul Jack
52  * @author Stephen Colebourne
53  * @author Neil O'Toole
54  */

55 public abstract class AbstractTestList extends AbstractTestCollection {
56
57     /**
58      * JUnit constructor.
59      *
60      * @param testName the test class name
61      */

62     public AbstractTestList(String JavaDoc testName) {
63         super(testName);
64     }
65
66     //-----------------------------------------------------------------------
67
/**
68      * Returns true if the collections produced by
69      * {@link #makeCollection()} and {@link #makeFullCollection()}
70      * support the <code>set operation.<p>
71      * Default implementation returns true. Override if your collection
72      * class does not support set.
73      */

74     public boolean isSetSupported() {
75         return true;
76     }
77
78     //-----------------------------------------------------------------------
79
/**
80      * Verifies that the test list implementation matches the confirmed list
81      * implementation.
82      */

83     public void verify() {
84         super.verify();
85
86         List JavaDoc list1 = getList();
87         List JavaDoc list2 = getConfirmedList();
88
89         assertEquals("List should equal confirmed", list1, list2);
90         assertEquals("Confirmed should equal list", list2, list1);
91
92         assertEquals("Hash codes should be equal", list1.hashCode(), list2.hashCode());
93
94         int i = 0;
95         Iterator JavaDoc iterator1 = list1.iterator();
96         Iterator JavaDoc iterator2 = list2.iterator();
97         Object JavaDoc[] array = list1.toArray();
98         while (iterator2.hasNext()) {
99             assertTrue("List iterator should have next", iterator1.hasNext());
100             Object JavaDoc o1 = iterator1.next();
101             Object JavaDoc o2 = iterator2.next();
102             assertEquals("Iterator elements should be equal", o1, o2);
103             o2 = list1.get(i);
104             assertEquals("get should return correct element", o1, o2);
105             o2 = array[i];
106             assertEquals("toArray should have correct element", o1, o2);
107             i++;
108         }
109     }
110
111     //-----------------------------------------------------------------------
112
/**
113      * List equals method is defined.
114      */

115     public boolean isEqualsCheckable() {
116         return true;
117     }
118
119     /**
120      * Returns an empty {@link ArrayList}.
121      */

122     public Collection JavaDoc makeConfirmedCollection() {
123         ArrayList JavaDoc list = new ArrayList JavaDoc();
124         return list;
125     }
126
127     /**
128      * Returns a full {@link ArrayList}.
129      */

130     public Collection JavaDoc makeConfirmedFullCollection() {
131         ArrayList JavaDoc list = new ArrayList JavaDoc();
132         list.addAll(Arrays.asList(getFullElements()));
133         return list;
134     }
135
136     /**
137      * Return a new, empty {@link List} to be used for testing.
138      *
139      * @return an empty list for testing.
140      */

141     public abstract List JavaDoc makeEmptyList();
142
143     /**
144      * Return a new, full {@link List} to be used for testing.
145      *
146      * @return a full list for testing
147      */

148     public List JavaDoc makeFullList() {
149         // only works if list supports optional "addAll(Collection)"
150
List JavaDoc list = makeEmptyList();
151         list.addAll(Arrays.asList(getFullElements()));
152         return list;
153     }
154
155     /**
156      * Returns {@link #makeEmptyList()}.
157      *
158      * @return an empty list to be used for testing
159      */

160     public final Collection JavaDoc makeCollection() {
161         return makeEmptyList();
162     }
163
164     /**
165      * Returns {@link #makeFullList()}.
166      *
167      * @return a full list to be used for testing
168      */

169     public final Collection JavaDoc makeFullCollection() {
170         return makeFullList();
171     }
172
173     //-----------------------------------------------------------------------
174
/**
175      * Returns the {@link #collection} field cast to a {@link List}.
176      *
177      * @return the collection field as a List
178      */

179     public List JavaDoc getList() {
180         return (List JavaDoc) collection;
181     }
182
183     /**
184      * Returns the {@link #confirmed} field cast to a {@link List}.
185      *
186      * @return the confirmed field as a List
187      */

188     public List JavaDoc getConfirmedList() {
189         return (List JavaDoc) confirmed;
190     }
191
192     //-----------------------------------------------------------------------
193
/**
194      * Tests bounds checking for {@link List#add(int, Object)} on an
195      * empty list.
196      */

197     public void testListAddByIndexBoundsChecking() {
198         if (!isAddSupported()) {
199             return;
200         }
201
202         List JavaDoc list;
203         Object JavaDoc element = getOtherElements()[0];
204
205         try {
206             list = makeEmptyList();
207             list.add(Integer.MIN_VALUE, element);
208             fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]");
209         } catch (IndexOutOfBoundsException JavaDoc e) {
210             // expected
211
}
212
213         try {
214             list = makeEmptyList();
215             list.add(-1, element);
216             fail("List.add should throw IndexOutOfBoundsException [-1]");
217         } catch (IndexOutOfBoundsException JavaDoc e) {
218             // expected
219
}
220
221         try {
222             list = makeEmptyList();
223             list.add(1, element);
224             fail("List.add should throw IndexOutOfBoundsException [1]");
225         } catch (IndexOutOfBoundsException JavaDoc e) {
226             // expected
227
}
228
229         try {
230             list = makeEmptyList();
231             list.add(Integer.MAX_VALUE, element);
232             fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]");
233         } catch (IndexOutOfBoundsException JavaDoc e) {
234             // expected
235
}
236     }
237
238     /**
239      * Tests bounds checking for {@link List#add(int, Object)} on a
240      * full list.
241      */

242     public void testListAddByIndexBoundsChecking2() {
243         if (!isAddSupported()) {
244             return;
245         }
246
247         List JavaDoc list;
248         Object JavaDoc element = getOtherElements()[0];
249
250         try {
251             list = makeFullList();
252             list.add(Integer.MIN_VALUE, element);
253             fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]");
254         } catch (IndexOutOfBoundsException JavaDoc e) {
255             // expected
256
}
257
258         try {
259             list = makeFullList();
260             list.add(-1, element);
261             fail("List.add should throw IndexOutOfBoundsException [-1]");
262         } catch (IndexOutOfBoundsException JavaDoc e) {
263             // expected
264
}
265
266         try {
267             list = makeFullList();
268             list.add(list.size() + 1, element);
269             fail("List.add should throw IndexOutOfBoundsException [size + 1]");
270         } catch (IndexOutOfBoundsException JavaDoc e) {
271             // expected
272
}
273
274         try {
275             list = makeFullList();
276             list.add(Integer.MAX_VALUE, element);
277             fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]");
278         } catch (IndexOutOfBoundsException JavaDoc e) {
279             // expected
280
}
281     }
282
283     /**
284      * Tests {@link List#add(int,Object)}.
285      */

286     public void testListAddByIndex() {
287         if (!isAddSupported()) {
288             return;
289         }
290
291         Object JavaDoc element = getOtherElements()[0];
292         int max = getFullElements().length;
293
294         for (int i = 0; i <= max; i++) {
295             resetFull();
296             ((List JavaDoc) collection).add(i, element);
297             ((List JavaDoc) confirmed).add(i, element);
298             verify();
299         }
300     }
301
302     /**
303      * Tests {@link List#equals(Object)}.
304      */

305     public void testListEquals() {
306         resetEmpty();
307         List JavaDoc list = getList();
308         assertEquals("Empty lists should be equal", true, list.equals(confirmed));
309         verify();
310         assertEquals("Empty list should equal self", true, list.equals(list));
311         verify();
312
313         List JavaDoc list2 = Arrays.asList(getFullElements());
314         assertEquals("Empty list shouldn't equal full", false, list.equals(list2));
315         verify();
316
317         list2 = Arrays.asList(getOtherElements());
318         assertEquals("Empty list shouldn't equal other", false, list.equals(list2));
319         verify();
320
321         resetFull();
322         list = getList();
323         assertEquals("Full lists should be equal", true, list.equals(confirmed));
324         verify();
325         assertEquals("Full list should equal self", true, list.equals(list));
326         verify();
327
328         list2 = makeEmptyList();
329         assertEquals("Full list shouldn't equal empty", false, list.equals(list2));
330         verify();
331
332         list2 = Arrays.asList(getOtherElements());
333         assertEquals("Full list shouldn't equal other", false, list.equals(list2));
334         verify();
335
336         list2 = Arrays.asList(getFullElements());
337         if (list2.size() < 2 && isAddSupported()) {
338             // main list is only size 1, so lets add other elements to get a better list
339
list.addAll(Arrays.asList(getOtherElements()));
340             confirmed.addAll(Arrays.asList(getOtherElements()));
341             list2 = new ArrayList JavaDoc(list2);
342             list2.addAll(Arrays.asList(getOtherElements()));
343         }
344         if (list2.size() > 1) {
345             Collections.reverse(list2);
346             assertEquals(
347                 "Full list shouldn't equal full list with same elements but different order",
348                 false, list.equals(list2));
349             verify();
350         }
351
352         resetFull();
353         list = getList();
354         assertEquals("List shouldn't equal String", false, list.equals(""));
355         verify();
356
357         final List JavaDoc listForC = Arrays.asList(getFullElements());
358         Collection JavaDoc c = new AbstractCollection JavaDoc() {
359             public int size() {
360                 return listForC.size();
361             }
362
363             public Iterator JavaDoc iterator() {
364                 return listForC.iterator();
365             }
366         };
367
368         assertEquals("List shouldn't equal nonlist with same elements in same order", false, list.equals(c));
369         verify();
370     }
371
372     /**
373      * Tests {@link List#hashCode()}.
374      */

375     public void testListHashCode() {
376         resetEmpty();
377         int hash1 = collection.hashCode();
378         int hash2 = confirmed.hashCode();
379         assertEquals("Empty lists should have equal hashCodes", hash1, hash2);
380         verify();
381
382         resetFull();
383         hash1 = collection.hashCode();
384         hash2 = confirmed.hashCode();
385         assertEquals("Full lists should have equal hashCodes", hash1, hash2);
386         verify();
387     }
388
389     /**
390      * Tests {@link List#get(int)}.
391      */

392     public void testListGetByIndex() {
393         resetFull();
394         List JavaDoc list = getList();
395         Object JavaDoc[] elements = getFullElements();
396         for (int i = 0; i < elements.length; i++) {
397             assertEquals("List should contain correct elements", elements[i], list.get(i));
398             verify();
399         }
400     }
401
402     /**
403      * Tests bounds checking for {@link List#get(int)} on an
404      * empty list.
405      */

406     public void testListGetByIndexBoundsChecking() {
407         List JavaDoc list = makeEmptyList();
408
409         try {
410             list.get(Integer.MIN_VALUE);
411             fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]");
412         } catch (IndexOutOfBoundsException JavaDoc e) {
413             // expected
414
}
415
416         try {
417             list.get(-1);
418             fail("List.get should throw IndexOutOfBoundsException [-1]");
419         } catch (IndexOutOfBoundsException JavaDoc e) {
420             // expected
421
}
422
423         try {
424             list.get(0);
425             fail("List.get should throw IndexOutOfBoundsException [0]");
426         } catch (IndexOutOfBoundsException JavaDoc e) {
427             // expected
428
}
429
430         try {
431             list.get(1);
432             fail("List.get should throw IndexOutOfBoundsException [1]");
433         } catch (IndexOutOfBoundsException JavaDoc e) {
434             // expected
435
}
436
437         try {
438             list.get(Integer.MAX_VALUE);
439             fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]");
440         } catch (IndexOutOfBoundsException JavaDoc e) {
441             // expected
442
}
443     }
444
445     /**
446      * Tests bounds checking for {@link List#get(int)} on a
447      * full list.
448      */

449     public void testListGetByIndexBoundsChecking2() {
450         List JavaDoc list = makeFullList();
451
452         try {
453             list.get(Integer.MIN_VALUE);
454             fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]");
455         } catch (IndexOutOfBoundsException JavaDoc e) {
456             // expected
457
}
458
459         try {
460             list.get(-1);
461             fail("List.get should throw IndexOutOfBoundsException [-1]");
462         } catch (IndexOutOfBoundsException JavaDoc e) {
463             // expected
464
}
465
466         try {
467             list.get(getFullElements().length);
468             fail("List.get should throw IndexOutOfBoundsException [size]");
469         } catch (IndexOutOfBoundsException JavaDoc e) {
470             // expected
471
}
472
473         try {
474             list.get(Integer.MAX_VALUE);
475             fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]");
476         } catch (IndexOutOfBoundsException JavaDoc e) {
477             // expected
478
}
479     }
480
481     /**
482      * Tests {@link List#indexOf}.
483      */

484     public void testListIndexOf() {
485         resetFull();
486         List JavaDoc list1 = getList();
487         List JavaDoc list2 = getConfirmedList();
488
489         Iterator JavaDoc iterator = list2.iterator();
490         while (iterator.hasNext()) {
491             Object JavaDoc element = iterator.next();
492             assertEquals("indexOf should return correct result",
493                 list1.indexOf(element), list2.indexOf(element));
494             verify();
495         }
496
497         Object JavaDoc[] other = getOtherElements();
498         for (int i = 0; i < other.length; i++) {
499             assertEquals("indexOf should return -1 for nonexistent element",
500                 list1.indexOf(other[i]), -1);
501             verify();
502         }
503     }
504
505     /**
506      * Tests {@link List#lastIndexOf}.
507      */

508     public void testListLastIndexOf() {
509         resetFull();
510         List JavaDoc list1 = getList();
511         List JavaDoc list2 = getConfirmedList();
512
513         Iterator JavaDoc iterator = list2.iterator();
514         while (iterator.hasNext()) {
515             Object JavaDoc element = iterator.next();
516             assertEquals("lastIndexOf should return correct result",
517               list1.lastIndexOf(element), list2.lastIndexOf(element));
518             verify();
519         }
520
521         Object JavaDoc[] other = getOtherElements();
522         for (int i = 0; i < other.length; i++) {
523             assertEquals("lastIndexOf should return -1 for nonexistent " +
524               "element", list1.lastIndexOf(other[i]), -1);
525             verify();
526         }
527     }
528
529     /**
530      * Tests bounds checking for {@link List#set(int,Object)} on an
531      * empty list.
532      */

533     public void testListSetByIndexBoundsChecking() {
534         if (!isSetSupported()) {
535             return;
536         }
537
538         List JavaDoc list = makeEmptyList();
539         Object JavaDoc element = getOtherElements()[0];
540
541         try {
542             list.set(Integer.MIN_VALUE, element);
543             fail("List.set should throw IndexOutOfBoundsException [Integer.MIN_VALUE]");
544         } catch (IndexOutOfBoundsException JavaDoc e) {
545             // expected
546
}
547
548         try {
549             list.set(-1, element);
550             fail("List.set should throw IndexOutOfBoundsException [-1]");
551         } catch (IndexOutOfBoundsException JavaDoc e) {
552             // expected
553
}
554
555         try {
556             list.set(0, element);
557             fail("List.set should throw IndexOutOfBoundsException [0]");
558         } catch (IndexOutOfBoundsException JavaDoc e) {
559             // expected
560
}
561
562         try {
563             list.set(1, element);
564             fail("List.set should throw IndexOutOfBoundsException [1]");
565         } catch (IndexOutOfBoundsException JavaDoc e) {
566             // expected
567
}
568
569         try {
570             list.set(Integer.MAX_VALUE, element);
571             fail("List.set should throw IndexOutOfBoundsException [Integer.MAX_VALUE]");
572         } catch (IndexOutOfBoundsException JavaDoc e) {
573             // expected
574
}
575     }
576
577
578     /**
579      * Tests bounds checking for {@link List#set(int,Object)} on a
580      * full list.
581      */

582     public void testListSetByIndexBoundsChecking2() {
583         if (!isSetSupported()) return;
584
585         List JavaDoc list = makeFullList();
586         Object JavaDoc element = getOtherElements()[0];
587
588         try {
589             list.set(Integer.MIN_VALUE, element);
590             fail("List.set should throw IndexOutOfBoundsException " +
591               "[Integer.MIN_VALUE]");
592         } catch(IndexOutOfBoundsException JavaDoc e) {
593             // expected
594
}
595
596         try {
597             list.set(-1, element);
598             fail("List.set should throw IndexOutOfBoundsException [-1]");
599         } catch(IndexOutOfBoundsException JavaDoc e) {
600             // expected
601
}
602
603         try {
604             list.set(getFullElements().length, element);
605             fail("List.set should throw IndexOutOfBoundsException [size]");
606         } catch(IndexOutOfBoundsException JavaDoc e) {
607             // expected
608
}
609
610         try {
611             list.set(Integer.MAX_VALUE, element);
612             fail("List.set should throw IndexOutOfBoundsException " +
613               "[Integer.MAX_VALUE]");
614         } catch(IndexOutOfBoundsException JavaDoc e) {
615             // expected
616
}
617     }
618
619
620     /**
621      * Test {@link List#set(int,Object)}.
622      */

623     public void testListSetByIndex() {
624         if (!isSetSupported()) return;
625
626         resetFull();
627         Object JavaDoc[] elements = getFullElements();
628         Object JavaDoc[] other = getOtherElements();
629
630         for (int i = 0; i < elements.length; i++) {
631             Object JavaDoc n = other[i % other.length];
632             Object JavaDoc v = ((List JavaDoc)collection).set(i, n);
633             assertEquals("Set should return correct element", elements[i], v);
634             ((List JavaDoc)confirmed).set(i, n);
635             verify();
636         }
637     }
638
639
640     /**
641      * If {@link #isSetSupported()} returns false, tests that set operation
642      * raises <Code>UnsupportedOperationException.
643      */

644     public void testUnsupportedSet() {
645         if (isSetSupported()) return;
646         
647         resetFull();
648         try {
649             ((List JavaDoc) collection).set(0, new Object JavaDoc());
650             fail("Emtpy collection should not support set.");
651         } catch (UnsupportedOperationException JavaDoc e) {
652             // expected
653
}
654         // make sure things didn't change even if the expected exception was
655
// thrown.
656
verify();
657     }
658     
659
660     /**
661      * Tests bounds checking for {@link List#remove(int)} on an
662      * empty list.
663      */

664     public void testListRemoveByIndexBoundsChecking() {
665         if (!isRemoveSupported()) return;
666
667         List JavaDoc list = makeEmptyList();
668
669         try {
670             list.remove(Integer.MIN_VALUE);
671             fail("List.remove should throw IndexOutOfBoundsException " +
672               "[Integer.MIN_VALUE]");
673         } catch(IndexOutOfBoundsException JavaDoc e) {
674             // expected
675
}
676
677         try {
678             list.remove(-1);
679             fail("List.remove should throw IndexOutOfBoundsException [-1]");
680         } catch(IndexOutOfBoundsException JavaDoc e) {
681             // expected
682
}
683
684         try {
685             list.remove(0);
686             fail("List.remove should throw IndexOutOfBoundsException [0]");
687         } catch(IndexOutOfBoundsException JavaDoc e) {
688             // expected
689
}
690
691         try {
692             list.remove(1);
693             fail("List.remove should throw IndexOutOfBoundsException [1]");
694         } catch(IndexOutOfBoundsException JavaDoc e) {
695             // expected
696
}
697
698         try {
699             list.remove(Integer.MAX_VALUE);
700             fail("List.remove should throw IndexOutOfBoundsException " +
701               "[Integer.MAX_VALUE]");
702         } catch(IndexOutOfBoundsException JavaDoc e) {
703             // expected
704
}
705     }
706
707
708     /**
709      * Tests bounds checking for {@link List#remove(int)} on a
710      * full list.
711      */

712     public void testListRemoveByIndexBoundsChecking2() {
713         if (!isRemoveSupported()) return;
714
715         List JavaDoc list = makeFullList();
716
717         try {
718             list.remove(Integer.MIN_VALUE);
719             fail("List.remove should throw IndexOutOfBoundsException " +
720               "[Integer.MIN_VALUE]");
721         } catch(IndexOutOfBoundsException JavaDoc e) {
722             // expected
723
}
724
725         try {
726             list.remove(-1);
727             fail("List.remove should throw IndexOutOfBoundsException [-1]");
728         } catch(IndexOutOfBoundsException JavaDoc e) {
729             // expected
730
}
731
732         try {
733             list.remove(getFullElements().length);
734             fail("List.remove should throw IndexOutOfBoundsException [size]");
735         } catch(IndexOutOfBoundsException JavaDoc e) {
736             // expected
737
}
738
739         try {
740             list.remove(Integer.MAX_VALUE);
741             fail("List.remove should throw IndexOutOfBoundsException " +
742               "[Integer.MAX_VALUE]");
743         } catch(IndexOutOfBoundsException JavaDoc e) {
744             // expected
745
}
746     }
747
748
749     /**
750      * Tests {@link List#remove(int)}.
751      */

752     public void testListRemoveByIndex() {
753         if (!isRemoveSupported()) return;
754
755         int max = getFullElements().length;
756         for (int i = 0; i < max; i++) {
757             resetFull();
758             Object JavaDoc o1 = ((List JavaDoc)collection).remove(i);
759             Object JavaDoc o2 = ((List JavaDoc)confirmed).remove(i);
760             assertEquals("remove should return correct element", o1, o2);
761             verify();
762         }
763     }
764
765
766     /**
767      * Tests the read-only bits of {@link List#listIterator()}.
768      */

769     public void testListListIterator() {
770         resetFull();
771         forwardTest(getList().listIterator(), 0);
772         backwardTest(getList().listIterator(), 0);
773     }
774
775
776     /**
777      * Tests the read-only bits of {@link List#listIterator(int)}.
778      */

779     public void testListListIteratorByIndex() {
780         resetFull();
781         try {
782             getList().listIterator(-1);
783         } catch (IndexOutOfBoundsException JavaDoc ex) {}
784         resetFull();
785         try {
786             getList().listIterator(getList().size() + 1);
787         } catch (IndexOutOfBoundsException JavaDoc ex) {}
788         resetFull();
789         for (int i = 0; i <= confirmed.size(); i++) {
790             forwardTest(getList().listIterator(i), i);
791             backwardTest(getList().listIterator(i), i);
792         }
793         resetFull();
794         for (int i = 0; i <= confirmed.size(); i++) {
795             backwardTest(getList().listIterator(i), i);
796         }
797     }
798
799     /**
800      * Tests remove on list iterator is correct.
801      */

802     public void testListListIteratorPreviousRemove() {
803         if (isRemoveSupported() == false) return;
804         resetFull();
805         ListIterator JavaDoc it = getList().listIterator();
806         Object JavaDoc zero = it.next();
807         Object JavaDoc one = it.next();
808         Object JavaDoc two = it.next();
809         Object JavaDoc two2 = it.previous();
810         Object JavaDoc one2 = it.previous();
811         assertSame(one, one2);
812         assertSame(two, two2);
813         assertSame(zero, getList().get(0));
814         assertSame(one, getList().get(1));
815         assertSame(two, getList().get(2));
816         it.remove();
817         assertSame(zero, getList().get(0));
818         assertSame(two, getList().get(1));
819     }
820
821     /**
822      * Traverses to the end of the given iterator.
823      *
824      * @param iter the iterator to traverse
825      * @param i the starting index
826      */

827     private void forwardTest(ListIterator JavaDoc iter, int i) {
828         List JavaDoc list = getList();
829         int max = getFullElements().length;
830
831         while (i < max) {
832             assertTrue("Iterator should have next", iter.hasNext());
833             assertEquals("Iterator.nextIndex should work",
834               iter.nextIndex(), i);
835             assertEquals("Iterator.previousIndex should work",
836               iter.previousIndex(), i - 1);
837             Object JavaDoc o = iter.next();
838             assertEquals("Iterator returned correct element", list.get(i), o);
839             i++;
840         }
841
842         assertTrue("Iterator shouldn't have next", !iter.hasNext());
843         assertEquals("nextIndex should be size", iter.nextIndex(), max);
844         assertEquals("previousIndex should be size - 1",
845           iter.previousIndex(), max - 1);
846
847         try {
848             iter.next();
849             fail("Exhausted iterator should raise NoSuchElement");
850         } catch (NoSuchElementException JavaDoc e) {
851             // expected
852
}
853     }
854
855
856     /**
857      * Traverses to the beginning of the given iterator.
858      *
859      * @param iter the iterator to traverse
860      * @param i the starting index
861      */

862     private void backwardTest(ListIterator JavaDoc iter, int i) {
863         List JavaDoc list = getList();
864
865         while (i > 0) {
866             assertTrue("Iterator should have previous, i:" + i, iter.hasPrevious());
867             assertEquals("Iterator.nextIndex should work, i:" + i, iter.nextIndex(), i);
868             assertEquals("Iterator.previousIndex should work, i:" + i, iter.previousIndex(), i - 1);
869             Object JavaDoc o = iter.previous();
870             assertEquals("Iterator returned correct element", list.get(i - 1), o);
871             i--;
872         }
873
874         assertTrue("Iterator shouldn't have previous", !iter.hasPrevious());
875         int nextIndex = iter.nextIndex();
876         assertEquals("nextIndex should be 0, actual value: " + nextIndex, nextIndex, 0);
877         int prevIndex = iter.previousIndex();
878         assertEquals("previousIndex should be -1, actual value: " + prevIndex, prevIndex, -1);
879
880         try {
881             iter.previous();
882             fail("Exhausted iterator should raise NoSuchElement");
883         } catch (NoSuchElementException JavaDoc e) {
884             // expected
885
}
886
887     }
888
889
890     /**
891      * Tests the {@link ListIterator#add(Object)} method of the list
892      * iterator.
893      */

894     public void testListIteratorAdd() {
895         if (!isAddSupported()) return;
896
897         resetEmpty();
898         List JavaDoc list1 = getList();
899         List JavaDoc list2 = getConfirmedList();
900
901         Object JavaDoc[] elements = getFullElements();
902         ListIterator JavaDoc iter1 = list1.listIterator();
903         ListIterator JavaDoc iter2 = list2.listIterator();
904
905         for (int i = 0; i < elements.length; i++) {
906             iter1.add(elements[i]);
907             iter2.add(elements[i]);
908             verify();
909         }
910
911         resetFull();
912         iter1 = getList().listIterator();
913         iter2 = getConfirmedList().listIterator();
914         for (int i = 0; i < elements.length; i++) {
915             iter1.next();
916             iter2.next();
917             iter1.add(elements[i]);
918             iter2.add(elements[i]);
919             verify();
920         }
921     }
922
923
924     /**
925      * Tests the {@link ListIterator#set(Object)} method of the list
926      * iterator.
927      */

928     public void testListIteratorSet() {
929         if (!isSetSupported()) return;
930
931         Object JavaDoc[] elements = getFullElements();
932
933         resetFull();
934         ListIterator JavaDoc iter1 = getList().listIterator();
935         ListIterator JavaDoc iter2 = getConfirmedList().listIterator();
936         for (int i = 0; i < elements.length; i++) {
937             iter1.next();
938             iter2.next();
939             iter1.set(elements[i]);
940             iter2.set(elements[i]);
941             verify();
942         }
943     }
944
945
946     public void testEmptyListSerialization()
947     throws IOException JavaDoc, ClassNotFoundException JavaDoc {
948         List JavaDoc list = makeEmptyList();
949         if (!(list instanceof Serializable JavaDoc && isTestSerialization())) return;
950         
951         byte[] objekt = writeExternalFormToBytes((Serializable JavaDoc) list);
952         List JavaDoc list2 = (List JavaDoc) readExternalFormFromBytes(objekt);
953
954         assertTrue("Both lists are empty",list.size() == 0);
955         assertTrue("Both lists are empty",list2.size() == 0);
956     }
957
958     public void testFullListSerialization()
959     throws IOException JavaDoc, ClassNotFoundException JavaDoc {
960         List JavaDoc list = makeFullList();
961         int size = getFullElements().length;
962         if (!(list instanceof Serializable JavaDoc && isTestSerialization())) return;
963         
964         byte[] objekt = writeExternalFormToBytes((Serializable JavaDoc) list);
965         List JavaDoc list2 = (List JavaDoc) readExternalFormFromBytes(objekt);
966
967         assertEquals("Both lists are same size",list.size(), size);
968         assertEquals("Both lists are same size",list2.size(), size);
969     }
970
971     /**
972      * Compare the current serialized form of the List
973      * against the canonical version in CVS.
974      */

975     public void testEmptyListCompatibility() throws IOException JavaDoc, ClassNotFoundException JavaDoc {
976         /**
977          * Create canonical objects with this code
978         List list = makeEmptyList();
979         if (!(list instanceof Serializable)) return;
980         
981         writeExternalFormToDisk((Serializable) list, getCanonicalEmptyCollectionName(list));
982         */

983
984         // test to make sure the canonical form has been preserved
985
List JavaDoc list = makeEmptyList();
986         if(list instanceof Serializable JavaDoc && !skipSerializedCanonicalTests() && isTestSerialization()) {
987             List JavaDoc list2 = (List JavaDoc) readExternalFormFromDisk(getCanonicalEmptyCollectionName(list));
988             assertTrue("List is empty",list2.size() == 0);
989             assertEquals(list, list2);
990         }
991     }
992
993     /**
994      * Compare the current serialized form of the List
995      * against the canonical version in CVS.
996      */

997     public void testFullListCompatibility() throws IOException JavaDoc, ClassNotFoundException JavaDoc {
998         /**
999          * Create canonical objects with this code
1000        List list = makeFullList();
1001        if (!(list instanceof Serializable)) return;
1002        
1003        writeExternalFormToDisk((Serializable) list, getCanonicalFullCollectionName(list));
1004        */

1005
1006        // test to make sure the canonical form has been preserved
1007
List JavaDoc list = makeFullList();
1008        if(list instanceof Serializable JavaDoc && !skipSerializedCanonicalTests() && isTestSerialization()) {
1009            List JavaDoc list2 = (List JavaDoc) readExternalFormFromDisk(getCanonicalFullCollectionName(list));
1010            if (list2.size() == 4) {
1011                // old serialized tests
1012
return;
1013            }
1014            assertEquals("List is the right size",list.size(), list2.size());
1015            assertEquals(list, list2);
1016        }
1017    }
1018
1019    //-----------------------------------------------------------------------
1020
/**
1021     * Returns a {@link BulkTest} for testing {@link List#subList(int,int)}.
1022     * The returned bulk test will run through every <code>TestList</code>
1023     * method, <i>including</i> another <code>bulkTestSubList</code>.
1024     * Sublists are tested until the size of the sublist is less than 10.
1025     * Each sublist is 6 elements smaller than its parent list.
1026     * (By default this means that two rounds of sublists will be tested).
1027     * The verify() method is overloaded to test that the original list is
1028     * modified when the sublist is.
1029     */

1030    public BulkTest bulkTestSubList() {
1031        if (getFullElements().length - 6 < 10) return null;
1032        return new BulkTestSubList(this);
1033    }
1034
1035
1036   public static class BulkTestSubList extends AbstractTestList {
1037
1038       private AbstractTestList outer;
1039
1040
1041       BulkTestSubList(AbstractTestList outer) {
1042           super("");
1043           this.outer = outer;
1044       }
1045
1046
1047       public Object JavaDoc[] getFullElements() {
1048           List JavaDoc l = Arrays.asList(outer.getFullElements());
1049           return l.subList(3, l.size() - 3).toArray();
1050       }
1051
1052
1053       public Object JavaDoc[] getOtherElements() {
1054           return outer.getOtherElements();
1055       }
1056
1057
1058       public boolean isAddSupported() {
1059           return outer.isAddSupported();
1060       }
1061
1062       public boolean isSetSupported() {
1063           return outer.isSetSupported();
1064       }
1065
1066       public boolean isRemoveSupported() {
1067           return outer.isRemoveSupported();
1068       }
1069
1070
1071       public List JavaDoc makeEmptyList() {
1072           return outer.makeFullList().subList(4, 4);
1073       }
1074
1075
1076       public List JavaDoc makeFullList() {
1077           int size = getFullElements().length;
1078           return outer.makeFullList().subList(3, size - 3);
1079       }
1080
1081
1082       public void resetEmpty() {
1083           outer.resetFull();
1084           this.collection = outer.getList().subList(4, 4);
1085           this.confirmed = outer.getConfirmedList().subList(4, 4);
1086       }
1087
1088       public void resetFull() {
1089           outer.resetFull();
1090           int size = outer.confirmed.size();
1091           this.collection = outer.getList().subList(3, size - 3);
1092           this.confirmed = outer.getConfirmedList().subList(3, size - 3);
1093       }
1094
1095
1096       public void verify() {
1097           super.verify();
1098           outer.verify();
1099       }
1100
1101       public boolean isTestSerialization() {
1102           return false;
1103       }
1104   }
1105
1106
1107   /**
1108    * Tests that a sublist raises a {@link java.util.ConcurrentModificationException ConcurrentModificationException}
1109    * if elements are added to the original list.
1110    */

1111   public void testListSubListFailFastOnAdd() {
1112       if (!isFailFastSupported()) return;
1113       if (!isAddSupported()) return;
1114
1115       resetFull();
1116       int size = collection.size();
1117       List JavaDoc sub = getList().subList(1, size);
1118       getList().add(getOtherElements()[0]);
1119       failFastAll(sub);
1120
1121       resetFull();
1122       sub = getList().subList(1, size);
1123       getList().add(0, getOtherElements()[0]);
1124       failFastAll(sub);
1125
1126       resetFull();
1127       sub = getList().subList(1, size);
1128       getList().addAll(Arrays.asList(getOtherElements()));
1129       failFastAll(sub);
1130
1131       resetFull();
1132       sub = getList().subList(1, size);
1133       getList().addAll(0, Arrays.asList(getOtherElements()));
1134       failFastAll(sub);
1135
1136   }
1137
1138
1139   /**
1140    * Tests that a sublist raises a {@link java.util.ConcurrentModificationException ConcurrentModificationException}
1141    * if elements are removed from the original list.
1142    */

1143   public void testListSubListFailFastOnRemove() {
1144       if (!isFailFastSupported()) return;
1145       if (!isRemoveSupported()) return;
1146
1147       resetFull();
1148       int size = collection.size();
1149       List JavaDoc sub = getList().subList(1, size);
1150       getList().remove(0);
1151       failFastAll(sub);
1152
1153       resetFull();
1154       sub = getList().subList(1, size);
1155       getList().remove(getFullElements()[2]);
1156       failFastAll(sub);
1157
1158       resetFull();
1159       sub = getList().subList(1, size);
1160       getList().removeAll(Arrays.asList(getFullElements()));
1161       failFastAll(sub);
1162
1163       resetFull();
1164       sub = getList().subList(1, size);
1165       getList().retainAll(Arrays.asList(getOtherElements()));
1166       failFastAll(sub);
1167
1168       resetFull();
1169       sub = getList().subList(1, size);
1170       getList().clear();
1171       failFastAll(sub);
1172   }
1173
1174
1175   /**
1176    * Invokes all the methods on the given sublist to make sure they raise
1177    * a {@link java.util.ConcurrentModificationException ConcurrentModificationException}.
1178    */

1179   protected void failFastAll(List JavaDoc list) {
1180       Method JavaDoc[] methods = List JavaDoc.class.getMethods();
1181       for (int i = 0; i < methods.length; i++) {
1182           failFastMethod(list, methods[i]);
1183       }
1184   }
1185
1186
1187   /**
1188    * Invokes the given method on the given sublist to make sure it raises
1189    * a {@link java.util.ConcurrentModificationException ConcurrentModificationException}.
1190    *
1191    * Unless the method happens to be the equals() method, in which case
1192    * the test is skipped. There seems to be a bug in
1193    * java.util.AbstractList.subList(int,int).equals(Object) -- it never
1194    * raises a ConcurrentModificationException.
1195    *
1196    * @param list the sublist to test
1197    * @param m the method to invoke
1198    */

1199   protected void failFastMethod(List JavaDoc list, Method JavaDoc m) {
1200       if (m.getName().equals("equals")) return;
1201
1202       Object JavaDoc element = getOtherElements()[0];
1203       Collection JavaDoc c = Collections.singleton(element);
1204
1205       Class JavaDoc[] types = m.getParameterTypes();
1206       Object JavaDoc[] params = new Object JavaDoc[types.length];
1207       for (int i = 0; i < params.length; i++) {
1208           if (types[i] == Integer.TYPE) params[i] = new Integer JavaDoc(0);
1209           else if (types[i] == Collection JavaDoc.class) params[i] = c;
1210           else if (types[i] == Object JavaDoc.class) params[i] = element;
1211           else if (types[i] == Object JavaDoc[].class) params[i] = new Object JavaDoc[0];
1212       }
1213
1214       try {
1215           m.invoke(list, params);
1216           fail(m.getName() + " should raise ConcurrentModification");
1217       } catch (IllegalAccessException JavaDoc e) {
1218           // impossible
1219
} catch (InvocationTargetException JavaDoc e) {
1220           Throwable JavaDoc t = e.getTargetException();
1221           if (t instanceof ConcurrentModificationException JavaDoc) {
1222               // expected
1223
return;
1224           } else {
1225               fail(m.getName() + " raised unexpected " + e);
1226           }
1227       }
1228   }
1229
1230   //-----------------------------------------------------------------------
1231
public BulkTest bulkTestListIterator() {
1232       return new TestListIterator();
1233   }
1234    
1235   public class TestListIterator extends AbstractTestListIterator {
1236       public TestListIterator() {
1237           super("TestListIterator");
1238       }
1239        
1240       public Object JavaDoc addSetValue() {
1241           return AbstractTestList.this.getOtherElements()[0];
1242       }
1243        
1244       public boolean supportsRemove() {
1245           return AbstractTestList.this.isRemoveSupported();
1246       }
1247
1248       public boolean supportsAdd() {
1249           return AbstractTestList.this.isAddSupported();
1250       }
1251
1252       public boolean supportsSet() {
1253           return AbstractTestList.this.isSetSupported();
1254       }
1255
1256       public ListIterator JavaDoc makeEmptyListIterator() {
1257           resetEmpty();
1258           return ((List JavaDoc) AbstractTestList.this.collection).listIterator();
1259       }
1260
1261       public ListIterator JavaDoc makeFullListIterator() {
1262           resetFull();
1263           return ((List JavaDoc) AbstractTestList.this.collection).listIterator();
1264       }
1265   }
1266    
1267}
1268
Popular Tags