code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.testers.NavigableSetNavigationTester; import java.util.List; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a NavigableSet implementation. */ public final class NavigableSetTestSuiteBuilder<E> extends SortedSetTestSuiteBuilder<E> { public static <E> NavigableSetTestSuiteBuilder<E> using( TestSetGenerator<E> generator) { NavigableSetTestSuiteBuilder<E> builder = new NavigableSetTestSuiteBuilder<E>(); builder.usingGenerator(generator); return builder; } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); testers.add(NavigableSetNavigationTester.class); return testers; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import com.google.common.annotations.GwtCompatible; import junit.framework.AssertionFailedError; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.Stack; /** * Most of the logic for {@link IteratorTester} and {@link ListIteratorTester}. * * <p>This class is GWT compatible. * * @param <E> the type of element returned by the iterator * @param <I> the type of the iterator ({@link Iterator} or * {@link ListIterator}) * * @author Kevin Bourrillion * @author Chris Povirk */ @GwtCompatible abstract class AbstractIteratorTester<E, I extends Iterator<E>> { private boolean whenNextThrowsExceptionStopTestingCallsToRemove; private boolean whenAddThrowsExceptionStopTesting; /** * Don't verify iterator behavior on remove() after a call to next() * throws an exception. * * <p>JDK 6 currently has a bug where some iterators get into a undefined * state when next() throws a NoSuchElementException. The correct * behavior is for remove() to remove the last element returned by * next, even if a subsequent next() call threw an exception; however * JDK 6's HashMap and related classes throw an IllegalStateException * in this case. * * <p>Calling this method causes the iterator tester to skip testing * any remove() in a stimulus sequence after the reference iterator * throws an exception in next(). * * <p>TODO: remove this once we're on 6u5, which has the fix. * * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6529795"> * Sun Java Bug 6529795</a> */ public void ignoreSunJavaBug6529795() { whenNextThrowsExceptionStopTestingCallsToRemove = true; } /** * Don't verify iterator behavior after a call to add() throws an exception. * * <p>AbstractList's ListIterator implementation gets into a undefined state * when add() throws an UnsupportedOperationException. Instead of leaving the * iterator's position unmodified, it increments it, skipping an element or * even moving past the end of the list. * * <p>Calling this method causes the iterator tester to skip testing in a * stimulus sequence after the iterator under test throws an exception in * add(). * * <p>TODO: remove this once the behavior is fixed. * * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6533203"> * Sun Java Bug 6533203</a> */ public void stopTestingWhenAddThrowsException() { whenAddThrowsExceptionStopTesting = true; } private Stimulus<E, ? super I>[] stimuli; private final Iterator<E> elementsToInsert; private final Set<IteratorFeature> features; private final List<E> expectedElements; private final int startIndex; private final KnownOrder knownOrder; /** * Meta-exception thrown by * {@link AbstractIteratorTester.MultiExceptionListIterator} instead of * throwing any particular exception type. */ // This class is accessible but not supported in GWT. private static final class PermittedMetaException extends RuntimeException { final Set<? extends Class<? extends RuntimeException>> exceptionClasses; PermittedMetaException( Set<? extends Class<? extends RuntimeException>> exceptionClasses) { super("one of " + exceptionClasses); this.exceptionClasses = exceptionClasses; } PermittedMetaException(Class<? extends RuntimeException> exceptionClass) { this(Collections.singleton(exceptionClass)); } // It's not supported In GWT, it always returns true. boolean isPermitted(RuntimeException exception) { for (Class<? extends RuntimeException> clazz : exceptionClasses) { if (Platform.checkIsInstance(clazz, exception)) { return true; } } return false; } // It's not supported in GWT, it always passes. void assertPermitted(RuntimeException exception) { if (!isPermitted(exception)) { // TODO: use simple class names String message = "Exception " + exception.getClass() + " was thrown; expected " + this; Helpers.fail(exception, message); } } @Override public String toString() { return getMessage(); } private static final long serialVersionUID = 0; } private static final class UnknownElementException extends RuntimeException { private UnknownElementException(Collection<?> expected, Object actual) { super("Returned value '" + actual + "' not found. Remaining elements: " + expected); } private static final long serialVersionUID = 0; } /** * Quasi-implementation of {@link ListIterator} that works from a list of * elements and a set of features to support (from the enclosing * {@link AbstractIteratorTester} instance). Instead of throwing exceptions * like {@link NoSuchElementException} at the appropriate times, it throws * {@link PermittedMetaException} instances, which wrap a set of all * exceptions that the iterator could throw during the invocation of that * method. This is necessary because, e.g., a call to * {@code iterator().remove()} of an unmodifiable list could throw either * {@link IllegalStateException} or {@link UnsupportedOperationException}. * Note that iterator implementations should always throw one of the * exceptions in a {@code PermittedExceptions} instance, since * {@code PermittedExceptions} is thrown only when a method call is invalid. * * <p>This class is accessible but not supported in GWT as it references * {@link PermittedMetaException}. */ protected final class MultiExceptionListIterator implements ListIterator<E> { // TODO: track seen elements when order isn't guaranteed // TODO: verify contents afterward // TODO: something shiny and new instead of Stack // TODO: test whether null is supported (create a Feature) /** * The elements to be returned by future calls to {@code next()}, with the * first at the top of the stack. */ final Stack<E> nextElements = new Stack<E>(); /** * The elements to be returned by future calls to {@code previous()}, with * the first at the top of the stack. */ final Stack<E> previousElements = new Stack<E>(); /** * {@link #nextElements} if {@code next()} was called more recently then * {@code previous}, {@link #previousElements} if the reverse is true, or -- * overriding both of these -- {@code null} if {@code remove()} or * {@code add()} has been called more recently than either. We use this to * determine which stack to pop from on a call to {@code remove()} (or to * pop from and push to on a call to {@code set()}. */ Stack<E> stackWithLastReturnedElementAtTop = null; MultiExceptionListIterator(List<E> expectedElements) { Helpers.addAll(nextElements, Helpers.reverse(expectedElements)); for (int i = 0; i < startIndex; i++) { previousElements.push(nextElements.pop()); } } @Override public void add(E e) { if (!features.contains(IteratorFeature.SUPPORTS_ADD)) { throw new PermittedMetaException(UnsupportedOperationException.class); } previousElements.push(e); stackWithLastReturnedElementAtTop = null; } @Override public boolean hasNext() { return !nextElements.isEmpty(); } @Override public boolean hasPrevious() { return !previousElements.isEmpty(); } @Override public E next() { return transferElement(nextElements, previousElements); } @Override public int nextIndex() { return previousElements.size(); } @Override public E previous() { return transferElement(previousElements, nextElements); } @Override public int previousIndex() { return nextIndex() - 1; } @Override public void remove() { throwIfInvalid(IteratorFeature.SUPPORTS_REMOVE); stackWithLastReturnedElementAtTop.pop(); stackWithLastReturnedElementAtTop = null; } @Override public void set(E e) { throwIfInvalid(IteratorFeature.SUPPORTS_SET); stackWithLastReturnedElementAtTop.pop(); stackWithLastReturnedElementAtTop.push(e); } /** * Moves the given element from its current position in * {@link #nextElements} to the top of the stack so that it is returned by * the next call to {@link Iterator#next()}. If the element is not in * {@link #nextElements}, this method throws an * {@link UnknownElementException}. * * <p>This method is used when testing iterators without a known ordering. * We poll the target iterator's next element and pass it to the reference * iterator through this method so it can return the same element. This * enables the assertion to pass and the reference iterator to properly * update its state. */ void promoteToNext(E e) { if (nextElements.remove(e)) { nextElements.push(e); } else { throw new UnknownElementException(nextElements, e); } } private E transferElement(Stack<E> source, Stack<E> destination) { if (source.isEmpty()) { throw new PermittedMetaException(NoSuchElementException.class); } destination.push(source.pop()); stackWithLastReturnedElementAtTop = destination; return destination.peek(); } private void throwIfInvalid(IteratorFeature methodFeature) { Set<Class<? extends RuntimeException>> exceptions = new HashSet<Class<? extends RuntimeException>>(); if (!features.contains(methodFeature)) { exceptions.add(UnsupportedOperationException.class); } if (stackWithLastReturnedElementAtTop == null) { exceptions.add(IllegalStateException.class); } if (!exceptions.isEmpty()) { throw new PermittedMetaException(exceptions); } } private List<E> getElements() { List<E> elements = new ArrayList<E>(); Helpers.addAll(elements, previousElements); Helpers.addAll(elements, Helpers.reverse(nextElements)); return elements; } } public enum KnownOrder { KNOWN_ORDER, UNKNOWN_ORDER } @SuppressWarnings("unchecked") // creating array of generic class Stimulus AbstractIteratorTester(int steps, Iterable<E> elementsToInsertIterable, Iterable<? extends IteratorFeature> features, Iterable<E> expectedElements, KnownOrder knownOrder, int startIndex) { // periodically we should manually try (steps * 3 / 2) here; all tests but // one should still pass (testVerifyGetsCalled()). stimuli = new Stimulus[steps]; if (!elementsToInsertIterable.iterator().hasNext()) { throw new IllegalArgumentException(); } elementsToInsert = Helpers.cycle(elementsToInsertIterable); this.features = Helpers.copyToSet(features); this.expectedElements = Helpers.copyToList(expectedElements); this.knownOrder = knownOrder; this.startIndex = startIndex; } /** * I'd like to make this a parameter to the constructor, but I can't because * the stimulus instances refer to {@code this}. */ protected abstract Iterable<? extends Stimulus<E, ? super I>> getStimulusValues(); /** * Returns a new target iterator each time it's called. This is the iterator * you are trying to test. This must return an Iterator that returns the * expected elements passed to the constructor in the given order. Warning: it * is not enough to simply pull multiple iterators from the same source * Iterable, unless that Iterator is unmodifiable. */ protected abstract I newTargetIterator(); /** * Override this to verify anything after running a list of Stimuli. * * <p>For example, verify that calls to remove() actually removed * the correct elements. * * @param elements the expected elements passed to the constructor, as mutated * by {@code remove()}, {@code set()}, and {@code add()} calls */ protected void verify(List<E> elements) {} /** * Executes the test. */ public final void test() { try { recurse(0); } catch (RuntimeException e) { throw new RuntimeException(Arrays.toString(stimuli), e); } } private void recurse(int level) { // We're going to reuse the stimuli array 3^steps times by overwriting it // in a recursive loop. Sneaky. if (level == stimuli.length) { // We've filled the array. compareResultsForThisListOfStimuli(); } else { // Keep recursing to fill the array. for (Stimulus<E, ? super I> stimulus : getStimulusValues()) { stimuli[level] = stimulus; recurse(level + 1); } } } private void compareResultsForThisListOfStimuli() { MultiExceptionListIterator reference = new MultiExceptionListIterator(expectedElements); I target = newTargetIterator(); boolean shouldStopTestingCallsToRemove = false; for (int i = 0; i < stimuli.length; i++) { Stimulus<E, ? super I> stimulus = stimuli[i]; if (stimulus.equals(remove) && shouldStopTestingCallsToRemove) { break; } try { boolean threwException = stimulus.executeAndCompare(reference, target); if (threwException && stimulus.equals(next) && whenNextThrowsExceptionStopTestingCallsToRemove) { shouldStopTestingCallsToRemove = true; } if (threwException && stimulus.equals(add) && whenAddThrowsExceptionStopTesting) { break; } List<E> elements = reference.getElements(); verify(elements); } catch (AssertionFailedError cause) { Helpers.fail(cause, "failed with stimuli " + subListCopy(stimuli, i + 1)); } } } private static List<Object> subListCopy(Object[] source, int size) { final Object[] copy = new Object[size]; System.arraycopy(source, 0, copy, 0, size); return Arrays.asList(copy); } private interface IteratorOperation { Object execute(Iterator<?> iterator); } /** * Apply this method to both iterators and return normally only if both * produce the same response. * * @return {@code true} if an exception was thrown by the iterators. * * @see Stimulus#executeAndCompare(ListIterator, Iterator) */ private <T extends Iterator<E>> boolean internalExecuteAndCompare( T reference, T target, IteratorOperation method) throws AssertionFailedError { Object referenceReturnValue = null; PermittedMetaException referenceException = null; Object targetReturnValue = null; RuntimeException targetException = null; try { targetReturnValue = method.execute(target); } catch (RuntimeException e) { targetException = e; } try { if (method == NEXT_METHOD && targetException == null && knownOrder == KnownOrder.UNKNOWN_ORDER) { /* * We already know the iterator is an Iterator<E>, and now we know that * we called next(), so the returned element must be of type E. */ @SuppressWarnings("unchecked") E targetReturnValueFromNext = (E) targetReturnValue; /* * We have an Iterator<E> and want to cast it to * MultiExceptionListIterator. Because we're inside an * AbstractIteratorTester<E>, that's implicitly a cast to * AbstractIteratorTester<E>.MultiExceptionListIterator. The runtime * won't be able to verify the AbstractIteratorTester<E> part, so it's * an unchecked cast. We know, however, that the only possible value for * the type parameter is <E>, since otherwise the * MultiExceptionListIterator wouldn't be an Iterator<E>. The cast is * safe, even though javac can't tell. * * Sun bug 6665356 is an additional complication. Until OpenJDK 7, javac * doesn't recognize this kind of cast as unchecked cast. Neither does * Eclipse 3.4. Right now, this suppression is mostly unecessary. */ MultiExceptionListIterator multiExceptionListIterator = (MultiExceptionListIterator) reference; multiExceptionListIterator.promoteToNext(targetReturnValueFromNext); } referenceReturnValue = method.execute(reference); } catch (PermittedMetaException e) { referenceException = e; } catch (UnknownElementException e) { Helpers.fail(e, e.getMessage()); } if (referenceException == null) { if (targetException != null) { Helpers.fail(targetException, "Target threw exception when reference did not"); } /* * Reference iterator returned a value, so we should expect the * same value from the target */ assertEquals(referenceReturnValue, targetReturnValue); return false; } if (targetException == null) { fail("Target failed to throw " + referenceException); } /* * Reference iterator threw an exception, so we should expect an acceptable * exception from the target. */ referenceException.assertPermitted(targetException); return true; } private static final IteratorOperation REMOVE_METHOD = new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { iterator.remove(); return null; } }; private static final IteratorOperation NEXT_METHOD = new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { return iterator.next(); } }; private static final IteratorOperation PREVIOUS_METHOD = new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { return ((ListIterator<?>) iterator).previous(); } }; private final IteratorOperation newAddMethod() { final Object toInsert = elementsToInsert.next(); return new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { @SuppressWarnings("unchecked") ListIterator<Object> rawIterator = (ListIterator<Object>) iterator; rawIterator.add(toInsert); return null; } }; } private final IteratorOperation newSetMethod() { final E toInsert = elementsToInsert.next(); return new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { @SuppressWarnings("unchecked") ListIterator<E> li = (ListIterator<E>) iterator; li.set(toInsert); return null; } }; } abstract static class Stimulus<E, T extends Iterator<E>> { private final String toString; protected Stimulus(String toString) { this.toString = toString; } /** * Send this stimulus to both iterators and return normally only if both * produce the same response. * * @return {@code true} if an exception was thrown by the iterators. */ abstract boolean executeAndCompare(ListIterator<E> reference, T target); @Override public String toString() { return toString; } } Stimulus<E, Iterator<E>> hasNext = new Stimulus<E, Iterator<E>>("hasNext") { @Override boolean executeAndCompare(ListIterator<E> reference, Iterator<E> target) { // return only if both are true or both are false assertEquals(reference.hasNext(), target.hasNext()); return false; } }; Stimulus<E, Iterator<E>> next = new Stimulus<E, Iterator<E>>("next") { @Override boolean executeAndCompare(ListIterator<E> reference, Iterator<E> target) { return internalExecuteAndCompare(reference, target, NEXT_METHOD); } }; Stimulus<E, Iterator<E>> remove = new Stimulus<E, Iterator<E>>("remove") { @Override boolean executeAndCompare(ListIterator<E> reference, Iterator<E> target) { return internalExecuteAndCompare(reference, target, REMOVE_METHOD); } }; @SuppressWarnings("unchecked") List<Stimulus<E, Iterator<E>>> iteratorStimuli() { return Arrays.asList(hasNext, next, remove); } Stimulus<E, ListIterator<E>> hasPrevious = new Stimulus<E, ListIterator<E>>("hasPrevious") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { // return only if both are true or both are false assertEquals(reference.hasPrevious(), target.hasPrevious()); return false; } }; Stimulus<E, ListIterator<E>> nextIndex = new Stimulus<E, ListIterator<E>>("nextIndex") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { assertEquals(reference.nextIndex(), target.nextIndex()); return false; } }; Stimulus<E, ListIterator<E>> previousIndex = new Stimulus<E, ListIterator<E>>("previousIndex") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { assertEquals(reference.previousIndex(), target.previousIndex()); return false; } }; Stimulus<E, ListIterator<E>> previous = new Stimulus<E, ListIterator<E>>("previous") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { return internalExecuteAndCompare(reference, target, PREVIOUS_METHOD); } }; Stimulus<E, ListIterator<E>> add = new Stimulus<E, ListIterator<E>>("add") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { return internalExecuteAndCompare(reference, target, newAddMethod()); } }; Stimulus<E, ListIterator<E>> set = new Stimulus<E, ListIterator<E>>("set") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { return internalExecuteAndCompare(reference, target, newSetMethod()); } }; @SuppressWarnings("unchecked") List<Stimulus<E, ListIterator<E>>> listIteratorStimuli() { return Arrays.asList( hasPrevious, nextIndex, previousIndex, previous, add, set); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.NavigableMap; /** * A generic JUnit test which tests operations on a NavigableMap. Can't be * invoked directly; please see {@code NavigableMapTestSuiteBuilder}. * * @author Jesse Wilson * @author Louis Wasserman */ public class NavigableMapNavigationTester<K, V> extends AbstractMapTester<K, V> { private NavigableMap<K, V> navigableMap; private List<Entry<K, V>> entries; private Entry<K, V> a; private Entry<K, V> b; private Entry<K, V> c; @Override public void setUp() throws Exception { super.setUp(); navigableMap = (NavigableMap<K, V>) getMap(); entries = Helpers.copyToList(getSubjectGenerator().getSampleElements( getSubjectGenerator().getCollectionSize().getNumElements())); Collections.sort(entries, Helpers.<K, V>entryComparator(navigableMap.comparator())); // some tests assume SEVERAL == 3 if (entries.size() >= 1) { a = entries.get(0); if (entries.size() >= 3) { b = entries.get(1); c = entries.get(2); } } } /** * Resets the contents of navigableMap to have entries a, c, for the * navigation tests. */ @SuppressWarnings("unchecked") // Needed to stop Eclipse whining private void resetWithHole() { Entry<K, V>[] entries = new Entry[] {a, c}; super.resetMap(entries); navigableMap = (NavigableMap<K, V>) getMap(); } @CollectionSize.Require(ZERO) public void testEmptyMapFirst() { assertNull(navigableMap.firstEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptyMapPollFirst() { assertNull(navigableMap.pollFirstEntry()); } @CollectionSize.Require(ZERO) public void testEmptyMapNearby() { assertNull(navigableMap.lowerEntry(samples.e0.getKey())); assertNull(navigableMap.lowerKey(samples.e0.getKey())); assertNull(navigableMap.floorEntry(samples.e0.getKey())); assertNull(navigableMap.floorKey(samples.e0.getKey())); assertNull(navigableMap.ceilingEntry(samples.e0.getKey())); assertNull(navigableMap.ceilingKey(samples.e0.getKey())); assertNull(navigableMap.higherEntry(samples.e0.getKey())); assertNull(navigableMap.higherKey(samples.e0.getKey())); } @CollectionSize.Require(ZERO) public void testEmptyMapLast() { assertNull(navigableMap.lastEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptyMapPollLast() { assertNull(navigableMap.pollLastEntry()); } @CollectionSize.Require(ONE) public void testSingletonMapFirst() { assertEquals(a, navigableMap.firstEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonMapPollFirst() { assertEquals(a, navigableMap.pollFirstEntry()); assertTrue(navigableMap.isEmpty()); } @CollectionSize.Require(ONE) public void testSingletonMapNearby() { assertNull(navigableMap.lowerEntry(samples.e0.getKey())); assertNull(navigableMap.lowerKey(samples.e0.getKey())); assertEquals(a, navigableMap.floorEntry(samples.e0.getKey())); assertEquals(a.getKey(), navigableMap.floorKey(samples.e0.getKey())); assertEquals(a, navigableMap.ceilingEntry(samples.e0.getKey())); assertEquals(a.getKey(), navigableMap.ceilingKey(samples.e0.getKey())); assertNull(navigableMap.higherEntry(samples.e0.getKey())); assertNull(navigableMap.higherKey(samples.e0.getKey())); } @CollectionSize.Require(ONE) public void testSingletonMapLast() { assertEquals(a, navigableMap.lastEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonMapPollLast() { assertEquals(a, navigableMap.pollLastEntry()); assertTrue(navigableMap.isEmpty()); } @CollectionSize.Require(SEVERAL) public void testFirst() { assertEquals(a, navigableMap.firstEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollFirst() { assertEquals(a, navigableMap.pollFirstEntry()); assertEquals(entries.subList(1, entries.size()), Helpers.copyToList(navigableMap.entrySet())); } @MapFeature.Require(absent = SUPPORTS_REMOVE) public void testPollFirstUnsupported() { try { navigableMap.pollFirstEntry(); fail(); } catch (UnsupportedOperationException e) { } } @CollectionSize.Require(SEVERAL) public void testLower() { resetWithHole(); assertEquals(null, navigableMap.lowerEntry(a.getKey())); assertEquals(null, navigableMap.lowerKey(a.getKey())); assertEquals(a, navigableMap.lowerEntry(b.getKey())); assertEquals(a.getKey(), navigableMap.lowerKey(b.getKey())); assertEquals(a, navigableMap.lowerEntry(c.getKey())); assertEquals(a.getKey(), navigableMap.lowerKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testFloor() { resetWithHole(); assertEquals(a, navigableMap.floorEntry(a.getKey())); assertEquals(a.getKey(), navigableMap.floorKey(a.getKey())); assertEquals(a, navigableMap.floorEntry(b.getKey())); assertEquals(a.getKey(), navigableMap.floorKey(b.getKey())); assertEquals(c, navigableMap.floorEntry(c.getKey())); assertEquals(c.getKey(), navigableMap.floorKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testCeiling() { resetWithHole(); assertEquals(a, navigableMap.ceilingEntry(a.getKey())); assertEquals(a.getKey(), navigableMap.ceilingKey(a.getKey())); assertEquals(c, navigableMap.ceilingEntry(b.getKey())); assertEquals(c.getKey(), navigableMap.ceilingKey(b.getKey())); assertEquals(c, navigableMap.ceilingEntry(c.getKey())); assertEquals(c.getKey(), navigableMap.ceilingKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testHigher() { resetWithHole(); assertEquals(c, navigableMap.higherEntry(a.getKey())); assertEquals(c.getKey(), navigableMap.higherKey(a.getKey())); assertEquals(c, navigableMap.higherEntry(b.getKey())); assertEquals(c.getKey(), navigableMap.higherKey(b.getKey())); assertEquals(null, navigableMap.higherEntry(c.getKey())); assertEquals(null, navigableMap.higherKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testLast() { assertEquals(c, navigableMap.lastEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLast() { assertEquals(c, navigableMap.pollLastEntry()); assertEquals(entries.subList(0, entries.size() - 1), Helpers.copyToList(navigableMap.entrySet())); } @MapFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLastUnsupported() { try { navigableMap.pollLastEntry(); fail(); } catch (UnsupportedOperationException e) { } } @CollectionSize.Require(SEVERAL) public void testDescendingNavigation() { List<Entry<K, V>> descending = new ArrayList<Entry<K, V>>(); for (Entry<K, V> entry : navigableMap.descendingMap().entrySet()) { descending.add(entry); } Collections.reverse(descending); assertEquals(entries, descending); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.Helpers.getMethod; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; import static java.util.Collections.emptyList; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import com.google.common.testing.SerializableTester; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * A generic JUnit test which tests {@code subList()} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class ListSubListTester<E> extends AbstractListTester<E> { public void testSubList_startNegative() { try { getList().subList(-1, 0); fail("subList(-1, 0) should throw"); } catch (IndexOutOfBoundsException expected) { } } public void testSubList_endTooLarge() { try { getList().subList(0, getNumElements() + 1); fail("subList(0, size + 1) should throw"); } catch (IndexOutOfBoundsException expected) { } } public void testSubList_startGreaterThanEnd() { try { getList().subList(1, 0); fail("subList(1, 0) should throw"); } catch (IndexOutOfBoundsException expected) { } catch (IllegalArgumentException expected) { /* * The subList() docs claim that this should be an * IndexOutOfBoundsException, but many JDK implementations throw * IllegalArgumentException: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4506427 */ } } public void testSubList_empty() { assertEquals("subList(0, 0) should be empty", emptyList(), getList().subList(0, 0)); } public void testSubList_entireList() { assertEquals("subList(0, size) should be equal to the original list", getList(), getList().subList(0, getNumElements())); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testSubList_subListRemoveAffectsOriginal() { List<E> subList = getList().subList(0, 1); subList.remove(0); List<E> expected = Arrays.asList(createSamplesArray()).subList(1, getNumElements()); expectContents(expected); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testSubList_subListAddAffectsOriginal() { List<E> subList = getList().subList(0, 0); subList.add(samples.e3); expectAdded(0, samples.e3); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = ZERO) public void testSubList_subListSetAffectsOriginal() { List<E> subList = getList().subList(0, 1); subList.set(0, samples.e3); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.set(0, samples.e3); expectContents(expected); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = ZERO) public void testSubList_originalListSetAffectsSubList() { List<E> subList = getList().subList(0, 1); getList().set(0, samples.e3); assertEquals("A set() call to a list after a sublist has been created " + "should be reflected in the sublist", Collections.singletonList(samples.e3), subList); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_subListRemoveAffectsOriginalLargeList() { List<E> subList = getList().subList(1, 3); subList.remove(samples.e2); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.remove(2); expectContents(expected); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_subListAddAtIndexAffectsOriginalLargeList() { List<E> subList = getList().subList(2, 3); subList.add(0, samples.e3); expectAdded(2, samples.e3); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_subListSetAffectsOriginalLargeList() { List<E> subList = getList().subList(1, 2); subList.set(0, samples.e3); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.set(1, samples.e3); expectContents(expected); } @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_originalListSetAffectsSubListLargeList() { List<E> subList = getList().subList(1, 3); getList().set(1, samples.e3); assertEquals("A set() call to a list after a sublist has been created " + "should be reflected in the sublist", Arrays.asList(samples.e3, samples.e2), subList); } public void testSubList_ofSubListEmpty() { List<E> subList = getList().subList(0, 0).subList(0, 0); assertEquals("subList(0, 0).subList(0, 0) should be an empty list", emptyList(), subList); } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_ofSubListNonEmpty() { List<E> subList = getList().subList(0, 2).subList(1, 2); assertEquals("subList(0, 2).subList(1, 2) " + "should be a single-element list of the element at index 1", Collections.singletonList(samples.e1), subList); } @CollectionSize.Require(absent = {ZERO}) public void testSubList_size() { List<E> list = getList(); int size = getNumElements(); assertEquals(list.subList(0, size).size(), size); assertEquals(list.subList(0, size - 1).size(), size - 1); assertEquals(list.subList(1, size).size(), size - 1); assertEquals(list.subList(size, size).size(), 0); assertEquals(list.subList(0, 0).size(), 0); } @CollectionSize.Require(absent = {ZERO}) public void testSubList_isEmpty() { List<E> list = getList(); int size = getNumElements(); for (List<E> subList : Arrays.asList( list.subList(0, size), list.subList(0, size - 1), list.subList(1, size), list.subList(0, 0), list.subList(size, size))) { assertEquals(subList.isEmpty(), subList.size() == 0); } } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_get() { List<E> list = getList(); int size = getNumElements(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertEquals(list.get(0), copy.get(0)); assertEquals(list.get(size - 1), copy.get(size - 1)); assertEquals(list.get(1), tail.get(0)); assertEquals(list.get(size - 1), tail.get(size - 2)); assertEquals(list.get(0), head.get(0)); assertEquals(list.get(size - 2), head.get(size - 2)); for (List<E> subList : Arrays.asList(copy, head, tail)) { for (int index : Arrays.asList(-1, subList.size())) { try { subList.get(index); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expected) { } } } } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_contains() { List<E> list = getList(); int size = getNumElements(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertTrue(copy.contains(list.get(0))); assertTrue(head.contains(list.get(0))); assertTrue(tail.contains(list.get(1))); // The following assumes all elements are distinct. assertTrue(copy.contains(list.get(size - 1))); assertTrue(head.contains(list.get(size - 2))); assertTrue(tail.contains(list.get(size - 1))); assertFalse(head.contains(list.get(size - 1))); assertFalse(tail.contains(list.get(0))); } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_indexOf() { List<E> list = getList(); int size = getNumElements(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertEquals(copy.indexOf(list.get(0)), 0); assertEquals(head.indexOf(list.get(0)), 0); assertEquals(tail.indexOf(list.get(1)), 0); // The following assumes all elements are distinct. assertEquals(copy.indexOf(list.get(size - 1)), size - 1); assertEquals(head.indexOf(list.get(size - 2)), size - 2); assertEquals(tail.indexOf(list.get(size - 1)), size - 2); assertEquals(head.indexOf(list.get(size - 1)), -1); assertEquals(tail.indexOf(list.get(0)), -1); } @CollectionSize.Require(absent = {ZERO, ONE}) public void testSubList_lastIndexOf() { List<E> list = getList(); int size = list.size(); List<E> copy = list.subList(0, size); List<E> head = list.subList(0, size - 1); List<E> tail = list.subList(1, size); assertEquals(copy.lastIndexOf(list.get(size - 1)), size - 1); assertEquals(head.lastIndexOf(list.get(size - 2)), size - 2); assertEquals(tail.lastIndexOf(list.get(size - 1)), size - 2); // The following assumes all elements are distinct. assertEquals(copy.lastIndexOf(list.get(0)), 0); assertEquals(head.lastIndexOf(list.get(0)), 0); assertEquals(tail.lastIndexOf(list.get(1)), 0); assertEquals(head.lastIndexOf(list.get(size - 1)), -1); assertEquals(tail.lastIndexOf(list.get(0)), -1); } @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) public void testReserializeWholeSubList() { SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements())); } @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) public void testReserializeEmptySubList() { SerializableTester.reserializeAndAssert(getList().subList(0, 0)); } @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS) @CollectionSize.Require(absent = {ZERO, ONE}) public void testReserializeSubList() { SerializableTester.reserializeAndAssert(getList().subList(0, 2)); } /** * Returns the {@link Method} instance for * {@link #testSubList_originalListSetAffectsSubList()} so that tests * of {@link CopyOnWriteArrayList} can suppress them with * {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570631">Sun bug * 6570631</a> is fixed. */ @GwtIncompatible("reflection") public static Method getSubListOriginalListSetAffectsSubListMethod() { return getMethod(ListSubListTester.class, "testSubList_originalListSetAffectsSubList"); } /** * Returns the {@link Method} instance for * {@link #testSubList_originalListSetAffectsSubListLargeList()} ()} so that * tests of {@link CopyOnWriteArrayList} can suppress them with * {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570631">Sun bug * 6570631</a> is fixed. */ @GwtIncompatible("reflection") public static Method getSubListOriginalListSetAffectsSubListLargeListMethod() { return getMethod(ListSubListTester.class, "testSubList_originalListSetAffectsSubListLargeList"); } /** * Returns the {@link Method} instance for * {@link #testSubList_subListRemoveAffectsOriginalLargeList()} so that tests * of {@link CopyOnWriteArrayList} can suppress it with * {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570575">Sun bug * 6570575</a> is fixed. */ @GwtIncompatible("reflection") public static Method getSubListSubListRemoveAffectsOriginalLargeListMethod() { return getMethod(ListSubListTester.class, "testSubList_subListRemoveAffectsOriginalLargeList"); } /* * TODO: perform all List tests on subList(), but beware infinite recursion */ }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code addAll(Collection)} operations on a * list. Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class ListAddAllTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_supportedAllPresent() { assertTrue("addAll(allPresent) should return true", getList().addAll(MinimalCollection.of(samples.e0))); expectAdded(samples.e0); } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_unsupportedAllPresent() { try { getList().addAll(MinimalCollection.of(samples.e0)); fail("addAll(allPresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_withDuplicates() { MinimalCollection<E> elementsToAdd = MinimalCollection.of(samples.e0, samples.e1, samples.e0, samples.e1); assertTrue("addAll(hasDuplicates) should return true", getList().addAll(elementsToAdd)); expectAdded(samples.e0, samples.e1, samples.e0, samples.e1); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map.Entry; /** * A generic JUnit test which tests {@code clear()} operations on a map. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche * @author Chris Povirk */ @GwtCompatible public class MapClearTester<K, V> extends AbstractMapTester<K, V> { @MapFeature.Require(SUPPORTS_REMOVE) public void testClear() { getMap().clear(); assertTrue("After clear(), a map should be empty.", getMap().isEmpty()); } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testClearConcurrentWithEntrySetIteration() { try { Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator(); getMap().clear(); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testClearConcurrentWithKeySetIteration() { try { Iterator<K> iterator = getMap().keySet().iterator(); getMap().clear(); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testClearConcurrentWithValuesIteration() { try { Iterator<V> iterator = getMap().values().iterator(); getMap().clear(); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testClear_unsupported() { try { getMap().clear(); fail("clear() should throw UnsupportedOperation if a map does " + "not support it and is not empty."); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @MapFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testClear_unsupportedByEmptyCollection() { try { getMap().clear(); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalSet; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Tests {@link List#equals}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class ListEqualsTester<E> extends AbstractListTester<E> { public void testEquals_otherListWithSameElements() { assertTrue( "A List should equal any other List containing the same elements.", getList().equals(new ArrayList<E>(getSampleElements()))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherListWithDifferentElements() { ArrayList<E> other = new ArrayList<E>(getSampleElements()); other.set(other.size() / 2, getSubjectGenerator().samples().e3); assertFalse( "A List should not equal another List containing different elements.", getList().equals(other)); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherListContainingNull() { List<E> other = new ArrayList<E>(getSampleElements()); other.set(other.size() / 2, null); assertFalse("Two Lists should not be equal if exactly one of them has " + "null at a given index.", getList().equals(other)); } @CollectionSize.Require(absent = CollectionSize.ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testEquals_containingNull() { ArrayList<E> elements = new ArrayList<E>(getSampleElements()); elements.set(elements.size() / 2, null); collection = getSubjectGenerator().create(elements.toArray()); List<E> other = new ArrayList<E>(getSampleElements()); assertFalse("Two Lists should not be equal if exactly one of them has " + "null at a given index.", getList().equals(other)); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_shorterList() { Collection<E> fewerElements = getSampleElements(getNumElements() - 1); assertFalse("Lists of different sizes should not be equal.", getList().equals(new ArrayList<E>(fewerElements))); } public void testEquals_longerList() { Collection<E> moreElements = getSampleElements(getNumElements() + 1); assertFalse("Lists of different sizes should not be equal.", getList().equals(new ArrayList<E>(moreElements))); } public void testEquals_set() { assertFalse("A List should never equal a Set.", getList().equals(MinimalSet.from(getList()))); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; /** * A generic JUnit test which tests offer operations on a queue. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Jared Levy */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class QueueOfferTester<E> extends AbstractQueueTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) public void testOffer_supportedNotPresent() { assertTrue("offer(notPresent) should return true", getQueue().offer(samples.e3)); expectAdded(samples.e3); } @CollectionFeature.Require({SUPPORTS_ADD, ALLOWS_NULL_VALUES}) public void testOffer_nullSupported() { assertTrue("offer(null) should return true", getQueue().offer(null)); expectAdded((E) null); } @CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES) public void testOffer_nullUnsupported() { try { getQueue().offer(null); fail("offer(null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported offer(null)"); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.SortedMap; /** * A generic JUnit test which tests operations on a SortedMap. Can't be * invoked directly; please see {@code SortedMapTestSuiteBuilder}. * * @author Jesse Wilson * @author Louis Wasserman */ @GwtCompatible public class SortedMapNavigationTester<K, V> extends AbstractMapTester<K, V> { private SortedMap<K, V> navigableMap; private Entry<K, V> a; private Entry<K, V> c; @Override public void setUp() throws Exception { super.setUp(); navigableMap = (SortedMap<K, V>) getMap(); List<Entry<K, V>> entries = Helpers.copyToList(getSubjectGenerator().getSampleElements( getSubjectGenerator().getCollectionSize().getNumElements())); Collections.sort(entries, Helpers.<K, V>entryComparator(navigableMap.comparator())); // some tests assume SEVERAL == 3 if (entries.size() >= 1) { a = entries.get(0); if (entries.size() >= 3) { c = entries.get(2); } } } @CollectionSize.Require(ZERO) public void testEmptyMapFirst() { try { navigableMap.firstKey(); fail(); } catch (NoSuchElementException e) { } } @CollectionSize.Require(ZERO) public void testEmptyMapLast() { try { assertNull(navigableMap.lastKey()); fail(); } catch (NoSuchElementException e) { } } @CollectionSize.Require(ONE) public void testSingletonMapFirst() { assertEquals(a.getKey(), navigableMap.firstKey()); } @CollectionSize.Require(ONE) public void testSingletonMapLast() { assertEquals(a.getKey(), navigableMap.lastKey()); } @CollectionSize.Require(SEVERAL) public void testFirst() { assertEquals(a.getKey(), navigableMap.firstKey()); } @CollectionSize.Require(SEVERAL) public void testLast() { assertEquals(c.getKey(), navigableMap.lastKey()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Arrays; import java.util.List; /** * A generic JUnit test which tests creation (typically through a constructor or * static factory method) of a set. Can't be invoked directly; please see * {@link com.google.common.collect.testing.SetTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class SetCreationTester<E> extends AbstractSetTester<E> { @CollectionFeature.Require(value = ALLOWS_NULL_VALUES, absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesNotRejected() { E[] array = createArrayWithNullElement(); array[0] = null; collection = getSubjectGenerator().create(array); List<E> expectedWithDuplicateRemoved = Arrays.asList(array).subList(1, getNumElements()); expectContents(expectedWithDuplicateRemoved); } @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { E[] array = createSamplesArray(); array[1] = samples.e0; collection = getSubjectGenerator().create(array); List<E> expectedWithDuplicateRemoved = Arrays.asList(array).subList(1, getNumElements()); expectContents(expectedWithDuplicateRemoved); } @CollectionFeature.Require( {ALLOWS_NULL_VALUES, REJECTS_DUPLICATES_AT_CREATION}) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesRejected() { E[] array = createArrayWithNullElement(); array[0] = null; try { collection = getSubjectGenerator().create(array); fail("Should reject duplicate null elements at creation"); } catch (IllegalArgumentException expected) { } } @CollectionFeature.Require(REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesRejected() { E[] array = createSamplesArray(); array[1] = samples.e0; try { collection = getSubjectGenerator().create(array); fail("Should reject duplicate non-null elements at creation"); } catch (IllegalArgumentException expected) { } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.*; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; /** * A generic JUnit test which tests {@code containsValue()} operations on a map. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche * @author Chris Povirk */ @GwtCompatible public class MapContainsValueTester<K, V> extends AbstractMapTester<K, V> { @CollectionSize.Require(absent = ZERO) public void testContains_yes() { assertTrue("containsValue(present) should return true", getMap().containsValue(samples.e0.getValue())); } public void testContains_no() { assertFalse("containsValue(notPresent) should return false", getMap().containsValue(samples.e3.getValue())); } @MapFeature.Require(ALLOWS_NULL_QUERIES) public void testContains_nullNotContainedButAllowed() { assertFalse("containsValue(null) should return false", getMap().containsValue(null)); } @MapFeature.Require(absent = ALLOWS_NULL_QUERIES) public void testContains_nullNotContainedAndUnsupported() { expectNullValueMissingWhenNullValuesUnsupported( "containsValue(null) should return false or throw"); } @MapFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testContains_nonNullWhenNullContained() { initMapWithNullValue(); assertFalse("containsValue(notPresent) should return false", getMap().containsValue(samples.e3.getValue())); } @MapFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testContains_nullContained() { initMapWithNullValue(); assertTrue("containsValue(null) should return true", getMap().containsValue(null)); } public void testContains_wrongType() { try { //noinspection SuspiciousMethodCalls assertFalse("containsValue(wrongType) should return false or throw", getMap().containsValue(WrongType.VALUE)); } catch (ClassCastException tolerated) { } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; /** * A generic JUnit test which tests {@code get()} operations on a list. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class ListGetTester<E> extends AbstractListTester<E> { public void testGet_valid() { // This calls get() on each index and checks the result: expectContents(createSamplesArray()); } public void testGet_negative() { try { getList().get(-1); fail("get(-1) should throw"); } catch (IndexOutOfBoundsException expected) { } } public void testGet_tooLarge() { try { getList().get(getNumElements()); fail("get(size) should throw"); } catch (IndexOutOfBoundsException expected) { } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.NON_STANDARD_TOSTRING; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code toString()} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible public class CollectionToStringTester<E> extends AbstractCollectionTester<E> { public void testToString_minimal() { assertNotNull("toString() should not return null", collection.toString()); } @CollectionSize.Require(ZERO) @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) public void testToString_size0() { assertEquals("emptyCollection.toString should return []", "[]", collection.toString()); } @CollectionSize.Require(ONE) @CollectionFeature.Require(absent = NON_STANDARD_TOSTRING) public void testToString_size1() { assertEquals("size1Collection.toString should return [{element}]", "[" + samples.e0 + "]", collection.toString()); } @CollectionSize.Require(SEVERAL) @CollectionFeature.Require( value = KNOWN_ORDER, absent = NON_STANDARD_TOSTRING) public void testToString_sizeSeveral() { String expected = Helpers.copyToList(getOrderedElements()).toString(); assertEquals("collection.toString() incorrect", expected, collection.toString()); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.testing.SerializableTester; /** * Basic reserialization test for collections. * * @author Louis Wasserman */ @GwtCompatible public class CollectionSerializationTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SERIALIZABLE) public void testReserialize() { // For a bare Collection, the most we can guarantee is that the elements are preserved. Helpers.assertEqualIgnoringOrder( actualContents(), SerializableTester.reserialize(actualContents())); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionSize; import java.util.Arrays; /** * A generic JUnit test which tests {@code toArray()} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class ListToArrayTester<E> extends AbstractListTester<E> { // CollectionToArrayTester tests everything except ordering. public void testToArray_noArg() { Object[] actual = getList().toArray(); assertArrayEquals("toArray() order should match list", createSamplesArray(), actual); } @CollectionSize.Require(absent = ZERO) public void testToArray_tooSmall() { Object[] actual = getList().toArray(new Object[0]); assertArrayEquals("toArray(tooSmall) order should match list", createSamplesArray(), actual); } public void testToArray_largeEnough() { Object[] actual = getList().toArray(new Object[getNumElements()]); assertArrayEquals("toArray(largeEnough) order should match list", createSamplesArray(), actual); } private static void assertArrayEquals(String message, Object[] expected, Object[] actual) { assertEquals(message, Arrays.asList(expected), Arrays.asList(actual)); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code isEmpty()} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible public class CollectionIsEmptyTester<E> extends AbstractCollectionTester<E> { @CollectionSize.Require(ZERO) public void testIsEmpty_yes() { assertTrue("isEmpty() should return true", collection.isEmpty()); } @CollectionSize.Require(absent = ZERO) public void testIsEmpty_no() { assertFalse("isEmpty() should return false", collection.isEmpty()); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import java.util.Set; /** * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class AbstractSetTester<E> extends AbstractCollectionTester<E> { /* * Previously we had a field named set that was initialized to the value of * collection in setUp(), but that caused problems when a tester changed the * value of set or collection but not both. */ protected final Set<E> getSet() { return (Set<E>) collection; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests remove operations on a set. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class SetRemoveTester<E> extends AbstractSetTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemove_present() { getSet().remove(samples.e0); assertFalse("After remove(present) a set should not contain " + "the removed element.", getSet().contains(samples.e0)); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collection; /** * A generic JUnit test which tests {@code containsAll()} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class CollectionContainsAllTester<E> extends AbstractCollectionTester<E> { public void testContainsAll_empty() { assertTrue("containsAll(empty) should return true", collection.containsAll(MinimalCollection.of())); } @CollectionSize.Require(absent = ZERO) public void testContainsAll_subset() { assertTrue("containsAll(subset) should return true", collection.containsAll(MinimalCollection.of(samples.e0))); } public void testContainsAll_sameElements() { assertTrue("containsAll(sameElements) should return true", collection.containsAll(MinimalCollection.of(createSamplesArray()))); } public void testContainsAll_self() { assertTrue("containsAll(this) should return true", collection.containsAll(collection)); } public void testContainsAll_partialOverlap() { assertFalse("containsAll(partialOverlap) should return false", collection.containsAll(MinimalCollection.of(samples.e0, samples.e3))); } public void testContainsAll_disjoint() { assertFalse("containsAll(disjoint) should return false", collection.containsAll(MinimalCollection.of(samples.e3))); } @CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES) public void testContainsAll_nullNotAllowed() { try { assertFalse(collection.containsAll(MinimalCollection.of((E) null))); } catch (NullPointerException tolerated) {} } @CollectionFeature.Require(ALLOWS_NULL_QUERIES) public void testContainsAll_nullAllowed() { assertFalse(collection.containsAll(MinimalCollection.of((E) null))); } @CollectionFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testContainsAll_nullPresent() { initCollectionWithNullElement(); assertTrue(collection.containsAll(MinimalCollection.of((E) null))); } public void testContainsAll_wrongType() { Collection<WrongType> wrong = MinimalCollection.of(WrongType.VALUE); try { assertFalse("containsAll(wrongType) should return false or throw", collection.containsAll(wrong)); } catch (ClassCastException tolerated) { } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code lastIndexOf()} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class ListLastIndexOfTester<E> extends AbstractListIndexOfTester<E> { @Override protected int find(Object o) { return getList().lastIndexOf(o); } @Override protected String getMethodName() { return "lastIndexOf"; } @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testLastIndexOf_duplicate() { E[] array = createSamplesArray(); array[getNumElements() / 2] = samples.e0; collection = getSubjectGenerator().create(array); assertEquals( "lastIndexOf(duplicate) should return index of last occurrence", getNumElements() / 2, getList().lastIndexOf(samples.e0)); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.Collection; import java.util.Map; /** * Tests {@link java.util.Map#hashCode}. * * <p>This class is GWT compatible. * * @author George van den Driessche * @author Chris Povirk */ @GwtCompatible public class MapHashCodeTester<K, V> extends AbstractMapTester<K, V> { public void testHashCode() { int expectedHashCode = 0; for (Map.Entry<K, V> entry : getSampleEntries()) { expectedHashCode += hash(entry); } assertEquals( "A Map's hashCode() should be the sum of those of its entries.", expectedHashCode, getMap().hashCode()); } @CollectionSize.Require(absent = CollectionSize.ZERO) @MapFeature.Require(ALLOWS_NULL_KEYS) public void testHashCode_containingNullKey() { Map.Entry<K, V> entryWithNull = entry(null, samples.e3.getValue()); runEntryWithNullTest(entryWithNull); } @CollectionSize.Require(absent = CollectionSize.ZERO) @MapFeature.Require(ALLOWS_NULL_VALUES) public void testHashCode_containingNullValue() { Map.Entry<K, V> entryWithNull = entry(samples.e3.getKey(), null); runEntryWithNullTest(entryWithNull); } private void runEntryWithNullTest(Map.Entry<K, V> entryWithNull) { Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1); entries.add(entryWithNull); int expectedHashCode = 0; for (Map.Entry<K, V> entry : entries) { expectedHashCode += hash(entry); } resetContainer(getSubjectGenerator().create(entries.toArray())); assertEquals( "A Map's hashCode() should be the sum of those of its entries (where " + "a null element in an entry counts as having a hash of zero).", expectedHashCode, getMap().hashCode()); } private static int hash(Map.Entry<?, ?> e) { return (e.getKey() == null ? 0 : e.getKey().hashCode()) ^ (e.getValue() == null ? 0 : e.getValue().hashCode()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.NoSuchElementException; /** * A generic JUnit test which tests {@code element()} operations on a queue. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Jared Levy */ @GwtCompatible public class QueueElementTester<E> extends AbstractQueueTester<E> { @CollectionSize.Require(ZERO) public void testElement_empty() { try { getQueue().element(); fail("emptyQueue.element() should throw"); } catch (NoSuchElementException expected) {} expectUnchanged(); } @CollectionSize.Require(ONE) public void testElement_size1() { assertEquals("size1Queue.element() should return first element", samples.e0, getQueue().element()); expectUnchanged(); } @CollectionFeature.Require(KNOWN_ORDER) @CollectionSize.Require(SEVERAL) public void testElement_sizeMany() { assertEquals("sizeManyQueue.element() should return first element", samples.e0, getQueue().element()); expectUnchanged(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import java.lang.reflect.Method; /** * Tests {@link java.util.List#hashCode}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible(emulated = true) public class ListHashCodeTester<E> extends AbstractListTester<E> { public void testHashCode() { int expectedHashCode = 1; for (E element : getSampleElements()) { expectedHashCode = 31 * expectedHashCode + ((element == null) ? 0 : element.hashCode()); } assertEquals( "A List's hashCode() should be computed from those of its elements.", expectedHashCode, getList().hashCode()); } /** * Returns the {@link Method} instance for {@link #testHashCode()} so that * list tests on unhashable objects can suppress it with * {@code FeatureSpecificTestSuiteBuilder.suppressing()}. */ @GwtIncompatible("reflection") public static Method getHashCodeMethod() { return Helpers.getMethod(ListHashCodeTester.class, "testHashCode"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import java.lang.reflect.Method; /** * A generic JUnit test which tests {@code set()} operations on a list. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible(emulated = true) public class ListSetTester<E> extends AbstractListTester<E> { @ListFeature.Require(SUPPORTS_SET) @CollectionSize.Require(absent = ZERO) public void testSet() { doTestSet(samples.e3); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) @ListFeature.Require(SUPPORTS_SET) public void testSet_null() { doTestSet(null); } @CollectionSize.Require(absent = ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) @ListFeature.Require(SUPPORTS_SET) public void testSet_replacingNull() { E[] elements = createSamplesArray(); int i = aValidIndex(); elements[i] = null; collection = getSubjectGenerator().create(elements); doTestSet(samples.e3); } private void doTestSet(E newValue) { int index = aValidIndex(); E initialValue = getList().get(index); assertEquals("set(i, x) should return the old element at position i.", initialValue, getList().set(index, newValue)); assertEquals("After set(i, x), get(i) should return x", newValue, getList().get(index)); assertEquals("set() should not change the size of a list.", getNumElements(), getList().size()); } @ListFeature.Require(SUPPORTS_SET) public void testSet_indexTooLow() { try { getList().set(-1, samples.e3); fail("set(-1) should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_SET) public void testSet_indexTooHigh() { int index = getNumElements(); try { getList().set(index, samples.e3); fail("set(size) should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @CollectionSize.Require(absent = ZERO) @ListFeature.Require(absent = SUPPORTS_SET) public void testSet_unsupported() { try { getList().set(aValidIndex(), samples.e3); fail("set() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @CollectionSize.Require(ZERO) @ListFeature.Require(absent = SUPPORTS_SET) public void testSet_unsupportedByEmptyList() { try { getList().set(0, samples.e3); fail("set() should throw UnsupportedOperationException " + "or IndexOutOfBoundsException"); } catch (UnsupportedOperationException tolerated) { } catch (IndexOutOfBoundsException tolerated) { } expectUnchanged(); } @CollectionSize.Require(absent = ZERO) @ListFeature.Require(SUPPORTS_SET) @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testSet_nullUnsupported() { try { getList().set(aValidIndex(), null); fail("set(null) should throw NullPointerException"); } catch (NullPointerException expected) { } expectUnchanged(); } private int aValidIndex() { return getList().size() / 2; } /** * Returns the {@link java.lang.reflect.Method} instance for * {@link #testSet_null()} so that tests of {@link * java.util.Collections#checkedCollection(java.util.Collection, Class)} can * suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()} * until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6409434">Sun bug * 6409434</a> is fixed. It's unclear whether nulls were to be permitted or * forbidden, but presumably the eventual fix will be to permit them, as it * seems more likely that code would depend on that behavior than on the * other. Thus, we say the bug is in set(), which fails to support null. */ @GwtIncompatible("reflection") public static Method getSetNullSupportedMethod() { return Helpers.getMethod(ListSetTester.class, "testSet_null"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * A generic JUnit test which tests {@code retainAll} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class CollectionRetainAllTester<E> extends AbstractCollectionTester<E> { /** * A collection of elements to retain, along with a description for use in * failure messages. */ private class Target { private final Collection<E> toRetain; private final String description; private Target(Collection<E> toRetain, String description) { this.toRetain = toRetain; this.description = description; } @Override public String toString() { return description; } } private Target empty; private Target disjoint; private Target superset; private Target nonEmptyProperSubset; private Target sameElements; private Target partialOverlap; private Target containsDuplicates; private Target nullSingleton; @Override public void setUp() throws Exception { super.setUp(); empty = new Target(emptyCollection(), "empty"); /* * We test that nullSingleton.retainAll(disjointList) does NOT throw a * NullPointerException when disjointList does not, so we can't use * MinimalCollection, which throws NullPointerException on calls to * contains(null). */ List<E> disjointList = Arrays.asList(samples.e3, samples.e4); disjoint = new Target(disjointList, "disjoint"); superset = new Target(MinimalCollection.of( samples.e0, samples.e1, samples.e2, samples.e3, samples.e4), "superset"); nonEmptyProperSubset = new Target(MinimalCollection.of(samples.e1), "subset"); sameElements = new Target(Arrays.asList(createSamplesArray()), "sameElements"); containsDuplicates = new Target( MinimalCollection.of(samples.e0, samples.e0, samples.e3, samples.e3), "containsDuplicates"); partialOverlap = new Target(MinimalCollection.of(samples.e2, samples.e3), "partialOverlap"); nullSingleton = new Target(Collections.<E>singleton(null), "nullSingleton"); } // retainAll(empty) @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRetainAll_emptyPreviouslyEmpty() { expectReturnsFalse(empty); expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRetainAll_emptyPreviouslyEmptyUnsupported() { expectReturnsFalseOrThrows(empty); expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRetainAll_emptyPreviouslyNonEmpty() { expectReturnsTrue(empty); expectContents(); expectMissing(samples.e0, samples.e1, samples.e2); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRetainAll_emptyPreviouslyNonEmptyUnsupported() { expectThrows(empty); expectUnchanged(); } // retainAll(disjoint) @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRetainAll_disjointPreviouslyEmpty() { expectReturnsFalse(disjoint); expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRetainAll_disjointPreviouslyEmptyUnsupported() { expectReturnsFalseOrThrows(disjoint); expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRetainAll_disjointPreviouslyNonEmpty() { expectReturnsTrue(disjoint); expectContents(); expectMissing(samples.e0, samples.e1, samples.e2); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRetainAll_disjointPreviouslyNonEmptyUnsupported() { expectThrows(disjoint); expectUnchanged(); } // retainAll(superset) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRetainAll_superset() { expectReturnsFalse(superset); expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testRetainAll_supersetUnsupported() { expectReturnsFalseOrThrows(superset); expectUnchanged(); } // retainAll(subset) @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRetainAll_subset() { expectReturnsTrue(nonEmptyProperSubset); expectContents(nonEmptyProperSubset.toRetain); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRetainAll_subsetUnsupported() { expectThrows(nonEmptyProperSubset); expectUnchanged(); } // retainAll(sameElements) @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRetainAll_sameElements() { expectReturnsFalse(sameElements); expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testRetainAll_sameElementsUnsupported() { expectReturnsFalseOrThrows(sameElements); expectUnchanged(); } // retainAll(partialOverlap) @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRetainAll_partialOverlap() { expectReturnsTrue(partialOverlap); expectContents(samples.e2); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRetainAll_partialOverlapUnsupported() { expectThrows(partialOverlap); expectUnchanged(); } // retainAll(containsDuplicates) @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testRetainAll_containsDuplicatesSizeOne() { expectReturnsFalse(containsDuplicates); expectContents(samples.e0); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRetainAll_containsDuplicatesSizeSeveral() { expectReturnsTrue(containsDuplicates); expectContents(samples.e0); } // retainAll(nullSingleton) @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRetainAll_nullSingletonPreviouslyEmpty() { expectReturnsFalse(nullSingleton); expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRetainAll_nullSingletonPreviouslyNonEmpty() { expectReturnsTrue(nullSingleton); expectContents(); } @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES}) @CollectionSize.Require(ONE) public void testRetainAll_nullSingletonPreviouslySingletonWithNull() { initCollectionWithNullElement(); expectReturnsFalse(nullSingleton); expectContents(createArrayWithNullElement()); } @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRetainAll_nullSingletonPreviouslySeveralWithNull() { initCollectionWithNullElement(); expectReturnsTrue(nullSingleton); expectContents(nullSingleton.toRetain); } // nullSingleton.retainAll() @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testRetainAll_containsNonNullWithNull() { initCollectionWithNullElement(); expectReturnsTrue(disjoint); expectContents(); } // retainAll(null) /* * AbstractCollection fails the retainAll(null) test when the subject * collection is empty, but we'd still like to test retainAll(null) when we * can. We split the test into empty and non-empty cases. This allows us to * suppress only the former. */ @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRetainAll_nullCollectionReferenceEmptySubject() { try { collection.retainAll(null); // Returning successfully is not ideal, but tolerated. } catch (NullPointerException expected) { } } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRetainAll_nullCollectionReferenceNonEmptySubject() { try { collection.retainAll(null); fail("retainAll(null) should throw NullPointerException"); } catch (NullPointerException expected) { } } private void expectReturnsTrue(Target target) { String message = Platform.format("retainAll(%s) should return true", target); assertTrue(message, collection.retainAll(target.toRetain)); } private void expectReturnsFalse(Target target) { String message = Platform.format("retainAll(%s) should return false", target); assertFalse(message, collection.retainAll(target.toRetain)); } private void expectThrows(Target target) { try { collection.retainAll(target.toRetain); String message = Platform.format("retainAll(%s) should throw", target); fail(message); } catch (UnsupportedOperationException expected) { } } private void expectReturnsFalseOrThrows(Target target) { String message = Platform.format("retainAll(%s) should return false or throw", target); try { assertFalse(message, collection.retainAll(target.toRetain)); } catch (UnsupportedOperationException tolerated) { } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; /** * A generic JUnit test which tests creation (typically through a constructor or * static factory method) of a collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible(emulated = true) public class CollectionCreationTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNull_supported() { E[] array = createArrayWithNullElement(); collection = getSubjectGenerator().create(array); expectContents(array); } @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNull_unsupported() { E[] array = createArrayWithNullElement(); try { getSubjectGenerator().create(array); fail("Creating a collection containing null should fail"); } catch (NullPointerException expected) { } } /** * Returns the {@link Method} instance for {@link * #testCreateWithNull_unsupported()} so that tests can suppress it * with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun * bug 5045147</a> is fixed. */ @GwtIncompatible("reflection") public static Method getCreateWithNullUnsupportedMethod() { return Helpers.getMethod(CollectionCreationTester.class, "testCreateWithNull_unsupported"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * A generic JUnit test which tests {@code remove} operations on a collection. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class CollectionRemoveTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemove_present() { int initialSize = collection.size(); assertTrue("remove(present) should return true", collection.remove(samples.e0)); assertEquals("remove(present) should decrease a collection's size by one.", initialSize - 1, collection.size()); expectMissing(samples.e0); } @CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(SEVERAL) public void testRemovePresentConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertTrue(collection.remove(samples.e0)); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_notPresent() { assertFalse("remove(notPresent) should return false", collection.remove(samples.e3)); expectUnchanged(); } @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testRemove_nullPresent() { collection = getSubjectGenerator().create(createArrayWithNullElement()); int initialSize = collection.size(); assertTrue("remove(null) should return true", collection.remove(null)); assertEquals("remove(present) should decrease a collection's size by one.", initialSize - 1, collection.size()); expectMissing((E) null); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemove_unsupported() { try { collection.remove(samples.e0); fail("remove(present) should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); assertTrue("remove(present) should not remove the element", collection.contains(samples.e0)); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testRemove_unsupportedNotPresent() { try { assertFalse("remove(notPresent) should return false or throw " + "UnsupportedOperationException", collection.remove(samples.e3)); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); expectMissing(samples.e3); } @CollectionFeature.Require( value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES) public void testRemove_nullNotSupported() { try { assertFalse("remove(null) should return false or throw " + "NullPointerException", collection.remove(null)); } catch (NullPointerException tolerated) { } expectUnchanged(); } @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES}) public void testRemove_nullAllowed() { assertFalse("remove(null) should return false", collection.remove(null)); expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testIteratorRemove_unsupported() { Iterator<E> iterator = collection.iterator(); iterator.next(); try { iterator.remove(); fail("iterator.remove() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); assertTrue(collection.contains(samples.e0)); } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemove_wrongType() { try { assertFalse(collection.remove(WrongType.VALUE)); } catch (ClassCastException tolerated) { } expectUnchanged(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code peek()} operations on a queue. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Jared Levy */ @GwtCompatible public class QueuePeekTester<E> extends AbstractQueueTester<E> { @CollectionSize.Require(ZERO) public void testPeek_empty() { assertNull("emptyQueue.peek() should return null", getQueue().peek()); expectUnchanged(); } @CollectionSize.Require(ONE) public void testPeek_size1() { assertEquals("size1Queue.peek() should return first element", samples.e0, getQueue().peek()); expectUnchanged(); } @CollectionFeature.Require(KNOWN_ORDER) @CollectionSize.Require(SEVERAL) public void testPeek_sizeMany() { assertEquals("sizeManyQueue.peek() should return first element", samples.e0, getQueue().peek()); expectUnchanged(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * A generic JUnit test which tests {@code add} operations on a collection. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class CollectionAddTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) public void testAdd_supportedNotPresent() { assertTrue("add(notPresent) should return true", collection.add(samples.e3)); expectAdded(samples.e3); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testAdd_unsupportedNotPresent() { try { collection.add(samples.e3); fail("add(notPresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3); } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAdd_unsupportedPresent() { try { assertFalse("add(present) should return false or throw", collection.add(samples.e0)); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require( value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS) public void testAdd_nullSupported() { assertTrue("add(null) should return true", collection.add(null)); expectAdded((E) null); } @CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES) public void testAdd_nullUnsupported() { try { collection.add(null); fail("add(null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported add(null)"); } @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testAddConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertTrue(collection.add(samples.e3)); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } /** * Returns the {@link Method} instance for {@link #testAdd_nullSupported()} so * that tests of {@link * java.util.Collections#checkedCollection(java.util.Collection, Class)} can * suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()} * until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6409434">Sun bug * 6409434</a> is fixed. It's unclear whether nulls were to be permitted or * forbidden, but presumably the eventual fix will be to permit them, as it * seems more likely that code would depend on that behavior than on the * other. Thus, we say the bug is in add(), which fails to support null. */ @GwtIncompatible("reflection") public static Method getAddNullSupportedMethod() { return Helpers.getMethod(CollectionAddTester.class, "testAdd_nullSupported"); } /** * Returns the {@link Method} instance for {@link #testAdd_nullSupported()} * so that tests of {@link java.util.TreeSet} can suppress it with {@code * FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun bug * 5045147</a> is fixed. */ @GwtIncompatible("reflection") public static Method getAddNullUnsupportedMethod() { return Helpers.getMethod(CollectionAddTester.class, "testAdd_nullUnsupported"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.MinimalSet; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collection; import java.util.Set; /** * Tests {@link java.util.Set#equals}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class SetEqualsTester<E> extends AbstractSetTester<E> { public void testEquals_otherSetWithSameElements() { assertTrue( "A Set should equal any other Set containing the same elements.", getSet().equals(MinimalSet.from(getSampleElements()))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherSetWithDifferentElements() { Collection<E> elements = getSampleElements(getNumElements() - 1); elements.add(getSubjectGenerator().samples().e3); assertFalse( "A Set should not equal another Set containing different elements.", getSet().equals(MinimalSet.from(elements)) ); } @CollectionSize.Require(absent = CollectionSize.ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testEquals_containingNull() { Collection<E> elements = getSampleElements(getNumElements() - 1); elements.add(null); collection = getSubjectGenerator().create(elements.toArray()); assertTrue("A Set should equal any other Set containing the same elements," + " even if some elements are null.", getSet().equals(MinimalSet.from(elements))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherContainsNull() { Collection<E> elements = getSampleElements(getNumElements() - 1); elements.add(null); Set<E> other = MinimalSet.from(elements); assertFalse( "Two Sets should not be equal if exactly one of them contains null.", getSet().equals(other)); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_smallerSet() { Collection<E> fewerElements = getSampleElements(getNumElements() - 1); assertFalse("Sets of different sizes should not be equal.", getSet().equals(MinimalSet.from(fewerElements))); } public void testEquals_largerSet() { Collection<E> moreElements = getSampleElements(getNumElements() + 1); assertFalse("Sets of different sizes should not be equal.", getSet().equals(MinimalSet.from(moreElements))); } public void testEquals_list() { assertFalse("A List should never equal a Set.", getSet().equals(Helpers.copyToList(getSet()))); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code contains()} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion * @author Chris Povirk */ @GwtCompatible public class CollectionContainsTester<E> extends AbstractCollectionTester<E> { @CollectionSize.Require(absent = ZERO) public void testContains_yes() { assertTrue("contains(present) should return true", collection.contains(samples.e0)); } public void testContains_no() { assertFalse("contains(notPresent) should return false", collection.contains(samples.e3)); } @CollectionFeature.Require(ALLOWS_NULL_QUERIES) public void testContains_nullNotContainedButQueriesSupported() { assertFalse("contains(null) should return false", collection.contains(null)); } @CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES) public void testContains_nullNotContainedAndUnsupported() { expectNullMissingWhenNullUnsupported( "contains(null) should return false or throw"); } @CollectionFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testContains_nonNullWhenNullContained() { initCollectionWithNullElement(); assertFalse("contains(notPresent) should return false", collection.contains(samples.e3)); } @CollectionFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testContains_nullContained() { initCollectionWithNullElement(); assertTrue("contains(null) should return true", collection.contains(null)); } public void testContains_wrongType() { try { assertFalse("contains(wrongType) should return false or throw", collection.contains(WrongType.VALUE)); } catch (ClassCastException tolerated) { } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map.Entry; /** * A generic JUnit test which tests {@code remove} operations on a map. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class MapRemoveTester<K, V> extends AbstractMapTester<K, V> { @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemove_present() { int initialSize = getMap().size(); assertEquals("remove(present) should return the associated value", samples.e0.getValue(), getMap().remove(samples.e0.getKey())); assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); expectMissing(samples.e0); } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testRemovePresentConcurrentWithEntrySetIteration() { try { Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator(); getMap().remove(samples.e0.getKey()); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testRemovePresentConcurrentWithKeySetIteration() { try { Iterator<K> iterator = getMap().keySet().iterator(); getMap().remove(samples.e0.getKey()); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testRemovePresentConcurrentWithValuesIteration() { try { Iterator<V> iterator = getMap().values().iterator(); getMap().remove(samples.e0.getKey()); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require(SUPPORTS_REMOVE) public void testRemove_notPresent() { assertNull("remove(notPresent) should return null", getMap().remove(samples.e3.getKey())); expectUnchanged(); } @MapFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_KEYS}) @CollectionSize.Require(absent = ZERO) public void testRemove_nullPresent() { initMapWithNullKey(); int initialSize = getMap().size(); assertEquals("remove(null) should return the associated value", getValueForNullKey(), getMap().remove(null)); assertEquals("remove(present) should decrease a map's size by one.", initialSize - 1, getMap().size()); expectMissing(entry(null, getValueForNullKey())); } @MapFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemove_unsupported() { try { getMap().remove(samples.e0.getKey()); fail("remove(present) should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); assertEquals("remove(present) should not remove the element", samples.e0.getValue(), get(samples.e0.getKey())); } @MapFeature.Require(absent = SUPPORTS_REMOVE) public void testRemove_unsupportedNotPresent() { try { assertNull("remove(notPresent) should return null or throw " + "UnsupportedOperationException", getMap().remove(samples.e3.getKey())); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); expectMissing(samples.e3); } @MapFeature.Require( value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES) public void testRemove_nullQueriesNotSupported() { try { assertNull("remove(null) should return null or throw " + "NullPointerException", getMap().remove(null)); } catch (NullPointerException tolerated) { } expectUnchanged(); } @MapFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES}) public void testRemove_nullSupportedMissing() { assertNull("remove(null) should return null", getMap().remove(null)); expectUnchanged(); } @MapFeature.Require(SUPPORTS_REMOVE) public void testRemove_wrongType() { try { assertNull(getMap().remove(WrongType.VALUE)); } catch (ClassCastException tolerated) { } expectUnchanged(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.IteratorFeature; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.features.CollectionFeature; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; /** * A generic JUnit test which tests {@code iterator} operations on a collection. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible(emulated = true) public class CollectionIteratorTester<E> extends AbstractCollectionTester<E> { public void testIterator() { List<E> iteratorElements = new ArrayList<E>(); for (E element : collection) { // uses iterator() iteratorElements.add(element); } Helpers.assertEqualIgnoringOrder( Arrays.asList(createSamplesArray()), iteratorElements); } @CollectionFeature.Require(KNOWN_ORDER) public void testIterationOrdering() { List<E> iteratorElements = new ArrayList<E>(); for (E element : collection) { // uses iterator() iteratorElements.add(element); } List<E> expected = Helpers.copyToList(getOrderedElements()); assertEquals("Different ordered iteration", expected, iteratorElements); } // TODO: switch to DerivedIteratorTestSuiteBuilder @CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE}) public void testIterator_knownOrderRemoveSupported() { runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER, getOrderedElements()); } @CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_REMOVE) public void testIterator_knownOrderRemoveUnsupported() { runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER, getOrderedElements()); } @CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_REMOVE) public void testIterator_unknownOrderRemoveSupported() { runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER, getSampleElements()); } @CollectionFeature.Require(absent = {KNOWN_ORDER, SUPPORTS_REMOVE}) public void testIterator_unknownOrderRemoveUnsupported() { runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER, getSampleElements()); } private void runIteratorTest(Set<IteratorFeature> features, IteratorTester.KnownOrder knownOrder, Iterable<E> elements) { new IteratorTester<E>(Platform.collectionIteratorTesterNumIterations(), features, elements, knownOrder) { { // TODO: don't set this universally ignoreSunJavaBug6529795(); } @Override protected Iterator<E> newTargetIterator() { resetCollection(); return collection.iterator(); } @Override protected void verify(List<E> elements) { expectContents(elements); } }.test(); } /** * Returns the {@link Method} instance for * {@link #testIterator_knownOrderRemoveSupported()} so that tests of * {@link CopyOnWriteArraySet} and {@link CopyOnWriteArrayList} can suppress * it with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570575">Sun bug * 6570575</a> is fixed. */ @GwtIncompatible("reflection") public static Method getIteratorKnownOrderRemoveSupportedMethod() { return Helpers.getMethod( CollectionIteratorTester.class, "testIterator_knownOrderRemoveSupported"); } /** * Returns the {@link Method} instance for * {@link #testIterator_unknownOrderRemoveSupported()} so that tests of * classes with unmodifiable iterators can suppress it. */ @GwtIncompatible("reflection") public static Method getIteratorUnknownOrderRemoveSupportedMethod() { return Helpers.getMethod( CollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported"); } public void testIteratorNoSuchElementException() { Iterator<E> iterator = collection.iterator(); while (iterator.hasNext()) { iterator.next(); } try { iterator.next(); fail("iterator.next() should throw NoSuchElementException"); } catch (NoSuchElementException expected) {} } /** * Returns the {@link Method} instance for * {@link #testIterator_knownOrderRemoveUnsupported()} so that tests of * {@code ArrayStack} can suppress it with * {@code FeatureSpecificTestSuiteBuilder.suppressing()}. {@code ArrayStack} * supports {@code remove()} on only the first element, and the iterator * tester can't handle that. */ @GwtIncompatible("reflection") public static Method getIteratorKnownOrderRemoveUnsupportedMethod() { return Helpers.getMethod( CollectionIteratorTester.class, "testIterator_knownOrderRemoveUnsupported"); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; /** * A generic JUnit test which tests add operations on a set. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.SetTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class SetAddTester<E> extends AbstractSetTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedPresent() { assertFalse("add(present) should return false", getSet().add(samples.e0)); expectUnchanged(); } @CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedNullPresent() { E[] array = createArrayWithNullElement(); collection = getSubjectGenerator().create(array); assertFalse("add(nullPresent) should return false", getSet().add(null)); expectContents(array); } /** * Returns the {@link Method} instance for * {@link #testAdd_supportedNullPresent()} so that tests can suppress it. See * {@link CollectionAddTester#getAddNullSupportedMethod()} for details. */ @GwtIncompatible("reflection") public static Method getAddSupportedNullPresentMethod() { return Helpers.getMethod(SetAddTester.class, "testAdd_supportedNullPresent"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code poll()} operations on a queue. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Jared Levy */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class QueuePollTester<E> extends AbstractQueueTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testPoll_empty() { assertNull("emptyQueue.poll() should return null", getQueue().poll()); expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testPoll_size1() { assertEquals("size1Queue.poll() should return first element", samples.e0, getQueue().poll()); expectMissing(samples.e0); } @CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testPoll_sizeMany() { assertEquals("sizeManyQueue.poll() should return first element", samples.e0, getQueue().poll()); expectMissing(samples.e0); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code isEmpty()} operations on a * map. Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible public class MapIsEmptyTester<K, V> extends AbstractMapTester<K, V> { @CollectionSize.Require(ZERO) public void testIsEmpty_yes() { assertTrue("isEmpty() should return true", getMap().isEmpty()); } @CollectionSize.Require(absent = ZERO) public void testIsEmpty_no() { assertFalse("isEmpty() should return false", getMap().isEmpty()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; /** * A generic JUnit test which tests {@code remove(int)} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class ListRemoveAtIndexTester<E> extends AbstractListTester<E> { @ListFeature.Require(absent = SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndex_unsupported() { try { getList().remove(0); fail("remove(i) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) public void testRemoveAtIndex_negative() { try { getList().remove(-1); fail("remove(-1) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) public void testRemoveAtIndex_tooLarge() { try { getList().remove(getNumElements()); fail("remove(size) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndex_first() { runRemoveTest(0); } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRemoveAtIndex_middle() { runRemoveTest(getNumElements() / 2); } @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndexConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); getList().remove(getNumElements() / 2); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testRemoveAtIndex_last() { runRemoveTest(getNumElements() - 1); } private void runRemoveTest(int index) { assertEquals(Platform.format( "remove(%d) should return the element at index %d", index, index), getList().get(index), getList().remove(index)); List<E> expected = Helpers.copyToList(createSamplesArray()); expected.remove(index); expectContents(expected); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.NoSuchElementException; /** * A generic JUnit test which tests {@code remove()} operations on a queue. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Jared Levy */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class QueueRemoveTester<E> extends AbstractQueueTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRemove_empty() { try { getQueue().remove(); fail("emptyQueue.remove() should throw"); } catch (NoSuchElementException expected) {} expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testRemove_size1() { assertEquals("size1Queue.remove() should return first element", samples.e0, getQueue().remove()); expectMissing(samples.e0); } @CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testRemove_sizeMany() { assertEquals("sizeManyQueue.remove() should return first element", samples.e0, getQueue().remove()); expectMissing(samples.e0); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * Common parent class for {@link ListIndexOfTester} and * {@link ListLastIndexOfTester}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public abstract class AbstractListIndexOfTester<E> extends AbstractListTester<E> { /** Override to call {@code indexOf()} or {@code lastIndexOf()}. */ protected abstract int find(Object o); /** * Override to return "indexOf" or "lastIndexOf()" for use in failure * messages. */ protected abstract String getMethodName(); @CollectionSize.Require(absent = ZERO) public void testFind_yes() { assertEquals(getMethodName() + "(firstElement) should return 0", 0, find(samples.e0)); } public void testFind_no() { assertEquals(getMethodName() + "(notPresent) should return -1", -1, find(samples.e3)); } @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testFind_nullNotContainedButSupported() { assertEquals(getMethodName() + "(nullNotPresent) should return -1", -1, find(null)); } @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testFind_nullNotContainedAndUnsupported() { try { assertEquals( getMethodName() + "(nullNotPresent) should return -1 or throw", -1, find(null)); } catch (NullPointerException tolerated) { } } @CollectionFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testFind_nonNullWhenNullContained() { initCollectionWithNullElement(); assertEquals(getMethodName() + "(notPresent) should return -1", -1, find(samples.e3)); } @CollectionFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testFind_nullContained() { initCollectionWithNullElement(); assertEquals(getMethodName() + "(null) should return " + getNullLocation(), getNullLocation(), find(null)); } public void testFind_wrongType() { try { assertEquals(getMethodName() + "(wrongType) should return -1 or throw", -1, find(WrongType.VALUE)); } catch (ClassCastException tolerated) { } } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NavigableSet; import java.util.TreeSet; /** * A generic JUnit test which tests operations on a NavigableSet. Can't be * invoked directly; please see {@code NavigableSetTestSuiteBuilder}. * * @author Jesse Wilson * @author Louis Wasserman */ public class NavigableSetNavigationTester<E> extends AbstractSetTester<E> { private NavigableSet<E> navigableSet; private List<E> values; private E a; private E b; private E c; @Override public void setUp() throws Exception { super.setUp(); navigableSet = (NavigableSet<E>) getSet(); values = Helpers.copyToList(getSubjectGenerator().getSampleElements( getSubjectGenerator().getCollectionSize().getNumElements())); Collections.sort(values, navigableSet.comparator()); // some tests assume SEVERAL == 3 if (values.size() >= 1) { a = values.get(0); if (values.size() >= 3) { b = values.get(1); c = values.get(2); } } } /** * Resets the contents of navigableSet to have elements a, c, for the * navigation tests. */ protected void resetWithHole() { super.resetContainer(getSubjectGenerator().create(a, c)); navigableSet = (NavigableSet<E>) getSet(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptySetPollFirst() { assertNull(navigableSet.pollFirst()); } @CollectionSize.Require(ZERO) public void testEmptySetNearby() { assertNull(navigableSet.lower(samples.e0)); assertNull(navigableSet.floor(samples.e0)); assertNull(navigableSet.ceiling(samples.e0)); assertNull(navigableSet.higher(samples.e0)); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptySetPollLast() { assertNull(navigableSet.pollLast()); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonSetPollFirst() { assertEquals(a, navigableSet.pollFirst()); assertTrue(navigableSet.isEmpty()); } @CollectionSize.Require(ONE) public void testSingletonSetNearby() { assertNull(navigableSet.lower(samples.e0)); assertEquals(a, navigableSet.floor(samples.e0)); assertEquals(a, navigableSet.ceiling(samples.e0)); assertNull(navigableSet.higher(samples.e0)); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonSetPollLast() { assertEquals(a, navigableSet.pollLast()); assertTrue(navigableSet.isEmpty()); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollFirst() { assertEquals(a, navigableSet.pollFirst()); assertEquals( values.subList(1, values.size()), Helpers.copyToList(navigableSet)); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testPollFirstUnsupported() { try { navigableSet.pollFirst(); fail(); } catch (UnsupportedOperationException e) { } } @CollectionSize.Require(SEVERAL) public void testLowerHole() { resetWithHole(); assertEquals(null, navigableSet.lower(a)); assertEquals(a, navigableSet.lower(b)); assertEquals(a, navigableSet.lower(c)); } @CollectionSize.Require(SEVERAL) public void testFloorHole() { resetWithHole(); assertEquals(a, navigableSet.floor(a)); assertEquals(a, navigableSet.floor(b)); assertEquals(c, navigableSet.floor(c)); } @CollectionSize.Require(SEVERAL) public void testCeilingHole() { resetWithHole(); assertEquals(a, navigableSet.ceiling(a)); assertEquals(c, navigableSet.ceiling(b)); assertEquals(c, navigableSet.ceiling(c)); } @CollectionSize.Require(SEVERAL) public void testHigherHole() { resetWithHole(); assertEquals(c, navigableSet.higher(a)); assertEquals(c, navigableSet.higher(b)); assertEquals(null, navigableSet.higher(c)); } /* * TODO(cpovirk): make "too small" and "too large" elements available for better navigation * testing. At that point, we may be able to eliminate the "hole" tests, which would mean that * ContiguousSet's tests would no longer need to suppress them. */ @CollectionSize.Require(SEVERAL) public void testLower() { assertEquals(null, navigableSet.lower(a)); assertEquals(a, navigableSet.lower(b)); assertEquals(b, navigableSet.lower(c)); } @CollectionSize.Require(SEVERAL) public void testFloor() { assertEquals(a, navigableSet.floor(a)); assertEquals(b, navigableSet.floor(b)); assertEquals(c, navigableSet.floor(c)); } @CollectionSize.Require(SEVERAL) public void testCeiling() { assertEquals(a, navigableSet.ceiling(a)); assertEquals(b, navigableSet.ceiling(b)); assertEquals(c, navigableSet.ceiling(c)); } @CollectionSize.Require(SEVERAL) public void testHigher() { assertEquals(b, navigableSet.higher(a)); assertEquals(c, navigableSet.higher(b)); assertEquals(null, navigableSet.higher(c)); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLast() { assertEquals(c, navigableSet.pollLast()); assertEquals( values.subList(0, values.size() - 1), Helpers.copyToList(navigableSet)); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testPollLastUnsupported() { try { navigableSet.pollLast(); fail(); } catch (UnsupportedOperationException e) { } } @CollectionSize.Require(SEVERAL) public void testDescendingNavigation() { List<E> descending = new ArrayList<E>(); for (Iterator<E> i = navigableSet.descendingIterator(); i.hasNext();) { descending.add(i.next()); } Collections.reverse(descending); assertEquals(values, descending); } public void testEmptySubSet() { NavigableSet<E> empty = navigableSet.subSet(samples.e0, false, samples.e0, false); assertEquals(new TreeSet<E>(), empty); } /* * TODO(cpovirk): more testing of subSet/headSet/tailSet/descendingSet? and/or generate derived * suites? */ /** * Returns the {@link Method} instances for the test methods in this class that create a set with * a "hole" in it so that set tests of {@code ContiguousSet} can suppress them with {@code * FeatureSpecificTestSuiteBuilder.suppressing()}. */ /* * TODO(cpovirk): or we could make HOLES_FORBIDDEN a feature. Or we could declare that * implementations are permitted to throw IAE if a hole is requested, and we could update * test*Hole to permit IAE. (But might this ignore genuine bugs?) But see the TODO above * testLower, which could make this all unnecessary */ public static Method[] getHoleMethods() { return new Method[] { Helpers.getMethod(NavigableSetNavigationTester.class, "testLowerHole"), Helpers.getMethod(NavigableSetNavigationTester.class, "testFloorHole"), Helpers.getMethod(NavigableSetNavigationTester.class, "testCeilingHole"), Helpers.getMethod(NavigableSetNavigationTester.class, "testHigherHole"), }; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; /** * A generic JUnit test which tests {@code size()} operations on a collection. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible public class CollectionSizeTester<E> extends AbstractCollectionTester<E> { public void testSize() { assertEquals("size():", getNumElements(), collection.size()); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.SortedSet; /** * A generic JUnit test which tests operations on a SortedSet. Can't be * invoked directly; please see {@code SortedSetTestSuiteBuilder}. * * @author Jesse Wilson * @author Louis Wasserman */ @GwtCompatible public class SortedSetNavigationTester<E> extends AbstractSetTester<E> { private SortedSet<E> sortedSet; private List<E> values; private E a; private E b; private E c; @Override public void setUp() throws Exception { super.setUp(); sortedSet = (SortedSet<E>) getSet(); values = Helpers.copyToList(getSubjectGenerator().getSampleElements( getSubjectGenerator().getCollectionSize().getNumElements())); Collections.sort(values, sortedSet.comparator()); // some tests assume SEVERAL == 3 if (values.size() >= 1) { a = values.get(0); if (values.size() >= 3) { b = values.get(1); c = values.get(2); } } } @CollectionSize.Require(ZERO) public void testEmptySetFirst() { try { sortedSet.first(); fail(); } catch (NoSuchElementException e) { } } @CollectionSize.Require(ZERO) public void testEmptySetLast() { try { sortedSet.last(); fail(); } catch (NoSuchElementException e) { } } @CollectionSize.Require(ONE) public void testSingletonSetFirst() { assertEquals(a, sortedSet.first()); } @CollectionSize.Require(ONE) public void testSingletonSetLast() { assertEquals(a, sortedSet.last()); } @CollectionSize.Require(SEVERAL) public void testFirst() { assertEquals(a, sortedSet.first()); } @CollectionSize.Require(SEVERAL) public void testLast() { assertEquals(c, sortedSet.last()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * A generic JUnit test which tests {@code removeAll} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class CollectionRemoveAllTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveAll_emptyCollection() { assertFalse("removeAll(emptyCollection) should return false", collection.removeAll(MinimalCollection.of())); expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveAll_nonePresent() { assertFalse("removeAll(disjointCollection) should return false", collection.removeAll(MinimalCollection.of(samples.e3))); expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveAll_allPresent() { assertTrue("removeAll(intersectingCollection) should return true", collection.removeAll(MinimalCollection.of(samples.e0))); expectMissing(samples.e0); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveAll_somePresent() { assertTrue("removeAll(intersectingCollection) should return true", collection.removeAll(MinimalCollection.of(samples.e0, samples.e3))); expectMissing(samples.e0); } @CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(SEVERAL) public void testRemoveAllSomePresentConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertTrue(collection.removeAll(MinimalCollection.of(samples.e0, samples.e3))); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } /** * Trigger the other.size() >= this.size() case in AbstractSet.removeAll(). */ @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveAll_somePresentLargeCollectionToRemove() { assertTrue("removeAll(largeIntersectingCollection) should return true", collection.removeAll(MinimalCollection.of( samples.e0, samples.e0, samples.e0, samples.e3, samples.e3, samples.e3))); expectMissing(samples.e0); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testRemoveAll_unsupportedEmptyCollection() { try { assertFalse("removeAll(emptyCollection) should return false or throw " + "UnsupportedOperationException", collection.removeAll(MinimalCollection.of())); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testRemoveAll_unsupportedNonePresent() { try { assertFalse("removeAll(disjointCollection) should return false or throw " + "UnsupportedOperationException", collection.removeAll(MinimalCollection.of(samples.e3))); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveAll_unsupportedPresent() { try { collection.removeAll(MinimalCollection.of(samples.e0)); fail("removeAll(intersectingCollection) should throw " + "UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); assertTrue(collection.contains(samples.e0)); } /* * AbstractCollection fails the removeAll(null) test when the subject * collection is empty, but we'd still like to test removeAll(null) when we * can. We split the test into empty and non-empty cases. This allows us to * suppress only the former. */ @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testRemoveAll_nullCollectionReferenceEmptySubject() { try { collection.removeAll(null); // Returning successfully is not ideal, but tolerated. } catch (NullPointerException expected) { } } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testRemoveAll_nullCollectionReferenceNonEmptySubject() { try { collection.removeAll(null); fail("removeAll(null) should throw NullPointerException"); } catch (NullPointerException expected) { } } @CollectionFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES) public void testRemoveAll_containsNullNo() { MinimalCollection<?> containsNull = MinimalCollection.of((Object) null); try { assertFalse("removeAll(containsNull) should return false or throw", collection.removeAll(containsNull)); } catch (NullPointerException tolerated) { } expectUnchanged(); } @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES}) public void testRemoveAll_containsNullNoButAllowed() { MinimalCollection<?> containsNull = MinimalCollection.of((Object) null); assertFalse("removeAll(containsNull) should return false", collection.removeAll(containsNull)); expectUnchanged(); } @CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testRemoveAll_containsNullYes() { initCollectionWithNullElement(); assertTrue("removeAll(containsNull) should return true", collection.removeAll(Collections.singleton(null))); // TODO: make this work with MinimalCollection } @CollectionFeature.Require(SUPPORTS_REMOVE) public void testRemoveAll_containsWrongType() { try { assertFalse("removeAll(containsWrongType) should return false or throw", collection.removeAll(MinimalCollection.of(WrongType.VALUE))); } catch (ClassCastException tolerated) { } expectUnchanged(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code indexOf()} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class ListIndexOfTester<E> extends AbstractListIndexOfTester<E> { @Override protected int find(Object o) { return getList().indexOf(o); } @Override protected String getMethodName() { return "indexOf"; } @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testIndexOf_duplicate() { E[] array = createSamplesArray(); array[getNumElements() / 2] = samples.e0; collection = getSubjectGenerator().create(array); assertEquals("indexOf(duplicate) should return index of first occurrence", 0, getList().indexOf(samples.e0)); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import java.lang.reflect.Method; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * A generic JUnit test which tests {@code add(int, Object)} operations on a * list. Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class ListAddAtIndexTester<E> extends AbstractListTester<E> { @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAtIndex_supportedPresent() { getList().add(0, samples.e0); expectAdded(0, samples.e0); } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) /* * absent = ZERO isn't required, since unmodList.add() must * throw regardless, but it keeps the method name accurate. */ public void testAddAtIndex_unsupportedPresent() { try { getList().add(0, samples.e0); fail("add(n, present) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_supportedNotPresent() { getList().add(0, samples.e3); expectAdded(0, samples.e3); } @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndexConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); getList().add(0, samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_unsupportedNotPresent() { try { getList().add(0, samples.e3); fail("add(n, notPresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testAddAtIndex_middle() { getList().add(getNumElements() / 2, samples.e3); expectAdded(getNumElements() / 2, samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAtIndex_end() { getList().add(getNumElements(), samples.e3); expectAdded(getNumElements(), samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testAddAtIndex_nullSupported() { getList().add(0, null); expectAdded(0, (E) null); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testAddAtIndex_nullUnsupported() { try { getList().add(0, null); fail("add(n, null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported add(n, null)"); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_negative() { try { getList().add(-1, samples.e3); fail("add(-1, e) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); expectMissing(samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_tooLarge() { try { getList().add(getNumElements() + 1, samples.e3); fail("add(size + 1, e) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); expectMissing(samples.e3); } /** * Returns the {@link Method} instance for * {@link #testAddAtIndex_nullSupported()} so that tests can suppress it. See * {@link CollectionAddTester#getAddNullSupportedMethod()} for details. */ @GwtIncompatible("reflection") public static Method getAddNullSupportedMethod() { return Helpers.getMethod( ListAddAtIndexTester.class, "testAddAtIndex_nullSupported"); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; import java.util.List; /** * A generic JUnit test which tests {@code add(Object)} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class ListAddTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedPresent() { assertTrue("add(present) should return true", getList().add(samples.e0)); expectAdded(samples.e0); } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) /* * absent = ZERO isn't required, since unmodList.add() must * throw regardless, but it keeps the method name accurate. */ public void testAdd_unsupportedPresent() { try { getList().add(samples.e0); fail("add(present) should throw"); } catch (UnsupportedOperationException expected) { } } @CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testAdd_supportedNullPresent() { E[] array = createArrayWithNullElement(); collection = getSubjectGenerator().create(array); assertTrue("add(nullPresent) should return true", getList().add(null)); List<E> expected = Helpers.copyToList(array); expected.add(null); expectContents(expected); } /** * Returns the {@link Method} instance for * {@link #testAdd_supportedNullPresent()} so that tests can suppress it. See * {@link CollectionAddTester#getAddNullSupportedMethod()} for details. */ @GwtIncompatible("reflection") public static Method getAddSupportedNullPresentMethod() { return Helpers.getMethod(ListAddTester.class, "testAdd_supportedNullPresent"); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.testing.SerializableTester; /** * Basic serialization test for maps. * * @author Louis Wasserman */ @GwtCompatible public class MapSerializationTester<K, V> extends AbstractMapTester<K, V> { @CollectionFeature.Require(SERIALIZABLE) public void testReserializeMap() { SerializableTester.reserializeAndAssert(getMap()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import java.util.Collection; import java.util.List; /** * Base class for list testers. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class AbstractListTester<E> extends AbstractCollectionTester<E> { /* * Previously we had a field named list that was initialized to the value of * collection in setUp(), but that caused problems when a tester changed the * value of list or collection but not both. */ protected final List<E> getList() { return (List<E>) collection; } /** * {@inheritDoc} * <p> * The {@code AbstractListTester} implementation overrides * {@link AbstractCollectionTester#expectContents(Collection)} to verify that * the order of the elements in the list under test matches what is expected. */ @Override protected void expectContents(Collection<E> expectedCollection) { List<E> expectedList = Helpers.copyToList(expectedCollection); // Avoid expectEquals() here to delay reason manufacture until necessary. if (getList().size() != expectedList.size()) { fail("size mismatch: " + reportContext(expectedList)); } for (int i = 0; i < expectedList.size(); i++) { E expected = expectedList.get(i); E actual = getList().get(i); if (expected != actual && (expected == null || !expected.equals(actual))) { fail("mismatch at index " + i + ": " + reportContext(expectedList)); } } } /** * Used to delay string formatting until actually required, as it * otherwise shows up in the test execution profile when running an * extremely large numbers of tests. */ private String reportContext(List<E> expected) { return Platform.format("expected collection %s; actual collection %s", expected, this.collection); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests removeAll operations on a list. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class ListRemoveAllTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRemoveAll_duplicate() { ArrayWithDuplicate<E> arrayAndDuplicate = createArrayWithDuplicateElement(); collection = getSubjectGenerator().create(arrayAndDuplicate.elements); E duplicate = arrayAndDuplicate.duplicate; assertTrue("removeAll(intersectingCollection) should return true", getList().removeAll(MinimalCollection.of(duplicate))); assertFalse("after removeAll(e), a collection should not contain e even " + "if it initially contained e more than once.", getList().contains(duplicate)); } // All other cases are covered by CollectionRemoveAllTester. }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET; import static com.google.common.collect.testing.testers.Platform.listListIteratorTesterNumIterations; import static java.util.Collections.singleton; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.IteratorFeature; import com.google.common.collect.testing.ListIteratorTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.ListFeature; import java.lang.reflect.Method; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; /** * A generic JUnit test which tests {@code listIterator} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class ListListIteratorTester<E> extends AbstractListTester<E> { // TODO: switch to DerivedIteratorTestSuiteBuilder @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @ListFeature.Require(absent = {SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX}) public void testListIterator_unmodifiable() { runListIteratorTest(UNMODIFIABLE); } /* * For now, we don't cope with testing this when the list supports only some * modification operations. */ @CollectionFeature.Require(SUPPORTS_REMOVE) @ListFeature.Require({SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX}) public void testListIterator_fullyModifiable() { runListIteratorTest(MODIFIABLE); } private void runListIteratorTest(Set<IteratorFeature> features) { new ListIteratorTester<E>( listListIteratorTesterNumIterations(), singleton(samples.e4), features, Helpers.copyToList(getSampleElements()), 0) { { // TODO: don't set this universally stopTestingWhenAddThrowsException(); } @Override protected ListIterator<E> newTargetIterator() { resetCollection(); return getList().listIterator(); } @Override protected void verify(List<E> elements) { expectContents(elements); } }.test(); } public void testListIterator_tooLow() { try { getList().listIterator(-1); fail(); } catch (IndexOutOfBoundsException expected) { } } public void testListIterator_tooHigh() { try { getList().listIterator(getNumElements() + 1); fail(); } catch (IndexOutOfBoundsException expected) { } } public void testListIterator_atSize() { getList().listIterator(getNumElements()); // TODO: run the iterator through ListIteratorTester } /** * Returns the {@link Method} instance for * {@link #testListIterator_fullyModifiable()} so that tests of * {@link CopyOnWriteArraySet} can suppress it with * {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570575">Sun bug * 6570575</a> is fixed. */ @GwtIncompatible("reflection") public static Method getListIteratorFullyModifiableMethod() { return Helpers.getMethod( ListListIteratorTester.class, "testListIterator_fullyModifiable"); } /** * Returns the {@link Method} instance for * {@link #testListIterator_unmodifiable()} so that it can be suppressed in * GWT tests. */ @GwtIncompatible("reflection") public static Method getListIteratorUnmodifiableMethod() { return Helpers.getMethod( ListListIteratorTester.class, "testListIterator_unmodifiable"); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * A generic JUnit test which tests {@code toArray()} operations on a * collection. Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion * @author Chris Povirk */ @GwtCompatible(emulated = true) public class CollectionToArrayTester<E> extends AbstractCollectionTester<E> { public void testToArray_noArgs() { Object[] array = collection.toArray(); expectArrayContentsAnyOrder(createSamplesArray(), array); } /** * {@link Collection#toArray(Object[])} says: "Note that * <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>." * * <p>For maximum effect, the collection under test should be created from an * element array of a type other than {@code Object[]}. */ public void testToArray_isPlainObjectArray() { Object[] array = collection.toArray(); assertEquals(Object[].class, array.getClass()); } public void testToArray_emptyArray() { E[] empty = getSubjectGenerator().createArray(0); E[] array = collection.toArray(empty); assertEquals("toArray(emptyT[]) should return an array of type T", empty.getClass(), array.getClass()); assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length); expectArrayContentsAnyOrder(createSamplesArray(), array); } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_emptyArray_ordered() { E[] empty = getSubjectGenerator().createArray(0); E[] array = collection.toArray(empty); assertEquals("toArray(emptyT[]) should return an array of type T", empty.getClass(), array.getClass()); assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length); expectArrayContentsInOrder(getOrderedElements(), array); } public void testToArray_emptyArrayOfObject() { Object[] in = new Object[0]; Object[] array = collection.toArray(in); assertEquals("toArray(emptyObject[]) should return an array of type Object", Object[].class, array.getClass()); assertEquals("toArray(emptyObject[]).length", getNumElements(), array.length); expectArrayContentsAnyOrder(createSamplesArray(), array); } public void testToArray_rightSizedArray() { E[] array = getSubjectGenerator().createArray(getNumElements()); assertSame("toArray(sameSizeE[]) should return the given array", array, collection.toArray(array)); expectArrayContentsAnyOrder(createSamplesArray(), array); } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_rightSizedArray_ordered() { E[] array = getSubjectGenerator().createArray(getNumElements()); assertSame("toArray(sameSizeE[]) should return the given array", array, collection.toArray(array)); expectArrayContentsInOrder(getOrderedElements(), array); } public void testToArray_rightSizedArrayOfObject() { Object[] array = new Object[getNumElements()]; assertSame("toArray(sameSizeObject[]) should return the given array", array, collection.toArray(array)); expectArrayContentsAnyOrder(createSamplesArray(), array); } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_rightSizedArrayOfObject_ordered() { Object[] array = new Object[getNumElements()]; assertSame("toArray(sameSizeObject[]) should return the given array", array, collection.toArray(array)); expectArrayContentsInOrder(getOrderedElements(), array); } public void testToArray_oversizedArray() { E[] array = getSubjectGenerator().createArray(getNumElements() + 2); array[getNumElements()] = samples.e3; array[getNumElements() + 1] = samples.e3; assertSame("toArray(overSizedE[]) should return the given array", array, collection.toArray(array)); List<E> subArray = Arrays.asList(array).subList(0, getNumElements()); E[] expectedSubArray = createSamplesArray(); for (int i = 0; i < getNumElements(); i++) { assertTrue( "toArray(overSizedE[]) should contain element " + expectedSubArray[i], subArray.contains(expectedSubArray[i])); } assertNull("The array element " + "immediately following the end of the collection should be nulled", array[getNumElements()]); // array[getNumElements() + 1] might or might not have been nulled } @CollectionFeature.Require(KNOWN_ORDER) public void testToArray_oversizedArray_ordered() { E[] array = getSubjectGenerator().createArray(getNumElements() + 2); array[getNumElements()] = samples.e3; array[getNumElements() + 1] = samples.e3; assertSame("toArray(overSizedE[]) should return the given array", array, collection.toArray(array)); List<E> expected = getOrderedElements(); for (int i = 0; i < getNumElements(); i++) { assertEquals(expected.get(i), array[i]); } assertNull("The array element " + "immediately following the end of the collection should be nulled", array[getNumElements()]); // array[getNumElements() + 1] might or might not have been nulled } @CollectionSize.Require(absent = ZERO) public void testToArray_emptyArrayOfWrongTypeForNonEmptyCollection() { try { WrongType[] array = new WrongType[0]; collection.toArray(array); fail("toArray(notAssignableTo[]) should throw"); } catch (ArrayStoreException expected) { } } @CollectionSize.Require(ZERO) public void testToArray_emptyArrayOfWrongTypeForEmptyCollection() { WrongType[] array = new WrongType[0]; assertSame( "toArray(sameSizeNotAssignableTo[]) should return the given array", array, collection.toArray(array)); } private void expectArrayContentsAnyOrder(Object[] expected, Object[] actual) { Helpers.assertEqualIgnoringOrder( Arrays.asList(expected), Arrays.asList(actual)); } private void expectArrayContentsInOrder(List<E> expected, Object[] actual) { assertEquals("toArray() ordered contents: ", expected, Arrays.asList(actual)); } /** * Returns the {@link Method} instance for * {@link #testToArray_isPlainObjectArray()} so that tests of * {@link Arrays#asList(Object[])} can suppress it with {@code * FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6260652">Sun bug * 6260652</a> is fixed. */ @GwtIncompatible("reflection") public static Method getToArrayIsPlainObjectArrayMethod() { return Helpers.getMethod(CollectionToArrayTester.class, "testToArray_isPlainObjectArray"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX; import static java.util.Collections.singletonList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import java.util.List; /** * A generic JUnit test which tests {@code addAll(int, Collection)} operations * on a list. Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class ListAddAllAtIndexTester<E> extends AbstractListTester<E> { @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAllAtIndex_supportedAllPresent() { assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, MinimalCollection.of(samples.e0))); expectAdded(0, samples.e0); } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAllAtIndex_unsupportedAllPresent() { try { getList().addAll(0, MinimalCollection.of(samples.e0)); fail("addAll(n, allPresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAllAtIndex_supportedSomePresent() { assertTrue("addAll(n, allPresent) should return true", getList().addAll(0, MinimalCollection.of(samples.e0, samples.e3))); expectAdded(0, samples.e0, samples.e3); } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAllAtIndex_unsupportedSomePresent() { try { getList().addAll(0, MinimalCollection.of(samples.e0, samples.e3)); fail("addAll(n, allPresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAllAtIndex_supportedNothing() { assertFalse("addAll(n, nothing) should return false", getList().addAll(0, emptyCollection())); expectUnchanged(); } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) public void testAddAllAtIndex_unsupportedNothing() { try { assertFalse("addAll(n, nothing) should return false or throw", getList().addAll(0, emptyCollection())); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAllAtIndex_withDuplicates() { MinimalCollection<E> elementsToAdd = MinimalCollection.of(samples.e0, samples.e1, samples.e0, samples.e1); assertTrue("addAll(n, hasDuplicates) should return true", getList().addAll(0, elementsToAdd)); expectAdded(0, samples.e0, samples.e1, samples.e0, samples.e1); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testAddAllAtIndex_nullSupported() { List<E> containsNull = singletonList(null); assertTrue("addAll(n, containsNull) should return true", getList().addAll(0, containsNull)); /* * We need (E) to force interpretation of null as the single element of a * varargs array, not the array itself */ expectAdded(0, (E) null); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testAddAllAtIndex_nullUnsupported() { List<E> containsNull = singletonList(null); try { getList().addAll(0, containsNull); fail("addAll(n, containsNull) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported addAll(n, containsNull)"); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testAddAllAtIndex_middle() { assertTrue("addAll(middle, disjoint) should return true", getList().addAll(getNumElements() / 2, createDisjointCollection())); expectAdded(getNumElements() / 2, createDisjointCollection()); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAllAtIndex_end() { assertTrue("addAll(end, disjoint) should return true", getList().addAll(getNumElements(), createDisjointCollection())); expectAdded(getNumElements(), createDisjointCollection()); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAllAtIndex_nullCollectionReference() { try { getList().addAll(0, null); fail("addAll(n, null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAllAtIndex_negative() { try { getList().addAll(-1, MinimalCollection.of(samples.e3)); fail("addAll(-1, e) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); expectMissing(samples.e3); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAllAtIndex_tooLarge() { try { getList().addAll(getNumElements() + 1, MinimalCollection.of(samples.e3)); fail("addAll(size + 1, e) should throw"); } catch (IndexOutOfBoundsException expected) { } expectUnchanged(); expectMissing(samples.e3); } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.testing.SerializableTester; /** * Basic reserialization test for collection types that must preserve {@code equals()} behavior * when reserialized. (Sets and Lists, but not bare Collections.) * * @author Louis Wasserman */ @GwtCompatible public class CollectionSerializationEqualTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SERIALIZABLE) public void testReserialize() { assertEquals( actualContents(), SerializableTester.reserialize(actualContents())); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; import java.util.Collection; /** * Tests {@link java.util.Set#hashCode}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible(emulated = true) public class SetHashCodeTester<E> extends AbstractSetTester<E> { public void testHashCode() { int expectedHashCode = 0; for (E element : getSampleElements()) { expectedHashCode += ((element == null) ? 0 : element.hashCode()); } assertEquals( "A Set's hashCode() should be the sum of those of its elements.", expectedHashCode, getSet().hashCode()); } @CollectionSize.Require(absent = CollectionSize.ZERO) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testHashCode_containingNull() { Collection<E> elements = getSampleElements(getNumElements() - 1); int expectedHashCode = 0; for (E element : elements) { expectedHashCode += ((element == null) ? 0 : element.hashCode()); } elements.add(null); collection = getSubjectGenerator().create(elements.toArray()); assertEquals( "A Set's hashCode() should be the sum of those of its elements (with " + "a null element counting as having a hash of zero).", expectedHashCode, getSet().hashCode()); } /** * Returns the {@link Method} instances for the test methods in this class * which call {@code hashCode()} on the set values so that set tests on * unhashable objects can suppress it with * {@code FeatureSpecificTestSuiteBuilder.suppressing()}. */ @GwtIncompatible("reflection") public static Method[] getHashCodeMethods() { return new Method[]{ Helpers.getMethod(SetHashCodeTester.class, "testHashCode"), Helpers.getMethod(SetHashCodeTester.class, "testHashCode_containingNull") }; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; /** * Tests {@link java.util.Collection#equals}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class CollectionEqualsTester<E> extends AbstractCollectionTester<E> { public void testEquals_self() { assertTrue("An Object should be equal to itself.", collection.equals(collection)); } public void testEquals_null() { //noinspection ObjectEqualsNull assertFalse("An object should not be equal to null.", collection.equals(null)); } public void testEquals_notACollection() { //noinspection EqualsBetweenInconvertibleTypes assertFalse("A Collection should never equal an " + "object that is not a Collection.", collection.equals("huh?")); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; /** * This class is emulated in GWT. * * @author Hayward Chan */ @GwtCompatible class Platform { /** * Format the template with args, only supports the placeholder * {@code %s}. */ static String format(String template, Object... args) { return String.format(template, args); } /** See {@link ListListIteratorTester} */ static int listListIteratorTesterNumIterations() { return 4; } /** See {@link CollectionIteratorTester} */ static int collectionIteratorTesterNumIterations() { return 5; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.lang.reflect.Method; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * A generic JUnit test which tests {@code put} operations on a map. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class MapPutTester<K, V> extends AbstractMapTester<K, V> { private Entry<K, V> nullKeyEntry; private Entry<K, V> nullValueEntry; private Entry<K, V> nullKeyValueEntry; private Entry<K, V> presentKeyNullValueEntry; @Override public void setUp() throws Exception { super.setUp(); nullKeyEntry = entry(null, samples.e3.getValue()); nullValueEntry = entry(samples.e3.getKey(), null); nullKeyValueEntry = entry(null, null); presentKeyNullValueEntry = entry(samples.e0.getKey(), null); } @MapFeature.Require(SUPPORTS_PUT) public void testPut_supportedNotPresent() { assertNull("put(notPresent, value) should return null", put(samples.e3)); expectAdded(samples.e3); } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT}) @CollectionSize.Require(absent = ZERO) public void testPutAbsentConcurrentWithEntrySetIteration() { try { Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator(); put(samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT}) @CollectionSize.Require(absent = ZERO) public void testPutAbsentConcurrentWithKeySetIteration() { try { Iterator<K> iterator = getMap().keySet().iterator(); put(samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT}) @CollectionSize.Require(absent = ZERO) public void testPutAbsentConcurrentWithValueIteration() { try { Iterator<V> iterator = getMap().values().iterator(); put(samples.e3); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require(absent = SUPPORTS_PUT) public void testPut_unsupportedNotPresent() { try { put(samples.e3); fail("put(notPresent, value) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3); } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPut_unsupportedPresentExistingValue() { try { assertEquals("put(present, existingValue) should return present or throw", samples.e0.getValue(), put(samples.e0)); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPut_unsupportedPresentDifferentValue() { try { getMap().put(samples.e0.getKey(), samples.e3.getValue()); fail("put(present, differentValue) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS}) public void testPut_nullKeySupportedNotPresent() { assertNull("put(null, value) should return null", put(nullKeyEntry)); expectAdded(nullKeyEntry); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS}) @CollectionSize.Require(absent = ZERO) public void testPut_nullKeySupportedPresent() { Entry<K, V> newEntry = entry(null, samples.e3.getValue()); initMapWithNullKey(); assertEquals("put(present, value) should return the associated value", getValueForNullKey(), put(newEntry)); Entry<K, V>[] expected = createArrayWithNullKey(); expected[getNullLocation()] = newEntry; expectContents(expected); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS) public void testPut_nullKeyUnsupported() { try { put(nullKeyEntry); fail("put(null, value) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullKeyMissingWhenNullKeysUnsupported( "Should not contain null key after unsupported put(null, value)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) public void testPut_nullValueSupported() { assertNull("put(key, null) should return null", put(nullValueEntry)); expectAdded(nullValueEntry); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES) public void testPut_nullValueUnsupported() { try { put(nullValueEntry); fail("put(key, null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullValueMissingWhenNullValuesUnsupported( "Should not contain null value after unsupported put(key, null)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testPut_replaceWithNullValueSupported() { assertEquals("put(present, null) should return the associated value", samples.e0.getValue(), put(presentKeyNullValueEntry)); expectReplacement(presentKeyNullValueEntry); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testPut_replaceWithNullValueUnsupported() { try { put(presentKeyNullValueEntry); fail("put(present, null) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullValueMissingWhenNullValuesUnsupported( "Should not contain null after unsupported put(present, null)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testPut_replaceNullValueWithNullSupported() { initMapWithNullValue(); assertNull("put(present, null) should return the associated value (null)", getMap().put(getKeyForNullValue(), null)); expectContents(createArrayWithNullValue()); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testPut_replaceNullValueWithNonNullSupported() { Entry<K, V> newEntry = entry(getKeyForNullValue(), samples.e3.getValue()); initMapWithNullValue(); assertNull("put(present, value) should return the associated value (null)", put(newEntry)); Entry<K, V>[] expected = createArrayWithNullValue(); expected[getNullLocation()] = newEntry; expectContents(expected); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES}) public void testPut_nullKeyAndValueSupported() { assertNull("put(null, null) should return null", put(nullKeyValueEntry)); expectAdded(nullKeyValueEntry); } private V put(Map.Entry<K, V> entry) { return getMap().put(entry.getKey(), entry.getValue()); } /** * Returns the {@link Method} instance for {@link * #testPut_nullKeyUnsupported()} so that tests of {@link java.util.TreeMap} * can suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()} * until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun bug * 5045147</a> is fixed. */ @GwtIncompatible("reflection") public static Method getPutNullKeyUnsupportedMethod() { return Helpers.getMethod(MapPutTester.class, "testPut_nullKeyUnsupported"); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; /** * A generic JUnit test which tests {@code get} operations on a map. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion * @author Chris Povirk */ @GwtCompatible public class MapGetTester<K, V> extends AbstractMapTester<K, V> { @CollectionSize.Require(absent = ZERO) public void testGet_yes() { assertEquals("get(present) should return the associated value", samples.e0.getValue(), get(samples.e0.getKey())); } public void testGet_no() { assertNull("get(notPresent) should return null", get(samples.e3.getKey())); } @CollectionFeature.Require(ALLOWS_NULL_QUERIES) public void testGet_nullNotContainedButAllowed() { assertNull("get(null) should return null", get(null)); } @CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES) public void testGet_nullNotContainedAndUnsupported() { try { assertNull("get(null) should return null or throw", get(null)); } catch (NullPointerException tolerated) { } } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testGet_nonNullWhenNullContained() { initMapWithNullKey(); assertNull("get(notPresent) should return null", get(samples.e3.getKey())); } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testGet_nullContained() { initMapWithNullKey(); assertEquals("get(null) should return the associated value", getValueForNullKey(), get(null)); } public void testGet_wrongType() { try { assertNull("get(wrongType) should return null or throw", getMap().get(WrongType.VALUE)); } catch (ClassCastException tolerated) { } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; /** * A generic JUnit test which tests {@code size()} operations on a map. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class MapSizeTester<K, V> extends AbstractMapTester<K, V> { public void testSize() { assertEquals("size():", getNumElements(), getMap().size()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code remove(Object)} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class ListRemoveTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRemove_duplicate() { ArrayWithDuplicate<E> arrayAndDuplicate = createArrayWithDuplicateElement(); collection = getSubjectGenerator().create(arrayAndDuplicate.elements); E duplicate = arrayAndDuplicate.duplicate; int firstIndex = getList().indexOf(duplicate); int initialSize = getList().size(); assertTrue("remove(present) should return true", getList().remove(duplicate)); assertTrue("After remove(duplicate), a list should still contain " + "the duplicate element", getList().contains(duplicate)); assertFalse("remove(duplicate) should remove the first instance of the " + "duplicate element in the list", firstIndex == getList().indexOf(duplicate)); assertEquals("remove(present) should decrease the size of a list by one.", initialSize - 1, getList().size()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_QUERIES; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.WrongType; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; /** * A generic JUnit test which tests {@code containsKey()} operations on a map. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class MapContainsKeyTester<K, V> extends AbstractMapTester<K, V> { @CollectionSize.Require(absent = ZERO) public void testContains_yes() { assertTrue("containsKey(present) should return true", getMap().containsKey(samples.e0.getKey())); } public void testContains_no() { assertFalse("containsKey(notPresent) should return false", getMap().containsKey(samples.e3.getKey())); } @MapFeature.Require(ALLOWS_NULL_QUERIES) public void testContains_nullNotContainedButAllowed() { assertFalse("containsKey(null) should return false", getMap().containsKey(null)); } @MapFeature.Require(absent = ALLOWS_NULL_QUERIES) public void testContains_nullNotContainedAndUnsupported() { expectNullKeyMissingWhenNullKeysUnsupported( "containsKey(null) should return false or throw"); } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testContains_nonNullWhenNullContained() { initMapWithNullKey(); assertFalse("containsKey(notPresent) should return false", getMap().containsKey(samples.e3.getKey())); } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testContains_nullContained() { initMapWithNullKey(); assertTrue("containsKey(null) should return true", getMap().containsKey(null)); } public void testContains_wrongType() { try { //noinspection SuspiciousMethodCalls assertFalse("containsKey(wrongType) should return false or throw", getMap().containsKey(WrongType.VALUE)); } catch (ClassCastException tolerated) { } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static java.util.Collections.singletonList; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.lang.reflect.Method; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; /** * A generic JUnit test which tests addAll operations on a collection. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class CollectionAddAllTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_supportedNothing() { assertFalse("addAll(nothing) should return false", collection.addAll(emptyCollection())); expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testAddAll_unsupportedNothing() { try { assertFalse("addAll(nothing) should return false or throw", collection.addAll(emptyCollection())); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_supportedNonePresent() { assertTrue("addAll(nonePresent) should return true", collection.addAll(createDisjointCollection())); expectAdded(samples.e3, samples.e4); } @CollectionFeature.Require(absent = SUPPORTS_ADD) public void testAddAll_unsupportedNonePresent() { try { collection.addAll(createDisjointCollection()); fail("addAll(nonePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3, samples.e4); } @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_supportedSomePresent() { assertTrue("addAll(somePresent) should return true", collection.addAll(MinimalCollection.of(samples.e3, samples.e0))); assertTrue("should contain " + samples.e3, collection.contains(samples.e3)); assertTrue("should contain " + samples.e0, collection.contains(samples.e0)); } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_unsupportedSomePresent() { try { collection.addAll(MinimalCollection.of(samples.e3, samples.e0)); fail("addAll(somePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testAddAllConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); assertTrue(collection.addAll(MinimalCollection.of(samples.e3, samples.e0))); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @CollectionFeature.Require(absent = SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_unsupportedAllPresent() { try { assertFalse("addAll(allPresent) should return false or throw", collection.addAll(MinimalCollection.of(samples.e0))); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS) public void testAddAll_nullSupported() { List<E> containsNull = singletonList(null); assertTrue("addAll(containsNull) should return true", collection .addAll(containsNull)); /* * We need (E) to force interpretation of null as the single element of a * varargs array, not the array itself */ expectAdded((E) null); } @CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES) public void testAddAll_nullUnsupported() { List<E> containsNull = singletonList(null); try { collection.addAll(containsNull); fail("addAll(containsNull) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullMissingWhenNullUnsupported( "Should not contain null after unsupported addAll(containsNull)"); } @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_nullCollectionReference() { try { collection.addAll(null); fail("addAll(null) should throw NullPointerException"); } catch (NullPointerException expected) { } } /** * Returns the {@link Method} instance for {@link * #testAddAll_nullUnsupported()} so that tests can suppress it with {@code * FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun * bug 5045147</a> is fixed. */ @GwtIncompatible("reflection") public static Method getAddAllNullUnsupportedMethod() { return Helpers.getMethod(CollectionAddAllTester.class, "testAddAll_nullUnsupported"); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests addAll operations on a set. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.SetTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible public class SetAddAllTester<E> extends AbstractSetTester<E> { @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_supportedSomePresent() { assertTrue("add(somePresent) should return true", getSet().addAll(MinimalCollection.of(samples.e3, samples.e0))); expectAdded(samples.e3); } @CollectionFeature.Require(SUPPORTS_ADD) public void testAddAll_withDuplicates() { MinimalCollection<E> elementsToAdd = MinimalCollection.of(samples.e3, samples.e4, samples.e3, samples.e4); assertTrue("add(hasDuplicates) should return true", getSet().addAll(elementsToAdd)); expectAdded(samples.e3, samples.e4); } @CollectionFeature.Require(SUPPORTS_ADD) @CollectionSize.Require(absent = ZERO) public void testAddAll_supportedAllPresent() { assertFalse("add(allPresent) should return false", getSet().addAll(MinimalCollection.of(samples.e0))); expectUnchanged(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests creation (typically through a constructor or * static factory method) of a list. Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class ListCreationTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates() { E[] array = createSamplesArray(); array[1] = samples.e0; collection = getSubjectGenerator().create(array); expectContents(array); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import java.util.ConcurrentModificationException; import java.util.Iterator; /** * A generic JUnit test which tests {@code clear()} operations on a collection. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public class CollectionClearTester<E> extends AbstractCollectionTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) public void testClear() { collection.clear(); assertTrue("After clear(), a collection should be empty.", collection.isEmpty()); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(absent = ZERO) public void testClear_unsupported() { try { collection.clear(); fail("clear() should throw UnsupportedOperation if a collection does " + "not support it and is not empty."); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @CollectionFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testClear_unsupportedByEmptyCollection() { try { collection.clear(); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(SEVERAL) public void testClearConcurrentWithIteration() { try { Iterator<E> iterator = collection.iterator(); collection.clear(); iterator.next(); /* * We prefer for iterators to fail immediately on hasNext, but ArrayList * and LinkedList will notably return true on hasNext here! */ fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Tests {@link java.util.Map#equals}. * * <p>This class is GWT compatible. * * @author George van den Driessche * @author Chris Povirk */ @GwtCompatible public class MapEqualsTester<K, V> extends AbstractMapTester<K, V> { public void testEquals_otherMapWithSameEntries() { assertTrue( "A Map should equal any other Map containing the same entries.", getMap().equals(newHashMap(getSampleEntries()))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherMapWithDifferentEntries() { Map<K, V> other = newHashMap(getSampleEntries(getNumEntries() - 1)); Entry<K, V> e3 = getSubjectGenerator().samples().e3; other.put(e3.getKey(), e3.getValue()); assertFalse( "A Map should not equal another Map containing different entries.", getMap().equals(other) ); } @CollectionSize.Require(absent = CollectionSize.ZERO) @MapFeature.Require(ALLOWS_NULL_KEYS) public void testEquals_containingNullKey() { Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1); entries.add(entry(null, samples.e3.getValue())); resetContainer(getSubjectGenerator().create(entries.toArray())); assertTrue("A Map should equal any other Map containing the same entries," + " even if some keys are null.", getMap().equals(newHashMap(entries))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherContainsNullKey() { Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1); entries.add(entry(null, samples.e3.getValue())); Map<K, V> other = newHashMap(entries); assertFalse( "Two Maps should not be equal if exactly one of them contains a null " + "key.", getMap().equals(other)); } @CollectionSize.Require(absent = CollectionSize.ZERO) @MapFeature.Require(ALLOWS_NULL_VALUES) public void testEquals_containingNullValue() { Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1); entries.add(entry(samples.e3.getKey(), null)); resetContainer(getSubjectGenerator().create(entries.toArray())); assertTrue("A Map should equal any other Map containing the same entries," + " even if some values are null.", getMap().equals(newHashMap(entries))); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_otherContainsNullValue() { Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1); entries.add(entry(samples.e3.getKey(), null)); Map<K, V> other = newHashMap(entries); assertFalse( "Two Maps should not be equal if exactly one of them contains a null " + "value.", getMap().equals(other)); } @CollectionSize.Require(absent = CollectionSize.ZERO) public void testEquals_smallerMap() { Collection<Map.Entry<K, V>> fewerEntries = getSampleEntries(getNumEntries() - 1); assertFalse("Maps of different sizes should not be equal.", getMap().equals(newHashMap(fewerEntries))); } public void testEquals_largerMap() { Collection<Map.Entry<K, V>> moreEntries = getSampleEntries(getNumEntries() + 1); assertFalse("Maps of different sizes should not be equal.", getMap().equals(newHashMap(moreEntries))); } public void testEquals_list() { assertFalse("A List should never equal a Map.", getMap().equals(Helpers.copyToList(getMap().entrySet()))); } private static <K, V> HashMap<K, V> newHashMap( Collection<? extends Map.Entry<? extends K, ? extends V>> entries) { HashMap<K, V> map = new HashMap<K, V>(); for (Map.Entry<? extends K, ? extends V> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT; import static java.util.Collections.singletonList; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.lang.reflect.Method; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * A generic JUnit test which tests {@code putAll} operations on a map. Can't be * invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Kevin Bourrillion */ @SuppressWarnings("unchecked") // too many "unchecked generic array creations" @GwtCompatible(emulated = true) public class MapPutAllTester<K, V> extends AbstractMapTester<K, V> { private List<Entry<K, V>> containsNullKey; private List<Entry<K, V>> containsNullValue; @Override public void setUp() throws Exception { super.setUp(); containsNullKey = singletonList(entry(null, samples.e3.getValue())); containsNullValue = singletonList(entry(samples.e3.getKey(), null)); } @MapFeature.Require(SUPPORTS_PUT) public void testPutAll_supportedNothing() { getMap().putAll(emptyMap()); expectUnchanged(); } @MapFeature.Require(absent = SUPPORTS_PUT) public void testPutAll_unsupportedNothing() { try { getMap().putAll(emptyMap()); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @MapFeature.Require(SUPPORTS_PUT) public void testPutAll_supportedNonePresent() { putAll(createDisjointCollection()); expectAdded(samples.e3, samples.e4); } @MapFeature.Require(absent = SUPPORTS_PUT) public void testPutAll_unsupportedNonePresent() { try { putAll(createDisjointCollection()); fail("putAll(nonePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); expectMissing(samples.e3, samples.e4); } @MapFeature.Require(SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPutAll_supportedSomePresent() { putAll(MinimalCollection.of(samples.e3, samples.e0)); expectAdded(samples.e3); } @MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT }) @CollectionSize.Require(absent = ZERO) public void testPutAllSomePresentConcurrentWithEntrySetIteration() { try { Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator(); putAll(MinimalCollection.of(samples.e3, samples.e0)); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { // success } } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPutAll_unsupportedSomePresent() { try { putAll(MinimalCollection.of(samples.e3, samples.e0)); fail("putAll(somePresent) should throw"); } catch (UnsupportedOperationException expected) { } expectUnchanged(); } @MapFeature.Require(absent = SUPPORTS_PUT) @CollectionSize.Require(absent = ZERO) public void testPutAll_unsupportedAllPresent() { try { putAll(MinimalCollection.of(samples.e0)); } catch (UnsupportedOperationException tolerated) { } expectUnchanged(); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS}) public void testPutAll_nullKeySupported() { putAll(containsNullKey); expectAdded(containsNullKey.get(0)); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS) public void testPutAll_nullKeyUnsupported() { try { putAll(containsNullKey); fail("putAll(containsNullKey) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullKeyMissingWhenNullKeysUnsupported( "Should not contain null key after unsupported " + "putAll(containsNullKey)"); } @MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES}) public void testPutAll_nullValueSupported() { putAll(containsNullValue); expectAdded(containsNullValue.get(0)); } @MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES) public void testPutAll_nullValueUnsupported() { try { putAll(containsNullValue); fail("putAll(containsNullValue) should throw"); } catch (NullPointerException expected) { } expectUnchanged(); expectNullValueMissingWhenNullValuesUnsupported( "Should not contain null value after unsupported " + "putAll(containsNullValue)"); } @MapFeature.Require(SUPPORTS_PUT) public void testPutAll_nullCollectionReference() { try { getMap().putAll(null); fail("putAll(null) should throw NullPointerException"); } catch (NullPointerException expected) { } } private Map<K, V> emptyMap() { return Collections.emptyMap(); } private void putAll(Iterable<Entry<K, V>> entries) { Map<K, V> map = new LinkedHashMap<K, V>(); for (Entry<K, V> entry : entries) { map.put(entry.getKey(), entry.getValue()); } getMap().putAll(map); } /** * Returns the {@link Method} instance for {@link * #testPutAll_nullKeyUnsupported()} so that tests can suppress it with {@code * FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun * bug 5045147</a> is fixed. */ @GwtIncompatible("reflection") public static Method getPutAllNullKeyUnsupportedMethod() { return Helpers.getMethod(MapPutAllTester.class, "testPutAll_nullKeyUnsupported"); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; /** * A generic JUnit test which tests creation (typically through a constructor or * static factory method) of a map. Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class MapCreationTester<K, V> extends AbstractMapTester<K, V> { @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeySupported() { initMapWithNullKey(); expectContents(createArrayWithNullKey()); } @MapFeature.Require(absent = ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeyUnsupported() { try { initMapWithNullKey(); fail("Creating a map containing a null key should fail"); } catch (NullPointerException expected) { } } @MapFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullValueSupported() { initMapWithNullValue(); expectContents(createArrayWithNullValue()); } @MapFeature.Require(absent = ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullValueUnsupported() { try { initMapWithNullValue(); fail("Creating a map containing a null value should fail"); } catch (NullPointerException expected) { } } @MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeyAndValueSupported() { Entry<K, V>[] entries = createSamplesArray(); entries[getNullLocation()] = entry(null, null); resetMap(entries); expectContents(entries); } @MapFeature.Require(value = ALLOWS_NULL_KEYS, absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesNotRejected() { expectFirstRemoved(getEntriesMultipleNullKeys()); } @MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { expectFirstRemoved(getEntriesMultipleNonNullKeys()); } @MapFeature.Require({ALLOWS_NULL_KEYS, REJECTS_DUPLICATES_AT_CREATION}) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesRejected() { Entry<K, V>[] entries = getEntriesMultipleNullKeys(); try { resetMap(entries); fail("Should reject duplicate null elements at creation"); } catch (IllegalArgumentException expected) { } } @MapFeature.Require(REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesRejected() { Entry<K, V>[] entries = getEntriesMultipleNonNullKeys(); try { resetMap(entries); fail("Should reject duplicate non-null elements at creation"); } catch (IllegalArgumentException expected) { } } private Entry<K, V>[] getEntriesMultipleNullKeys() { Entry<K, V>[] entries = createArrayWithNullKey(); entries[0] = entry(null, entries[0].getValue()); return entries; } private Entry<K, V>[] getEntriesMultipleNonNullKeys() { Entry<K, V>[] entries = createSamplesArray(); entries[0] = entry(samples.e1.getKey(), samples.e0.getValue()); return entries; } private void expectFirstRemoved(Entry<K, V>[] entries) { resetMap(entries); List<Entry<K, V>> expectedWithDuplicateRemoved = Arrays.asList(entries).subList(1, getNumElements()); expectContents(expectedWithDuplicateRemoved); } /** * Returns the {@link Method} instance for {@link * #testCreateWithNullKeyUnsupported()} so that tests can suppress it * with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun * bug 5045147</a> is fixed. */ @GwtIncompatible("reflection") public static Method getCreateWithNullKeyUnsupportedMethod() { return Helpers.getMethod(MapCreationTester.class, "testCreateWithNullKeyUnsupported"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.AbstractCollectionTester; import java.util.Queue; /** * Base class for queue collection tests. * * <p>This class is GWT compatible. * * @author Jared Levy */ @GwtCompatible public class AbstractQueueTester<E> extends AbstractCollectionTester<E> { protected final Queue<E> getQueue() { return (Queue<E>) collection; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MinimalCollection; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; /** * A generic JUnit test which tests {@code retainAll} operations on a list. * Can't be invoked directly; please see * {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * <p>This class is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public class ListRetainAllTester<E> extends AbstractListTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(absent = {ZERO, ONE}) public void testRetainAll_duplicatesKept() { E[] array = createSamplesArray(); array[1] = samples.e0; collection = getSubjectGenerator().create(array); assertFalse("containsDuplicates.retainAll(superset) should return false", collection.retainAll(MinimalCollection.of(createSamplesArray()))); expectContents(array); } @SuppressWarnings("unchecked") @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testRetainAll_duplicatesRemoved() { E[] array = createSamplesArray(); array[1] = samples.e0; collection = getSubjectGenerator().create(array); assertTrue("containsDuplicates.retainAll(subset) should return true", collection.retainAll(MinimalCollection.of(samples.e2))); expectContents(samples.e2); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.List; /** * Reserializes the sets created by another test set generator. * * TODO: make CollectionTestSuiteBuilder test reserialized collections * * @author Jesse Wilson */ public class ReserializingTestCollectionGenerator<E> implements TestCollectionGenerator<E> { private final TestCollectionGenerator<E> delegate; ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) { this.delegate = delegate; } public static <E> ReserializingTestCollectionGenerator<E> newInstance( TestCollectionGenerator<E> delegate) { return new ReserializingTestCollectionGenerator<E>(delegate); } @Override public Collection<E> create(Object... elements) { return reserialize(delegate.create(elements)); } @SuppressWarnings("unchecked") static <T> T reserialize(T object) { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(object); ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bytes.toByteArray())); return (T) in.readObject(); } catch (IOException e) { Helpers.fail(e, e.getMessage()); } catch (ClassNotFoundException e) { Helpers.fail(e, e.getMessage()); } throw new AssertionError("not reachable"); } @Override public SampleElements<E> samples() { return delegate.samples(); } @Override public E[] createArray(int length) { return delegate.createArray(length); } @Override public Iterable<E> order(List<E> insertionOrder) { return delegate.order(insertionOrder); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import static com.google.common.collect.testing.Helpers.castOrCopyToList; import static java.util.Collections.reverse; import com.google.common.collect.testing.DerivedCollectionGenerators.Bound; import com.google.common.collect.testing.DerivedCollectionGenerators.SortedMapSubmapTestMapGenerator; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.testers.NavigableMapNavigationTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.SortedMap; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a NavigableMap implementation. */ public class NavigableMapTestSuiteBuilder<K, V> extends SortedMapTestSuiteBuilder<K, V> { public static <K, V> NavigableMapTestSuiteBuilder<K, V> using( TestMapGenerator<K, V> generator) { NavigableMapTestSuiteBuilder<K, V> result = new NavigableMapTestSuiteBuilder<K, V>(); result.usingGenerator(generator); return result; } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); testers.add(NavigableMapNavigationTester.class); return testers; } @Override protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>> parentBuilder) { List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder); if (!parentBuilder.getFeatures().contains(NoRecurse.DESCENDING)) { derivedSuites.add(createDescendingSuite(parentBuilder)); } if (!parentBuilder.getFeatures().contains(NoRecurse.SUBMAP)) { // Other combinations are inherited from SortedMapTestSuiteBuilder. derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE)); derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND)); derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE)); derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE)); derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE)); } return derivedSuites; } @Override protected NavigableSetTestSuiteBuilder<K> createDerivedKeySetSuite( TestSetGenerator<K> keySetGenerator) { return NavigableSetTestSuiteBuilder.using(keySetGenerator); } public static final class NavigableMapSubmapTestMapGenerator<K, V> extends SortedMapSubmapTestMapGenerator<K, V> { public NavigableMapSubmapTestMapGenerator( TestMapGenerator<K, V> delegate, Bound to, Bound from) { super(delegate, to, from); } @Override NavigableMap<K, V> createSubMap(SortedMap<K, V> sortedMap, K firstExclusive, K lastExclusive) { NavigableMap<K, V> map = (NavigableMap<K, V>) sortedMap; if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) { return map.headMap(lastInclusive, true); } else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) { return map.tailMap(firstExclusive, false); } else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) { return map.subMap(firstExclusive, false, lastExclusive, false); } else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) { return map.subMap(firstExclusive, false, lastInclusive, true); } else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) { return map.subMap(firstInclusive, true, lastInclusive, true); } else { return (NavigableMap<K, V>) super.createSubMap(map, firstExclusive, lastExclusive); } } } @Override public NavigableMapTestSuiteBuilder<K, V> newBuilderUsing( TestMapGenerator<K, V> delegate, Bound to, Bound from) { return using(new NavigableMapSubmapTestMapGenerator<K, V>(delegate, to, from)); } /** * Create a suite whose maps are descending views of other maps. */ private TestSuite createDescendingSuite(final FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>> parentBuilder) { final TestMapGenerator<K, V> delegate = (TestMapGenerator<K, V>) parentBuilder.getSubjectGenerator().getInnerGenerator(); List<Feature<?>> features = new ArrayList<Feature<?>>(); features.add(NoRecurse.DESCENDING); features.addAll(parentBuilder.getFeatures()); return NavigableMapTestSuiteBuilder .using(new ForwardingTestMapGenerator<K, V>(delegate) { @Override public Map<K, V> create(Object... entries) { NavigableMap<K, V> map = (NavigableMap<K, V>) delegate.create(entries); return map.descendingMap(); } @Override public Iterable<Entry<K, V>> order(List<Entry<K, V>> insertionOrder) { insertionOrder = castOrCopyToList(delegate.order(insertionOrder)); reverse(insertionOrder); return insertionOrder; } }) .named(parentBuilder.getName() + " descending") .withFeatures(features) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite(); } static class ForwardingTestMapGenerator<K, V> implements TestMapGenerator<K, V> { private TestMapGenerator<K, V> delegate; ForwardingTestMapGenerator(TestMapGenerator<K, V> delegate) { this.delegate = delegate; } @Override public Iterable<Entry<K, V>> order(List<Entry<K, V>> insertionOrder) { return delegate.order(insertionOrder); } @Override public K[] createKeyArray(int length) { return delegate.createKeyArray(length); } @Override public V[] createValueArray(int length) { return delegate.createValueArray(length); } @Override public SampleElements<Entry<K, V>> samples() { return delegate.samples(); } @Override public Map<K, V> create(Object... elements) { return delegate.create(elements); } @Override public Entry<K, V>[] createArray(int length) { return delegate.createArray(length); } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; /** * Adapts a test iterable generator to give a TestIteratorGenerator. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public final class DerivedTestIteratorGenerator<E> implements TestIteratorGenerator<E>, DerivedGenerator { private final TestSubjectGenerator<? extends Iterable<E>> collectionGenerator; public DerivedTestIteratorGenerator( TestSubjectGenerator<? extends Iterable<E>> collectionGenerator) { this.collectionGenerator = collectionGenerator; } @Override public TestSubjectGenerator<? extends Iterable<E>> getInnerGenerator() { return collectionGenerator; } @Override public Iterator<E> get() { return collectionGenerator.createTestSubject().iterator(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.testers.CollectionAddAllTester; import com.google.common.collect.testing.testers.CollectionAddTester; import com.google.common.collect.testing.testers.CollectionClearTester; import com.google.common.collect.testing.testers.CollectionContainsAllTester; import com.google.common.collect.testing.testers.CollectionContainsTester; import com.google.common.collect.testing.testers.CollectionCreationTester; import com.google.common.collect.testing.testers.CollectionEqualsTester; import com.google.common.collect.testing.testers.CollectionIsEmptyTester; import com.google.common.collect.testing.testers.CollectionIteratorTester; import com.google.common.collect.testing.testers.CollectionRemoveAllTester; import com.google.common.collect.testing.testers.CollectionRemoveTester; import com.google.common.collect.testing.testers.CollectionRetainAllTester; import com.google.common.collect.testing.testers.CollectionSerializationTester; import com.google.common.collect.testing.testers.CollectionSizeTester; import com.google.common.collect.testing.testers.CollectionToArrayTester; import com.google.common.collect.testing.testers.CollectionToStringTester; import junit.framework.TestSuite; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Abstract superclass of all test-suite builders for collection interfaces. * * @author George van den Driessche */ public abstract class AbstractCollectionTestSuiteBuilder< B extends AbstractCollectionTestSuiteBuilder<B, E>, E> extends PerCollectionSizeTestSuiteBuilder< B, TestCollectionGenerator<E>, Collection<E>, E> { // Class parameters must be raw. @SuppressWarnings("unchecked") @Override protected List<Class<? extends AbstractTester>> getTesters() { return Arrays.<Class<? extends AbstractTester>>asList( CollectionAddAllTester.class, CollectionAddTester.class, CollectionClearTester.class, CollectionContainsAllTester.class, CollectionContainsTester.class, CollectionCreationTester.class, CollectionEqualsTester.class, CollectionIsEmptyTester.class, CollectionIteratorTester.class, CollectionRemoveAllTester.class, CollectionRemoveTester.class, CollectionRetainAllTester.class, CollectionSerializationTester.class, CollectionSizeTester.class, CollectionToArrayTester.class, CollectionToStringTester.class ); } @Override protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { DerivedIteratorTestSuiteBuilder<?> iteratorTestSuiteBuilder = new DerivedIteratorTestSuiteBuilder<E>() .named(parentBuilder.getName()) .usingGenerator(parentBuilder.getSubjectGenerator()) .withFeatures(parentBuilder.getFeatures()); return Collections.singletonList( iteratorTestSuiteBuilder.createTestSuite()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import java.util.Collections; import java.util.List; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * an Iterator implementation. * * <p>At least, it will do when it's finished. * * @author George van den Driessche */ public class IteratorTestSuiteBuilder<E> extends FeatureSpecificTestSuiteBuilder< IteratorTestSuiteBuilder<E>, TestIteratorGenerator<?>> { @Override protected List<Class<? extends AbstractTester>> getTesters() { return Collections.<Class<? extends AbstractTester>>singletonList( ExampleIteratorTester.class); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; /** * A simplistic set which implements the bare minimum so that it can be used in * tests without relying on any specific Set implementations. Slow. Explicitly * allows null elements so that they can be used in the testers. * * <p>This class is GWT compatible. * * @author Regina O'Dell */ @GwtCompatible public class MinimalSet<E> extends MinimalCollection<E> implements Set<E> { @SuppressWarnings("unchecked") // empty Object[] as E[] public static <E> MinimalSet<E> of(E... contents) { return ofClassAndContents( Object.class, (E[]) new Object[0], Arrays.asList(contents)); } @SuppressWarnings("unchecked") // empty Object[] as E[] public static <E> MinimalSet<E> from(Collection<? extends E> contents) { return ofClassAndContents(Object.class, (E[]) new Object[0], contents); } public static <E> MinimalSet<E> ofClassAndContents( Class<? super E> type, E[] emptyArrayForContents, Iterable<? extends E> contents) { List<E> setContents = new ArrayList<E>(); for (E e : contents) { if (!setContents.contains(e)) { setContents.add(e); } } return new MinimalSet<E>(type, setContents.toArray(emptyArrayForContents)); } private MinimalSet(Class<? super E> type, E... contents) { super(type, true, contents); } /* * equals() and hashCode() are more specific in the Set contract. */ @Override public boolean equals(Object object) { if (object instanceof Set) { Set<?> that = (Set<?>) object; return (this.size() == that.size()) && this.containsAll(that); } return false; } @Override public int hashCode() { int hashCodeSum = 0; for (Object o : this) { hashCodeSum += (o == null) ? 0 : o.hashCode(); } return hashCodeSum; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; /** * Base class for map testers. * * <p>This class is GWT compatible. * * TODO: see how much of this is actually needed once Map testers are written. * (It was cloned from AbstractCollectionTester.) * * @param <K> the key type of the map to be tested. * @param <V> the value type of the map to be tested. * * @author George van den Driessche */ @GwtCompatible public abstract class AbstractMapTester<K, V> extends AbstractContainerTester<Map<K, V>, Map.Entry<K, V>> { protected Map<K, V> getMap() { return container; } @Override public void setUp() throws Exception { super.setUp(); samples = this.getSubjectGenerator().samples(); resetMap(); } @Override protected Collection<Map.Entry<K, V>> actualContents() { return getMap().entrySet(); } /** @see AbstractContainerTester#resetContainer() */ protected void resetMap() { resetContainer(); } protected void expectMissingKeys(K... elements) { for (K element : elements) { assertFalse("Should not contain key " + element, getMap().containsKey(element)); } } protected void expectMissingValues(V... elements) { for (V element : elements) { assertFalse("Should not contain value " + element, getMap().containsValue(element)); } } /** * @return an array of the proper size with {@code null} as the key of the * middle element. */ protected Map.Entry<K, V>[] createArrayWithNullKey() { Map.Entry<K, V>[] array = createSamplesArray(); final int nullKeyLocation = getNullLocation(); final Map.Entry<K, V> oldEntry = array[nullKeyLocation]; array[nullKeyLocation] = entry(null, oldEntry.getValue()); return array; } protected V getValueForNullKey() { return getEntryNullReplaces().getValue(); } protected K getKeyForNullValue() { return getEntryNullReplaces().getKey(); } private Entry<K, V> getEntryNullReplaces() { Iterator<Entry<K, V>> entries = getSampleElements().iterator(); for (int i = 0; i < getNullLocation(); i++) { entries.next(); } return entries.next(); } /** * @return an array of the proper size with {@code null} as the value of the * middle element. */ protected Map.Entry<K, V>[] createArrayWithNullValue() { Map.Entry<K, V>[] array = createSamplesArray(); final int nullValueLocation = getNullLocation(); final Map.Entry<K, V> oldEntry = array[nullValueLocation]; array[nullValueLocation] = entry(oldEntry.getKey(), null); return array; } protected void initMapWithNullKey() { resetMap(createArrayWithNullKey()); } protected void initMapWithNullValue() { resetMap(createArrayWithNullValue()); } /** * Equivalent to {@link #expectMissingKeys(Object[]) expectMissingKeys} * {@code (null)} * except that the call to {@code contains(null)} is permitted to throw a * {@code NullPointerException}. * @param message message to use upon assertion failure */ protected void expectNullKeyMissingWhenNullKeysUnsupported(String message) { try { assertFalse(message, getMap().containsKey(null)); } catch (NullPointerException tolerated) { // Tolerated } } /** * Equivalent to {@link #expectMissingValues(Object[]) expectMissingValues} * {@code (null)} * except that the call to {@code contains(null)} is permitted to throw a * {@code NullPointerException}. * @param message message to use upon assertion failure */ protected void expectNullValueMissingWhenNullValuesUnsupported( String message) { try { assertFalse(message, getMap().containsValue(null)); } catch (NullPointerException tolerated) { // Tolerated } } @SuppressWarnings("unchecked") @Override protected MinimalCollection<Map.Entry<K, V>> createDisjointCollection() { return MinimalCollection.of(samples.e3, samples.e4); } protected int getNumEntries() { return getNumElements(); } protected Collection<Map.Entry<K, V>> getSampleEntries(int howMany) { return getSampleElements(howMany); } protected Collection<Map.Entry<K, V>> getSampleEntries() { return getSampleElements(); } @Override protected void expectMissing(Entry<K, V>... entries) { for (Entry<K, V> entry : entries) { assertFalse("Should not contain entry " + entry, actualContents().contains(entry)); assertFalse("Should not contain key " + entry.getKey() + " mapped to" + " value " + entry.getValue(), equal(getMap().get(entry.getKey()), entry.getValue())); } } private static boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } // This one-liner saves us from some ugly casts protected Entry<K, V> entry(K key, V value) { return Helpers.mapEntry(key, value); } @Override protected void expectContents(Collection<Entry<K, V>> expected) { // TODO: move this to invariant checks once the appropriate hook exists? super.expectContents(expected); for (Entry<K, V> entry : expected) { assertEquals("Wrong value for key " + entry.getKey(), entry.getValue(), getMap().get(entry.getKey())); } } protected final void expectReplacement(Entry<K, V> newEntry) { List<Entry<K, V>> expected = Helpers.copyToList(getSampleElements()); replaceValue(expected, newEntry); expectContents(expected); } private void replaceValue(List<Entry<K, V>> expected, Entry<K, V> newEntry) { for (ListIterator<Entry<K, V>> i = expected.listIterator(); i.hasNext();) { if (Helpers.equal(i.next().getKey(), newEntry.getKey())) { i.set(newEntry); return; } } throw new IllegalArgumentException(Platform.format( "key %s not found in entries %s", newEntry.getKey(), expected)); } /** * Wrapper for {@link Map#get(Object)} that forces the caller to pass in a key * of the same type as the map. Besides being slightly shorter than code that * uses {@link #getMap()}, it also ensures that callers don't pass an * {@link Entry} by mistake. */ protected V get(K key) { return getMap().get(key); } protected void resetMap(Entry<K, V>[] entries) { resetContainer(getSubjectGenerator().create((Object[]) entries)); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; /** * An implementation of {@code Iterable} which throws an exception on all * invocations of the {@link #iterator()} method after the first, and whose * iterator is always unmodifiable. * * <p>The {@code Iterable} specification does not make it absolutely clear what * should happen on a second invocation, so implementors have made various * choices, including: * * <ul> * <li>returning the same iterator again * <li>throwing an exception of some kind * <li>or the usual, <i>robust</i> behavior, which all known {@link Collection} * implementations have, of returning a new, independent iterator * </ul> * * Because of this situation, any public method accepting an iterable should * invoke the {@code iterator} method only once, and should be tested using this * class. Exceptions to this rule should be clearly documented. * * <p>Note that although your APIs should be liberal in what they accept, your * methods which <i>return</i> iterables should make every attempt to return * ones of the robust variety. * * <p>This testing utility is not thread-safe. * * @author Kevin Bourrillion */ @GwtCompatible public final class MinimalIterable<E> implements Iterable<E> { /** * Returns an iterable whose iterator returns the given elements in order. */ public static <E> MinimalIterable<E> of(E... elements) { // Make sure to get an unmodifiable iterator return new MinimalIterable<E>(Arrays.asList(elements).iterator()); } /** * Returns an iterable whose iterator returns the given elements in order. * The elements are copied out of the source collection at the time this * method is called. */ @SuppressWarnings("unchecked") // Es come in, Es go out public static <E> MinimalIterable<E> from(final Collection<E> elements) { return (MinimalIterable) of(elements.toArray()); } private Iterator<E> iterator; private MinimalIterable(Iterator<E> iterator) { this.iterator = iterator; } @Override public Iterator<E> iterator() { if (iterator == null) { // TODO: throw something else? Do we worry that people's code and tests // might be relying on this particular type of exception? throw new IllegalStateException(); } try { return iterator; } finally { iterator = null; } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.EnumSet; import java.util.Iterator; import java.util.ListIterator; import java.util.Set; /** * A method supported by implementations of the {@link Iterator} or * {@link ListIterator} interface. * * <p>This enum is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public enum IteratorFeature { /** * Support for {@link Iterator#remove()}. */ SUPPORTS_REMOVE, /** * Support for {@link ListIterator#add(Object)}; ignored for plain * {@link Iterator} implementations. */ SUPPORTS_ADD, /** * Support for {@link ListIterator#set(Object)}; ignored for plain * {@link Iterator} implementations. */ SUPPORTS_SET; /** * A set containing none of the optional features of the {@link Iterator} or * {@link ListIterator} interfaces. */ public static final Set<IteratorFeature> UNMODIFIABLE = Collections.emptySet(); /** * A set containing all of the optional features of the {@link Iterator} and * {@link ListIterator} interfaces. */ public static final Set<IteratorFeature> MODIFIABLE = Collections.unmodifiableSet(EnumSet.allOf(IteratorFeature.class)); }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * This abstract base class for testers allows the framework to inject needed * information after JUnit constructs the instances. * * <p>This class is emulated in GWT. * * @param <G> the type of the test generator required by this tester. An * instance of G should somehow provide an instance of the class under test, * plus any other information required to parameterize the test. * * @author George van den Driessche */ @GwtCompatible public class AbstractTester<G> extends TestCase { private G subjectGenerator; private String suiteName; private Runnable setUp; private Runnable tearDown; // public so that it can be referenced in generated GWT tests. @Override public void setUp() throws Exception { if (setUp != null) { setUp.run(); } } // public so that it can be referenced in generated GWT tests. @Override public void tearDown() throws Exception { if (tearDown != null) { tearDown.run(); } } // public so that it can be referenced in generated GWT tests. public final void init( G subjectGenerator, String suiteName, Runnable setUp, Runnable tearDown) { this.subjectGenerator = subjectGenerator; this.suiteName = suiteName; this.setUp = setUp; this.tearDown = tearDown; } // public so that it can be referenced in generated GWT tests. public final void init(G subjectGenerator, String suiteName) { init(subjectGenerator, suiteName, null, null); } public G getSubjectGenerator() { return subjectGenerator; } /** Returns the name of the test method invoked by this test instance. */ public final String getTestMethodName() { return super.getName(); } @Override public String getName() { return Platform.format("%s[%s]", super.getName(), suiteName); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import junit.framework.Test; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; /** * Generates a test suite covering the {@link Queue} implementations in the * {@link java.util} package. Can be subclassed to specify tests that should * be suppressed. * * @author Jared Levy */ public class TestsForQueuesInJavaUtil { public static Test suite() { return new TestsForQueuesInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite(); suite.addTest(testsForLinkedList()); suite.addTest(testsForArrayBlockingQueue()); suite.addTest(testsForConcurrentLinkedQueue()); suite.addTest(testsForLinkedBlockingQueue()); suite.addTest(testsForPriorityBlockingQueue()); suite.addTest(testsForPriorityQueue()); return suite; } protected Collection<Method> suppressForLinkedList() { return Collections.emptySet(); } protected Collection<Method> suppressForArrayBlockingQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForConcurrentLinkedQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForLinkedBlockingQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForPriorityBlockingQueue() { return Collections.emptySet(); } protected Collection<Method> suppressForPriorityQueue() { return Collections.emptySet(); } public Test testsForLinkedList() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new LinkedList<String>(MinimalCollection.of(elements)); } }) .named("LinkedList") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .skipCollectionTests() // already covered in TestsForListsInJavaUtil .suppressing(suppressForLinkedList()) .createTestSuite(); } public Test testsForArrayBlockingQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new ArrayBlockingQueue<String>( 100, false, MinimalCollection.of(elements)); } }) .named("ArrayBlockingQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForArrayBlockingQueue()) .createTestSuite(); } public Test testsForConcurrentLinkedQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new ConcurrentLinkedQueue<String>( MinimalCollection.of(elements)); } }) .named("ConcurrentLinkedQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForConcurrentLinkedQueue()) .createTestSuite(); } public Test testsForLinkedBlockingQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new LinkedBlockingQueue<String>( MinimalCollection.of(elements)); } }) .named("LinkedBlockingQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .suppressing(suppressForLinkedBlockingQueue()) .createTestSuite(); } // Not specifying KNOWN_ORDER for PriorityQueue and PriorityBlockingQueue // even though they do have it, because our tests interpret KNOWN_ORDER to // also mean that the iterator returns the head element first, which those // don't. public Test testsForPriorityBlockingQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new PriorityBlockingQueue<String>( MinimalCollection.of(elements)); } }) .named("PriorityBlockingQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionSize.ANY) .suppressing(suppressForPriorityBlockingQueue()) .createTestSuite(); } public Test testsForPriorityQueue() { return QueueTestSuiteBuilder .using(new TestStringQueueGenerator() { @Override public Queue<String> create(String[] elements) { return new PriorityQueue<String>(MinimalCollection.of(elements)); } }) .named("PriorityQueue") .withFeatures( CollectionFeature.GENERAL_PURPOSE, CollectionSize.ANY) .suppressing(suppressForPriorityQueue()) .createTestSuite(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.List; import java.util.Map; import java.util.Set; /** * Creates map entries using sample keys and sample values. * * <p>This class is GWT compatible. * * @author Jesse Wilson */ @GwtCompatible public abstract class TestMapEntrySetGenerator<K, V> implements TestSetGenerator<Map.Entry<K, V>> { private final SampleElements<K> keys; private final SampleElements<V> values; protected TestMapEntrySetGenerator( SampleElements<K> keys, SampleElements<V> values) { this.keys = keys; this.values = values; } @Override public SampleElements<Map.Entry<K, V>> samples() { return SampleElements.mapEntries(keys, values); } @Override public Set<Map.Entry<K, V>> create(Object... elements) { Map.Entry<K, V>[] entries = createArray(elements.length); System.arraycopy(elements, 0, entries, 0, elements.length); return createFromEntries(entries); } public abstract Set<Map.Entry<K, V>> createFromEntries( Map.Entry<K, V>[] entries); @Override @SuppressWarnings("unchecked") // generic arrays make typesafety sad public Map.Entry<K, V>[] createArray(int length) { return new Map.Entry[length]; } /** Returns the original element list, unchanged. */ @Override public List<Map.Entry<K, V>> order(List<Map.Entry<K, V>> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Implementation helper for {@link TestMapGenerator} for use with maps of * strings. * * <p>This class is GWT compatible. * * @author Chris Povirk * @author Jared Levy * @author George van den Driessche */ @GwtCompatible public abstract class TestStringMapGenerator implements TestMapGenerator<String, String> { @Override public SampleElements<Map.Entry<String, String>> samples() { return new SampleElements<Map.Entry<String, String>>( Helpers.mapEntry("one", "January"), Helpers.mapEntry("two", "February"), Helpers.mapEntry("three", "March"), Helpers.mapEntry("four", "April"), Helpers.mapEntry("five", "May") ); } @Override public final Map<String, String> create(Object... entries) { @SuppressWarnings("unchecked") Entry<String, String>[] array = new Entry[entries.length]; int i = 0; for (Object o : entries) { @SuppressWarnings("unchecked") Entry<String, String> e = (Entry<String, String>) o; array[i++] = e; } return create(array); } protected abstract Map<String, String> create( Entry<String, String>[] entries); @Override @SuppressWarnings("unchecked") public final Entry<String, String>[] createArray(int length) { return new Entry[length]; } @Override public final String[] createKeyArray(int length) { return new String[length]; } @Override public final String[] createValueArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public Iterable<Entry<String, String>> order( List<Entry<String, String>> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Queue; /** * Creates queues, containing sample elements, to be tested. * * <p>This class is GWT compatible. * * @author Jared Levy */ @GwtCompatible public interface TestQueueGenerator<E> extends TestCollectionGenerator<E> { @Override Queue<E> create(Object... elements); }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements.Strings; import java.util.List; /** * TODO: javadoc. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible public abstract class TestStringListGenerator implements TestListGenerator<String> { @Override public SampleElements<String> samples() { return new Strings(); } @Override public List<String> create(Object... elements) { String[] array = new String[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (String) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<String> create(String[] elements); @Override public String[] createArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.DerivedCollectionGenerators.MapEntrySetGenerator; import com.google.common.collect.testing.DerivedCollectionGenerators.MapKeySetGenerator; import com.google.common.collect.testing.DerivedCollectionGenerators.MapValueCollectionGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.MapFeature; import com.google.common.collect.testing.testers.MapClearTester; import com.google.common.collect.testing.testers.MapContainsKeyTester; import com.google.common.collect.testing.testers.MapContainsValueTester; import com.google.common.collect.testing.testers.MapCreationTester; import com.google.common.collect.testing.testers.MapEqualsTester; import com.google.common.collect.testing.testers.MapGetTester; import com.google.common.collect.testing.testers.MapHashCodeTester; import com.google.common.collect.testing.testers.MapIsEmptyTester; import com.google.common.collect.testing.testers.MapPutAllTester; import com.google.common.collect.testing.testers.MapPutTester; import com.google.common.collect.testing.testers.MapRemoveTester; import com.google.common.collect.testing.testers.MapSerializationTester; import com.google.common.collect.testing.testers.MapSizeTester; import com.google.common.testing.SerializableTester; import junit.framework.TestSuite; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a Map implementation. * * @author George van den Driessche */ public class MapTestSuiteBuilder<K, V> extends PerCollectionSizeTestSuiteBuilder< MapTestSuiteBuilder<K, V>, TestMapGenerator<K, V>, Map<K, V>, Map.Entry<K, V>> { public static <K, V> MapTestSuiteBuilder<K, V> using( TestMapGenerator<K, V> generator) { return new MapTestSuiteBuilder<K, V>().usingGenerator(generator); } @SuppressWarnings("unchecked") // Class parameters must be raw. @Override protected List<Class<? extends AbstractTester>> getTesters() { return Arrays.<Class<? extends AbstractTester>>asList( MapClearTester.class, MapContainsKeyTester.class, MapContainsValueTester.class, MapCreationTester.class, MapEqualsTester.class, MapGetTester.class, MapHashCodeTester.class, MapIsEmptyTester.class, MapPutTester.class, MapPutAllTester.class, MapRemoveTester.class, MapSerializationTester.class, MapSizeTester.class ); } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>>> parentBuilder) { // TODO: Once invariant support is added, supply invariants to each of the // derived suites, to check that mutations to the derived collections are // reflected in the underlying map. List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder); if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add(MapTestSuiteBuilder.using( new ReserializedMapGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " reserialized") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); } derivedSuites.add(SetTestSuiteBuilder.using( new MapEntrySetGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " entrySet") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); derivedSuites.add(createDerivedKeySetSuite( new MapKeySetGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + " keys") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); derivedSuites.add(CollectionTestSuiteBuilder.using( new MapValueCollectionGenerator<K, V>( parentBuilder.getSubjectGenerator())) .named(parentBuilder.getName() + " values") .withFeatures(computeValuesCollectionFeatures( parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); return derivedSuites; } protected SetTestSuiteBuilder<K> createDerivedKeySetSuite(TestSetGenerator<K> keySetGenerator) { return SetTestSuiteBuilder.using(keySetGenerator); } private static Set<Feature<?>> computeReserializedMapFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> derivedFeatures = Helpers.copyToSet(mapFeatures); derivedFeatures.remove(CollectionFeature.SERIALIZABLE); derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return derivedFeatures; } private static Set<Feature<?>> computeEntrySetFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> entrySetFeatures = computeCommonDerivedCollectionFeatures(mapFeatures); entrySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); return entrySetFeatures; } private static Set<Feature<?>> computeKeySetFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> keySetFeatures = computeCommonDerivedCollectionFeatures(mapFeatures); if (mapFeatures.contains(MapFeature.ALLOWS_NULL_KEYS)) { keySetFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); } else if (mapFeatures.contains(MapFeature.ALLOWS_NULL_QUERIES)) { keySetFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); } return keySetFeatures; } private static Set<Feature<?>> computeValuesCollectionFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> valuesCollectionFeatures = computeCommonDerivedCollectionFeatures(mapFeatures); if (mapFeatures.contains(MapFeature.ALLOWS_NULL_QUERIES)) { valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES); } if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) { valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES); } return valuesCollectionFeatures; } private static Set<Feature<?>> computeCommonDerivedCollectionFeatures( Set<Feature<?>> mapFeatures) { Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>(); if (mapFeatures.contains(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) { derivedFeatures.add(CollectionFeature.SERIALIZABLE); } if (mapFeatures.contains(MapFeature.SUPPORTS_REMOVE)) { derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE); } if (mapFeatures.contains(MapFeature.REJECTS_DUPLICATES_AT_CREATION)) { derivedFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION); } if (mapFeatures.contains(MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION)) { derivedFeatures.add(CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION); } if (mapFeatures.contains(CollectionFeature.KNOWN_ORDER)) { derivedFeatures.add(CollectionFeature.KNOWN_ORDER); } // add the intersection of CollectionSize.values() and mapFeatures for (CollectionSize size : CollectionSize.values()) { if (mapFeatures.contains(size)) { derivedFeatures.add(size); } } return derivedFeatures; } private static class ReserializedMapGenerator<K, V> implements TestMapGenerator<K, V> { private final OneSizeTestContainerGenerator<Map<K, V>, Map.Entry<K, V>> mapGenerator; public ReserializedMapGenerator( OneSizeTestContainerGenerator< Map<K, V>, Map.Entry<K, V>> mapGenerator) { this.mapGenerator = mapGenerator; } @Override public SampleElements<Map.Entry<K, V>> samples() { return mapGenerator.samples(); } @Override public Map.Entry<K, V>[] createArray(int length) { return mapGenerator.createArray(length); } @Override public Iterable<Map.Entry<K, V>> order( List<Map.Entry<K, V>> insertionOrder) { return mapGenerator.order(insertionOrder); } @Override public Map<K, V> create(Object... elements) { return SerializableTester.reserialize(mapGenerator.create(elements)); } @Override public K[] createKeyArray(int length) { return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()) .createKeyArray(length); } @Override public V[] createValueArray(int length) { return ((TestMapGenerator<K, V>) mapGenerator.getInnerGenerator()) .createValueArray(length); } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements.Colliders; import java.util.List; /** * A generator using sample elements whose hash codes all collide badly. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible public abstract class TestCollidingSetGenerator implements TestSetGenerator<Object> { @Override public SampleElements<Object> samples() { return new Colliders(); } @Override public Object[] createArray(int length) { return new Object[length]; } /** Returns the original element list, unchanged. */ @Override public List<Object> order(List<Object> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import junit.framework.Test; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.util.AbstractList; import java.util.AbstractSequentialList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; /** * Generates a test suite covering the {@link List} implementations in the * {@link java.util} package. Can be subclassed to specify tests that should * be suppressed. * * @author Kevin Bourrillion */ public class TestsForListsInJavaUtil { public static Test suite() { return new TestsForListsInJavaUtil().allTests(); } public Test allTests() { TestSuite suite = new TestSuite("java.util Lists"); suite.addTest(testsForEmptyList()); suite.addTest(testsForSingletonList()); suite.addTest(testsForArraysAsList()); suite.addTest(testsForArrayList()); suite.addTest(testsForLinkedList()); suite.addTest(testsForCopyOnWriteArrayList()); suite.addTest(testsForUnmodifiableList()); suite.addTest(testsForCheckedList()); suite.addTest(testsForAbstractList()); suite.addTest(testsForAbstractSequentialList()); return suite; } protected Collection<Method> suppressForEmptyList() { return Collections.emptySet(); } protected Collection<Method> suppressForSingletonList() { return Collections.emptySet(); } protected Collection<Method> suppressForArraysAsList() { return Collections.emptySet(); } protected Collection<Method> suppressForArrayList() { return Collections.emptySet(); } protected Collection<Method> suppressForLinkedList() { return Collections.emptySet(); } protected Collection<Method> suppressForCopyOnWriteArrayList() { return Collections.emptySet(); } protected Collection<Method> suppressForUnmodifiableList() { return Collections.emptySet(); } protected Collection<Method> suppressForCheckedList() { return Collections.emptySet(); } protected Collection<Method> suppressForAbstractList() { return Collections.emptySet(); } protected Collection<Method> suppressForAbstractSequentialList() { return Collections.emptySet(); } public Test testsForEmptyList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return Collections.emptyList(); } }) .named("emptyList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionSize.ZERO) .suppressing(suppressForEmptyList()) .createTestSuite(); } public Test testsForSingletonList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return Collections.singletonList(elements[0]); } }) .named("singletonList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ONE) .suppressing(suppressForSingletonList()) .createTestSuite(); } public Test testsForArraysAsList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return Arrays.asList(elements.clone()); } }) .named("Arrays.asList") .withFeatures( ListFeature.SUPPORTS_SET, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForArraysAsList()) .createTestSuite(); } public Test testsForArrayList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new ArrayList<String>(MinimalCollection.of(elements)); } }) .named("ArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForArrayList()) .createTestSuite(); } public Test testsForLinkedList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new LinkedList<String>(MinimalCollection.of(elements)); } }) .named("LinkedList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionSize.ANY) .suppressing(suppressForLinkedList()) .createTestSuite(); } public Test testsForCopyOnWriteArrayList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { return new CopyOnWriteArrayList<String>( MinimalCollection.of(elements)); } }) .named("CopyOnWriteArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForCopyOnWriteArrayList()) .createTestSuite(); } public Test testsForUnmodifiableList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { List<String> innerList = new ArrayList<String>(); Collections.addAll(innerList, elements); return Collections.unmodifiableList(innerList); } }) .named("unmodifiableList/ArrayList") .withFeatures( CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForUnmodifiableList()) .createTestSuite(); } public Test testsForCheckedList() { return ListTestSuiteBuilder .using(new TestStringListGenerator() { @Override public List<String> create(String[] elements) { List<String> innerList = new ArrayList<String>(); Collections.addAll(innerList, elements); return Collections.checkedList(innerList, String.class); } }) .named("checkedList/ArrayList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE, CollectionFeature.RESTRICTS_ELEMENTS, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForCheckedList()) .createTestSuite(); } public Test testsForAbstractList() { return ListTestSuiteBuilder .using(new TestStringListGenerator () { @Override protected List<String> create(final String[] elements) { return new AbstractList<String>() { @Override public int size() { return elements.length; } @Override public String get(int index) { return elements[index]; } }; } }) .named("AbstractList") .withFeatures( CollectionFeature.NONE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForAbstractList()) .createTestSuite(); } public Test testsForAbstractSequentialList() { return ListTestSuiteBuilder .using(new TestStringListGenerator () { @Override protected List<String> create(final String[] elements) { // For this test we trust ArrayList works final List<String> list = new ArrayList<String>(); Collections.addAll(list, elements); return new AbstractSequentialList<String>() { @Override public int size() { return list.size(); } @Override public ListIterator<String> listIterator(int index) { return list.listIterator(index); } }; } }) .named("AbstractSequentialList") .withFeatures( ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY) .suppressing(suppressForAbstractSequentialList()) .createTestSuite(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.List; import java.util.SortedSet; /** * Create string sets for testing collections that are sorted by natural * ordering. * * <p>This class is GWT compatible. * * @author Jared Levy */ @GwtCompatible public abstract class TestStringSortedSetGenerator extends TestStringSetGenerator { @Override protected abstract SortedSet<String> create(String[] elements); /** Sorts the elements by their natural ordering. */ @Override public List<String> order(List<String> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Set; /** * Creates sets, containing sample elements, to be tested. * * <p>This class is GWT compatible. * * @author Kevin Bourrillion */ @GwtCompatible public interface TestSetGenerator<E> extends TestCollectionGenerator<E> { @Override Set<E> create(Object... elements); }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; /** * Methods factored out so that they can be emulated differently in GWT. * * <p>This class is emulated in GWT. * * @author Hayward Chan */ @GwtCompatible class Platform { /** * Calls {@link Class#isInstance(Object)}. Factored out so that it can be * emulated in GWT. * * <p>This method always returns {@code true} in GWT. */ static boolean checkIsInstance(Class<?> clazz, Object obj) { return clazz.isInstance(obj); } static <T> T[] clone(T[] array) { return array.clone(); } // Class.cast is not supported in GWT. This method is a no-op in GWT. static void checkCast(Class<?> clazz, Object obj) { clazz.cast(obj); } static String format(String template, Object... args) { return String.format(template, args); } static String classGetSimpleName(Class<?> clazz) { return clazz.getSimpleName(); } private Platform() {} }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements.Strings; import java.util.Collection; import java.util.List; /** * String creation for testing arbitrary collections. * * <p>This class is GWT compatible. * * @author Jared Levy */ @GwtCompatible public abstract class TestStringCollectionGenerator implements TestCollectionGenerator<String> { @Override public SampleElements<String> samples() { return new Strings(); } @Override public Collection<String> create(Object... elements) { String[] array = new String[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (String) e; } return create(array); } protected abstract Collection<String> create(String[] elements); @Override public String[] createArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; /** * To be implemented by test generators that can produce test subjects without * requiring any parameters. * * <p>This class is GWT compatible. * * @param <T> the type created by this generator. * * @author George van den Driessche */ @GwtCompatible public interface TestSubjectGenerator<T> { T createTestSubject(); }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Set; /** * Optional features of classes derived from {@code Set}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum SetFeature implements Feature<Set> { GENERAL_PURPOSE( CollectionFeature.GENERAL_PURPOSE ); private final Set<Feature<? super Set>> implied; SetFeature(Feature<? super Set> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super Set>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { public abstract SetFeature[] value() default {}; public abstract SetFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Utilities for collecting and validating tester requirements from annotations. * * <p>This class can be referenced in GWT tests. * * @author George van den Driessche */ @GwtCompatible public class FeatureUtil { /** * A cache of annotated objects (typically a Class or Method) to its * set of annotations. */ private static Map<AnnotatedElement, Annotation[]> annotationCache = new HashMap<AnnotatedElement, Annotation[]>(); private static final Map<Class<?>, TesterRequirements> classTesterRequirementsCache = new HashMap<Class<?>, TesterRequirements>(); /** * Given a set of features, add to it all the features directly or indirectly * implied by any of them, and return it. * @param features the set of features to expand * @return the same set of features, expanded with all implied features */ public static Set<Feature<?>> addImpliedFeatures(Set<Feature<?>> features) { // The base case of the recursion is an empty set of features, which will // occur when the previous set contained only simple features. if (!features.isEmpty()) { features.addAll(impliedFeatures(features)); } return features; } /** * Given a set of features, return a new set of all features directly or * indirectly implied by any of them. * @param features the set of features whose implications to find * @return the implied set of features */ public static Set<Feature<?>> impliedFeatures(Set<Feature<?>> features) { Set<Feature<?>> implied = new LinkedHashSet<Feature<?>>(); for (Feature<?> feature : features) { implied.addAll(feature.getImpliedFeatures()); } addImpliedFeatures(implied); return implied; } /** * Get the full set of requirements for a tester class. * @param testerClass a tester class * @return all the constraints implicitly or explicitly required by the class * or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ public static TesterRequirements getTesterRequirements(Class<?> testerClass) throws ConflictingRequirementsException { synchronized (classTesterRequirementsCache) { TesterRequirements requirements = classTesterRequirementsCache.get(testerClass); if (requirements == null) { requirements = buildTesterRequirements(testerClass); classTesterRequirementsCache.put(testerClass, requirements); } return requirements; } } /** * Get the full set of requirements for a tester class. * @param testerMethod a test method of a tester class * @return all the constraints implicitly or explicitly required by the * method, its declaring class, or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are * mutually inconsistent. */ public static TesterRequirements getTesterRequirements(Method testerMethod) throws ConflictingRequirementsException { return buildTesterRequirements(testerMethod); } /** * Construct the full set of requirements for a tester class. * @param testerClass a tester class * @return all the constraints implicitly or explicitly required by the class * or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ static TesterRequirements buildTesterRequirements(Class<?> testerClass) throws ConflictingRequirementsException { final TesterRequirements declaredRequirements = buildDeclaredTesterRequirements(testerClass); Class<?> baseClass = testerClass.getSuperclass(); if (baseClass == null) { return declaredRequirements; } else { final TesterRequirements clonedBaseRequirements = new TesterRequirements(getTesterRequirements(baseClass)); return incorporateRequirements( clonedBaseRequirements, declaredRequirements, testerClass); } } /** * Construct the full set of requirements for a tester method. * @param testerMethod a test method of a tester class * @return all the constraints implicitly or explicitly required by the * method, its declaring class, or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ static TesterRequirements buildTesterRequirements(Method testerMethod) throws ConflictingRequirementsException { TesterRequirements clonedClassRequirements = new TesterRequirements( getTesterRequirements(testerMethod.getDeclaringClass())); TesterRequirements declaredRequirements = buildDeclaredTesterRequirements(testerMethod); return incorporateRequirements( clonedClassRequirements, declaredRequirements, testerMethod); } /** * Construct the set of requirements specified by annotations * directly on a tester class or method. * @param classOrMethod a tester class or a test method thereof * @return all the constraints implicitly or explicitly required by * annotations on the class or method. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ public static TesterRequirements buildDeclaredTesterRequirements( AnnotatedElement classOrMethod) throws ConflictingRequirementsException { TesterRequirements requirements = new TesterRequirements(); Iterable<Annotation> testerAnnotations = getTesterAnnotations(classOrMethod); for (Annotation testerAnnotation : testerAnnotations) { TesterRequirements moreRequirements = buildTesterRequirements(testerAnnotation); incorporateRequirements( requirements, moreRequirements, testerAnnotation); } return requirements; } /** * Find all the tester annotations declared on a tester class or method. * @param classOrMethod a class or method whose tester annotations to find * @return an iterable sequence of tester annotations on the class */ public static Iterable<Annotation> getTesterAnnotations( AnnotatedElement classOrMethod) { List<Annotation> result = new ArrayList<Annotation>(); Annotation[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(classOrMethod); if (annotations == null) { annotations = classOrMethod.getDeclaredAnnotations(); annotationCache.put(classOrMethod, annotations); } } for (Annotation a : annotations) { Class<? extends Annotation> annotationClass = a.annotationType(); if (annotationClass.isAnnotationPresent(TesterAnnotation.class)) { result.add(a); } } return result; } /** * Find all the constraints explicitly or implicitly specified by a single * tester annotation. * @param testerAnnotation a tester annotation * @return the requirements specified by the annotation * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ private static TesterRequirements buildTesterRequirements( Annotation testerAnnotation) throws ConflictingRequirementsException { Class<? extends Annotation> annotationClass = testerAnnotation.getClass(); final Feature<?>[] presentFeatures; final Feature<?>[] absentFeatures; try { presentFeatures = (Feature[]) annotationClass.getMethod("value") .invoke(testerAnnotation); absentFeatures = (Feature[]) annotationClass.getMethod("absent") .invoke(testerAnnotation); } catch (Exception e) { throw new IllegalArgumentException( "Error extracting features from tester annotation.", e); } Set<Feature<?>> allPresentFeatures = addImpliedFeatures(Helpers.<Feature<?>>copyToSet(presentFeatures)); Set<Feature<?>> allAbsentFeatures = addImpliedFeatures(Helpers.<Feature<?>>copyToSet(absentFeatures)); Set<Feature<?>> conflictingFeatures = intersection(allPresentFeatures, allAbsentFeatures); if (!conflictingFeatures.isEmpty()) { throw new ConflictingRequirementsException("Annotation explicitly or " + "implicitly requires one or more features to be both present " + "and absent.", conflictingFeatures, testerAnnotation); } return new TesterRequirements(allPresentFeatures, allAbsentFeatures); } /** * Incorporate additional requirements into an existing requirements object. * @param requirements the existing requirements object * @param moreRequirements more requirements to incorporate * @param source the source of the additional requirements * (used only for error reporting) * @return the existing requirements object, modified to include the * additional requirements * @throws ConflictingRequirementsException if the additional requirements * are inconsistent with the existing requirements */ private static TesterRequirements incorporateRequirements( TesterRequirements requirements, TesterRequirements moreRequirements, Object source) throws ConflictingRequirementsException { Set<Feature<?>> presentFeatures = requirements.getPresentFeatures(); Set<Feature<?>> absentFeatures = requirements.getAbsentFeatures(); Set<Feature<?>> morePresentFeatures = moreRequirements.getPresentFeatures(); Set<Feature<?>> moreAbsentFeatures = moreRequirements.getAbsentFeatures(); checkConflict( "absent", absentFeatures, "present", morePresentFeatures, source); checkConflict( "present", presentFeatures, "absent", moreAbsentFeatures, source); presentFeatures.addAll(morePresentFeatures); absentFeatures.addAll(moreAbsentFeatures); return requirements; } // Used by incorporateRequirements() only private static void checkConflict( String earlierRequirement, Set<Feature<?>> earlierFeatures, String newRequirement, Set<Feature<?>> newFeatures, Object source) throws ConflictingRequirementsException { Set<Feature<?>> conflictingFeatures; conflictingFeatures = intersection(newFeatures, earlierFeatures); if (!conflictingFeatures.isEmpty()) { throw new ConflictingRequirementsException(String.format( "Annotation requires to be %s features that earlier " + "annotations required to be %s.", newRequirement, earlierRequirement), conflictingFeatures, source); } } /** * Construct a new {@link java.util.Set} that is the intersection * of the given sets. */ // Calls generic varargs method. @SuppressWarnings("unchecked") public static <T> Set<T> intersection( Set<? extends T> set1, Set<? extends T> set2) { return intersection(new Set[] {set1, set2}); } /** * Construct a new {@link java.util.Set} that is the intersection * of all the given sets. * @param sets the sets to intersect * @return the intersection of the sets * @throws java.lang.IllegalArgumentException if there are no sets to * intersect */ public static <T> Set<T> intersection(Set<? extends T> ... sets) { if (sets.length == 0) { throw new IllegalArgumentException( "Can't intersect no sets; would have to return the universe."); } Set<T> results = Helpers.copyToSet(sets[0]); for (int i = 1; i < sets.length; i++) { Set<? extends T> set = sets[i]; results.retainAll(set); } return results; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import java.util.SortedSet; /** * Optional features of classes derived from {@code Collection}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum CollectionFeature implements Feature<Collection> { /** * The collection must not throw {@code NullPointerException} on calls * such as {@code contains(null)} or {@code remove(null)}, but instead * must return a simple {@code false}. */ ALLOWS_NULL_QUERIES, ALLOWS_NULL_VALUES (ALLOWS_NULL_QUERIES), /** * Indicates that a collection disallows certain elements (other than * {@code null}, whose validity as an element is indicated by the presence * or absence of {@link #ALLOWS_NULL_VALUES}). * From the documentation for {@link Collection}: * <blockquote>"Some collection implementations have restrictions on the * elements that they may contain. For example, some implementations * prohibit null elements, and some have restrictions on the types of their * elements."</blockquote> */ RESTRICTS_ELEMENTS, /** * Indicates that a collection has a well-defined ordering of its elements. * The ordering may depend on the element values, such as a {@link SortedSet}, * or on the insertion ordering, such as a {@link LinkedHashSet}. All list * tests and sorted-collection tests automatically specify this feature. */ KNOWN_ORDER, /** * Indicates that a collection has a different {@link Object#toString} * representation than most collections. If not specified, the collection * tests will examine the value returned by {@link Object#toString}. */ NON_STANDARD_TOSTRING, /** * Indicates that the constructor or factory method of a collection, usually * an immutable set, throws an {@link IllegalArgumentException} when presented * with duplicate elements instead of collapsing them to a single element or * including duplicate instances in the collection. */ REJECTS_DUPLICATES_AT_CREATION, SUPPORTS_ADD, SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION, /** * Features supported by general-purpose collections - * everything but {@link #RESTRICTS_ELEMENTS}. * @see java.util.Collection the definition of general-purpose collections. */ GENERAL_PURPOSE( SUPPORTS_ADD, SUPPORTS_REMOVE), /** Features supported by collections where only removal is allowed. */ REMOVE_OPERATIONS( SUPPORTS_REMOVE), SERIALIZABLE, SERIALIZABLE_INCLUDING_VIEWS(SERIALIZABLE), /** * For documenting collections that support no optional features, such as * {@link java.util.Collections#emptySet} */ NONE(); private final Set<Feature<? super Collection>> implied; CollectionFeature(Feature<? super Collection> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super Collection>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { CollectionFeature[] value() default {}; CollectionFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Map; import java.util.Set; /** * Optional features of classes derived from {@code Map}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum MapFeature implements Feature<Map> { /** * The map does not throw {@code NullPointerException} on calls such as * {@code containsKey(null)}, {@code get(null)}, or {@code remove(null)}. */ ALLOWS_NULL_QUERIES, ALLOWS_NULL_KEYS (ALLOWS_NULL_QUERIES), ALLOWS_NULL_VALUES, RESTRICTS_KEYS, RESTRICTS_VALUES, SUPPORTS_PUT, SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION, /** * Indicates that the constructor or factory method of a map, usually an * immutable map, throws an {@link IllegalArgumentException} when presented * with duplicate keys instead of discarding all but one. */ REJECTS_DUPLICATES_AT_CREATION, GENERAL_PURPOSE( SUPPORTS_PUT, SUPPORTS_REMOVE ); private final Set<Feature<? super Map>> implied; MapFeature(Feature<? super Map> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super Map>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { public abstract MapFeature[] value() default {}; public abstract MapFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; import java.util.Set; /** * Optional features of classes derived from {@code List}. * * <p>This class is GWT compatible. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum ListFeature implements Feature<List> { SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX(CollectionFeature.SUPPORTS_ADD), SUPPORTS_REMOVE_WITH_INDEX(CollectionFeature.SUPPORTS_REMOVE), GENERAL_PURPOSE( CollectionFeature.GENERAL_PURPOSE, SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX, SUPPORTS_REMOVE_WITH_INDEX ), /** Features supported by lists where only removal is allowed. */ REMOVE_OPERATIONS( CollectionFeature.SUPPORTS_REMOVE, SUPPORTS_REMOVE_WITH_INDEX ); private final Set<Feature<? super List>> implied; ListFeature(Feature<? super List> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super List>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { ListFeature[] value() default {}; ListFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.util.Collections; import java.util.Set; /** * Encapsulates the constraints that a class under test must satisfy in order * for a tester method to be run against that class. * * <p>This class is GWT compatible. * * @author George van den Driessche */ @GwtCompatible public final class TesterRequirements { private final Set<Feature<?>> presentFeatures; private final Set<Feature<?>> absentFeatures; public TesterRequirements( Set<Feature<?>> presentFeatures, Set<Feature<?>> absentFeatures) { this.presentFeatures = Helpers.copyToSet(presentFeatures); this.absentFeatures = Helpers.copyToSet(absentFeatures); } public TesterRequirements(TesterRequirements tr) { this(tr.getPresentFeatures(), tr.getAbsentFeatures()); } public TesterRequirements() { this(Collections.<Feature<?>>emptySet(), Collections.<Feature<?>>emptySet()); } public final Set<Feature<?>> getPresentFeatures() { return presentFeatures; } public final Set<Feature<?>> getAbsentFeatures() { return absentFeatures; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof TesterRequirements) { TesterRequirements that = (TesterRequirements) object; return this.presentFeatures.equals(that.presentFeatures) && this.absentFeatures.equals(that.absentFeatures); } return false; } @Override public int hashCode() { return presentFeatures.hashCode() * 31 + absentFeatures.hashCode(); } @Override public String toString() { return "{TesterRequirements: present=" + presentFeatures + ", absent=" + absentFeatures + "}"; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import java.util.Set; /** * Base class for enumerating the features of an interface to be tested. * * <p>This class is GWT compatible. * * @param <T> The interface whose features are to be enumerated. * @author George van den Driessche */ @GwtCompatible public interface Feature<T> { /** Returns the set of features that are implied by this feature. */ Set<Feature<? super T>> getImpliedFeatures(); }
Java