code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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;
/**
* Base class for collection testers.
*
* @param <E> the element type of the collection to be tested.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public abstract class AbstractCollectionTester<E>
extends AbstractContainerTester<Collection<E>, E> {
// TODO: replace this with an accessor.
protected Collection<E> collection;
@Override protected Collection<E> actualContents() {
return collection;
}
// TODO: dispose of this once collection is encapsulated.
@Override protected Collection<E> resetContainer(Collection<E> newContents) {
collection = super.resetContainer(newContents);
return collection;
}
/** @see AbstractContainerTester#resetContainer() */
protected void resetCollection() {
resetContainer();
}
/**
* @return an array of the proper size with {@code null} inserted into the
* middle element.
*/
protected E[] createArrayWithNullElement() {
E[] array = createSamplesArray();
array[getNullLocation()] = null;
return array;
}
protected void initCollectionWithNullElement() {
E[] array = createArrayWithNullElement();
resetContainer(getSubjectGenerator().create(array));
}
/**
* Equivalent to {@link #expectMissing(Object[]) expectMissing}{@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 expectNullMissingWhenNullUnsupported(String message) {
try {
assertFalse(message, actualContents().contains(null));
} catch (NullPointerException tolerated) {
// 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;
import com.google.common.collect.testing.DerivedCollectionGenerators.Bound;
import com.google.common.collect.testing.DerivedCollectionGenerators.SortedMapSubmapTestMapGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.SortedMapNavigationTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collections;
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 SortedMap implementation.
*/
public class SortedMapTestSuiteBuilder<K, V> extends MapTestSuiteBuilder<K, V> {
public static <K, V> SortedMapTestSuiteBuilder<K, V> using(
TestSortedMapGenerator<K, V> generator) {
SortedMapTestSuiteBuilder<K, V> result = new SortedMapTestSuiteBuilder<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(SortedMapNavigationTester.class);
return testers;
}
@Override public TestSuite createTestSuite() {
if (!getFeatures().contains(CollectionFeature.KNOWN_ORDER)) {
List<Feature<?>> features = Helpers.copyToList(getFeatures());
features.add(CollectionFeature.KNOWN_ORDER);
withFeatures(features);
}
return super.createTestSuite();
}
@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.SUBMAP)) {
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE));
}
return derivedSuites;
}
@Override protected SortedSetTestSuiteBuilder<K> createDerivedKeySetSuite(
TestSetGenerator<K> keySetGenerator) {
return SortedSetTestSuiteBuilder.using((TestSortedSetGenerator<K>) keySetGenerator);
}
/**
* To avoid infinite recursion, test suites with these marker features won't
* have derived suites created for them.
*/
enum NoRecurse implements Feature<Void> {
SUBMAP,
DESCENDING;
@Override
public Set<Feature<? super Void>> getImpliedFeatures() {
return Collections.emptySet();
}
}
/**
* Creates a suite whose map has some elements filtered out of view.
*
* <p>Because the map may be ascending or descending, this test must derive
* the relative order of these extreme values rather than relying on their
* regular sort ordering.
*/
final TestSuite createSubmapSuite(final FeatureSpecificTestSuiteBuilder<?,
? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>>
parentBuilder, final Bound from, final Bound to) {
final TestSortedMapGenerator<K, V> delegate
= (TestSortedMapGenerator<K, V>) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<Feature<?>>();
features.add(NoRecurse.SUBMAP);
features.addAll(parentBuilder.getFeatures());
return newBuilderUsing(delegate, to, from)
.named(parentBuilder.getName() + " subMap " + from + "-" + to)
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
/** Like using() but overrideable by NavigableMapTestSuiteBuilder. */
SortedMapTestSuiteBuilder<K, V> newBuilderUsing(
TestSortedMapGenerator<K, V> delegate, Bound to, Bound from) {
return using(new SortedMapSubmapTestMapGenerator<K, V>(delegate, to, from));
}
}
| 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.
*
* @author Jared Levy
*/
@GwtCompatible
public interface TestQueueGenerator<E> extends TestCollectionGenerator<E> {
@Override
Queue<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 java.util.Set;
/**
* Reserializes the sets created by another test set generator.
*
* TODO: make CollectionTestSuiteBuilder test reserialized collections
*
* @author Jesse Wilson
*/
public class ReserializingTestSetGenerator<E>
extends ReserializingTestCollectionGenerator<E>
implements TestSetGenerator<E> {
ReserializingTestSetGenerator(TestSetGenerator<E> delegate) {
super(delegate);
}
public static <E> TestSetGenerator<E> newInstance(
TestSetGenerator<E> delegate) {
return new ReserializingTestSetGenerator<E>(delegate);
}
@Override public Set<E> create(Object... elements) {
return (Set<E>) super.create(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;
/**
* A type which will never be used as the element type of any collection in our
* tests, and so can be used to test how a Collection behaves when given input
* of the wrong type.
*/
@GwtCompatible
public enum WrongType {
VALUE
}
| 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 com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
/**
* Simple base class to verify that we handle generics correctly.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class BaseComparable implements Comparable<BaseComparable>, Serializable {
private final String s;
public BaseComparable(String s) {
this.s = s;
}
@Override public int hashCode() { // delegate to 's'
return s.hashCode();
}
@Override public boolean equals(Object other) {
if (other == null) {
return false;
} else if (other instanceof BaseComparable) {
return s.equals(((BaseComparable) other).s);
} else {
return false;
}
}
@Override
public int compareTo(BaseComparable o) {
return s.compareTo(o.s);
}
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;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.FeatureUtil;
import junit.framework.TestSuite;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* This builder creates a composite test suite, containing a separate test suite
* for each {@link CollectionSize} present in the features specified
* by {@link #withFeatures(Feature...)}.
*
* @param <B> The concrete type of this builder (the 'self-type'). All the
* Builder methods of this class (such as {@link #named(String)}) return this
* type, so that Builder methods of more derived classes can be chained onto
* them without casting.
* @param <G> The type of the generator to be passed to testers in the
* generated test suite. An instance of G should somehow provide an
* instance of the class under test, plus any other information required
* to parameterize the test.
*
* @see FeatureSpecificTestSuiteBuilder
*
* @author George van den Driessche
*/
public abstract class PerCollectionSizeTestSuiteBuilder<
B extends PerCollectionSizeTestSuiteBuilder<B, G, T, E>,
G extends TestContainerGenerator<T, E>,
T,
E>
extends FeatureSpecificTestSuiteBuilder<B, G> {
private static final Logger logger = Logger.getLogger(
PerCollectionSizeTestSuiteBuilder.class.getName());
/**
* Creates a runnable JUnit test suite based on the criteria already given.
*/
@Override public TestSuite createTestSuite() {
checkCanCreate();
String name = getName();
// Copy this set, so we can modify it.
Set<Feature<?>> features = Helpers.copyToSet(getFeatures());
List<Class<? extends AbstractTester>> testers = getTesters();
logger.fine(" Testing: " + name);
// Split out all the specified sizes.
Set<Feature<?>> sizesToTest =
Helpers.<Feature<?>>copyToSet(CollectionSize.values());
sizesToTest.retainAll(features);
features.removeAll(sizesToTest);
FeatureUtil.addImpliedFeatures(sizesToTest);
sizesToTest.retainAll(Arrays.asList(
CollectionSize.ZERO, CollectionSize.ONE, CollectionSize.SEVERAL));
logger.fine(" Sizes: " + formatFeatureSet(sizesToTest));
if (sizesToTest.isEmpty()) {
throw new IllegalStateException(name
+ ": no CollectionSizes specified (check the argument to "
+ "FeatureSpecificTestSuiteBuilder.withFeatures().)");
}
TestSuite suite = new TestSuite(name);
for (Feature<?> collectionSize : sizesToTest) {
String oneSizeName = Platform.format("%s [collection size: %s]",
name, collectionSize.toString().toLowerCase());
OneSizeGenerator<T, E> oneSizeGenerator = new OneSizeGenerator<T, E>(
getSubjectGenerator(), (CollectionSize) collectionSize);
Set<Feature<?>> oneSizeFeatures = Helpers.copyToSet(features);
oneSizeFeatures.add(collectionSize);
Set<Method> oneSizeSuppressedTests = getSuppressedTests();
OneSizeTestSuiteBuilder<T, E> oneSizeBuilder =
new OneSizeTestSuiteBuilder<T, E>(testers)
.named(oneSizeName)
.usingGenerator(oneSizeGenerator)
.withFeatures(oneSizeFeatures)
.withSetUp(getSetUp())
.withTearDown(getTearDown())
.suppressing(oneSizeSuppressedTests);
TestSuite oneSizeSuite = oneSizeBuilder.createTestSuite();
suite.addTest(oneSizeSuite);
for (TestSuite derivedSuite : createDerivedSuites(oneSizeBuilder)) {
oneSizeSuite.addTest(derivedSuite);
}
}
return suite;
}
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<T, E>> parentBuilder) {
return new ArrayList<TestSuite>();
}
/** Builds a test suite for one particular {@link CollectionSize}. */
private static final class OneSizeTestSuiteBuilder<T, E> extends
FeatureSpecificTestSuiteBuilder<
OneSizeTestSuiteBuilder<T, E>, OneSizeGenerator<T, E>> {
private final List<Class<? extends AbstractTester>> testers;
public OneSizeTestSuiteBuilder(
List<Class<? extends AbstractTester>> testers) {
this.testers = testers;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
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 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.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestStringSortedSetGenerator
extends TestStringSetGenerator implements TestSortedSetGenerator<String> {
@Override
public SortedSet<String> create(Object... elements) {
return (SortedSet<String>) super.create(elements);
}
@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;
}
@Override
public String belowSamplesLesser() {
return "!! a";
}
@Override
public String belowSamplesGreater() {
return "!! b";
}
@Override
public String aboveSamplesLesser() {
return "~~ a";
}
@Override
public String aboveSamplesGreater() {
return "~~ b";
}
}
| 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.
*
* @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 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) 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.ArrayList;
import java.util.List;
import java.util.ListIterator;
/**
* A utility similar to {@link IteratorTester} for testing a
* {@link ListIterator} against a known good reference implementation. As with
* {@code IteratorTester}, a concrete subclass must provide target iterators on
* demand. It also requires three additional constructor parameters:
* {@code elementsToInsert}, the elements to be passed to {@code set()} and
* {@code add()} calls; {@code features}, the features supported by the
* iterator; and {@code expectedElements}, the elements the iterator should
* return in order.
* <p>
* The items in {@code elementsToInsert} will be repeated if {@code steps} is
* larger than the number of provided elements.
*
* @author Chris Povirk
*/
@GwtCompatible
public abstract class ListIteratorTester<E> extends
AbstractIteratorTester<E, ListIterator<E>> {
protected ListIteratorTester(int steps, Iterable<E> elementsToInsert,
Iterable<? extends IteratorFeature> features,
Iterable<E> expectedElements, int startIndex) {
super(steps, elementsToInsert, features, expectedElements,
KnownOrder.KNOWN_ORDER, startIndex);
}
@Override
protected final Iterable<? extends Stimulus<E, ? super ListIterator<E>>>
getStimulusValues() {
List<Stimulus<E, ? super ListIterator<E>>> list =
new ArrayList<Stimulus<E, ? super ListIterator<E>>>();
Helpers.addAll(list, iteratorStimuli());
Helpers.addAll(list, listIteratorStimuli());
return list;
}
@Override protected abstract ListIterator<E> newTargetIterator();
}
| 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(
TestSortedMapGenerator<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((TestSortedSetGenerator<K>) keySetGenerator);
}
public static final class NavigableMapSubmapTestMapGenerator<K, V>
extends SortedMapSubmapTestMapGenerator<K, V> {
public NavigableMapSubmapTestMapGenerator(
TestSortedMapGenerator<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(
TestSortedMapGenerator<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.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* A container class for the five sample elements we need for testing.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class SampleElements<E> implements Iterable<E> {
// TODO: rename e3, e4 => missing1, missing2
public final E e0;
public final E e1;
public final E e2;
public final E e3;
public final E e4;
public SampleElements(E e0, E e1, E e2, E e3, E e4) {
this.e0 = e0;
this.e1 = e1;
this.e2 = e2;
this.e3 = e3;
this.e4 = e4;
}
@Override
public Iterator<E> iterator() {
return asList().iterator();
}
public List<E> asList() {
return Arrays.asList(e0, e1, e2, e3, e4);
}
public static class Strings extends SampleElements<String> {
public Strings() {
// elements aren't sorted, to better test SortedSet iteration ordering
super("b", "a", "c", "d", "e");
}
// for testing SortedSet and SortedMap methods
public static final String BEFORE_FIRST = "\0";
public static final String BEFORE_FIRST_2 = "\0\0";
public static final String MIN_ELEMENT = "a";
public static final String AFTER_LAST = "z";
public static final String AFTER_LAST_2 = "zz";
}
public static class Chars extends SampleElements<Character> {
public Chars() {
// elements aren't sorted, to better test SortedSet iteration ordering
super('b', 'a', 'c', 'd', 'e');
}
}
public static class Enums extends SampleElements<AnEnum> {
public Enums() {
// elements aren't sorted, to better test SortedSet iteration ordering
super(AnEnum.B, AnEnum.A, AnEnum.C, AnEnum.D, AnEnum.E);
}
}
public static class Ints extends SampleElements<Integer> {
public Ints() {
// elements aren't sorted, to better test SortedSet iteration ordering
super(1, 0, 2, 3, 4);
}
}
public static <K, V> SampleElements<Map.Entry<K, V>> mapEntries(
SampleElements<K> keys, SampleElements<V> values) {
return new SampleElements<Map.Entry<K, V>>(
Helpers.mapEntry(keys.e0, values.e0),
Helpers.mapEntry(keys.e1, values.e1),
Helpers.mapEntry(keys.e2, values.e2),
Helpers.mapEntry(keys.e3, values.e3),
Helpers.mapEntry(keys.e4, values.e4));
}
public static class Unhashables extends SampleElements<UnhashableObject> {
public Unhashables() {
super(new UnhashableObject(1),
new UnhashableObject(2),
new UnhashableObject(3),
new UnhashableObject(4),
new UnhashableObject(5));
}
}
public static class Colliders extends SampleElements<Object> {
public Colliders() {
super(new Collider(1),
new Collider(2),
new Collider(3),
new Collider(4),
new Collider(5));
}
}
private static class Collider {
final int value;
Collider(int value) {
this.value = value;
}
@Override public boolean equals(Object obj) {
return obj instanceof Collider && ((Collider) obj).value == value;
}
@Override public int hashCode() {
return 1; // evil!
}
}
}
| 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 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) 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.
*
* @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) 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.QueueElementTester;
import com.google.common.collect.testing.testers.QueueOfferTester;
import com.google.common.collect.testing.testers.QueuePeekTester;
import com.google.common.collect.testing.testers.QueuePollTester;
import com.google.common.collect.testing.testers.QueueRemoveTester;
import java.util.ArrayList;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a queue implementation.
*
* @author Jared Levy
*/
public final class QueueTestSuiteBuilder<E>
extends AbstractCollectionTestSuiteBuilder<QueueTestSuiteBuilder<E>, E> {
public static <E> QueueTestSuiteBuilder<E> using(
TestQueueGenerator<E> generator) {
return new QueueTestSuiteBuilder<E>().usingGenerator(generator);
}
private boolean runCollectionTests = true;
/**
* Specify whether to skip the general collection tests. Call this method when
* testing a collection that's both a queue and a list, to avoid running the
* common collection tests twice. By default, collection tests do run.
*/
public QueueTestSuiteBuilder<E> skipCollectionTests() {
runCollectionTests = false;
return this;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
new ArrayList<Class<? extends AbstractTester>>();
if (runCollectionTests) {
testers.addAll(super.getTesters());
}
testers.add(QueueElementTester.class);
testers.add(QueueOfferTester.class);
testers.add(QueuePeekTester.class);
testers.add(QueuePollTester.class);
testers.add(QueueRemoveTester.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 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) 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;
import com.google.common.annotations.GwtCompatible;
/**
* A generator that relies on a preexisting generator for most of its work. For example, a derived
* iterator generator may delegate the work of creating the underlying collection to an inner
* collection generator.
*
* <p>{@code GwtTestSuiteGenerator} expects every {@code DerivedIterator} implementation to provide
* a one-arg constructor accepting its inner generator as an argument). This requirement enables it
* to generate source code (since GWT cannot use reflection to generate the suites).
*
* @author Chris Povirk
*/
@GwtCompatible
public interface DerivedGenerator {
TestSubjectGenerator<?> getInnerGenerator();
}
| 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.
*
* @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) 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.DerivedCollectionGenerators.Bound;
import com.google.common.collect.testing.DerivedCollectionGenerators.SortedSetSubsetTestSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.NavigableSetNavigationTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedSet;
/**
* 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(
TestSortedSetGenerator<E> generator) {
NavigableSetTestSuiteBuilder<E> builder =
new NavigableSetTestSuiteBuilder<E>();
builder.usingGenerator(generator);
return builder;
}
@Override
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
List<TestSuite> derivedSuites = new ArrayList<TestSuite>(
super.createDerivedSuites(parentBuilder));
if (!parentBuilder.getFeatures().contains(CollectionFeature.SUBSET_VIEW)) {
// Other combinations are inherited from SortedSetTestSuiteBuilder.
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE));
derivedSuites.add(createSubsetSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE));
}
if (!parentBuilder.getFeatures().contains(CollectionFeature.DESCENDING_VIEW)) {
derivedSuites.add(createDescendingSuite(parentBuilder));
}
return derivedSuites;
}
public static final class NavigableSetSubsetTestSetGenerator<E>
extends SortedSetSubsetTestSetGenerator<E> {
public NavigableSetSubsetTestSetGenerator(
TestSortedSetGenerator<E> delegate, Bound to, Bound from) {
super(delegate, to, from);
}
@Override NavigableSet<E> createSubSet(SortedSet<E> sortedSet, E firstExclusive,
E lastExclusive) {
NavigableSet<E> set = (NavigableSet<E>) sortedSet;
if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) {
return set.headSet(lastInclusive, true);
} else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) {
return set.tailSet(firstExclusive, false);
} else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) {
return set.subSet(firstExclusive, false, lastExclusive, false);
} else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) {
return set.subSet(firstExclusive, false, lastInclusive, true);
} else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) {
return set.subSet(firstInclusive, true, lastInclusive, true);
} else {
return (NavigableSet<E>) super.createSubSet(set, firstExclusive, lastExclusive);
}
}
}
@Override
public NavigableSetTestSuiteBuilder<E> newBuilderUsing(
TestSortedSetGenerator<E> delegate, Bound to, Bound from) {
return using(new NavigableSetSubsetTestSetGenerator<E>(delegate, to, from));
}
/**
* Create a suite whose maps are descending views of other maps.
*/
private TestSuite createDescendingSuite(final FeatureSpecificTestSuiteBuilder<?,
? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) {
final TestSetGenerator<E> delegate =
(TestSetGenerator<E>) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<Feature<?>>();
features.add(CollectionFeature.DESCENDING_VIEW);
features.addAll(parentBuilder.getFeatures());
return NavigableSetTestSuiteBuilder.using(new TestSetGenerator<E>() {
@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) {
List<E> list = new ArrayList<E>();
for (E e : delegate.order(insertionOrder)) {
list.add(e);
}
Collections.reverse(list);
return list;
}
@Override
public Set<E> create(Object... elements) {
NavigableSet<E> navigableSet = (NavigableSet<E>) delegate.create(elements);
return navigableSet.descendingSet();
}
})
.named(parentBuilder.getName() + " descending")
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
@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.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}.
*
* @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_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}.
*
* @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.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}.
*
* @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) 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}.
*
* @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) 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}.
*
* @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) 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}.
*
* @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(getOrderedElements()), 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) 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}.
*
* @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) 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 org.truth0.Truth.ASSERT;
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.Comparator;
import java.util.Iterator;
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());
}
@CollectionSize.Require(absent = ZERO)
public void testHeadMapExclusive() {
assertFalse(navigableMap.headMap(a.getKey()).containsKey(a.getKey()));
}
@CollectionSize.Require(absent = ZERO)
public void testTailMapInclusive() {
assertTrue(navigableMap.tailMap(a.getKey()).containsKey(a.getKey()));
}
public void testHeadMap() {
List<Entry<K, V>> entries = Helpers.copyToList(getSubjectGenerator().getSampleElements(
getSubjectGenerator().getCollectionSize().getNumElements()));
Collections.sort(entries, Helpers.<K, V>entryComparator(navigableMap.comparator()));
for (int i = 0; i < entries.size(); i++) {
ASSERT.that(navigableMap.headMap(entries.get(i).getKey()).entrySet())
.iteratesAs(entries.subList(0, i));
}
}
public void testTailMap() {
List<Entry<K, V>> entries = Helpers.copyToList(getSubjectGenerator().getSampleElements(
getSubjectGenerator().getCollectionSize().getNumElements()));
Collections.sort(entries, Helpers.<K, V>entryComparator(navigableMap.comparator()));
for (int i = 0; i < entries.size(); i++) {
ASSERT.that(navigableMap.tailMap(entries.get(i).getKey()).entrySet())
.iteratesAs(entries.subList(i, entries.size()));
}
}
public void testSubMap() {
List<Entry<K, V>> entries = Helpers.copyToList(getSubjectGenerator().getSampleElements(
getSubjectGenerator().getCollectionSize().getNumElements()));
Collections.sort(entries, Helpers.<K, V>entryComparator(navigableMap.comparator()));
for (int i = 0; i < entries.size(); i++) {
for (int j = i + 1; j < entries.size(); j++) {
ASSERT.that(navigableMap
.subMap(entries.get(i).getKey(), entries.get(j).getKey())
.entrySet())
.iteratesAs(entries.subList(i, j));
}
}
}
@CollectionSize.Require(SEVERAL)
public void testSubMapIllegal() {
try {
navigableMap.subMap(c.getKey(), a.getKey());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
@CollectionSize.Require(absent = ZERO)
public void testOrderedByComparator() {
@SuppressWarnings("unchecked")
Comparator<? super K> comparator = navigableMap.comparator();
if (comparator == null) {
comparator = new Comparator<K>() {
@SuppressWarnings("unchecked")
@Override
public int compare(K o1, K o2) {
return ((Comparable) o1).compareTo(o2);
}
};
}
Iterator<Entry<K, V>> entryItr = navigableMap.entrySet().iterator();
Entry<K, V> prevEntry = entryItr.next();
while (entryItr.hasNext()) {
Entry<K, V> nextEntry = entryItr.next();
assertTrue(comparator.compare(prevEntry.getKey(), nextEntry.getKey()) < 0);
prevEntry = nextEntry;
}
}
}
| 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}.
*
* @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_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListClearAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.clear();
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(getOrderedElements().get(1)), 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) 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}.
*
* @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) 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}.
*
* @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) 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}.
*
* @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.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_ITERATOR_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;
/**
* 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}.
*
* @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_ITERATOR_REMOVE})
public void testIterator_knownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE)
public void testIterator_knownOrderRemoveUnsupported() {
runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_ITERATOR_REMOVE)
public void testIterator_unknownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER,
getSampleElements());
}
@CollectionFeature.Require(absent = {KNOWN_ORDER, SUPPORTS_ITERATOR_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();
}
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 com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
/**
* Tests {@link java.util.Collection#equals}.
*
* @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) 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}.
*
* @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.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}.
*
* @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) 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}.
*
* @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 com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import java.util.Queue;
/**
* Base class for queue collection tests.
*
* @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.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}.
*
* @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) 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}.
*
* @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) 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}.
*
* @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) 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 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}.
*
* @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) 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) 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}.
*
* @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) 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}.
*
* @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) 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}.
*
* @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>(getOrderedElements())));
}
@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.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}.
*
* @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) 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}.
*
* @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.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}.
*
* @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) 2013 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 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.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* A generic JUnit test which tests {@code toString()} operations on a map. Can't be invoked
* directly; please see {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
*/
@GwtCompatible
public class MapToStringTester<K, V> extends AbstractMapTester<K, V> {
public void testToString_minimal() {
assertNotNull("toString() should not return null", getMap().toString());
}
@CollectionSize.Require(ZERO)
public void testToString_size0() {
assertEquals("emptyMap.toString should return {}", "{}", getMap().toString());
}
@CollectionSize.Require(ONE)
public void testToString_size1() {
assertEquals(
"size1Map.toString should return {entry}", "{" + samples.e0 + "}", getMap().toString());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testToStringWithNullKey() {
initMapWithNullKey();
testToString_formatting();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testToStringWithNullValue() {
initMapWithNullValue();
testToString_formatting();
}
public void testToString_formatting() {
assertEquals(
"map.toString() incorrect", expectedToString(getMap().entrySet()), getMap().toString());
}
private String expectedToString(Set<Entry<K, V>> entries) {
Map<K, V> reference = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : entries) {
reference.put(entry.getKey(), entry.getValue());
}
return reference.toString();
}
}
| 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}.
*
* @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) 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}.
*
* @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",
createOrderedArray(), actual);
}
@CollectionSize.Require(absent = ZERO)
public void testToArray_tooSmall() {
Object[] actual = getList().toArray(new Object[0]);
assertArrayEquals("toArray(tooSmall) order should match list",
createOrderedArray(), actual);
}
public void testToArray_largeEnough() {
Object[] actual = getList().toArray(new Object[getNumElements()]);
assertArrayEquals("toArray(largeEnough) order should match list",
createOrderedArray(), actual);
}
private static void assertArrayEquals(String message, Object[] expected,
Object[] actual) {
assertEquals(message, Arrays.asList(expected), Arrays.asList(actual));
}
}
| 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) 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}.
*
* @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) 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}.
*
* @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 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}.
*
* @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) 2013 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_ITERATOR_REMOVE;
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_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
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.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
/**
* Tests {@link java.util.Map#entrySet}.
*
* @author Louis Wasserman
* @param <K> The key type of the map implementation under test.
* @param <V> The value type of the map implementation under test.
*/
@GwtCompatible
public class MapEntrySetTester<K, V> extends AbstractMapTester<K, V> {
private enum IncomparableType {
INSTANCE;
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
public void testEntrySetIteratorRemove() {
Set<Entry<K, V>> entrySet = getMap().entrySet();
Iterator<Entry<K, V>> entryItr = entrySet.iterator();
assertEquals(samples.e0, entryItr.next());
entryItr.remove();
assertTrue(getMap().isEmpty());
assertFalse(entrySet.contains(samples.e0));
}
public void testContainsEntryWithIncomparableKey() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(IncomparableType.INSTANCE, samples.e0.getValue())));
}
public void testContainsEntryWithIncomparableValue() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(samples.e0.getKey(), IncomparableType.INSTANCE)));
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testContainsEntryWithNullKeyAbsent() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(null, samples.e0.getValue())));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testContainsEntryWithNullKeyPresent() {
initMapWithNullKey();
assertTrue(getMap()
.entrySet().contains(Helpers.mapEntry(null, getValueForNullKey())));
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testContainsEntryWithNullValueAbsent() {
assertFalse(getMap()
.entrySet().contains(Helpers.mapEntry(samples.e0.getKey(), null)));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testContainsEntryWithNullValuePresent() {
initMapWithNullValue();
assertTrue(getMap()
.entrySet().contains(Helpers.mapEntry(getKeyForNullValue(), null)));
}
@GwtIncompatible("reflection")
public static Method getContainsEntryWithIncomparableKeyMethod() {
return Helpers.getMethod(MapEntrySetTester.class, "testContainsEntryWithIncomparableKey");
}
@GwtIncompatible("reflection")
public static Method getContainsEntryWithIncomparableValueMethod() {
return Helpers.getMethod(MapEntrySetTester.class, "testContainsEntryWithIncomparableValue");
}
}
| 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}.
*
* @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) 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);
}
@CollectionSize.Require(absent = ZERO)
public void testHeadMapExclusive() {
assertFalse(navigableMap.headMap(a.getKey(), false).containsKey(a.getKey()));
}
@CollectionSize.Require(absent = ZERO)
public void testHeadMapInclusive() {
assertTrue(navigableMap.headMap(a.getKey(), true).containsKey(a.getKey()));
}
@CollectionSize.Require(absent = ZERO)
public void testTailMapExclusive() {
assertFalse(navigableMap.tailMap(a.getKey(), false).containsKey(a.getKey()));
}
@CollectionSize.Require(absent = ZERO)
public void testTailMapInclusive() {
assertTrue(navigableMap.tailMap(a.getKey(), true).containsKey(a.getKey()));
}
}
| 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}.
*
* @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) 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 static org.truth0.Truth.ASSERT;
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 java.util.Arrays;
/**
* 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}.
*
* @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);
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testRetainAll_countIgnored() {
resetContainer(getSubjectGenerator().create(samples.e0, samples.e2, samples.e1, samples.e0));
assertTrue(getList().retainAll(Arrays.asList(samples.e0, samples.e1)));
ASSERT.that(getList()).has().exactly(samples.e0, samples.e1, samples.e0).inOrder();
}
}
| 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}.
*
* @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) 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) 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}.
*
* @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.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}.
*
* @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.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}.
*
* @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;
import java.util.Set;
/**
* @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) 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}.
*
* @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 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}.
*
* @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.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}.
*
* @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 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}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class CollectionSizeTester<E> extends AbstractCollectionTester<E> {
public void testSize() {
assertEquals("size():", getNumElements(), collection.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.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}.
*
* @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 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.
*
* @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) 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}.
*
* @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(getOrderedElements().get(0)));
}
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) 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}.
*
* @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) 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 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}.
*
* @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) 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.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}.
*
* @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.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}.
*
* @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 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}.
*
* @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.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}.
*
* @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 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}.
*
* @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.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}.
*
* @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;
/**
* 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}.
*
* @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) 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}.
*
* @author George van den Driessche
*/
@GwtCompatible(emulated = true)
public class ListHashCodeTester<E> extends AbstractListTester<E> {
public void testHashCode() {
int expectedHashCode = 1;
for (E element : getOrderedElements()) {
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) 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.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}.
*
* @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());
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testToString_null() {
initCollectionWithNullElement();
testToString_minimal();
}
}
| 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}.
*
* @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(createOrderedArray());
}
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) 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}.
*
* @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) 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;
/**
* A non-empty tester for {@link java.util.Iterator}.
*
* @author George van den Driessche
*/
@GwtCompatible
public final class ExampleIteratorTester<E>
extends AbstractTester<TestIteratorGenerator<E>> {
public void testSomethingAboutIterators() {
assertTrue(true);
}
}
| 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 com.google.common.annotations.GwtCompatible;
/**
* Simple derived class to verify that we handle generics correctly.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class DerivedComparable extends BaseComparable {
public DerivedComparable(String s) {
super(s);
}
private static final long serialVersionUID = 0;
}
| 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;
import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import java.util.SortedMap;
/**
* Creates sorted maps, containing sample elements, to be tested.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestSortedMapGenerator<K, V> extends TestMapGenerator<K, V> {
@Override
SortedMap<K, V> create(Object... elements);
/**
* Returns an entry with a key less than the keys of the {@link #samples()}
* and less than the key of {@link #belowSamplesGreater()}.
*/
Map.Entry<K, V> belowSamplesLesser();
/**
* Returns an entry with a key less than the keys of the {@link #samples()}
* but greater than the key of {@link #belowSamplesLesser()}.
*/
Map.Entry<K, V> belowSamplesGreater();
/**
* Returns an entry with a key greater than the keys of the {@link #samples()}
* but less than the key of {@link #aboveSamplesGreater()}.
*/
Map.Entry<K, V> aboveSamplesLesser();
/**
* Returns an entry with a key greater than the keys of the {@link #samples()}
* and greater than the key of {@link #aboveSamplesLesser()}.
*/
Map.Entry<K, V> aboveSamplesGreater();
}
| 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.Chars;
import java.util.List;
/**
* Generates {@code List<Character>} instances for test suites.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestCharacterListGenerator
implements TestListGenerator<Character> {
@Override
public SampleElements<Character> samples() {
return new Chars();
}
@Override
public List<Character> create(Object... elements) {
Character[] array = new Character[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Character) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Character> create(Character[] elements);
@Override
public Character[] createArray(int length) {
return new Character[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Character> order(List<Character> 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 com.google.common.collect.testing.SampleElements.Strings;
import java.util.List;
/**
* TODO: javadoc.
*
* @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) 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.google;
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.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for the {@code containsKey} methods of {@code Multimap} and its {@code asMap()} view.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapContainsKeyTester<K, V>
extends AbstractMultimapTester<K, V, Multimap<K, V>> {
@CollectionSize.Require(absent = ZERO)
public void testContainsKeyYes() {
assertTrue(multimap().containsKey(sampleKeys().e0));
}
public void testContainsKeyNo() {
assertFalse(multimap().containsKey(sampleKeys().e3));
}
public void testContainsKeysFromKeySet() {
for (K k : multimap().keySet()) {
assertTrue(multimap().containsKey(k));
}
}
public void testContainsKeyAgreesWithGet() {
for (K k : sampleKeys()) {
assertEquals(!multimap().get(k).isEmpty(), multimap().containsKey(k));
}
}
public void testContainsKeyAgreesWithAsMap() {
for (K k : sampleKeys()) {
assertEquals(multimap().containsKey(k), multimap().asMap().containsKey(k));
}
}
public void testContainsKeyAgreesWithKeySet() {
for (K k : sampleKeys()) {
assertEquals(multimap().containsKey(k), multimap().keySet().contains(k));
}
}
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testContainsKeyNullPresent() {
initMultimapWithNullKey();
assertTrue(multimap().containsKey(null));
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testContainsKeyNullAbsent() {
assertFalse(multimap().containsKey(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContainsKeyNullDisallowed() {
try {
multimap().containsKey(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| Java |
/*
* Copyright (C) 2013 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.google;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.testing.EqualsTester;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Testers for {@link com.google.common.collect.ListMultimap#asMap}.
*
* @author Louis Wasserman
* @param <K> The key type of the tested multimap.
* @param <V> The value type of the tested multimap.
*/
@GwtCompatible
public class ListMultimapAsMapTester<K, V> extends AbstractListMultimapTester<K, V> {
public void testAsMapValuesImplementList() {
for (Collection<V> valueCollection : multimap().asMap().values()) {
assertTrue(valueCollection instanceof List);
}
}
public void testAsMapGetImplementsList() {
for (K key : multimap().keySet()) {
assertTrue(multimap().asMap().get(key) instanceof List);
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testAsMapRemoveImplementsList() {
List<K> keys = new ArrayList<K>(multimap().keySet());
for (K key : keys) {
resetCollection();
assertTrue(multimap().asMap().remove(key) instanceof List);
}
}
@CollectionSize.Require(SEVERAL)
public void testEquals() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Map<K, Collection<V>> expected = Maps.newHashMap();
expected.put(sampleKeys().e0, Lists.newArrayList(sampleValues().e0, sampleValues().e3));
expected.put(sampleKeys().e1, Lists.newArrayList(sampleValues().e0));
new EqualsTester()
.addEqualityGroup(expected, multimap().asMap())
.testEquals();
}
@CollectionSize.Require(SEVERAL)
public void testEntrySetEquals() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
Set<Entry<K, Collection<V>>> expected = Sets.newHashSet();
expected.add(Helpers.mapEntry(
sampleKeys().e0,
(Collection<V>) Lists.newArrayList(sampleValues().e0, sampleValues().e3)));
expected.add(Helpers.mapEntry(
sampleKeys().e1,
(Collection<V>) Lists.newArrayList(sampleValues().e0)));
new EqualsTester()
.addEqualityGroup(expected, multimap().asMap().entrySet())
.testEquals();
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testValuesRemove() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e1, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e3));
assertTrue(multimap().asMap().values().remove(Collections.singletonList(sampleValues().e0)));
assertEquals(2, multimap().size());
assertEquals(
Collections.singletonMap(
sampleKeys().e0, Lists.newArrayList(sampleValues().e0, sampleValues().e3)),
multimap().asMap());
}
}
| 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.google;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.AbstractContainerTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* Superclass for all {@code Multimap} testers.
*
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class AbstractMultimapTester<K, V, M extends Multimap<K, V>>
extends AbstractContainerTester<M, Map.Entry<K, V>> {
private M multimap;
protected M multimap() {
return multimap;
}
/**
* @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] = Helpers.mapEntry(null, oldEntry.getValue());
return array;
}
/**
* @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] = Helpers.mapEntry(oldEntry.getKey(), null);
return array;
}
/**
* @return an array of the proper size with {@code null} as the key and value of the
* middle element.
*/
protected Map.Entry<K, V>[] createArrayWithNullKeyAndValue() {
Map.Entry<K, V>[] array = createSamplesArray();
final int nullValueLocation = getNullLocation();
array[nullValueLocation] = Helpers.mapEntry(null, null);
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();
}
protected void initMultimapWithNullKey() {
resetContainer(getSubjectGenerator().create(createArrayWithNullKey()));
}
protected void initMultimapWithNullValue() {
resetContainer(getSubjectGenerator().create(createArrayWithNullValue()));
}
protected void initMultimapWithNullKeyAndValue() {
resetContainer(getSubjectGenerator().create(createArrayWithNullKeyAndValue()));
}
protected SampleElements<K> sampleKeys() {
return ((TestMultimapGenerator<K, V, ? extends Multimap<K, V>>) getSubjectGenerator()
.getInnerGenerator()).sampleKeys();
}
protected SampleElements<V> sampleValues() {
return ((TestMultimapGenerator<K, V, ? extends Multimap<K, V>>) getSubjectGenerator()
.getInnerGenerator()).sampleValues();
}
@Override
protected Collection<Entry<K, V>> actualContents() {
return multimap.entries();
}
// TODO: dispose of this once collection is encapsulated.
@Override
protected M resetContainer(M newContents) {
multimap = super.resetContainer(newContents);
return multimap;
}
protected Multimap<K, V> resetContainer(Entry<K, V>... newContents) {
multimap = super.resetContainer(getSubjectGenerator().create(newContents));
return multimap;
}
/** @see AbstractContainerTester#resetContainer() */
protected void resetCollection() {
resetContainer();
}
protected void assertGet(K key, V... values) {
assertGet(key, Arrays.asList(values));
}
protected void assertGet(K key, Collection<V> values) {
ASSERT.that(multimap().get(key)).has().exactlyAs(values);
if (!values.isEmpty()) {
ASSERT.that(multimap().asMap().get(key)).has().exactlyAs(values);
assertFalse(multimap().isEmpty());
} else {
ASSERT.that(multimap().asMap().get(key)).isNull();
}
// TODO(user): Add proper overrides to prevent autoboxing.
// Truth+autoboxing == compile error. Cast int to long to fix:
ASSERT.that(multimap().get(key).size()).is((long) values.size());
assertEquals(values.size() > 0, multimap().containsKey(key));
assertEquals(values.size() > 0, multimap().keySet().contains(key));
assertEquals(values.size() > 0, multimap().keys().contains(key));
}
}
| Java |
/*
* Copyright (C) 2011 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.google;
import static com.google.common.collect.BoundType.CLOSED;
import static com.google.common.collect.BoundType.OPEN;
import static com.google.common.collect.testing.Helpers.copyToList;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
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.BoundType;
import com.google.common.collect.Iterators;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.Multisets;
import com.google.common.collect.SortedMultiset;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Tester for navigation of SortedMultisets.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultisetNavigationTester<E> extends AbstractMultisetTester<E> {
private SortedMultiset<E> sortedMultiset;
private List<E> entries;
private Entry<E> a;
private Entry<E> b;
private Entry<E> c;
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> SortedMultiset<T> cast(Multiset<T> iterable) {
return (SortedMultiset<T>) iterable;
}
@Override
public void setUp() throws Exception {
super.setUp();
sortedMultiset = cast(getMultiset());
entries =
copyToList(getSubjectGenerator().getSampleElements(
getSubjectGenerator().getCollectionSize().getNumElements()));
Collections.sort(entries, sortedMultiset.comparator());
// some tests assume SEVERAL == 3
if (entries.size() >= 1) {
a = Multisets.immutableEntry(entries.get(0), sortedMultiset.count(entries.get(0)));
if (entries.size() >= 3) {
b = Multisets.immutableEntry(entries.get(1), sortedMultiset.count(entries.get(1)));
c = Multisets.immutableEntry(entries.get(2), sortedMultiset.count(entries.get(2)));
}
}
}
/**
* Resets the contents of sortedMultiset to have entries a, c, for the navigation tests.
*/
@SuppressWarnings("unchecked")
// Needed to stop Eclipse whining
private void resetWithHole() {
List<E> container = new ArrayList<E>();
container.addAll(Collections.nCopies(a.getCount(), a.getElement()));
container.addAll(Collections.nCopies(c.getCount(), c.getElement()));
super.resetContainer(getSubjectGenerator().create(container.toArray()));
sortedMultiset = (SortedMultiset<E>) getMultiset();
}
@CollectionSize.Require(ZERO)
public void testEmptyMultisetFirst() {
assertNull(sortedMultiset.firstEntry());
try {
sortedMultiset.elementSet().first();
fail();
} catch (NoSuchElementException e) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptyMultisetPollFirst() {
assertNull(sortedMultiset.pollFirstEntry());
}
@CollectionSize.Require(ZERO)
public void testEmptyMultisetNearby() {
for (BoundType type : BoundType.values()) {
assertNull(sortedMultiset.headMultiset(samples.e0, type).lastEntry());
assertNull(sortedMultiset.tailMultiset(samples.e0, type).firstEntry());
}
}
@CollectionSize.Require(ZERO)
public void testEmptyMultisetLast() {
assertNull(sortedMultiset.lastEntry());
try {
assertNull(sortedMultiset.elementSet().last());
fail();
} catch (NoSuchElementException e) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptyMultisetPollLast() {
assertNull(sortedMultiset.pollLastEntry());
}
@CollectionSize.Require(ONE)
public void testSingletonMultisetFirst() {
assertEquals(a, sortedMultiset.firstEntry());
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonMultisetPollFirst() {
assertEquals(a, sortedMultiset.pollFirstEntry());
assertTrue(sortedMultiset.isEmpty());
}
@CollectionSize.Require(ONE)
public void testSingletonMultisetNearby() {
assertNull(sortedMultiset.headMultiset(samples.e0, OPEN).lastEntry());
assertNull(sortedMultiset.tailMultiset(samples.e0, OPEN).lastEntry());
assertEquals(a, sortedMultiset.headMultiset(samples.e0, CLOSED).lastEntry());
assertEquals(a, sortedMultiset.tailMultiset(samples.e0, CLOSED).firstEntry());
}
@CollectionSize.Require(ONE)
public void testSingletonMultisetLast() {
assertEquals(a, sortedMultiset.lastEntry());
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonMultisetPollLast() {
assertEquals(a, sortedMultiset.pollLastEntry());
assertTrue(sortedMultiset.isEmpty());
}
@CollectionSize.Require(SEVERAL)
public void testFirst() {
assertEquals(a, sortedMultiset.firstEntry());
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollFirst() {
assertEquals(a, sortedMultiset.pollFirstEntry());
assertEquals(Arrays.asList(b, c), copyToList(sortedMultiset.entrySet()));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testPollFirstUnsupported() {
try {
sortedMultiset.pollFirstEntry();
fail();
} catch (UnsupportedOperationException e) {}
}
@CollectionSize.Require(SEVERAL)
public void testLower() {
resetWithHole();
assertEquals(null, sortedMultiset.headMultiset(a.getElement(), OPEN).lastEntry());
assertEquals(a, sortedMultiset.headMultiset(b.getElement(), OPEN).lastEntry());
assertEquals(a, sortedMultiset.headMultiset(c.getElement(), OPEN).lastEntry());
}
@CollectionSize.Require(SEVERAL)
public void testFloor() {
resetWithHole();
assertEquals(a, sortedMultiset.headMultiset(a.getElement(), CLOSED).lastEntry());
assertEquals(a, sortedMultiset.headMultiset(b.getElement(), CLOSED).lastEntry());
assertEquals(c, sortedMultiset.headMultiset(c.getElement(), CLOSED).lastEntry());
}
@CollectionSize.Require(SEVERAL)
public void testCeiling() {
resetWithHole();
assertEquals(a, sortedMultiset.tailMultiset(a.getElement(), CLOSED).firstEntry());
assertEquals(c, sortedMultiset.tailMultiset(b.getElement(), CLOSED).firstEntry());
assertEquals(c, sortedMultiset.tailMultiset(c.getElement(), CLOSED).firstEntry());
}
@CollectionSize.Require(SEVERAL)
public void testHigher() {
resetWithHole();
assertEquals(c, sortedMultiset.tailMultiset(a.getElement(), OPEN).firstEntry());
assertEquals(c, sortedMultiset.tailMultiset(b.getElement(), OPEN).firstEntry());
assertEquals(null, sortedMultiset.tailMultiset(c.getElement(), OPEN).firstEntry());
}
@CollectionSize.Require(SEVERAL)
public void testLast() {
assertEquals(c, sortedMultiset.lastEntry());
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollLast() {
assertEquals(c, sortedMultiset.pollLastEntry());
assertEquals(Arrays.asList(a, b), copyToList(sortedMultiset.entrySet()));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollLastUnsupported() {
try {
sortedMultiset.pollLastEntry();
fail();
} catch (UnsupportedOperationException e) {}
}
@CollectionSize.Require(SEVERAL)
public void testDescendingNavigation() {
List<Entry<E>> ascending = new ArrayList<Entry<E>>();
Iterators.addAll(ascending, sortedMultiset.entrySet().iterator());
List<Entry<E>> descending = new ArrayList<Entry<E>>();
Iterators.addAll(descending, sortedMultiset.descendingMultiset().entrySet().iterator());
Collections.reverse(descending);
assertEquals(ascending, descending);
}
void expectAddFailure(SortedMultiset<E> multiset, Entry<E> entry) {
try {
multiset.add(entry.getElement(), entry.getCount());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
multiset.add(entry.getElement());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
multiset.addAll(Collections.singletonList(entry.getElement()));
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
void expectRemoveZero(SortedMultiset<E> multiset, Entry<E> entry) {
assertEquals(0, multiset.remove(entry.getElement(), entry.getCount()));
assertFalse(multiset.remove(entry.getElement()));
assertFalse(multiset.elementSet().remove(entry.getElement()));
}
void expectSetCountFailure(SortedMultiset<E> multiset, Entry<E> entry) {
try {
multiset.setCount(entry.getElement(), multiset.count(entry.getElement()));
} catch (IllegalArgumentException acceptable) {}
try {
multiset.setCount(entry.getElement(), multiset.count(entry.getElement()) + 1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOutOfTailBoundsOne() {
expectAddFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOutOfTailBoundsSeveral() {
expectAddFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a);
expectAddFailure(sortedMultiset.tailMultiset(b.getElement(), CLOSED), a);
expectAddFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), a);
expectAddFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), b);
expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), a);
expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), b);
expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), a);
expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), b);
expectAddFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), c);
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOutOfHeadBoundsOne() {
expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOutOfHeadBoundsSeveral() {
expectAddFailure(sortedMultiset.headMultiset(c.getElement(), OPEN), c);
expectAddFailure(sortedMultiset.headMultiset(b.getElement(), CLOSED), c);
expectAddFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), c);
expectAddFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), b);
expectAddFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), c);
expectAddFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), b);
expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), c);
expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), b);
expectAddFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveOutOfTailBoundsOne() {
expectRemoveZero(sortedMultiset.tailMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveOutOfTailBoundsSeveral() {
expectRemoveZero(sortedMultiset.tailMultiset(a.getElement(), OPEN), a);
expectRemoveZero(sortedMultiset.tailMultiset(b.getElement(), CLOSED), a);
expectRemoveZero(sortedMultiset.tailMultiset(b.getElement(), OPEN), a);
expectRemoveZero(sortedMultiset.tailMultiset(b.getElement(), OPEN), b);
expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), CLOSED), a);
expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), CLOSED), b);
expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), OPEN), a);
expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), OPEN), b);
expectRemoveZero(sortedMultiset.tailMultiset(c.getElement(), OPEN), c);
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveOutOfHeadBoundsOne() {
expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveOutOfHeadBoundsSeveral() {
expectRemoveZero(sortedMultiset.headMultiset(c.getElement(), OPEN), c);
expectRemoveZero(sortedMultiset.headMultiset(b.getElement(), CLOSED), c);
expectRemoveZero(sortedMultiset.headMultiset(b.getElement(), OPEN), c);
expectRemoveZero(sortedMultiset.headMultiset(b.getElement(), OPEN), b);
expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), CLOSED), c);
expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), CLOSED), b);
expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), c);
expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), b);
expectRemoveZero(sortedMultiset.headMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCountOutOfTailBoundsOne() {
expectSetCountFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCountOutOfTailBoundsSeveral() {
expectSetCountFailure(sortedMultiset.tailMultiset(a.getElement(), OPEN), a);
expectSetCountFailure(sortedMultiset.tailMultiset(b.getElement(), CLOSED), a);
expectSetCountFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), a);
expectSetCountFailure(sortedMultiset.tailMultiset(b.getElement(), OPEN), b);
expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), a);
expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), CLOSED), b);
expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), a);
expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), b);
expectSetCountFailure(sortedMultiset.tailMultiset(c.getElement(), OPEN), c);
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCountOutOfHeadBoundsOne() {
expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require({SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCountOutOfHeadBoundsSeveral() {
expectSetCountFailure(sortedMultiset.headMultiset(c.getElement(), OPEN), c);
expectSetCountFailure(sortedMultiset.headMultiset(b.getElement(), CLOSED), c);
expectSetCountFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), c);
expectSetCountFailure(sortedMultiset.headMultiset(b.getElement(), OPEN), b);
expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), c);
expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), CLOSED), b);
expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), c);
expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), b);
expectSetCountFailure(sortedMultiset.headMultiset(a.getElement(), OPEN), a);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddWithConflictingBounds() {
testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(a.getElement(), CLOSED,
a.getElement(), OPEN));
testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(a.getElement(), OPEN,
a.getElement(), OPEN));
testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(a.getElement(), OPEN,
a.getElement(), CLOSED));
testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(b.getElement(), CLOSED,
a.getElement(), CLOSED));
testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(b.getElement(), CLOSED,
a.getElement(), OPEN));
testEmptyRangeSubMultisetSupportingAdd(sortedMultiset.subMultiset(b.getElement(), OPEN,
a.getElement(), OPEN));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testConflictingBounds() {
testEmptyRangeSubMultiset(sortedMultiset.subMultiset(a.getElement(), CLOSED, a.getElement(),
OPEN));
testEmptyRangeSubMultiset(sortedMultiset.subMultiset(a.getElement(), OPEN, a.getElement(),
OPEN));
testEmptyRangeSubMultiset(sortedMultiset.subMultiset(a.getElement(), OPEN, a.getElement(),
CLOSED));
testEmptyRangeSubMultiset(sortedMultiset.subMultiset(b.getElement(), CLOSED, a.getElement(),
CLOSED));
testEmptyRangeSubMultiset(sortedMultiset.subMultiset(b.getElement(), CLOSED, a.getElement(),
OPEN));
testEmptyRangeSubMultiset(sortedMultiset.subMultiset(b.getElement(), OPEN, a.getElement(),
OPEN));
}
public void testEmptyRangeSubMultiset(SortedMultiset<E> multiset) {
assertTrue(multiset.isEmpty());
assertEquals(0, multiset.size());
assertEquals(0, multiset.toArray().length);
assertTrue(multiset.entrySet().isEmpty());
assertFalse(multiset.iterator().hasNext());
assertEquals(0, multiset.entrySet().size());
assertEquals(0, multiset.entrySet().toArray().length);
assertFalse(multiset.entrySet().iterator().hasNext());
}
@SuppressWarnings("unchecked")
public void testEmptyRangeSubMultisetSupportingAdd(SortedMultiset<E> multiset) {
for (Entry<E> entry : Arrays.asList(a, b, c)) {
expectAddFailure(multiset, entry);
}
}
private int totalSize(Iterable<? extends Entry<?>> entries) {
int sum = 0;
for (Entry<?> entry : entries) {
sum += entry.getCount();
}
return sum;
}
private enum SubMultisetSpec {
TAIL_CLOSED {
@Override
<E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) {
return entries.subList(targetEntry, entries.size());
}
@Override
<E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries,
int targetEntry) {
return multiset.tailMultiset(entries.get(targetEntry).getElement(), CLOSED);
}
},
TAIL_OPEN {
@Override
<E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) {
return entries.subList(targetEntry + 1, entries.size());
}
@Override
<E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries,
int targetEntry) {
return multiset.tailMultiset(entries.get(targetEntry).getElement(), OPEN);
}
},
HEAD_CLOSED {
@Override
<E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) {
return entries.subList(0, targetEntry + 1);
}
@Override
<E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries,
int targetEntry) {
return multiset.headMultiset(entries.get(targetEntry).getElement(), CLOSED);
}
},
HEAD_OPEN {
@Override
<E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries) {
return entries.subList(0, targetEntry);
}
@Override
<E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries,
int targetEntry) {
return multiset.headMultiset(entries.get(targetEntry).getElement(), OPEN);
}
};
abstract <E> List<Entry<E>> expectedEntries(int targetEntry, List<Entry<E>> entries);
abstract <E> SortedMultiset<E> subMultiset(SortedMultiset<E> multiset, List<Entry<E>> entries,
int targetEntry);
}
private void testSubMultisetEntrySet(SubMultisetSpec spec) {
List<Entry<E>> entries = copyToList(sortedMultiset.entrySet());
for (int i = 0; i < entries.size(); i++) {
List<Entry<E>> expected = spec.expectedEntries(i, entries);
SortedMultiset<E> subMultiset = spec.subMultiset(sortedMultiset, entries, i);
assertEquals(expected, copyToList(subMultiset.entrySet()));
}
}
private void testSubMultisetSize(SubMultisetSpec spec) {
List<Entry<E>> entries = copyToList(sortedMultiset.entrySet());
for (int i = 0; i < entries.size(); i++) {
List<Entry<E>> expected = spec.expectedEntries(i, entries);
SortedMultiset<E> subMultiset = spec.subMultiset(sortedMultiset, entries, i);
assertEquals(totalSize(expected), subMultiset.size());
}
}
private void testSubMultisetDistinctElements(SubMultisetSpec spec) {
List<Entry<E>> entries = copyToList(sortedMultiset.entrySet());
for (int i = 0; i < entries.size(); i++) {
List<Entry<E>> expected = spec.expectedEntries(i, entries);
SortedMultiset<E> subMultiset = spec.subMultiset(sortedMultiset, entries, i);
assertEquals(expected.size(), subMultiset.entrySet().size());
assertEquals(expected.size(), subMultiset.elementSet().size());
}
}
public void testTailClosedEntrySet() {
testSubMultisetEntrySet(SubMultisetSpec.TAIL_CLOSED);
}
public void testTailClosedSize() {
testSubMultisetSize(SubMultisetSpec.TAIL_CLOSED);
}
public void testTailClosedDistinctElements() {
testSubMultisetDistinctElements(SubMultisetSpec.TAIL_CLOSED);
}
public void testTailOpenEntrySet() {
testSubMultisetEntrySet(SubMultisetSpec.TAIL_OPEN);
}
public void testTailOpenSize() {
testSubMultisetSize(SubMultisetSpec.TAIL_OPEN);
}
public void testTailOpenDistinctElements() {
testSubMultisetDistinctElements(SubMultisetSpec.TAIL_OPEN);
}
public void testHeadClosedEntrySet() {
testSubMultisetEntrySet(SubMultisetSpec.HEAD_CLOSED);
}
public void testHeadClosedSize() {
testSubMultisetSize(SubMultisetSpec.HEAD_CLOSED);
}
public void testHeadClosedDistinctElements() {
testSubMultisetDistinctElements(SubMultisetSpec.HEAD_CLOSED);
}
public void testHeadOpenEntrySet() {
testSubMultisetEntrySet(SubMultisetSpec.HEAD_OPEN);
}
public void testHeadOpenSize() {
testSubMultisetSize(SubMultisetSpec.HEAD_OPEN);
}
public void testHeadOpenDistinctElements() {
testSubMultisetDistinctElements(SubMultisetSpec.HEAD_OPEN);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearTailOpen() {
List<Entry<E>> expected =
copyToList(sortedMultiset.headMultiset(b.getElement(), CLOSED).entrySet());
sortedMultiset.tailMultiset(b.getElement(), OPEN).clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearTailOpenEntrySet() {
List<Entry<E>> expected =
copyToList(sortedMultiset.headMultiset(b.getElement(), CLOSED).entrySet());
sortedMultiset.tailMultiset(b.getElement(), OPEN).entrySet().clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearTailClosed() {
List<Entry<E>> expected =
copyToList(sortedMultiset.headMultiset(b.getElement(), OPEN).entrySet());
sortedMultiset.tailMultiset(b.getElement(), CLOSED).clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearTailClosedEntrySet() {
List<Entry<E>> expected =
copyToList(sortedMultiset.headMultiset(b.getElement(), OPEN).entrySet());
sortedMultiset.tailMultiset(b.getElement(), CLOSED).entrySet().clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearHeadOpen() {
List<Entry<E>> expected =
copyToList(sortedMultiset.tailMultiset(b.getElement(), CLOSED).entrySet());
sortedMultiset.headMultiset(b.getElement(), OPEN).clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearHeadOpenEntrySet() {
List<Entry<E>> expected =
copyToList(sortedMultiset.tailMultiset(b.getElement(), CLOSED).entrySet());
sortedMultiset.headMultiset(b.getElement(), OPEN).entrySet().clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearHeadClosed() {
List<Entry<E>> expected =
copyToList(sortedMultiset.tailMultiset(b.getElement(), OPEN).entrySet());
sortedMultiset.headMultiset(b.getElement(), CLOSED).clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testClearHeadClosedEntrySet() {
List<Entry<E>> expected =
copyToList(sortedMultiset.tailMultiset(b.getElement(), OPEN).entrySet());
sortedMultiset.headMultiset(b.getElement(), CLOSED).entrySet().clear();
assertEquals(expected, copyToList(sortedMultiset.entrySet()));
}
}
| 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.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.DerivedGenerator;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestMapGenerator;
import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.TestSubjectGenerator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Derived suite generators for Guava collection interfaces, split out of the suite builders so that
* they are available to GWT.
*
* @author Louis Wasserman
*/
@GwtCompatible
public final class DerivedGoogleCollectionGenerators {
public static class MapGenerator<K, V> implements TestMapGenerator<K, V>, DerivedGenerator {
private final OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> generator;
public MapGenerator(
OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> oneSizeTestContainerGenerator) {
this.generator = oneSizeTestContainerGenerator;
}
@Override
public SampleElements<Map.Entry<K, V>> samples() {
return generator.samples();
}
@Override
public Map<K, V> create(Object... elements) {
return generator.create(elements);
}
@Override
public Map.Entry<K, V>[] createArray(int length) {
return generator.createArray(length);
}
@Override
public Iterable<Map.Entry<K, V>> order(List<Map.Entry<K, V>> insertionOrder) {
return generator.order(insertionOrder);
}
@SuppressWarnings("unchecked")
@Override
public K[] createKeyArray(int length) {
return (K[]) new Object[length];
}
@SuppressWarnings("unchecked")
@Override
public V[] createValueArray(int length) {
return (V[]) new Object[length];
}
public TestSubjectGenerator<?> getInnerGenerator() {
return generator;
}
}
public static class InverseBiMapGenerator<K, V>
implements TestBiMapGenerator<V, K>, DerivedGenerator {
private final OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> generator;
public InverseBiMapGenerator(
OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> oneSizeTestContainerGenerator) {
this.generator = oneSizeTestContainerGenerator;
}
@Override
public SampleElements<Map.Entry<V, K>> samples() {
SampleElements<Entry<K, V>> samples = generator.samples();
return new SampleElements<Map.Entry<V, K>>(reverse(samples.e0), reverse(samples.e1),
reverse(samples.e2), reverse(samples.e3), reverse(samples.e4));
}
private Map.Entry<V, K> reverse(Map.Entry<K, V> entry) {
return Helpers.mapEntry(entry.getValue(), entry.getKey());
}
@SuppressWarnings("unchecked")
@Override
public BiMap<V, K> create(Object... elements) {
Entry<?, ?>[] entries = new Entry<?, ?>[elements.length];
for (int i = 0; i < elements.length; i++) {
entries[i] = reverse((Entry<K, V>) elements[i]);
}
return generator.create((Object[]) entries).inverse();
}
@SuppressWarnings("unchecked")
@Override
public Map.Entry<V, K>[] createArray(int length) {
return new Entry[length];
}
@Override
public Iterable<Entry<V, K>> order(List<Entry<V, K>> insertionOrder) {
return insertionOrder;
}
@SuppressWarnings("unchecked")
@Override
public V[] createKeyArray(int length) {
return (V[]) new Object[length];
}
@SuppressWarnings("unchecked")
@Override
public K[] createValueArray(int length) {
return (K[]) new Object[length];
}
public TestSubjectGenerator<?> getInnerGenerator() {
return generator;
}
}
public static class BiMapValueSetGenerator<K, V>
implements TestSetGenerator<V>, DerivedGenerator {
private final OneSizeTestContainerGenerator<BiMap<K, V>, Map.Entry<K, V>>
mapGenerator;
private final SampleElements<V> samples;
public BiMapValueSetGenerator(
OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> mapGenerator) {
this.mapGenerator = mapGenerator;
final SampleElements<Map.Entry<K, V>> mapSamples =
this.mapGenerator.samples();
this.samples = new SampleElements<V>(
mapSamples.e0.getValue(),
mapSamples.e1.getValue(),
mapSamples.e2.getValue(),
mapSamples.e3.getValue(),
mapSamples.e4.getValue());
}
@Override
public SampleElements<V> samples() {
return samples;
}
@Override
public Set<V> create(Object... elements) {
@SuppressWarnings("unchecked")
V[] valuesArray = (V[]) elements;
// Start with a suitably shaped collection of entries
Collection<Map.Entry<K, V>> originalEntries =
mapGenerator.getSampleElements(elements.length);
// Create a copy of that, with the desired value for each value
Collection<Map.Entry<K, V>> entries =
new ArrayList<Entry<K, V>>(elements.length);
int i = 0;
for (Map.Entry<K, V> entry : originalEntries) {
entries.add(Helpers.mapEntry(entry.getKey(), valuesArray[i++]));
}
return mapGenerator.create(entries.toArray()).values();
}
@Override
public V[] createArray(int length) {
final V[] vs = ((TestBiMapGenerator<K, V>) mapGenerator.getInnerGenerator())
.createValueArray(length);
return vs;
}
@Override
public Iterable<V> order(List<V> insertionOrder) {
return insertionOrder;
}
public TestSubjectGenerator<?> getInnerGenerator() {
return mapGenerator;
}
}
private DerivedGoogleCollectionGenerators() {}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.