ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
Revision: 1.12
Committed: Sat Nov 5 16:10:38 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.11: +11 -0 lines
Log Message:
test clones of empty collections

File Contents

# User Rev Content
1 jsr166 1.1 /*
2     * Written by Doug Lea and Martin Buchholz with assistance from
3     * members of JCP JSR-166 Expert Group and released to the public
4     * domain, as explained at
5     * http://creativecommons.org/publicdomain/zero/1.0/
6     */
7    
8     import static java.util.concurrent.TimeUnit.MILLISECONDS;
9    
10     import java.util.ArrayList;
11     import java.util.Collection;
12     import java.util.Collections;
13 jsr166 1.5 import java.util.Deque;
14     import java.util.HashSet;
15     import java.util.Iterator;
16     import java.util.List;
17     import java.util.NoSuchElementException;
18     import java.util.Queue;
19     import java.util.Spliterator;
20 jsr166 1.2 import java.util.concurrent.CountDownLatch;
21 jsr166 1.1 import java.util.concurrent.Executors;
22     import java.util.concurrent.ExecutorService;
23     import java.util.concurrent.Future;
24 jsr166 1.5 import java.util.concurrent.ThreadLocalRandom;
25 jsr166 1.1 import java.util.concurrent.atomic.AtomicBoolean;
26     import java.util.concurrent.atomic.AtomicLong;
27 jsr166 1.5 import java.util.concurrent.atomic.AtomicReference;
28 jsr166 1.1 import java.util.function.Consumer;
29 jsr166 1.5 import java.util.function.Predicate;
30 jsr166 1.1
31     import junit.framework.Test;
32    
33     /**
34     * Contains tests applicable to all jdk8+ Collection implementations.
35     * An extension of CollectionTest.
36     */
37     public class Collection8Test extends JSR166TestCase {
38     final CollectionImplementation impl;
39    
40     /** Tests are parameterized by a Collection implementation. */
41     Collection8Test(CollectionImplementation impl, String methodName) {
42     super(methodName);
43     this.impl = impl;
44     }
45    
46     public static Test testSuite(CollectionImplementation impl) {
47     return parameterizedTestSuite(Collection8Test.class,
48     CollectionImplementation.class,
49     impl);
50     }
51    
52 jsr166 1.10 Object bomb() {
53     return new Object() {
54     public boolean equals(Object x) { throw new AssertionError(); }
55     public int hashCode() { throw new AssertionError(); }
56     };
57     }
58    
59 jsr166 1.5 /** Checks properties of empty collections. */
60     public void testEmptyMeansEmpty() {
61     Collection c = impl.emptyCollection();
62 jsr166 1.12 emptyMeansEmpty(c);
63    
64     if (c instanceof java.io.Serializable)
65     emptyMeansEmpty(serialClone(c));
66    
67     Collection clone = cloneableClone(c);
68     if (clone != null)
69     emptyMeansEmpty(clone);
70     }
71    
72     void emptyMeansEmpty(Collection c) {
73 jsr166 1.5 assertTrue(c.isEmpty());
74     assertEquals(0, c.size());
75     assertEquals("[]", c.toString());
76     {
77     Object[] a = c.toArray();
78     assertEquals(0, a.length);
79     assertSame(Object[].class, a.getClass());
80     }
81     {
82     Object[] a = new Object[0];
83     assertSame(a, c.toArray(a));
84     }
85     {
86     Integer[] a = new Integer[0];
87     assertSame(a, c.toArray(a));
88     }
89     {
90     Integer[] a = { 1, 2, 3};
91     assertSame(a, c.toArray(a));
92     assertNull(a[0]);
93     assertSame(2, a[1]);
94     assertSame(3, a[2]);
95     }
96     assertIteratorExhausted(c.iterator());
97     Consumer alwaysThrows = (e) -> { throw new AssertionError(); };
98     c.forEach(alwaysThrows);
99     c.iterator().forEachRemaining(alwaysThrows);
100     c.spliterator().forEachRemaining(alwaysThrows);
101     assertFalse(c.spliterator().tryAdvance(alwaysThrows));
102 jsr166 1.9 if (c.spliterator().hasCharacteristics(Spliterator.SIZED))
103     assertEquals(0, c.spliterator().estimateSize());
104 jsr166 1.10 assertFalse(c.contains(bomb()));
105     assertFalse(c.remove(bomb()));
106 jsr166 1.11 if (c instanceof Queue) {
107 jsr166 1.5 Queue q = (Queue) c;
108     assertNull(q.peek());
109     assertNull(q.poll());
110     }
111 jsr166 1.11 if (c instanceof Deque) {
112 jsr166 1.5 Deque d = (Deque) c;
113     assertNull(d.peekFirst());
114     assertNull(d.peekLast());
115     assertNull(d.pollFirst());
116     assertNull(d.pollLast());
117     assertIteratorExhausted(d.descendingIterator());
118 jsr166 1.9 d.descendingIterator().forEachRemaining(alwaysThrows);
119 jsr166 1.10 assertFalse(d.removeFirstOccurrence(bomb()));
120     assertFalse(d.removeLastOccurrence(bomb()));
121 jsr166 1.5 }
122     }
123    
124     public void testNullPointerExceptions() {
125     Collection c = impl.emptyCollection();
126     assertThrows(
127     NullPointerException.class,
128     () -> c.addAll(null),
129     () -> c.containsAll(null),
130     () -> c.retainAll(null),
131     () -> c.removeAll(null),
132     () -> c.removeIf(null),
133 jsr166 1.6 () -> c.forEach(null),
134     () -> c.iterator().forEachRemaining(null),
135     () -> c.spliterator().forEachRemaining(null),
136     () -> c.spliterator().tryAdvance(null),
137 jsr166 1.5 () -> c.toArray(null));
138    
139     if (!impl.permitsNulls()) {
140     assertThrows(
141     NullPointerException.class,
142     () -> c.add(null));
143     }
144     if (!impl.permitsNulls()
145     && Queue.class.isAssignableFrom(impl.klazz())) {
146     Queue q = (Queue) c;
147     assertThrows(
148     NullPointerException.class,
149     () -> q.offer(null));
150     }
151     if (!impl.permitsNulls()
152     && Deque.class.isAssignableFrom(impl.klazz())) {
153     Deque d = (Deque) c;
154     assertThrows(
155     NullPointerException.class,
156     () -> d.addFirst(null),
157     () -> d.addLast(null),
158     () -> d.offerFirst(null),
159     () -> d.offerLast(null),
160 jsr166 1.6 () -> d.push(null),
161     () -> d.descendingIterator().forEachRemaining(null));
162 jsr166 1.5 }
163     }
164    
165     public void testNoSuchElementExceptions() {
166     Collection c = impl.emptyCollection();
167     assertThrows(
168     NoSuchElementException.class,
169     () -> c.iterator().next());
170    
171     if (Queue.class.isAssignableFrom(impl.klazz())) {
172     Queue q = (Queue) c;
173     assertThrows(
174     NoSuchElementException.class,
175     () -> q.element(),
176     () -> q.remove());
177     }
178     if (Deque.class.isAssignableFrom(impl.klazz())) {
179     Deque d = (Deque) c;
180     assertThrows(
181     NoSuchElementException.class,
182     () -> d.getFirst(),
183     () -> d.getLast(),
184     () -> d.removeFirst(),
185     () -> d.removeLast(),
186     () -> d.pop(),
187     () -> d.descendingIterator().next());
188     }
189     }
190    
191     public void testRemoveIf() {
192     Collection c = impl.emptyCollection();
193     ThreadLocalRandom rnd = ThreadLocalRandom.current();
194     int n = rnd.nextInt(6);
195     for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
196     AtomicReference threwAt = new AtomicReference(null);
197     ArrayList survivors = new ArrayList(c);
198     ArrayList accepts = new ArrayList();
199     ArrayList rejects = new ArrayList();
200     Predicate randomPredicate = (e) -> {
201     assertNull(threwAt.get());
202     switch (rnd.nextInt(3)) {
203     case 0: accepts.add(e); return true;
204     case 1: rejects.add(e); return false;
205     case 2: threwAt.set(e); throw new ArithmeticException();
206     default: throw new AssertionError();
207     }
208     };
209     try {
210 jsr166 1.8 assertFalse(survivors.contains(null));
211 jsr166 1.7 try {
212     boolean modified = c.removeIf(randomPredicate);
213     if (!modified) {
214     assertNull(threwAt.get());
215     assertEquals(n, rejects.size());
216     assertEquals(0, accepts.size());
217     }
218     } catch (ArithmeticException ok) {}
219     survivors.removeAll(accepts);
220     assertEquals(n - accepts.size(), c.size());
221     assertTrue(c.containsAll(survivors));
222     assertTrue(survivors.containsAll(rejects));
223     for (Object x : accepts) assertFalse(c.contains(x));
224     if (threwAt.get() == null)
225     assertEquals(accepts.size() + rejects.size(), n);
226     } catch (Throwable ex) {
227 jsr166 1.5 System.err.println(impl.klazz());
228 jsr166 1.7 System.err.printf("c=%s%n", c);
229     System.err.printf("n=%d%n", n);
230     System.err.printf("accepts=%s%n", accepts);
231     System.err.printf("rejects=%s%n", rejects);
232 jsr166 1.8 System.err.printf("survivors=%s%n", survivors);
233 jsr166 1.7 System.err.printf("threw=%s%n", threwAt.get());
234     throw ex;
235 jsr166 1.5 }
236     }
237    
238     /**
239     * Various ways of traversing a collection yield same elements
240     */
241     public void testIteratorEquivalence() {
242     Collection c = impl.emptyCollection();
243     ThreadLocalRandom rnd = ThreadLocalRandom.current();
244     int n = rnd.nextInt(6);
245     for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
246     ArrayList iterated = new ArrayList();
247     ArrayList iteratedForEachRemaining = new ArrayList();
248     ArrayList spliterated = new ArrayList();
249     ArrayList foreached = new ArrayList();
250     for (Object x : c) iterated.add(x);
251     c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
252     c.spliterator().forEachRemaining(e -> spliterated.add(e));
253     c.forEach(e -> foreached.add(e));
254     boolean ordered =
255     c.spliterator().hasCharacteristics(Spliterator.ORDERED);
256     if (c instanceof List || c instanceof Deque)
257     assertTrue(ordered);
258     if (ordered) {
259     assertEquals(iterated, iteratedForEachRemaining);
260     assertEquals(iterated, spliterated);
261     assertEquals(iterated, foreached);
262     } else {
263     HashSet cset = new HashSet(c);
264     assertEquals(cset, new HashSet(iterated));
265     assertEquals(cset, new HashSet(iteratedForEachRemaining));
266     assertEquals(cset, new HashSet(spliterated));
267     assertEquals(cset, new HashSet(foreached));
268     }
269     if (c instanceof Deque) {
270     Deque d = (Deque) c;
271     ArrayList descending = new ArrayList();
272     ArrayList descendingForEachRemaining = new ArrayList();
273     for (Iterator it = d.descendingIterator(); it.hasNext(); )
274     descending.add(it.next());
275     d.descendingIterator().forEachRemaining(
276     e -> descendingForEachRemaining.add(e));
277     Collections.reverse(descending);
278     Collections.reverse(descendingForEachRemaining);
279     assertEquals(iterated, descending);
280     assertEquals(iterated, descendingForEachRemaining);
281     }
282     }
283    
284     /**
285     * Calling Iterator#remove() after Iterator#forEachRemaining
286     * should remove last element
287     */
288     public void testRemoveAfterForEachRemaining() {
289     Collection c = impl.emptyCollection();
290     ThreadLocalRandom rnd = ThreadLocalRandom.current();
291     {
292     int n = 3 + rnd.nextInt(2);
293     for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
294     Iterator it = c.iterator();
295     assertTrue(it.hasNext());
296     assertEquals(impl.makeElement(0), it.next());
297     assertTrue(it.hasNext());
298     assertEquals(impl.makeElement(1), it.next());
299     it.forEachRemaining((e) -> {});
300     it.remove();
301     assertEquals(n - 1, c.size());
302     for (int i = 0; i < n - 1; i++)
303     assertTrue(c.contains(impl.makeElement(i)));
304     assertFalse(c.contains(impl.makeElement(n - 1)));
305     }
306     if (c instanceof Deque) {
307     Deque d = (Deque) impl.emptyCollection();
308     int n = 3 + rnd.nextInt(2);
309     for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
310     Iterator it = d.descendingIterator();
311     assertTrue(it.hasNext());
312     assertEquals(impl.makeElement(n - 1), it.next());
313     assertTrue(it.hasNext());
314     assertEquals(impl.makeElement(n - 2), it.next());
315     it.forEachRemaining((e) -> {});
316     it.remove();
317     assertEquals(n - 1, d.size());
318     for (int i = 1; i < n; i++)
319     assertTrue(d.contains(impl.makeElement(i)));
320     assertFalse(d.contains(impl.makeElement(0)));
321     }
322     }
323    
324 jsr166 1.1 /**
325     * stream().forEach returns elements in the collection
326     */
327 jsr166 1.3 public void testStreamForEach() throws Throwable {
328 jsr166 1.1 final Collection c = impl.emptyCollection();
329     final AtomicLong count = new AtomicLong(0L);
330     final Object x = impl.makeElement(1);
331     final Object y = impl.makeElement(2);
332     final ArrayList found = new ArrayList();
333     Consumer<Object> spy = (o) -> { found.add(o); };
334     c.stream().forEach(spy);
335     assertTrue(found.isEmpty());
336    
337     assertTrue(c.add(x));
338     c.stream().forEach(spy);
339     assertEquals(Collections.singletonList(x), found);
340     found.clear();
341    
342     assertTrue(c.add(y));
343     c.stream().forEach(spy);
344     assertEquals(2, found.size());
345     assertTrue(found.contains(x));
346     assertTrue(found.contains(y));
347     found.clear();
348    
349     c.clear();
350     c.stream().forEach(spy);
351     assertTrue(found.isEmpty());
352     }
353    
354 jsr166 1.3 public void testStreamForEachConcurrentStressTest() throws Throwable {
355     if (!impl.isConcurrent()) return;
356     final Collection c = impl.emptyCollection();
357     final long testDurationMillis = timeoutMillis();
358     final AtomicBoolean done = new AtomicBoolean(false);
359     final Object elt = impl.makeElement(1);
360     final Future<?> f1, f2;
361     final ExecutorService pool = Executors.newCachedThreadPool();
362     try (PoolCleaner cleaner = cleaner(pool, done)) {
363     final CountDownLatch threadsStarted = new CountDownLatch(2);
364     Runnable checkElt = () -> {
365     threadsStarted.countDown();
366     while (!done.get())
367     c.stream().forEach((x) -> { assertSame(x, elt); }); };
368     Runnable addRemove = () -> {
369     threadsStarted.countDown();
370     while (!done.get()) {
371     assertTrue(c.add(elt));
372     assertTrue(c.remove(elt));
373     }};
374     f1 = pool.submit(checkElt);
375     f2 = pool.submit(addRemove);
376     Thread.sleep(testDurationMillis);
377     }
378     assertNull(f1.get(0L, MILLISECONDS));
379     assertNull(f2.get(0L, MILLISECONDS));
380     }
381    
382     /**
383     * collection.forEach returns elements in the collection
384     */
385     public void testForEach() throws Throwable {
386     final Collection c = impl.emptyCollection();
387     final AtomicLong count = new AtomicLong(0L);
388     final Object x = impl.makeElement(1);
389     final Object y = impl.makeElement(2);
390     final ArrayList found = new ArrayList();
391     Consumer<Object> spy = (o) -> { found.add(o); };
392     c.forEach(spy);
393     assertTrue(found.isEmpty());
394    
395     assertTrue(c.add(x));
396     c.forEach(spy);
397     assertEquals(Collections.singletonList(x), found);
398     found.clear();
399    
400     assertTrue(c.add(y));
401     c.forEach(spy);
402     assertEquals(2, found.size());
403     assertTrue(found.contains(x));
404     assertTrue(found.contains(y));
405     found.clear();
406    
407     c.clear();
408     c.forEach(spy);
409     assertTrue(found.isEmpty());
410     }
411    
412 jsr166 1.1 public void testForEachConcurrentStressTest() throws Throwable {
413     if (!impl.isConcurrent()) return;
414     final Collection c = impl.emptyCollection();
415 jsr166 1.2 final long testDurationMillis = timeoutMillis();
416 jsr166 1.1 final AtomicBoolean done = new AtomicBoolean(false);
417     final Object elt = impl.makeElement(1);
418 jsr166 1.2 final Future<?> f1, f2;
419     final ExecutorService pool = Executors.newCachedThreadPool();
420     try (PoolCleaner cleaner = cleaner(pool, done)) {
421     final CountDownLatch threadsStarted = new CountDownLatch(2);
422     Runnable checkElt = () -> {
423     threadsStarted.countDown();
424     while (!done.get())
425 jsr166 1.3 c.forEach((x) -> { assertSame(x, elt); }); };
426 jsr166 1.2 Runnable addRemove = () -> {
427     threadsStarted.countDown();
428     while (!done.get()) {
429     assertTrue(c.add(elt));
430     assertTrue(c.remove(elt));
431     }};
432     f1 = pool.submit(checkElt);
433     f2 = pool.submit(addRemove);
434     Thread.sleep(testDurationMillis);
435     }
436     assertNull(f1.get(0L, MILLISECONDS));
437     assertNull(f2.get(0L, MILLISECONDS));
438 jsr166 1.1 }
439    
440 jsr166 1.4 // public void testCollection8DebugFail() {
441     // fail(impl.klazz().getSimpleName());
442     // }
443 jsr166 1.1 }