code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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.testing;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.Beta;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Defaults;
import com.google.common.base.Equivalence;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Ticker;
import com.google.common.collect.BiMap;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.Constraint;
import com.google.common.collect.Constraints;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterators;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MapConstraint;
import com.google.common.collect.MapConstraints;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.Ordering;
import com.google.common.collect.PeekingIterator;
import com.google.common.collect.Range;
import com.google.common.collect.RowSortedTable;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.SortedMapDifference;
import com.google.common.collect.SortedMultiset;
import com.google.common.collect.SortedSetMultimap;
import com.google.common.collect.Table;
import com.google.common.collect.Tables;
import com.google.common.collect.TreeBasedTable;
import com.google.common.collect.TreeMultimap;
import com.google.common.collect.TreeMultiset;
import com.google.common.primitives.Primitives;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Comparator;
import java.util.Currency;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Supplies an arbitrary "default" instance for a wide range of types, often useful in testing
* utilities.
*
* <p>Covers common types defined in {@code java.lang}, {@code java.lang.reflect}, {@code java.io},
* {@code java.nio}, {@code java.math}, {@code java.util}, {@code java.util.concurrent},
* {@code java.util.regex}, {@code com.google.common.base}, {@code com.google.common.collect}
* and {@code com.google.common.primitives}. In addition, any public class that exposes a public
* parameter-less constructor will be "new"d and returned.
*
* <p>All default instances returned by {@link #get} are generics-safe. Clients won't get type
* errors for using {@code get(Comparator.class)} as a {@code Comparator<Foo>}, for example.
* Immutable empty instances are returned for collection types; {@code ""} for string;
* {@code 0} for number types; reasonable default instance for other stateless types. For mutable
* types, a fresh instance is created each time {@code get()} is called.
*
* @author Kevin Bourrillion
* @author Ben Yu
* @since 12.0
*/
@Beta
public final class ArbitraryInstances {
// Compare by toString() to satisfy 2 properties:
// 1. compareTo(null) should throw NullPointerException
// 2. the order is deterministic and easy to understand, for debugging purpose.
private static final Comparable<Object> BY_TO_STRING = new Comparable<Object>() {
@Override public int compareTo(Object o) {
return toString().compareTo(o.toString());
}
@Override public String toString() {
return "BY_TO_STRING";
}
};
// Always equal is a valid total ordering. And it works for any Object.
private static final Ordering<Object> ALWAYS_EQUAL = new Ordering<Object>() {
@Override public int compare(Object o1, Object o2) {
return 0;
}
@Override public String toString() {
return "ALWAYS_EQUAL";
}
};
private static final ClassToInstanceMap<Object> DEFAULTS = ImmutableClassToInstanceMap.builder()
// primitives
.put(Number.class, 0)
.put(UnsignedInteger.class, UnsignedInteger.ZERO)
.put(UnsignedLong.class, UnsignedLong.ZERO)
.put(BigInteger.class, BigInteger.ZERO)
.put(BigDecimal.class, BigDecimal.ZERO)
.put(CharSequence.class, "")
.put(String.class, "")
.put(Pattern.class, Pattern.compile(""))
.put(MatchResult.class, Pattern.compile("").matcher("").toMatchResult())
.put(TimeUnit.class, TimeUnit.SECONDS)
.put(Charset.class, Charsets.UTF_8)
.put(Currency.class, Currency.getInstance(Locale.US))
.put(Locale.class, Locale.US)
// common.base
.put(CharMatcher.class, CharMatcher.NONE)
.put(Joiner.class, Joiner.on(','))
.put(Splitter.class, Splitter.on(','))
.put(Optional.class, Optional.absent())
.put(Predicate.class, Predicates.alwaysTrue())
.put(Equivalence.class, Equivalence.equals())
.put(Ticker.class, Ticker.systemTicker())
// io types
.put(InputStream.class, new ByteArrayInputStream(new byte[0]))
.put(ByteArrayInputStream.class, new ByteArrayInputStream(new byte[0]))
.put(Readable.class, new StringReader(""))
.put(Reader.class, new StringReader(""))
.put(StringReader.class, new StringReader(""))
.put(Buffer.class, ByteBuffer.allocate(0))
.put(CharBuffer.class, CharBuffer.allocate(0))
.put(ByteBuffer.class, ByteBuffer.allocate(0))
.put(ShortBuffer.class, ShortBuffer.allocate(0))
.put(IntBuffer.class, IntBuffer.allocate(0))
.put(LongBuffer.class, LongBuffer.allocate(0))
.put(FloatBuffer.class, FloatBuffer.allocate(0))
.put(DoubleBuffer.class, DoubleBuffer.allocate(0))
.put(File.class, new File(""))
// All collections are immutable empty. So safe for any type parameter.
.put(Iterator.class, Iterators.emptyIterator())
.put(PeekingIterator.class, Iterators.peekingIterator(Iterators.emptyIterator()))
.put(ListIterator.class, ImmutableList.of().listIterator())
.put(Iterable.class, ImmutableSet.of())
.put(Collection.class, ImmutableList.of())
.put(ImmutableCollection.class, ImmutableList.of())
.put(List.class, ImmutableList.of())
.put(ImmutableList.class, ImmutableList.of())
.put(Set.class, ImmutableSet.of())
.put(ImmutableSet.class, ImmutableSet.of())
.put(SortedSet.class, ImmutableSortedSet.of())
.put(ImmutableSortedSet.class, ImmutableSortedSet.of())
.put(NavigableSet.class, Sets.unmodifiableNavigableSet(Sets.newTreeSet()))
.put(Map.class, ImmutableMap.of())
.put(ImmutableMap.class, ImmutableMap.of())
.put(SortedMap.class, ImmutableSortedMap.of())
.put(ImmutableSortedMap.class, ImmutableSortedMap.of())
.put(NavigableMap.class, Maps.unmodifiableNavigableMap(Maps.newTreeMap()))
.put(Multimap.class, ImmutableMultimap.of())
.put(ImmutableMultimap.class, ImmutableMultimap.of())
.put(ListMultimap.class, ImmutableListMultimap.of())
.put(ImmutableListMultimap.class, ImmutableListMultimap.of())
.put(SetMultimap.class, ImmutableSetMultimap.of())
.put(ImmutableSetMultimap.class, ImmutableSetMultimap.of())
.put(SortedSetMultimap.class, Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create()))
.put(Multiset.class, ImmutableMultiset.of())
.put(ImmutableMultiset.class, ImmutableMultiset.of())
.put(SortedMultiset.class, Multisets.unmodifiableSortedMultiset(TreeMultiset.create()))
.put(BiMap.class, ImmutableBiMap.of())
.put(ImmutableBiMap.class, ImmutableBiMap.of())
.put(Table.class, ImmutableTable.of())
.put(ImmutableTable.class, ImmutableTable.of())
.put(RowSortedTable.class, Tables.unmodifiableRowSortedTable(TreeBasedTable.create()))
.put(ClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
.put(ImmutableClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
.put(Comparable.class, BY_TO_STRING)
.put(Comparator.class, ALWAYS_EQUAL)
.put(Ordering.class, ALWAYS_EQUAL)
.put(Range.class, Range.all())
.put(Constraint.class, Constraints.notNull())
.put(MapConstraint.class, MapConstraints.notNull())
.put(MapDifference.class, Maps.difference(ImmutableMap.of(), ImmutableMap.of()))
.put(SortedMapDifference.class,
Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of()))
// reflect
.put(AnnotatedElement.class, Object.class)
.put(GenericDeclaration.class, Object.class)
.put(Type.class, Object.class)
// concurrent
.put(Runnable.class, new Runnable() {
@Override public void run() {}
})
.put(ThreadFactory.class, new ThreadFactory() {
@Override public Thread newThread(Runnable r) {
return new Thread(r);
}
})
.put(Executor.class, new Executor() {
@Override public void execute(Runnable command) {}
})
.build();
/**
* type -> implementation. Inherently mutable interfaces and abstract classes are mapped to their
* default implementations and are "new"d upon get().
*/
private static final ConcurrentMap<Class<?>, Class<?>> implementations = Maps.newConcurrentMap();
private static <T> void setImplementation(Class<T> type, Class<? extends T> implementation) {
checkArgument(type != implementation, "Don't register %s to itself!", type);
checkArgument(!DEFAULTS.containsKey(type),
"A default value was already registered for %s", type);
checkArgument(implementations.put(type, implementation) == null,
"Implementation for %s was already registered", type);
}
static {
setImplementation(Appendable.class, StringBuilder.class);
setImplementation(BlockingQueue.class, LinkedBlockingDeque.class);
setImplementation(BlockingDeque.class, LinkedBlockingDeque.class);
setImplementation(ConcurrentMap.class, ConcurrentHashMap.class);
setImplementation(ConcurrentNavigableMap.class, ConcurrentSkipListMap.class);
setImplementation(CountDownLatch.class, Mutable.DummyCountDownLatch.class);
setImplementation(Deque.class, ArrayDeque.class);
setImplementation(OutputStream.class, ByteArrayOutputStream.class);
setImplementation(PrintStream.class, Mutable.InMemoryPrintStream.class);
setImplementation(PrintWriter.class, Mutable.InMemoryPrintWriter.class);
setImplementation(Queue.class, ArrayDeque.class);
setImplementation(Random.class, Mutable.DeterministicRandom.class);
setImplementation(ScheduledThreadPoolExecutor.class,
Mutable.DummyScheduledThreadPoolExecutor.class);
setImplementation(ThreadPoolExecutor.class, Mutable.DummyScheduledThreadPoolExecutor.class);
setImplementation(Writer.class, StringWriter.class);
}
@SuppressWarnings("unchecked") // it's a subtype map
@Nullable
private static <T> Class<? extends T> getImplementation(Class<T> type) {
return (Class<? extends T>) implementations.get(type);
}
private static final Logger logger = Logger.getLogger(ArbitraryInstances.class.getName());
/**
* Returns an arbitrary value for {@code type} as the null value, or {@code null} if empty-ness is
* unknown for the type.
*/
@Nullable public static <T> T get(Class<T> type) {
T defaultValue = DEFAULTS.getInstance(type);
if (defaultValue != null) {
return defaultValue;
}
Class<? extends T> implementation = getImplementation(type);
if (implementation != null) {
return get(implementation);
}
if (type.isEnum()) {
T[] enumConstants = type.getEnumConstants();
return (enumConstants.length == 0)
? null
: enumConstants[0];
}
if (type.isArray()) {
return createEmptyArray(type);
}
T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type));
if (jvmDefault != null) {
return jvmDefault;
}
if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) {
return null;
}
final Constructor<T> constructor;
try {
constructor = type.getConstructor();
} catch (NoSuchMethodException e) {
return null;
}
constructor.setAccessible(true); // accessibility check is too slow
try {
return constructor.newInstance();
} catch (InstantiationException impossible) {
throw new AssertionError(impossible);
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
} catch (InvocationTargetException e) {
logger.log(Level.WARNING, "Exception while invoking default constructor.", e.getCause());
return null;
}
}
@SuppressWarnings("unchecked") // same component type means same array type
private static <T> T createEmptyArray(Class<T> arrayType) {
return (T) Array.newInstance(arrayType.getComponentType(), 0);
}
// Internal implementations for mutable types, with public default constructor that get() needs.
private static final class Mutable {
public static final class InMemoryPrintStream extends PrintStream {
public InMemoryPrintStream() {
super(new ByteArrayOutputStream());
}
}
public static final class InMemoryPrintWriter extends PrintWriter {
public InMemoryPrintWriter() {
super(new StringWriter());
}
}
public static final class DeterministicRandom extends Random {
@SuppressWarnings("unused") // invoked by reflection
public DeterministicRandom() {
super(0);
}
}
public static final class DummyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
public DummyScheduledThreadPoolExecutor() {
super(1);
}
}
public static final class DummyCountDownLatch extends CountDownLatch {
public DummyCountDownLatch() {
super(0);
}
}
}
private ArbitraryInstances() {}
}
| 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.testing;
import static com.google.common.testing.AbstractPackageSanityTests.Chopper.suffix;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.MutableClassToInstanceMap;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.TypeToken;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.junit.Test;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Automatically runs sanity checks for the entire package of the subclass. Currently sanity checks
* include {@link NullPointerTester} and {@link SerializableTester}. For example:
* <pre>
* {@literal @MediumTest}(MediumTestAttributes.FILE)
* public class PackageSanityTests extends AbstractPackageSanityTests {}
* </pre>
*
* <p>If a certain type Foo's null check testing requires default value to be manually set, or that
* it needs custom code to instantiate an instance for testing instance methods, add a {@code
* public void testNulls()} method to FooTest and Foo will be ignored by the automated {@link
* #testNulls} test.
*
* <p>Since this class scans the classpath and reads classpath resources, the test is essentially
* a {@code MediumTest}.
*
* @author Ben Yu
* @since 14.0
*/
@Beta
// TODO: Switch to JUnit 4 and use @Parameterized and @BeforeClass
public abstract class AbstractPackageSanityTests extends TestCase {
/* The names of the expected method that tests null checks. */
private static final ImmutableList<String> NULL_TEST_METHOD_NAMES = ImmutableList.of(
"testNulls", "testNull", "testNullPointer", "testNullPointerException");
/* The names of the expected method that tests serializable. */
private static final ImmutableList<String> SERIALIZABLE_TEST_METHOD_NAMES =
ImmutableList.of("testSerializable", "testSerialization");
private static final Chopper TEST_SUFFIX =
suffix("Test")
.or(suffix("Tests"))
.or(suffix("TestCase"))
.or(suffix("TestSuite"));
/**
* Sorts methods/constructors with least number of parameters first since it's likely easier to
* fill dummy parameter values for them. Ties are broken by name then by the string form of the
* parameter list.
*/
private static final Ordering<Invokable<?, ?>> LEAST_PARAMETERS_FIRST =
new Ordering<Invokable<?, ?>>() {
@Override public int compare(Invokable<?, ?> left, Invokable<?, ?> right) {
List<Parameter> params1 = left.getParameters();
List<Parameter> params2 = right.getParameters();
return ComparisonChain.start()
.compare(params1.size(), params2.size())
.compare(left.getName(), right.getName())
.compare(params1, params2, Ordering.usingToString())
.result();
}
};
private final Logger logger = Logger.getLogger(getClass().getName());
private final MutableClassToInstanceMap<Object> defaultValues =
MutableClassToInstanceMap.create();
private final NullPointerTester nullPointerTester = new NullPointerTester();
public AbstractPackageSanityTests() {
// TODO(benyu): bake these into ArbitraryInstances.
setDefault(byte.class, (byte) 1);
setDefault(Byte.class, (byte) 1);
setDefault(short.class, (short) 1);
setDefault(Short.class, (short) 1);
setDefault(int.class, 1);
setDefault(Integer.class, 1);
setDefault(long.class, 1L);
setDefault(Long.class, 1L);
setDefault(float.class, 1F);
setDefault(Float.class, 1F);
setDefault(double.class, 1D);
setDefault(Double.class, 1D);
}
/** Tests all {@link Serializable} classes in the package. */
@Test
public void testSerializable() throws Exception {
// TODO: when we use @BeforeClass, we can pay the cost of class path scanning only once.
for (Class<?> classToTest
: findClassesToTest(loadPublicClassesInPackage(), SERIALIZABLE_TEST_METHOD_NAMES)) {
if (Serializable.class.isAssignableFrom(classToTest)) {
testSerializable(classToTest);
}
}
}
/** Tests null checks through the entire package. */
@Test
public void testNulls() throws Exception {
for (Class<?> classToTest
: findClassesToTest(loadPublicClassesInPackage(), NULL_TEST_METHOD_NAMES)) {
testNulls(classToTest);
}
}
/**
* Sets the default value for {@code type}, when dummy value for a parameter of the same type
* needs to be created in order to invoke a method or constructor.
*/
protected final <T> void setDefault(Class<T> type, T value) {
nullPointerTester.setDefault(type, value);
defaultValues.putInstance(type, value);
}
private void testNulls(Class<?> cls) throws Exception {
nullPointerTester.testAllPublicConstructors(cls);
nullPointerTester.testAllPublicStaticMethods(cls);
Object instance = instantiate(cls, TestErrorReporter.FOR_NULLS_TEST);
if (instance != null) {
nullPointerTester.testAllPublicInstanceMethods(instance);
}
}
private void testSerializable(Class<?> cls) throws Exception {
Object instance = instantiate(cls, TestErrorReporter.FOR_SERIALIZABLE_TEST);
if (instance != null) {
if (isEqualsDefined(cls)) {
SerializableTester.reserializeAndAssert(instance);
} else {
SerializableTester.reserialize(instance);
}
}
}
/**
* Finds the classes not ending with a test suffix and not covered by an explicit test
* whose name is {@code explicitTestName}.
*/
@VisibleForTesting static List<Class<?>> findClassesToTest(
Iterable<? extends Class<?>> classes, Iterable<String> explicitTestNames) {
// "a.b.Foo" -> a.b.Foo.class
TreeMap<String, Class<?>> classMap = Maps.newTreeMap();
for (Class<?> cls : classes) {
classMap.put(cls.getName(), cls);
}
// Foo.class -> [FooTest.class, FooTests.class, FooTestSuite.class, ...]
Multimap<Class<?>, Class<?>> testClasses = HashMultimap.create();
LinkedHashSet<Class<?>> nonTestClasses = Sets.newLinkedHashSet();
for (Class<?> cls : classes) {
Optional<String> testedClassName = TEST_SUFFIX.chop(cls.getName());
if (testedClassName.isPresent()) {
Class<?> testedClass = classMap.get(testedClassName.get());
if (testedClass != null) {
testClasses.put(testedClass, cls);
}
} else {
nonTestClasses.add(cls);
}
}
List<Class<?>> classesToTest = Lists.newArrayListWithExpectedSize(nonTestClasses.size());
NEXT_CANDIDATE: for (Class<?> cls : nonTestClasses) {
for (Class<?> testClass : testClasses.get(cls)) {
if (hasTest(testClass, explicitTestNames)) {
// covered by explicit test
continue NEXT_CANDIDATE;
}
}
classesToTest.add(cls);
}
return classesToTest;
}
/** Returns null if no instance can be created. */
@Nullable private Object instantiate(Class<?> cls, TestErrorReporter errorReporter)
throws Exception {
if (cls.isEnum()) {
Object[] constants = cls.getEnumConstants();
if (constants.length > 0) {
return constants[0];
} else {
return null;
}
}
TypeToken<?> type = TypeToken.of(cls);
List<AssertionFailedError> errors = Lists.newArrayList();
List<InvocationTargetException> instantiationExceptions = Lists.newArrayList();
for (Invokable<?, ?> factory : getFactories(type)) {
List<Object> args;
try {
args = getDummyArguments(factory, errorReporter);
} catch (AssertionFailedError e) {
errors.add(e);
continue;
}
Object instance;
try {
instance = factory.invoke(null, args.toArray());
} catch (InvocationTargetException e) {
instantiationExceptions.add(e);
continue;
}
try {
assertNotNull(factory + " returns null and cannot be used to test instance methods.",
instance);
return instance;
} catch (AssertionFailedError e) {
errors.add(e);
}
}
if (!errors.isEmpty()) {
throw errors.get(0);
}
if (!instantiationExceptions.isEmpty()) {
throw instantiationExceptions.get(0);
}
return null;
}
private static List<Invokable<?, ?>> getFactories(TypeToken<?> type) {
List<Invokable<?, ?>> invokables = Lists.newArrayList();
for (Method method : type.getRawType().getMethods()) {
Invokable<?, ?> invokable = type.method(method);
if (invokable.isStatic() && type.isAssignableFrom(invokable.getReturnType())) {
invokables.add(invokable);
}
}
if (!Modifier.isAbstract(type.getRawType().getModifiers())) {
for (Constructor<?> constructor : type.getRawType().getConstructors()) {
invokables.add(type.constructor(constructor));
}
}
Collections.sort(invokables, LEAST_PARAMETERS_FIRST);
return invokables;
}
private List<Object> getDummyArguments(
Invokable<?, ?> invokable, TestErrorReporter errorReporter) {
List<Object> args = Lists.newArrayList();
for (Parameter param : invokable.getParameters()) {
Object defaultValue = getDummyValue(param.getType());
assertTrue(errorReporter.cannotDetermineParameterValue(invokable, param),
defaultValue != null || param.isAnnotationPresent(Nullable.class));
args.add(defaultValue);
}
return args;
}
private <T> T getDummyValue(TypeToken<T> type) {
Class<? super T> rawType = type.getRawType();
@SuppressWarnings("unchecked") // Assume all default values are generics safe.
T defaultValue = (T) defaultValues.getInstance(rawType);
if (defaultValue != null) {
return defaultValue;
}
@SuppressWarnings("unchecked") // ArbitraryInstances always returns generics-safe dummies.
T value = (T) ArbitraryInstances.get(rawType);
if (value != null) {
return value;
}
if (rawType.isInterface()) {
return new DummyProxy() {
@Override <R> R dummyReturnValue(TypeToken<R> returnType) {
return getDummyValue(returnType);
}
}.newProxy(type);
}
return null;
}
private List<Class<?>> loadPublicClassesInPackage() throws IOException {
List<Class<?>> classes = Lists.newArrayList();
String packageName = getClass().getPackage().getName();
for (ClassPath.ClassInfo classInfo
: ClassPath.from(getClass().getClassLoader()).getClasses(packageName)) {
Class<?> cls;
try {
cls = classInfo.load();
} catch (NoClassDefFoundError e) {
// In case there were linking problems, this is probably not a class we care to test anyway.
logger.log(Level.SEVERE, "Cannot load class " + classInfo + ", skipping...", e);
continue;
}
if (!cls.isInterface() && Modifier.isPublic(cls.getModifiers())) {
classes.add(cls);
}
}
return classes;
}
private static boolean hasTest(Class<?> testClass, Iterable<String> testNames) {
for (String testName : testNames) {
try {
testClass.getMethod(testName);
return true;
} catch (NoSuchMethodException e) {
continue;
}
}
return false;
}
private static boolean isEqualsDefined(Class<?> cls) {
try {
cls.getDeclaredMethod("equals", Object.class);
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
private enum TestErrorReporter {
FOR_NULLS_TEST {
@Override String suggestExplicitTest(Class<?> classToTest) {
return "Please explicitly test null checks in "
+ classToTest.getName() + "Test." + NULL_TEST_METHOD_NAMES.get(0) + "()";
}
},
FOR_SERIALIZABLE_TEST {
@Override String suggestExplicitTest(Class<?> classToTest) {
return "Please explicitly test serialization in "
+ classToTest.getName() + "Test." + SERIALIZABLE_TEST_METHOD_NAMES.get(0) + "()";
}
},
;
final String cannotDetermineParameterValue(Invokable<?, ?> factory, Parameter param) {
return "Cannot use " + factory + " to instantiate " + factory.getDeclaringClass()
+ " because default value of " + param + " cannot be determined.\n"
+ suggestExplicitTest(factory.getDeclaringClass());
}
abstract String suggestExplicitTest(Class<?> classToTest);
}
static abstract class Chopper {
final Chopper or(final Chopper you) {
final Chopper i = this;
return new Chopper() {
@Override Optional<String> chop(String str) {
return i.chop(str).or(you.chop(str));
}
};
}
abstract Optional<String> chop(String str);
static Chopper suffix(final String suffix) {
return new Chopper() {
@Override Optional<String> chop(String str) {
if (str.endsWith(suffix)) {
return Optional.of(str.substring(0, str.length() - suffix.length()));
} else {
return Optional.absent();
}
}
};
}
}
}
| 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.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.testing.RelationshipTester.RelationshipAssertion;
import java.util.List;
/**
* Tester for equals() and hashCode() methods of a class.
*
* <p>To use, create a new EqualsTester and add equality groups where each group
* contains objects that are supposed to be equal to each other, and objects of
* different groups are expected to be unequal. For example:
* <pre>
* new EqualsTester()
* .addEqualityGroup("hello", "h" + "ello")
* .addEqualityGroup("world", "wor" + "ld")
* .addEqualityGroup(2, 1 + 1)
* .testEquals();
* </pre>
* This tests:
* <ul>
* <li>comparing each object against itself returns true
* <li>comparing each object against null returns false
* <li>comparing each object an instance of an incompatible class returns false
* <li>comparing each pair of objects within the same equality group returns
* true
* <li>comparing each pair of objects from different equality groups returns
* false
* <li>the hash code of any two equal objects are equal
* </ul>
*
* <p>When a test fails, the error message labels the objects involved in
* the failed comparison as follows:
* <ul>
* <li>"{@code [group }<i>i</i>{@code , item }<i>j</i>{@code ]}" refers to the
* <i>j</i><sup>th</sup> item in the <i>i</i><sup>th</sup> equality group,
* where both equality groups and the items within equality groups are
* numbered starting from 1. When either a constructor argument or an
* equal object is provided, that becomes group 1.
* </ul>
*
* @author Jim McMaster
* @author Jige Yu
* @since 10.0
*/
@Beta
@GwtCompatible
public final class EqualsTester {
private static final int REPETITIONS = 3;
private final List<List<Object>> equalityGroups = Lists.newArrayList();
/**
* Constructs an empty EqualsTester instance
*/
public EqualsTester() {}
/**
* Adds {@code equalityGroup} with objects that are supposed to be equal to
* each other and not equal to any other equality groups added to this tester.
*/
public EqualsTester addEqualityGroup(Object... equalityGroup) {
checkNotNull(equalityGroup);
equalityGroups.add(ImmutableList.copyOf(equalityGroup));
return this;
}
/**
* Run tests on equals method, throwing a failure on an invalid test
*/
public EqualsTester testEquals() {
RelationshipTester<Object> delegate = new RelationshipTester<Object>(
new RelationshipAssertion<Object>() {
@Override public void assertRelated(Object item, Object related) {
assertEquals("$ITEM must be equal to $RELATED", item, related);
int itemHash = item.hashCode();
int relatedHash = related.hashCode();
assertEquals("the hash (" + itemHash + ") of $ITEM must be equal to the hash ("
+ relatedHash +") of $RELATED", itemHash, relatedHash);
}
@Override public void assertUnrelated(Object item, Object unrelated) {
// TODO(cpovirk): should this implementation (and
// RelationshipAssertions in general) accept null inputs?
assertTrue("$ITEM must be unequal to $UNRELATED", !Objects.equal(item, unrelated));
}
});
for (List<Object> group : equalityGroups) {
delegate.addRelatedGroup(group);
}
for (int run = 0; run < REPETITIONS; run++) {
testItems();
delegate.test();
}
return this;
}
private void testItems() {
for (Object item : Iterables.concat(equalityGroups)) {
assertTrue(item + " must be unequal to null", !item.equals(null));
assertTrue(item + " must be unequal to an arbitrary object of another class",
!item.equals(NotAnInstance.EQUAL_TO_NOTHING));
assertEquals(item + " must be equal to itself", item, item);
assertEquals("the hash of " + item + " must be consistent", item.hashCode(), item.hashCode());
}
}
/**
* Class used to test whether equals() correctly handles an instance
* of an incompatible class. Since it is a private inner class, the
* invoker can never pass in an instance to the tester
*/
private enum NotAnInstance {
EQUAL_TO_NOTHING;
}
}
| Java |
/*
* Copyright (C) 2005 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.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MutableClassToInstanceMap;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.Reflection;
import com.google.common.reflect.TypeToken;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
/**
* A test utility that verifies that your methods and constructors throw {@link
* NullPointerException} or {@link UnsupportedOperationException} whenever null
* is passed to a parameter that isn't annotated with {@link Nullable}.
*
* <p>The tested methods and constructors are invoked -- each time with one
* parameter being null and the rest not null -- and the test fails if no
* expected exception is thrown. {@code NullPointerTester} uses best effort to
* pick non-null default values for many common JDK and Guava types, and also
* for interfaces and public classes that have public parameter-less
* constructors. When the non-null default value for a particular parameter type
* cannot be provided by {@code NullPointerTester}, the caller can provide a
* custom non-null default value for the parameter type via {@link #setDefault}.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
public final class NullPointerTester {
private final ClassToInstanceMap<Object> defaults =
MutableClassToInstanceMap.create();
private final List<Member> ignoredMembers = Lists.newArrayList();
/**
* Sets a default value that can be used for any parameter of type
* {@code type}. Returns this object.
*/
public <T> NullPointerTester setDefault(Class<T> type, T value) {
defaults.put(type, checkNotNull(value));
return this;
}
/**
* Ignore {@code method} in the tests that follow. Returns this object.
*
* @since 13.0
*/
public NullPointerTester ignore(Method method) {
ignoredMembers.add(checkNotNull(method));
return this;
}
/**
* Runs {@link #testConstructor} on every constructor in class {@code c} that
* has at least {@code minimalVisibility}.
*/
public void testConstructors(Class<?> c, Visibility minimalVisibility) {
for (Constructor<?> constructor : c.getDeclaredConstructors()) {
if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) {
testConstructor(constructor);
}
}
}
/**
* Runs {@link #testConstructor} on every public constructor in class {@code
* c}.
*/
public void testAllPublicConstructors(Class<?> c) {
testConstructors(c, Visibility.PUBLIC);
}
/**
* Runs {@link #testMethod} on every static method of class {@code c} that has
* at least {@code minimalVisibility}, including those "inherited" from
* superclasses of the same package.
*/
public void testStaticMethods(Class<?> c, Visibility minimalVisibility) {
for (Method method : minimalVisibility.getStaticMethods(c)) {
if (!isIgnored(method)) {
testMethod(null, method);
}
}
}
/**
* Runs {@link #testMethod} on every public static method of class {@code c},
* including those "inherited" from superclasses of the same package.
*/
public void testAllPublicStaticMethods(Class<?> c) {
testStaticMethods(c, Visibility.PUBLIC);
}
/**
* Runs {@link #testMethod} on every instance method of the class of
* {@code instance} with at least {@code minimalVisibility}, including those
* inherited from superclasses of the same package.
*/
public void testInstanceMethods(
Object instance, Visibility minimalVisibility) {
Class<?> c = instance.getClass();
for (Method method : minimalVisibility.getInstanceMethods(c)) {
if (!isIgnored(method)) {
testMethod(instance, method);
}
}
}
/**
* Runs {@link #testMethod} on every public instance method of the class of
* {@code instance}, including those inherited from superclasses of the same
* package.
*/
public void testAllPublicInstanceMethods(Object instance) {
testInstanceMethods(instance, Visibility.PUBLIC);
}
/**
* Verifies that {@code method} produces a {@link NullPointerException}
* or {@link UnsupportedOperationException} whenever <i>any</i> of its
* non-{@link Nullable} parameters are null.
*
* @param instance the instance to invoke {@code method} on, or null if
* {@code method} is static
*/
public void testMethod(@Nullable Object instance, Method method) {
Class<?>[] types = method.getParameterTypes();
for (int nullIndex = 0; nullIndex < types.length; nullIndex++) {
testMethodParameter(instance, method, nullIndex);
}
}
/**
* Verifies that {@code ctor} produces a {@link NullPointerException} or
* {@link UnsupportedOperationException} whenever <i>any</i> of its
* non-{@link Nullable} parameters are null.
*/
public void testConstructor(Constructor<?> ctor) {
Class<?>[] types = ctor.getParameterTypes();
for (int nullIndex = 0; nullIndex < types.length; nullIndex++) {
testConstructorParameter(ctor, nullIndex);
}
}
/**
* Verifies that {@code method} produces a {@link NullPointerException} or
* {@link UnsupportedOperationException} when the parameter in position {@code
* paramIndex} is null. If this parameter is marked {@link Nullable}, this
* method does nothing.
*
* @param instance the instance to invoke {@code method} on, or null if
* {@code method} is static
*/
public void testMethodParameter(
@Nullable final Object instance, final Method method, int paramIndex) {
method.setAccessible(true);
testParameter(instance, invokable(instance, method), paramIndex, method.getDeclaringClass());
}
/**
* Verifies that {@code ctor} produces a {@link NullPointerException} or
* {@link UnsupportedOperationException} when the parameter in position {@code
* paramIndex} is null. If this parameter is marked {@link Nullable}, this
* method does nothing.
*/
public void testConstructorParameter(
final Constructor<?> ctor, int paramIndex) {
ctor.setAccessible(true);
testParameter(null, Invokable.from(ctor), paramIndex, ctor.getDeclaringClass());
}
/** Visibility of any method or constructor. */
public enum Visibility {
PACKAGE {
@Override boolean isVisible(int modifiers) {
return !Modifier.isPrivate(modifiers);
}
},
PROTECTED {
@Override boolean isVisible(int modifiers) {
return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers);
}
},
PUBLIC {
@Override boolean isVisible(int modifiers) {
return Modifier.isPublic(modifiers);
}
};
abstract boolean isVisible(int modifiers);
/**
* Returns {@code true} if {@code member} is visible under {@code this}
* visibility.
*/
final boolean isVisible(Member member) {
return isVisible(member.getModifiers());
}
final Iterable<Method> getStaticMethods(Class<?> cls) {
ImmutableList.Builder<Method> builder = ImmutableList.builder();
for (Method method : getVisibleMethods(cls)) {
if (Invokable.from(method).isStatic()) {
builder.add(method);
}
}
return builder.build();
}
final Iterable<Method> getInstanceMethods(Class<?> cls) {
ConcurrentMap<Signature, Method> map = Maps.newConcurrentMap();
for (Method method : getVisibleMethods(cls)) {
if (!Invokable.from(method).isStatic()) {
map.putIfAbsent(new Signature(method), method);
}
}
return map.values();
}
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
// Don't use cls.getPackage() because it does nasty things like reading
// a file.
String visiblePackage = Reflection.getPackageName(cls);
ImmutableList.Builder<Method> builder = ImmutableList.builder();
for (Class<?> type : TypeToken.of(cls).getTypes().classes().rawTypes()) {
if (!Reflection.getPackageName(type).equals(visiblePackage)) {
break;
}
for (Method method : type.getDeclaredMethods()) {
if (!method.isSynthetic() && isVisible(method)) {
builder.add(method);
}
}
}
return builder.build();
}
}
// TODO(benyu): Use labs/reflect/Signature if it graduates.
private static final class Signature {
private final String name;
private final ImmutableList<Class<?>> parameterTypes;
Signature(Method method) {
this(method.getName(), ImmutableList.copyOf(method.getParameterTypes()));
}
Signature(String name, ImmutableList<Class<?>> parameterTypes) {
this.name = name;
this.parameterTypes = parameterTypes;
}
@Override public boolean equals(Object obj) {
if (obj instanceof Signature) {
Signature that = (Signature) obj;
return name.equals(that.name)
&& parameterTypes.equals(that.parameterTypes);
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(name, parameterTypes);
}
}
/**
* Verifies that {@code invokable} produces a {@link NullPointerException} or
* {@link UnsupportedOperationException} when the parameter in position {@code
* paramIndex} is null. If this parameter is marked {@link Nullable}, this
* method does nothing.
*
* @param instance the instance to invoke {@code invokable} on, or null if
* {@code invokable} is static
*/
private void testParameter(Object instance, Invokable<?, ?> invokable,
int paramIndex, Class<?> testedClass) {
if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) {
return; // there's nothing to test
}
Object[] params = buildParamList(invokable, paramIndex);
try {
@SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong.
Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable;
unsafe.invoke(instance, params);
Assert.fail("No exception thrown from " + invokable +
Arrays.toString(params) + " for " + testedClass);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof NullPointerException ||
cause instanceof UnsupportedOperationException) {
return;
}
AssertionFailedError error = new AssertionFailedError(
"wrong exception thrown from " + invokable + ": " + cause);
error.initCause(cause);
throw error;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
ImmutableList<Parameter> params = invokable.getParameters();
Object[] args = new Object[params.size()];
for (int i = 0; i < args.length; i++) {
Parameter param = params.get(i);
if (i != indexOfParamToSetToNull) {
args[i] = getDefaultValue(param.getType());
if (!isPrimitiveOrNullable(param)) {
Assert.assertTrue("No default value found for " + param + " of "+ invokable,
args[i] != null);
}
}
}
return args;
}
private <T> T getDefaultValue(TypeToken<T> type) {
// We assume that all defaults are generics-safe, even if they aren't,
// we take the risk.
@SuppressWarnings("unchecked")
T defaultValue = (T) defaults.getInstance(type.getRawType());
if (defaultValue != null) {
return defaultValue;
}
@SuppressWarnings("unchecked") // All null values are generics-safe
T nullValue = (T) ArbitraryInstances.get(type.getRawType());
if (nullValue != null) {
return nullValue;
}
if (type.getRawType() == Class.class) {
// If parameter is Class<? extends Foo>, we return Foo.class
@SuppressWarnings("unchecked")
T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType();
return defaultClass;
}
if (type.getRawType() == TypeToken.class) {
// If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>.
@SuppressWarnings("unchecked")
T defaultType = (T) getFirstTypeParameter(type.getType());
return defaultType;
}
if (type.getRawType().isInterface()) {
return newDefaultReturningProxy(type);
}
return null;
}
private static TypeToken<?> getFirstTypeParameter(Type type) {
if (type instanceof ParameterizedType) {
return TypeToken.of(
((ParameterizedType) type).getActualTypeArguments()[0]);
} else {
return TypeToken.of(Object.class);
}
}
private <T> T newDefaultReturningProxy(final TypeToken<T> type) {
return new DummyProxy() {
@Override <R> R dummyReturnValue(TypeToken<R> returnType) {
return getDefaultValue(returnType);
}
}.newProxy(type);
}
private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) {
if (instance == null) {
return Invokable.from(method);
} else {
return TypeToken.of(instance.getClass()).method(method);
}
}
private static boolean isPrimitiveOrNullable(Parameter param) {
return param.getType().getRawType().isPrimitive() || param.isAnnotationPresent(Nullable.class);
}
private boolean isIgnored(Member member) {
return member.isSynthetic() || ignoredMembers.contains(member);
}
}
| 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.testing;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
/**
* Tests serialization and deserialization of an object, optionally asserting
* that the resulting object is equal to the original.
*
* <p><b>GWT warning:</b> Under GWT, both methods simply returns their input,
* as proper GWT serialization tests require more setup. This no-op behavior
* allows test authors to intersperse {@code SerializableTester} calls with
* other, GWT-compatible tests.
*
*
* @author Mike Bostock
* @since 10.0
*/
@Beta
@GwtCompatible // but no-op!
public final class SerializableTester {
private SerializableTester() {}
/**
* Serializes and deserializes the specified object.
*
* <p><b>GWT warning:</b> Under GWT, this method simply returns its input, as
* proper GWT serialization tests require more setup. This no-op behavior
* allows test authors to intersperse {@code SerializableTester} calls with
* other, GWT-compatible tests.
*
* <p>Note that the specified object may not be known by the compiler to be a
* {@link java.io.Serializable} instance, and is thus declared an
* {@code Object}. For example, it might be declared as a {@code List}.
*
* @return the re-serialized object
* @throws RuntimeException if the specified object was not successfully
* serialized or deserialized
*/
@SuppressWarnings("unchecked")
public static <T> T reserialize(T object) {
return Platform.reserialize(object);
}
/**
* Serializes and deserializes the specified object and verifies that the
* re-serialized object is equal to the provided object, that the hashcodes
* are identical, and that the class of the re-serialized object is identical
* to that of the original.
*
* <p><b>GWT warning:</b> Under GWT, this method simply returns its input, as
* proper GWT serialization tests require more setup. This no-op behavior
* allows test authors to intersperse {@code SerializableTester} calls with
* other, GWT-compatible tests.
*
* <p>Note that the specified object may not be known by the compiler to be a
* {@link java.io.Serializable} instance, and is thus declared an
* {@code Object}. For example, it might be declared as a {@code List}.
*
* <p>Note also that serialization is not in general required to return an
* object that is {@linkplain Object#equals equal} to the original, nor is it
* required to return even an object of the same class. For example, if
* sublists of {@code MyList} instances were serializable, those sublists
* might implement a private {@code MySubList} type but serialize as a plain
* {@code MyList} to save space. So long as {@code MyList} has all the public
* supertypes of {@code MySubList}, this is safe. For these cases, for which
* {@code reserializeAndAssert} is too strict, use {@link #reserialize}.
*
* @return the re-serialized object
* @throws RuntimeException if the specified object was not successfully
* serialized or deserialized
* @throws AssertionFailedError if the re-serialized object is not equal to
* the original object, or if the hashcodes are different.
*/
public static <T> T reserializeAndAssert(T object) {
T copy = reserialize(object);
new EqualsTester()
.addEqualityGroup(object, copy)
.testEquals();
Assert.assertEquals(object.getClass(), copy.getClass());
return copy;
}
}
| 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.testing;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.Beta;
import java.lang.ref.WeakReference;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
/**
* Testing utilities relating to garbage collection finalization.
*
* <p>Use this class to test code triggered by <em>finalization</em>, that is, one of the
* following actions taken by the java garbage collection system:
*
* <ul>
* <li>invoking the {@code finalize} methods of unreachable objects
* <li>clearing weak references to unreachable referents
* <li>enqueuing weak references to unreachable referents in their reference queue
* </ul>
*
* <p>This class uses (possibly repeated) invocations of {@link java.lang.System#gc()} to cause
* finalization to happen. However, a call to {@code System.gc()} is specified to be no more
* than a hint, so this technique may fail at the whim of the JDK implementation, for example if
* a user specified the JVM flag {@code -XX:+DisableExplicitGC}. But in practice, it works very
* well for ordinary tests.
*
* <p>Failure of the expected event to occur within an implementation-defined "reasonable" time
* period or an interrupt while waiting for the expected event will result in a {@link
* RuntimeException}.
*
* <p>Here's an example that tests a {@code finalize} method:
*
* <pre> {@code
* final CountDownLatch latch = new CountDownLatch(1);
* Object x = new MyClass() {
* ...
* protected void finalize() { latch.countDown(); ... }
* };
* x = null; // Hint to the JIT that x is stack-unreachable
* GcFinalization.await(latch);
* }</pre>
*
* <p>Here's an example that uses a user-defined finalization predicate:
*
* <pre> {@code
* final WeakHashMap<Object, Object> map = new WeakHashMap<Object, Object>();
* map.put(new Object(), Boolean.TRUE);
* GcFinalization.awaitDone(new FinalizationPredicate() {
* public boolean isDone() {
* return map.isEmpty();
* }
* });
* }</pre>
*
* <p>Even if your non-test code does not use finalization, you can
* use this class to test for leaks, by ensuring that objects are no
* longer strongly referenced:
*
* <pre> {@code
* // Helper function keeps victim stack-unreachable.
* private WeakReference<Foo> fooWeakRef() {
* Foo x = ....;
* WeakReference<Foo> weakRef = new WeakReference<Foo>(x);
* // ... use x ...
* x = null; // Hint to the JIT that x is stack-unreachable
* return weakRef;
* }
* public void testFooLeak() {
* GcFinalization.awaitClear(fooWeakRef());
* }}</pre>
*
* <p>This class cannot currently be used to test soft references, since this class does not try to
* create the memory pressure required to cause soft references to be cleared.
*
* <p>This class only provides testing utilities. It is not designed for direct use in production
* or for benchmarking.
*
* @author mike nonemacher
* @author Martin Buchholz
* @since 11.0
*/
@Beta
public final class GcFinalization {
private GcFinalization() {}
/**
* 10 seconds ought to be long enough for any object to be GC'ed and finalized. Unless we have a
* gigantic heap, in which case we scale by heap size.
*/
private static long timeoutSeconds() {
// This class can make no hard guarantees. The methods in this class are inherently flaky, but
// we try hard to make them robust in practice. We could additionally try to add in a system
// load timeout multiplier. Or we could try to use a CPU time bound instead of wall clock time
// bound. But these ideas are harder to implement. We do not try to detect or handle a
// user-specified -XX:+DisableExplicitGC.
//
// TODO(user): Consider using
// java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage()
//
// TODO(user): Consider scaling by number of mutator threads,
// e.g. using Thread#activeCount()
return Math.max(10L, Runtime.getRuntime().totalMemory() / (32L * 1024L * 1024L));
}
/**
* Waits until the given future {@linkplain Future#isDone is done}, invoking the garbage
* collector as necessary to try to ensure that this will happen.
*
* @throws RuntimeException if timed out or interrupted while waiting
*/
public static void awaitDone(Future<?> future) {
if (future.isDone()) {
return;
}
final long timeoutSeconds = timeoutSeconds();
final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
do {
System.runFinalization();
if (future.isDone()) {
return;
}
System.gc();
try {
future.get(1L, SECONDS);
return;
} catch (CancellationException ok) {
return;
} catch (ExecutionException ok) {
return;
} catch (InterruptedException ie) {
throw new RuntimeException("Unexpected interrupt while waiting for future", ie);
} catch (TimeoutException tryHarder) {
/* OK */
}
} while (System.nanoTime() - deadline < 0);
throw new RuntimeException(
String.format("Future not done within %d second timeout", timeoutSeconds));
}
/**
* Waits until the given latch has {@linkplain CountDownLatch#countDown counted down} to zero,
* invoking the garbage collector as necessary to try to ensure that this will happen.
*
* @throws RuntimeException if timed out or interrupted while waiting
*/
public static void await(CountDownLatch latch) {
if (latch.getCount() == 0) {
return;
}
final long timeoutSeconds = timeoutSeconds();
final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
do {
System.runFinalization();
if (latch.getCount() == 0) {
return;
}
System.gc();
try {
if (latch.await(1L, SECONDS)) {
return;
}
} catch (InterruptedException ie) {
throw new RuntimeException("Unexpected interrupt while waiting for latch", ie);
}
} while (System.nanoTime() - deadline < 0);
throw new RuntimeException(
String.format("Latch failed to count down within %d second timeout", timeoutSeconds));
}
/**
* Creates a garbage object that counts down the latch in its finalizer. Sequestered into a
* separate method to make it somewhat more likely to be unreachable.
*/
private static void createUnreachableLatchFinalizer(final CountDownLatch latch) {
new Object() { @Override protected void finalize() { latch.countDown(); }};
}
/**
* A predicate that is expected to return true subsequent to <em>finalization</em>, that is, one
* of the following actions taken by the garbage collector when performing a full collection in
* response to {@link System#gc()}:
*
* <ul>
* <li>invoking the {@code finalize} methods of unreachable objects
* <li>clearing weak references to unreachable referents
* <li>enqueuing weak references to unreachable referents in their reference queue
* </ul>
*/
public interface FinalizationPredicate {
boolean isDone();
}
/**
* Waits until the given predicate returns true, invoking the garbage collector as necessary to
* try to ensure that this will happen.
*
* @throws RuntimeException if timed out or interrupted while waiting
*/
public static void awaitDone(FinalizationPredicate predicate) {
if (predicate.isDone()) {
return;
}
final long timeoutSeconds = timeoutSeconds();
final long deadline = System.nanoTime() + SECONDS.toNanos(timeoutSeconds);
do {
System.runFinalization();
if (predicate.isDone()) {
return;
}
CountDownLatch done = new CountDownLatch(1);
createUnreachableLatchFinalizer(done);
await(done);
if (predicate.isDone()) {
return;
}
} while (System.nanoTime() - deadline < 0);
throw new RuntimeException(
String.format("Predicate did not become true within %d second timeout", timeoutSeconds));
}
/**
* Waits until the given weak reference is cleared, invoking the garbage collector as necessary
* to try to ensure that this will happen.
*
* <p>This is a convenience method, equivalent to:
* <pre> {@code
* awaitDone(new FinalizationPredicate() {
* public boolean isDone() {
* return ref.get() == null;
* }
* });
* }</pre>
*
* @throws RuntimeException if timed out or interrupted while waiting
*/
public static void awaitClear(final WeakReference<?> ref) {
awaitDone(new FinalizationPredicate() {
public boolean isDone() {
return ref.get() == null;
}
});
}
/**
* Tries to perform a "full" garbage collection cycle (including processing of weak references
* and invocation of finalize methods) and waits for it to complete. Ensures that at least one
* weak reference has been cleared and one {@code finalize} method has been run before this
* method returns. This method may be useful when testing the garbage collection mechanism
* itself, or inhibiting a spontaneous GC initiation in subsequent code.
*
* <p>In contrast, a plain call to {@link java.lang.System#gc()} does not ensure finalization
* processing and may run concurrently, for example, if the JVM flag {@code
* -XX:+ExplicitGCInvokesConcurrent} is used.
*
* <p>Whenever possible, it is preferable to test directly for some observable change resulting
* from GC, as with {@link #awaitClear}. Because there are no guarantees for the order of GC
* finalization processing, there may still be some unfinished work for the GC to do after this
* method returns.
*
* <p>This method does not create any memory pressure as would be required to cause soft
* references to be processed.
*
* @throws RuntimeException if timed out or interrupted while waiting
* @since 12.0
*/
public static void awaitFullGc() {
final CountDownLatch finalizerRan = new CountDownLatch(1);
WeakReference<Object> ref = new WeakReference<Object>(
new Object() {
@Override protected void finalize() { finalizerRan.countDown(); }
});
await(finalizerRan);
awaitClear(ref);
// Hope to catch some stragglers queued up behind our finalizable object
System.runFinalization();
}
}
| 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.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Chris Povirk
*/
final class Platform {
/**
* Serializes and deserializes the specified object.
*/
@SuppressWarnings("unchecked")
static <T> T reserialize(T object) {
checkNotNull(object);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(object);
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()));
return (T) in.readObject();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private Platform() {}
}
| 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.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import junit.framework.AssertionFailedError;
import java.util.List;
/**
* Tests a collection of objects according to the rules specified in a
* {@link RelationshipAssertion}.
*
* @author Gregory Kick
*/
@GwtCompatible
final class RelationshipTester<T> {
private final List<ImmutableList<T>> groups = Lists.newArrayList();
private final RelationshipAssertion<T> assertion;
RelationshipTester(RelationshipAssertion<T> assertion) {
this.assertion = checkNotNull(assertion);
}
public RelationshipTester<T> addRelatedGroup(Iterable<? extends T> group) {
groups.add(ImmutableList.copyOf(group));
return this;
}
public void test() {
for (int groupNumber = 0; groupNumber < groups.size(); groupNumber++) {
ImmutableList<T> group = groups.get(groupNumber);
for (int itemNumber = 0; itemNumber < group.size(); itemNumber++) {
// check related items in same group
for (int relatedItemNumber = 0; relatedItemNumber < group.size(); relatedItemNumber++) {
if (itemNumber != relatedItemNumber) {
assertRelated(groupNumber, itemNumber, relatedItemNumber);
}
}
// check unrelated items in all other groups
for (int unrelatedGroupNumber = 0; unrelatedGroupNumber < groups.size();
unrelatedGroupNumber++) {
if (groupNumber != unrelatedGroupNumber) {
ImmutableList<T> unrelatedGroup = groups.get(unrelatedGroupNumber);
for (int unrelatedItemNumber = 0; unrelatedItemNumber < unrelatedGroup.size();
unrelatedItemNumber++) {
assertUnrelated(groupNumber, itemNumber, unrelatedGroupNumber, unrelatedItemNumber);
}
}
}
}
}
}
private void assertRelated(int groupNumber, int itemNumber, int relatedItemNumber) {
ImmutableList<T> group = groups.get(groupNumber);
T item = group.get(itemNumber);
T related = group.get(relatedItemNumber);
try {
assertion.assertRelated(item, related);
} catch (AssertionFailedError e) {
// TODO(gak): special handling for ComparisonFailure?
throw new AssertionFailedError(e.getMessage()
.replace("$ITEM", itemString(item, groupNumber, itemNumber))
.replace("$RELATED", itemString(related, groupNumber, relatedItemNumber)));
}
}
private void assertUnrelated(int groupNumber, int itemNumber, int unrelatedGroupNumber,
int unrelatedItemNumber) {
T item = groups.get(groupNumber).get(itemNumber);
T unrelated = groups.get(unrelatedGroupNumber).get(unrelatedItemNumber);
try {
assertion.assertUnrelated(item, unrelated);
} catch (AssertionFailedError e) {
// TODO(gak): special handling for ComparisonFailure?
throw new AssertionFailedError(e.getMessage()
.replace("$ITEM", itemString(item, groupNumber, itemNumber))
.replace("$UNRELATED", itemString(unrelated, unrelatedGroupNumber, unrelatedItemNumber)));
}
}
private static String itemString(Object item, int groupNumber, int itemNumber) {
return new StringBuilder()
.append(item)
.append(" [group ")
.append(groupNumber + 1)
.append(", item ")
.append(itemNumber + 1)
.append(']')
.toString();
}
/**
* A strategy for testing the relationship between objects. Methods are expected to throw
* {@link AssertionFailedError} whenever the relationship is violated.
*
* <p>As a convenience, any occurrence of {@code $ITEM}, {@code $RELATED} or {@code $UNRELATED} in
* the error message will be replaced with a string that combines the {@link Object#toString()},
* item number and group number of the respective item.
*
*/
interface RelationshipAssertion<T> {
void assertRelated(T item, T related);
void assertUnrelated(T item, T unrelated);
}
}
| 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.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A {@code TearDownStack} contains a stack of {@link TearDown} instances.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
@GwtCompatible
public class TearDownStack implements TearDownAccepter {
public static final Logger logger
= Logger.getLogger(TearDownStack.class.getName());
final LinkedList<TearDown> stack = new LinkedList<TearDown>();
private final boolean suppressThrows;
public TearDownStack() {
this.suppressThrows = false;
}
public TearDownStack(boolean suppressThrows) {
this.suppressThrows = suppressThrows;
}
@Override
public final void addTearDown(TearDown tearDown) {
stack.addFirst(checkNotNull(tearDown));
}
/**
* Causes teardown to execute.
*/
public final void runTearDown() {
List<Throwable> exceptions = new ArrayList<Throwable>();
for (TearDown tearDown : stack) {
try {
tearDown.tearDown();
} catch (Throwable t) {
if (suppressThrows) {
TearDownStack.logger.log(Level.INFO,
"exception thrown during tearDown: " + t.getMessage(), t);
} else {
exceptions.add(t);
}
}
}
stack.clear();
if ((!suppressThrows) && (exceptions.size() > 0)) {
throw ClusterException.create(exceptions);
}
}
}
| 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.testing;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* Any object which can accept registrations of {@link TearDown} instances.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
@GwtCompatible
public interface TearDownAccepter {
/**
* Registers a TearDown implementor which will be run after the test proper.
*
* <p>In JUnit4 language, that means as an {@code @After}.
*
* <p>In JUnit3 language, that means during the
* {@link junit.framework.TestCase#tearDown()} step.
*/
void addTearDown(TearDown tearDown);
}
| 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.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Equivalence;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.base.Ticker;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.primitives.Primitives;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Reflection;
import com.google.common.reflect.TypeToken;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.StringReader;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
/**
* Generates fresh instances of types that are different from each other (if possible).
*
* @author Ben Yu
*/
class FreshValueGenerator {
private final AtomicInteger differentiator = new AtomicInteger(1);
private final ListMultimap<Class<?>, Object> sampleInstances = ArrayListMultimap.create();
<T> void addSampleInstances(Class<T> type, Iterable<? extends T> instances) {
sampleInstances.putAll(checkNotNull(type), checkNotNull(instances));
}
final <T> T generate(Class<T> type) {
List<Object> samples = sampleInstances.get(type);
@SuppressWarnings("unchecked") // sampleInstances is always registered by type.
T sample = (T) nextInstance(samples, null);
if (sample != null) {
return sample;
}
for (Method method : FreshValueGenerator.class.getDeclaredMethods()) {
if (method.isAnnotationPresent(Generates.class)) {
if (Primitives.wrap(type).isAssignableFrom(Primitives.wrap(method.getReturnType()))) {
try {
@SuppressWarnings("unchecked") // protected by isAssignableFrom
T result = (T) method.invoke(this);
return result;
} catch (InvocationTargetException e) {
Throwables.propagate(e.getCause());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
}
if (type.isInterface()) {
// always create a new proxy
return newProxy(type);
}
if (type.isEnum()) {
return nextInstance(type.getEnumConstants(), null);
}
return ArbitraryInstances.get(type);
}
private <T> T nextInstance(T[] instances, T defaultValue) {
return nextInstance(Arrays.asList(instances), defaultValue);
}
private <T> T nextInstance(Collection<T> instances, T defaultValue) {
if (instances.isEmpty()) {
return defaultValue;
}
// freshInt() is 1-based.
return Iterables.get(instances, (freshInt() - 1) % instances.size());
}
final <T> T newProxy(final Class<T> interfaceType) {
final int identity = freshInt();
return Reflection.newProxy(interfaceType, new AbstractInvocationHandler() {
@Override protected Object handleInvocation(Object proxy, Method method, Object[] args) {
return interfaceMethodCalled(interfaceType, method);
}
@Override public String toString() {
return paramString(interfaceType, identity);
}
});
}
/** Subclasses can override to provide different return value for proxied interface methods. */
Object interfaceMethodCalled(
@SuppressWarnings("unused") Class<?> interfaceType,
@SuppressWarnings("unused") Method method) {
throw new UnsupportedOperationException();
}
private static String paramString(Class<?> type, int i) {
return type.getSimpleName() + '@' + i;
}
/** Annotates a method to be the instance supplier of a certain type. */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
private @interface Generates {}
@Generates private Class<?> freshClass() {
return nextInstance(
ImmutableList.of(
int.class, long.class, void.class,
Object.class, Object[].class, Iterable.class),
Object.class);
}
@Generates private int freshInt() {
return differentiator.getAndIncrement();
}
@Generates private long freshLong() {
return freshInt();
}
@SuppressWarnings("unused")
@Generates private float freshFloat() {
return freshInt();
}
@SuppressWarnings("unused")
@Generates private double freshDouble() {
return freshInt();
}
@SuppressWarnings("unused")
@Generates private short freshShort() {
return (short) freshInt();
}
@SuppressWarnings("unused")
@Generates private byte freshByte() {
return (byte) freshInt();
}
@SuppressWarnings("unused")
@Generates private char freshChar() {
return freshString().charAt(0);
}
@SuppressWarnings("unused")
@Generates private boolean freshBoolean() {
return freshInt() % 2 == 0;
}
@SuppressWarnings("unused")
@Generates private UnsignedInteger freshUnsignedInteger() {
return UnsignedInteger.asUnsigned(freshInt());
}
@SuppressWarnings("unused")
@Generates private UnsignedLong freshUnsignedLong() {
return UnsignedLong.asUnsigned(freshLong());
}
@SuppressWarnings("unused")
@Generates private BigInteger freshBigInteger() {
return BigInteger.valueOf(freshInt());
}
@SuppressWarnings("unused")
@Generates private BigDecimal freshBigDecimal() {
return BigDecimal.valueOf(freshInt());
}
@Generates private String freshString() {
return Integer.toString(freshInt());
}
@SuppressWarnings("unused")
@Generates private Pattern freshPattern() {
return Pattern.compile(freshString());
}
@SuppressWarnings("unused")
@Generates private Charset freshCharset() {
return nextInstance(Charset.availableCharsets().values(), Charsets.UTF_8);
}
@Generates private Locale freshLocale() {
return nextInstance(Locale.getAvailableLocales(), Locale.US);
}
@SuppressWarnings("unused")
@Generates private Currency freshCurrency() {
for (Set<Locale> uselessLocales = Sets.newHashSet(); ; ) {
Locale locale = freshLocale();
if (uselessLocales.contains(locale)) { // exhausted all locales
return Currency.getInstance(Locale.US);
}
try {
return Currency.getInstance(locale);
} catch (IllegalArgumentException e) {
uselessLocales.add(locale);
}
}
}
// common.base
@SuppressWarnings("unused")
@Generates private Joiner freshJoiner() {
return Joiner.on(freshString());
}
@SuppressWarnings("unused")
@Generates private Splitter freshSplitter() {
return Splitter.on(freshString());
}
@SuppressWarnings("unused")
@Generates private <T> Equivalence<T> freshEquivalence() {
return new Equivalence<T>() {
@Override protected boolean doEquivalent(T a, T b) {
return false;
}
@Override protected int doHash(T t) {
return 0;
}
final String string = paramString(Equivalence.class, freshInt());
@Override public String toString() {
return string;
}
};
}
@SuppressWarnings("unused")
@Generates private CharMatcher freshCharMatcher() {
return new CharMatcher() {
@Override public boolean matches(char c) {
return false;
}
final String string = paramString(CharMatcher.class, freshInt());
@Override public String toString() {
return string;
}
};
}
@SuppressWarnings("unused")
@Generates private Ticker freshTicker() {
return new Ticker() {
@Override public long read() {
return 0;
}
final String string = paramString(Ticker.class, freshInt());
@Override public String toString() {
return string;
}
};
}
// common.collect
@SuppressWarnings("unused")
@Generates private <T> Ordering<T> freshOrdering() {
return new Ordering<T>() {
@Override public int compare(T left, T right) {
return 0;
}
final String string = paramString(Ordering.class, freshInt());
@Override public String toString() {
return string;
}
};
}
// common.reflect
@SuppressWarnings("unused")
@Generates private TypeToken<?> freshTypeToken() {
return TypeToken.of(freshClass());
}
// io types
@SuppressWarnings("unused")
@Generates private File freshFile() {
return new File(freshString());
}
@SuppressWarnings("unused")
@Generates private static ByteArrayInputStream freshInputStream() {
return new ByteArrayInputStream(new byte[0]);
}
@SuppressWarnings("unused")
@Generates private StringReader freshStringReader() {
return new StringReader(freshString());
}
@SuppressWarnings("unused")
@Generates private CharBuffer freshCharBuffer() {
return CharBuffer.allocate(freshInt());
}
@SuppressWarnings("unused")
@Generates private ByteBuffer freshByteBuffer() {
return ByteBuffer.allocate(freshInt());
}
@SuppressWarnings("unused")
@Generates private ShortBuffer freshShortBuffer() {
return ShortBuffer.allocate(freshInt());
}
@SuppressWarnings("unused")
@Generates private IntBuffer freshIntBuffer() {
return IntBuffer.allocate(freshInt());
}
@SuppressWarnings("unused")
@Generates private LongBuffer freshLongBuffer() {
return LongBuffer.allocate(freshInt());
}
@SuppressWarnings("unused")
@Generates private FloatBuffer freshFloatBuffer() {
return FloatBuffer.allocate(freshInt());
}
@SuppressWarnings("unused")
@Generates private DoubleBuffer freshDoubleBuffer() {
return DoubleBuffer.allocate(freshInt());
}
}
| 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.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* An {@link ClusterException} is a data structure that allows for some code to
* "throw multiple exceptions", or something close to it. The prototypical code
* that calls for this class is presented below:
*
* <pre>
* void runManyThings(List<ThingToRun> thingsToRun) {
* for (ThingToRun thingToRun : thingsToRun) {
* thingToRun.run(); // <-- say this may throw an exception, but you want to
* // always run all thingsToRun
* }
* }
* </pre>
*
* This is what the code would become:
*
* <pre>
* void runManyThings(List<ThingToRun> thingsToRun) {
* List<Exception> exceptions = Lists.newArrayList();
* for (ThingToRun thingToRun : thingsToRun) {
* try {
* thingToRun.run();
* } catch (Exception e) {
* exceptions.add(e);
* }
* }
* if (exceptions.size() > 0) {
* throw ClusterException.create(exceptions);
* }
* }
* </pre>
*
* <p>See semantic details at {@link #create(Collection)}.
*
* @author Luiz-Otavio Zorzella
*/
@GwtCompatible
final class ClusterException extends RuntimeException {
public final Collection<? extends Throwable> exceptions;
private ClusterException(Collection<? extends Throwable> exceptions) {
super(
exceptions.size() + " exceptions were thrown. The first exception is listed as a cause.",
exceptions.iterator().next());
ArrayList<Throwable> temp = new ArrayList<Throwable>();
temp.addAll(exceptions);
this.exceptions = Collections.unmodifiableCollection(temp);
}
/**
* @see #create(Collection)
*/
public static RuntimeException create(Throwable... exceptions) {
ArrayList<Throwable> temp = new ArrayList<Throwable>();
for (Throwable exception : exceptions) {
temp.add(exception);
}
return create(temp);
}
/**
* Given a collection of exceptions, returns a {@link RuntimeException}, with
* the following rules:
*
* <ul>
* <li>If {@code exceptions} has a single exception and that exception is a
* {@link RuntimeException}, return it
* <li>If {@code exceptions} has a single exceptions and that exceptions is
* <em>not</em> a {@link RuntimeException}, return a simple
* {@code RuntimeException} that wraps it
* <li>Otherwise, return an instance of {@link ClusterException} that wraps
* the first exception in the {@code exceptions} collection.
* </ul>
*
* <p>Though this method takes any {@link Collection}, it often makes most
* sense to pass a {@link java.util.List} or some other collection that
* preserves the order in which the exceptions got added.
*
* @throws NullPointerException if {@code exceptions} is null
* @throws IllegalArgumentException if {@code exceptions} is empty
*/
public static RuntimeException create(Collection<? extends Throwable> exceptions) {
if (exceptions.size() == 0) {
throw new IllegalArgumentException(
"Can't create an ExceptionCollection with no exceptions");
}
if (exceptions.size() == 1) {
Throwable temp = exceptions.iterator().next();
if (temp instanceof RuntimeException) {
return (RuntimeException)temp;
} else {
return new RuntimeException(temp);
}
}
return new ClusterException(exceptions);
}
}
| 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 static java.util.Collections.sort;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@GwtCompatible(emulated = true)
public class Helpers {
// Clone of Objects.equal
static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
// Clone of Lists.newArrayList
public static <E> List<E> copyToList(Iterable<? extends E> elements) {
List<E> list = new ArrayList<E>();
addAll(list, elements);
return list;
}
public static <E> List<E> copyToList(E[] elements) {
return copyToList(Arrays.asList(elements));
}
// Clone of Sets.newLinkedHashSet
public static <E> Set<E> copyToSet(Iterable<? extends E> elements) {
Set<E> set = new LinkedHashSet<E>();
addAll(set, elements);
return set;
}
public static <E> Set<E> copyToSet(E[] elements) {
return copyToSet(Arrays.asList(elements));
}
// Would use Maps.immutableEntry
public static <K, V> Entry<K, V> mapEntry(K key, V value) {
return Collections.singletonMap(key, value).entrySet().iterator().next();
}
public static void assertEqualIgnoringOrder(
Iterable<?> expected, Iterable<?> actual) {
List<?> exp = copyToList(expected);
List<?> act = copyToList(actual);
String actString = act.toString();
// Of course we could take pains to give the complete description of the
// problem on any failure.
// Yeah it's n^2.
for (Object object : exp) {
if (!act.remove(object)) {
Assert.fail("did not contain expected element " + object + ", "
+ "expected = " + exp + ", actual = " + actString);
}
}
assertTrue("unexpected elements: " + act, act.isEmpty());
}
public static void assertContentsAnyOrder(
Iterable<?> actual, Object... expected) {
assertEqualIgnoringOrder(Arrays.asList(expected), actual);
}
public static <E> boolean addAll(
Collection<E> addTo, Iterable<? extends E> elementsToAdd) {
boolean modified = false;
for (E e : elementsToAdd) {
modified |= addTo.add(e);
}
return modified;
}
static <T> Iterable<T> reverse(final List<T> list) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
final ListIterator<T> listIter = list.listIterator(list.size());
return new Iterator<T>() {
@Override
public boolean hasNext() {
return listIter.hasPrevious();
}
@Override
public T next() {
return listIter.previous();
}
@Override
public void remove() {
listIter.remove();
}
};
}
};
}
static <T> Iterator<T> cycle(final Iterable<T> iterable) {
return new Iterator<T>() {
Iterator<T> iterator = Collections.<T>emptySet().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
if (!iterator.hasNext()) {
iterator = iterable.iterator();
}
return iterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
static <T> T get(Iterator<T> iterator, int position) {
for (int i = 0; i < position; i++) {
iterator.next();
}
return iterator.next();
}
static void fail(Throwable cause, Object message) {
AssertionFailedError assertionFailedError =
new AssertionFailedError(String.valueOf(message));
assertionFailedError.initCause(cause);
throw assertionFailedError;
}
public static <K, V> Comparator<Entry<K, V>> entryComparator(
final Comparator<? super K> keyComparator) {
return new Comparator<Entry<K, V>>() {
@Override
@SuppressWarnings("unchecked") // no less safe than putting it in the map!
public int compare(Entry<K, V> a, Entry<K, V> b) {
return (keyComparator == null)
? ((Comparable) a.getKey()).compareTo(b.getKey())
: keyComparator.compare(a.getKey(), b.getKey());
}
};
}
public static <T> void testComparator(
Comparator<? super T> comparator, T... valuesInExpectedOrder) {
testComparator(comparator, Arrays.asList(valuesInExpectedOrder));
}
public static <T> void testComparator(
Comparator<? super T> comparator, List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
T t = valuesInExpectedOrder.get(i);
for (int j = 0; j < i; j++) {
T lesser = valuesInExpectedOrder.get(j);
assertTrue(comparator + ".compare(" + lesser + ", " + t + ")",
comparator.compare(lesser, t) < 0);
}
assertEquals(comparator + ".compare(" + t + ", " + t + ")",
0, comparator.compare(t, t));
for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) {
T greater = valuesInExpectedOrder.get(j);
assertTrue(comparator + ".compare(" + greater + ", " + t + ")",
comparator.compare(greater, t) > 0);
}
}
}
public static <T extends Comparable<? super T>> void testCompareToAndEquals(
List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
T t = valuesInExpectedOrder.get(i);
for (int j = 0; j < i; j++) {
T lesser = valuesInExpectedOrder.get(j);
assertTrue(lesser + ".compareTo(" + t + ')', lesser.compareTo(t) < 0);
assertFalse(lesser.equals(t));
}
assertEquals(t + ".compareTo(" + t + ')', 0, t.compareTo(t));
assertTrue(t.equals(t));
for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) {
T greater = valuesInExpectedOrder.get(j);
assertTrue(greater + ".compareTo(" + t + ')', greater.compareTo(t) > 0);
assertFalse(greater.equals(t));
}
}
}
/**
* Returns a collection that simulates concurrent modification by
* having its size method return incorrect values. This is useful
* for testing methods that must treat the return value from size()
* as a hint only.
*
* @param delta the difference between the true size of the
* collection and the values returned by the size method
*/
public static <T> Collection<T> misleadingSizeCollection(final int delta) {
// It would be nice to be able to return a real concurrent
// collection like ConcurrentLinkedQueue, so that e.g. concurrent
// iteration would work, but that would not be GWT-compatible.
return new ArrayList<T>() {
@Override public int size() { return Math.max(0, super.size() + delta); }
};
}
/**
* Returns a "nefarious" map entry with the specified key and value,
* meaning an entry that is suitable for testing that map entries cannot be
* modified via a nefarious implementation of equals. This is used for testing
* unmodifiable collections of map entries; for example, it should not be
* possible to access the raw (modifiable) map entry via a nefarious equals
* method.
*/
public static <K, V> Map.Entry<K, V> nefariousMapEntry(final K key,
final V value) {
return new Map.Entry<K, V>() {
@Override public K getKey() {
return key;
}
@Override public V getValue() {
return value;
}
@Override public V setValue(V value) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override public boolean equals(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<K, V> e = (Map.Entry<K, V>) o;
e.setValue(value); // muhahaha!
return equal(this.getKey(), e.getKey())
&& equal(this.getValue(), e.getValue());
}
return false;
}
@Override public int hashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ?
0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/**
* Returns a string representation of the form <code>{key}={value}</code>.
*/
@Override public String toString() {
return getKey() + "=" + getValue();
}
};
}
static <E> List<E> castOrCopyToList(Iterable<E> iterable) {
if (iterable instanceof List) {
return (List<E>) iterable;
}
List<E> list = new ArrayList<E>();
for (E e : iterable) {
list.add(e);
}
return list;
}
private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() {
@SuppressWarnings("unchecked") // assume any Comparable is Comparable<Self>
@Override public int compare(Comparable left, Comparable right) {
return left.compareTo(right);
}
};
public static <K extends Comparable, V> Iterable<Entry<K, V>> orderEntriesByKey(
List<Entry<K, V>> insertionOrder) {
sort(insertionOrder, Helpers.<K, V>entryComparator(NATURAL_ORDER));
return insertionOrder;
}
/**
* Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient} to work around
* build-system quirks.
*/
private @interface GwtTransient {}
/**
* Compares strings in natural order except that null comes immediately before a given value. This
* works better than Ordering.natural().nullsFirst() because, if null comes before all other
* values, it lies outside the submap/submultiset ranges we test, and the variety of tests that
* exercise null handling fail on those subcollections.
*/
public abstract static class NullsBefore implements Comparator<String>, Serializable {
/*
* We don't serialize this class in GWT, so we don't care about whether GWT will serialize this
* field.
*/
@GwtTransient private final String justAfterNull;
protected NullsBefore(String justAfterNull) {
if (justAfterNull == null) {
throw new NullPointerException();
}
this.justAfterNull = justAfterNull;
}
@Override
public int compare(String lhs, String rhs) {
if (lhs == rhs) {
return 0;
}
if (lhs == null) {
// lhs (null) comes just before justAfterNull.
// If rhs is b, lhs comes first.
if (rhs.equals(justAfterNull)) {
return -1;
}
return justAfterNull.compareTo(rhs);
}
if (rhs == null) {
// rhs (null) comes just before justAfterNull.
// If lhs is b, rhs comes first.
if (lhs.equals(justAfterNull)) {
return 1;
}
return lhs.compareTo(justAfterNull);
}
return lhs.compareTo(rhs);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NullsBefore) {
NullsBefore other = (NullsBefore) obj;
return justAfterNull.equals(other.justAfterNull);
}
return false;
}
@Override
public int hashCode() {
return justAfterNull.hashCode();
}
}
public static final class NullsBeforeB extends NullsBefore {
public static final NullsBeforeB INSTANCE = new NullsBeforeB();
private NullsBeforeB() {
super("b");
}
}
public static final class NullsBeforeTwo extends NullsBefore {
public static final NullsBeforeTwo INSTANCE = new NullsBeforeTwo();
private NullsBeforeTwo() {
super("two"); // from TestStringSortedMapGenerator's sample keys
}
}
@GwtIncompatible("reflection")
public static Method getMethod(Class<?> clazz, String name) {
try {
return clazz.getMethod(name);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
| 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.Collection;
import java.util.List;
import java.util.Map;
/**
* To be implemented by test generators of things that can contain
* elements. Such things include both {@link Collection} and {@link Map}; since
* there isn't an established collective noun that encompasses both of these,
* 'container' is used.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface TestContainerGenerator<T, E> {
/**
* Returns the sample elements that this generate populates its container
* with.
*/
SampleElements<E> samples();
/**
* Creates a new container containing the given elements. TODO: would be nice
* to figure out how to use E... or E[] as a parameter type, but this doesn't
* seem to work because Java creates an array of the erased type.
*/
T create(Object ... elements);
/**
* Helper method to create an array of the appropriate type used by this
* generator. The returned array will contain only nulls.
*/
E[] createArray(int length);
/**
* Returns the iteration ordering of elements, given the order in
* which they were added to the container. This method may return the
* original list unchanged, the original list modified in place, or a
* different list.
*
* <p>This method runs only when {@link
* com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER}
* is specified when creating the test suite. It should never run when testing
* containers such as {@link java.util.HashSet}, which have a
* non-deterministic iteration order.
*/
Iterable<E> order(List<E> 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.Ints;
import java.util.List;
import java.util.Set;
/**
* Create integer sets for collection tests.
*
* <p>This class is GWT compatible.
*
* @author Gregory Kick
*/
@GwtCompatible
public abstract class TestIntegerSetGenerator implements TestSetGenerator<Integer> {
@Override public SampleElements<Integer> samples() {
return new Ints();
}
@Override public Set<Integer> create(Object... elements) {
Integer[] array = new Integer[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Integer) e;
}
return create(array);
}
protected abstract Set<Integer> create(Integer[] elements);
@Override public Integer[] createArray(int length) {
return new Integer[length];
}
/**
* {@inheritDoc}
*
* <p>By default, returns the supplied elements in their given order; however,
* generators for containers with a known order other than insertion order
* must override this method.
*
* <p>Note: This default implementation is overkill (but valid) for an
* unordered container. An equally valid implementation for an unordered
* container is to throw an exception. The chosen implementation, however, has
* the advantage of working for insertion-ordered containers, as well.
*/
@Override public List<Integer> order(List<Integer> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
/**
* An unhashable object to be used in testing as values in our collections.
*
* <p>This class is GWT compatible.
*
* @author Regina O'Dell
*/
@GwtCompatible
public class UnhashableObject implements Comparable<UnhashableObject> {
private final int value;
public UnhashableObject(int value) {
this.value = value;
}
@Override public boolean equals(Object object) {
if (object instanceof UnhashableObject) {
UnhashableObject that = (UnhashableObject) object;
return this.value == that.value;
}
return false;
}
@Override public int hashCode() {
throw new UnsupportedOperationException();
}
// needed because otherwise Object.toString() calls hashCode()
@Override public String toString() {
return "DontHashMe" + value;
}
@Override
public int compareTo(UnhashableObject o) {
return (this.value < o.value) ? -1 : (this.value > o.value) ? 1 : 0;
}
}
| 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;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* 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(
TestMapGenerator<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 SetTestSuiteBuilder<K> createDerivedKeySetSuite(
TestSetGenerator<K> keySetGenerator) {
/*
* TODO(cpovirk): Consider requiring a SortedSet by default and requiring tests of a given
* implementation to opt out if they wish to return Set. This would encourage us to return
* keySets that implement SortedSet
*/
return (keySetGenerator.create() instanceof SortedSet)
? SortedSetTestSuiteBuilder.using(keySetGenerator)
: SetTestSuiteBuilder.using(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 TestMapGenerator<K, V> delegate
= (TestMapGenerator<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(
TestMapGenerator<K, V> delegate, Bound to, Bound from) {
return using(new SortedMapSubmapTestMapGenerator<K, V>(delegate, to, from));
}
}
| 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 java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* A wrapper around {@code TreeSet} that aggressively checks to see if elements
* are mutually comparable. This implementation passes the navigable set test
* suites.
*
* @author Louis Wasserman
*/
public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> {
@SuppressWarnings("unchecked")
private static final Comparator NATURAL_ORDER = new Comparator<Comparable>() {
@Override public int compare(Comparable o1, Comparable o2) {
return o1.compareTo(o2);
}
};
private final NavigableSet<E> delegate;
public SafeTreeSet() {
this(new TreeSet<E>());
}
public SafeTreeSet(Collection<? extends E> collection) {
this(new TreeSet<E>(collection));
}
public SafeTreeSet(Comparator<? super E> comparator) {
this(new TreeSet<E>(comparator));
}
public SafeTreeSet(SortedSet<E> set) {
this(new TreeSet<E>(set));
}
private SafeTreeSet(NavigableSet<E> delegate) {
this.delegate = delegate;
for (E e : this) {
checkValid(e);
}
}
@Override public boolean add(E element) {
return delegate.add(checkValid(element));
}
@Override public boolean addAll(Collection<? extends E> collection) {
for (E e : collection) {
checkValid(e);
}
return delegate.addAll(collection);
}
@Override public E ceiling(E e) {
return delegate.ceiling(checkValid(e));
}
@Override public void clear() {
delegate.clear();
}
@SuppressWarnings("unchecked")
@Override public Comparator<? super E> comparator() {
Comparator<? super E> comparator = delegate.comparator();
if (comparator == null) {
comparator = NATURAL_ORDER;
}
return comparator;
}
@Override public boolean contains(Object object) {
return delegate.contains(checkValid(object));
}
@Override public boolean containsAll(Collection<?> c) {
return delegate.containsAll(c);
}
@Override public Iterator<E> descendingIterator() {
return delegate.descendingIterator();
}
@Override public NavigableSet<E> descendingSet() {
return new SafeTreeSet<E>(delegate.descendingSet());
}
@Override public E first() {
return delegate.first();
}
@Override public E floor(E e) {
return delegate.floor(checkValid(e));
}
@Override public SortedSet<E> headSet(E toElement) {
return headSet(toElement, false);
}
@Override public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new SafeTreeSet<E>(
delegate.headSet(checkValid(toElement), inclusive));
}
@Override public E higher(E e) {
return delegate.higher(checkValid(e));
}
@Override public boolean isEmpty() {
return delegate.isEmpty();
}
@Override public Iterator<E> iterator() {
return delegate.iterator();
}
@Override public E last() {
return delegate.last();
}
@Override public E lower(E e) {
return delegate.lower(checkValid(e));
}
@Override public E pollFirst() {
return delegate.pollFirst();
}
@Override public E pollLast() {
return delegate.pollLast();
}
@Override public boolean remove(Object object) {
return delegate.remove(checkValid(object));
}
@Override public boolean removeAll(Collection<?> c) {
return delegate.removeAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return delegate.retainAll(c);
}
@Override public int size() {
return delegate.size();
}
@Override public NavigableSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return new SafeTreeSet<E>(
delegate.subSet(checkValid(fromElement), fromInclusive,
checkValid(toElement), toInclusive));
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override public SortedSet<E> tailSet(E fromElement) {
return tailSet(fromElement, true);
}
@Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return delegate.tailSet(checkValid(fromElement), inclusive);
}
@Override public Object[] toArray() {
return delegate.toArray();
}
@Override public <T> T[] toArray(T[] a) {
return delegate.toArray(a);
}
private <T> T checkValid(T t) {
// a ClassCastException is what's supposed to happen!
@SuppressWarnings("unchecked")
E e = (E) t;
comparator().compare(e, e);
return t;
}
@Override public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override public int hashCode() {
return delegate.hashCode();
}
@Override public String toString() {
return delegate.toString();
}
private static final long serialVersionUID = 0L;
}
| 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.google;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.testing.TestStringSortedMapGenerator;
import java.util.Map;
import java.util.Map.Entry;
/**
* Generators of sorted maps and derived collections.
*
* @author Kevin Bourrillion
* @author Jesse Wilson
* @author Jared Levy
* @author Hayward Chan
* @author Chris Povirk
*/
@GwtCompatible
public class SortedMapGenerators {
public static class ImmutableSortedMapGenerator extends TestStringSortedMapGenerator {
@Override public Map<String, String> create(Entry<String, String>[] entries) {
ImmutableSortedMap.Builder<String, String> builder = ImmutableSortedMap.naturalOrder();
for (Entry<String, String> entry : entries) {
checkNotNull(entry);
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
}
}
}
| 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.collect.ListMultimap;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.TestListGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.ListFeature;
import junit.framework.TestSuite;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a {@code ListMultimap} implementation.
*
* @author Louis Wasserman
*/
public class ListMultimapTestSuiteBuilder<K, V> extends
MultimapTestSuiteBuilder<K, V, ListMultimap<K, V>> {
public static <K, V> ListMultimapTestSuiteBuilder<K, V> using(
TestListMultimapGenerator<K, V> generator) {
ListMultimapTestSuiteBuilder<K, V> result = new ListMultimapTestSuiteBuilder<K, V>();
result.usingGenerator(generator);
return result;
}
@Override
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<ListMultimap<K, V>, Entry<K, V>>> parentBuilder) {
return ListTestSuiteBuilder.using(
new MultimapGetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeMultimapGetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
@Override
Set<Feature<?>> computeMultimapGetFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = super.computeMultimapGetFeatures(multimapFeatures);
if (derivedFeatures.contains(CollectionFeature.SUPPORTS_ADD)) {
derivedFeatures.add(ListFeature.SUPPORTS_ADD_WITH_INDEX);
}
if (derivedFeatures.contains(CollectionFeature.GENERAL_PURPOSE)) {
derivedFeatures.add(ListFeature.GENERAL_PURPOSE);
}
return derivedFeatures;
}
private static class MultimapGetGenerator<K, V>
extends MultimapTestSuiteBuilder.MultimapGetGenerator<K, V, ListMultimap<K, V>>
implements TestListGenerator<V> {
public MultimapGetGenerator(
OneSizeTestContainerGenerator<ListMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public List<V> create(Object... elements) {
return (List<V>) super.create(elements);
}
}
}
| 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.collect.SetMultimap;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.SortedSetTestSuiteBuilder;
import com.google.common.collect.testing.TestSetGenerator;
import junit.framework.TestSuite;
import java.util.Map.Entry;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a {@code SortedSetMultimap} implementation.
*
* @author Louis Wasserman
*/
public class SortedSetMultimapTestSuiteBuilder<K, V>
extends MultimapTestSuiteBuilder<K, V, SetMultimap<K, V>> {
public static <K, V> SortedSetMultimapTestSuiteBuilder<K, V> using(
TestSetMultimapGenerator<K, V> generator) {
SortedSetMultimapTestSuiteBuilder<K, V> result = new SortedSetMultimapTestSuiteBuilder<K, V>();
result.usingGenerator(generator);
return result;
}
@Override
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>>> parentBuilder) {
return SortedSetTestSuiteBuilder.using(
new MultimapGetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeMultimapGetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
private static class MultimapGetGenerator<K, V>
extends MultimapTestSuiteBuilder.MultimapGetGenerator<K, V, SetMultimap<K, V>>
implements TestSetGenerator<V> {
public MultimapGetGenerator(
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Set<V> create(Object... elements) {
return (Set<V>) super.create(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.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.SampleElements.Strings;
import java.util.List;
/**
* Create multisets of strings for tests.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestStringMultisetGenerator
implements TestMultisetGenerator<String>
{
@Override
public SampleElements<String> samples() {
return new Strings();
}
@Override
public Multiset<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 Multiset<String> create(String[] elements);
@Override
public String[] createArray(int length) {
return new String[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<String> order(List<String> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.AnEnum;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.SampleElements.Enums;
import java.util.Collections;
import java.util.List;
/**
* An abstract {@code TestMultisetGenerator} for generating multisets containing
* enum values.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestEnumMultisetGenerator
implements TestMultisetGenerator<AnEnum> {
@Override
public SampleElements<AnEnum> samples() {
return new Enums();
}
@Override
public Multiset<AnEnum> create(Object... elements) {
AnEnum[] array = new AnEnum[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (AnEnum) e;
}
return create(array);
}
protected abstract Multiset<AnEnum> create(AnEnum[] elements);
@Override
public AnEnum[] createArray(int length) {
return new AnEnum[length];
}
/**
* Sorts the enums according to their natural ordering.
*/
@Override
public List<AnEnum> order(List<AnEnum> insertionOrder) {
Collections.sort(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 com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
/**
* A generator for {@code ListMultimap} implementations based on test data.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestListMultimapGenerator<K, V>
extends TestMultimapGenerator<K, V, ListMultimap<K, V>> {
}
| 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_VALUES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
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.List;
/**
* Tester for {@link Multimap#put}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapPutTester<K, V> extends AbstractMultimapTester<K, V> {
private static final Object[] EMPTY = new Object[0];
@MapFeature.Require(SUPPORTS_PUT)
public void testPutEmpty() {
int size = getNumElements();
K key = sampleKeys().e3;
V value = sampleValues().e3;
assertGet(key, EMPTY);
assertTrue(multimap().put(key, value));
assertGet(key, value);
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutPresent() {
int size = getNumElements();
K key = sampleKeys().e0;
V oldValue = sampleValues().e0;
V newValue = sampleValues().e3;
assertGet(key, oldValue);
assertTrue(multimap().put(key, newValue));
assertGet(key, oldValue, newValue);
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutTwoElements() {
int size = getNumElements();
K key = sampleKeys().e0;
V v1 = sampleValues().e3;
V v2 = sampleValues().e4;
List<V> values = Helpers.copyToList(multimap().get(key));
assertTrue(multimap().put(key, v1));
assertTrue(multimap().put(key, v2));
values.add(v1);
values.add(v2);
assertGet(key, values.toArray());
assertEquals(size + 2, multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPutNullValue() {
int size = getNumElements();
multimap().put(sampleKeys().e3, null);
assertGet(sampleKeys().e3, new Object[] {null});
assertEquals(size + 1, multimap().size());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPutNullKey() {
int size = getNumElements();
multimap().put(null, sampleValues().e3);
assertGet(null, sampleValues().e3);
assertEquals(size + 1, multimap().size());
}
}
| 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.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for {@code BiMap.clear}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class BiMapClearTester<K, V> extends AbstractBiMapTester<K, V> {
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearClearsInverse() {
BiMap<V, K> inv = getMap().inverse();
getMap().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testKeySetClearClearsInverse() {
BiMap<V, K> inv = getMap().inverse();
getMap().keySet().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testValuesClearClearsInverse() {
BiMap<V, K> inv = getMap().inverse();
getMap().values().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseClears() {
BiMap<V, K> inv = getMap().inverse();
inv.clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseKeySetClears() {
BiMap<V, K> inv = getMap().inverse();
inv.keySet().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseValuesClears() {
BiMap<V, K> inv = getMap().inverse();
inv.values().clear();
assertTrue(getMap().isEmpty());
assertTrue(inv.isEmpty());
}
}
| 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.SetMultimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A skeleton generator for a {@code SetMultimap} implementation.
*
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestStringSetMultimapGenerator
implements TestSetMultimapGenerator<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 SampleElements<String> sampleKeys() {
return new SampleElements<String>("one", "two", "three", "four", "five");
}
@Override
public SampleElements<String> sampleValues() {
return new SampleElements<String>("January", "February", "March", "April", "May");
}
@Override
public Collection<String> createCollection(Iterable<? extends String> values) {
return Helpers.copyToSet(values);
}
@Override
public final SetMultimap<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 SetMultimap<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) 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.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.SUPPORTS_REMOVE;
import static org.junit.contrib.truth.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multimap;
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;
/**
* Tests for {@link Multimap#removeAll(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapRemoveAllTester<K, V> extends AbstractMultimapTester<K, V> {
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllAbsentKey() {
ASSERT.that(multimap().removeAll(sampleKeys().e3)).isEmpty();
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllPresentKey() {
ASSERT.that(multimap().removeAll(sampleKeys().e0)).hasContentsInOrder(
sampleValues().e0);
expectMissing(samples.e0);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllPropagatesToGet() {
Collection<V> getResult = multimap().get(sampleKeys().e0);
multimap().removeAll(sampleKeys().e0);
ASSERT.that(getResult).isEmpty();
expectMissing(samples.e0);
}
@CollectionSize.Require(SEVERAL)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllMultipleValues() {
resetContainer(
Helpers.mapEntry(sampleKeys().e0, sampleValues().e0),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e1),
Helpers.mapEntry(sampleKeys().e0, sampleValues().e2));
ASSERT.that(multimap().removeAll(sampleKeys().e0))
.hasContentsAnyOrder(sampleValues().e0, sampleValues().e1, sampleValues().e2);
assertTrue(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_KEYS })
public void testRemoveAllNullKeyPresent() {
initMultimapWithNullKey();
ASSERT.that(multimap().removeAll(null)).hasContentsInOrder(getValueForNullKey());
expectMissing(Helpers.mapEntry((K) null, getValueForNullKey()));
}
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES })
public void testRemoveAllNullKeyAbsent() {
ASSERT.that(multimap().removeAll(null)).isEmpty();
expectUnchanged();
}
}
| 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.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Implementation helper for {@link TestBiMapGenerator} for use with bimaps of
* strings.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Jared Levy
* @author George van den Driessche
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestStringBiMapGenerator
implements TestBiMapGenerator<String, String> {
@Override
public SampleElements<Map.Entry<String, String>> samples() {
return new SampleElements<Map.Entry<String, String>>(
Helpers.mapEntry("one", "January"),
Helpers.mapEntry("two", "February"),
Helpers.mapEntry("three", "March"),
Helpers.mapEntry("four", "April"),
Helpers.mapEntry("five", "May")
);
}
@Override
public final BiMap<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 BiMap<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) 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.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> {
@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) 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.Multimap;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestContainerGenerator;
import java.util.Collection;
import java.util.Map;
/**
* Creates multimaps, containing sample elements, to be tested.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestMultimapGenerator<K, V, M extends Multimap<K, V>>
extends TestContainerGenerator<M, Map.Entry<K, V>> {
K[] createKeyArray(int length);
V[] createValueArray(int length);
SampleElements<K> sampleKeys();
SampleElements<V> sampleValues();
Collection<V> createCollection(Iterable<? extends V> values);
}
| 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.TestContainerGenerator;
import java.util.Map;
/**
* Creates bimaps, containing sample entries, to be tested.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestBiMapGenerator<K, V>
extends TestContainerGenerator<BiMap<K, V>, Map.Entry<K, V>> {
K[] createKeyArray(int length);
V[] createValueArray(int length);
}
| 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.google;
import com.google.common.annotations.GwtCompatible;
/**
* A generic JUnit test which tests unconditional {@code setCount()} operations
* on a multiset. Can't be invoked directly; please see
* {@link MultisetTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@GwtCompatible
public class MultisetSetCountUnconditionallyTester<E>
extends AbstractMultisetSetCountTester<E> {
@Override void setCountCheckReturnValue(E element, int count) {
assertEquals("multiset.setCount() should return the old count",
getMultiset().count(element), setCount(element, count));
}
@Override void setCountNoCheckReturnValue(E element, int count) {
setCount(element, count);
}
private int setCount(E element, int count) {
return getMultiset().setCount(element, count);
}
}
| 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.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collections;
import java.util.Iterator;
/**
* Tests for {@link Multimap#putAll(Object, Iterable)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapPutIterableTester<K, V> extends AbstractMultimapTester<K, V> {
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyOnPresentKey() {
multimap().putAll(sampleKeys().e0, new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Lists.newArrayList(sampleValues().e3, sampleValues().e4).iterator();
}
});
assertGet(sampleKeys().e0, sampleValues().e0, sampleValues().e3, sampleValues().e4);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllNonEmptyOnAbsentKey() {
multimap().putAll(sampleKeys().e3, new Iterable<V>() {
@Override
public Iterator<V> iterator() {
return Lists.newArrayList(sampleValues().e3, sampleValues().e4).iterator();
}
});
assertGet(sampleKeys().e3, sampleValues().e3, sampleValues().e4);
}
private static final Object[] EMPTY = new Object[0];
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyIterableOnAbsentKey() {
Iterable<V> iterable = Collections.emptyList();
multimap().putAll(sampleKeys().e3, iterable);
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAllEmptyIterableOnPresentKey() {
multimap().putAll(sampleKeys().e0, Collections.<V>emptyList());
expectUnchanged();
}
}
| 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.google;
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.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.annotations.GwtIncompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
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.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
/**
* Common superclass for {@link MultisetSetCountUnconditionallyTester} and
* {@link MultisetSetCountConditionallyTester}. It is used by those testers to
* test calls to the unconditional {@code setCount()} method and calls to the
* conditional {@code setCount()} method when the expected present count is
* correct.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public abstract class AbstractMultisetSetCountTester<E>
extends AbstractMultisetTester<E> {
/*
* TODO: consider adding MultisetFeatures.SUPPORTS_SET_COUNT. Currently we
* assume that using setCount() to increase the count is permitted iff add()
* is permitted and similarly for decrease/remove(). We assume that a
* setCount() no-op is permitted if either add() or remove() is permitted,
* though we also allow it to "succeed" if neither is permitted.
*/
private void assertSetCount(E element, int count) {
setCountCheckReturnValue(element, count);
assertEquals(
"multiset.count() should return the value passed to setCount()",
count, getMultiset().count(element));
int size = 0;
for (Multiset.Entry<E> entry : getMultiset().entrySet()) {
size += entry.getCount();
}
assertEquals(
"multiset.size() should be the sum of the counts of all entries",
size, getMultiset().size());
}
/**
* Call the {@code setCount()} method under test, and check its return value.
*/
abstract void setCountCheckReturnValue(E element, int count);
/**
* Call the {@code setCount()} method under test, but do not check its return
* value. Callers should use this method over
* {@link #setCountCheckReturnValue(Object, int)} when they expect
* {@code setCount()} to throw an exception, as checking the return value
* could produce an incorrect error message like
* "setCount() should return the original count" instead of the message passed
* to a later invocation of {@code fail()}, like "setCount should throw
* UnsupportedOperationException."
*/
abstract void setCountNoCheckReturnValue(E element, int count);
private void assertSetCountIncreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to increase an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
private void assertSetCountDecreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to decrease an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
// Unconditional setCount no-ops.
private void assertZeroToZero() {
assertSetCount(samples.e3, 0);
}
private void assertOneToOne() {
assertSetCount(samples.e0, 1);
}
private void assertThreeToThree() {
initThreeCopies();
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToZero_addSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_zeroToZero_removeSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_zeroToZero_unsupported() {
try {
assertZeroToZero();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToOne_addSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToOne_removeSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_oneToOne_unsupported() {
try {
assertOneToOne();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_threeToThree_addSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToThree_removeSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_threeToThree_unsupported() {
try {
assertThreeToThree();
} catch (UnsupportedOperationException tolerated) {
}
}
// Unconditional setCount size increases:
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToOne_supported() {
assertSetCount(samples.e3, 1);
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToThree_supported() {
assertSetCount(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToThree_supported() {
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToOne_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 1);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_oneToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
// Unconditional setCount size decreases:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToZero_supported() {
assertSetCount(samples.e0, 0);
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountOneToZeroConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToZero_supported() {
initThreeCopies();
assertSetCount(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToOne_supported() {
initThreeCopies();
assertSetCount(samples.e0, 1);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_oneToZero_unsupported() {
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToZero_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToOne_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 1);
}
// setCount with nulls:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
public void testSetCount_removeNull_nullSupported() {
initCollectionWithNullElement();
assertSetCount(null, 0);
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testSetCount_addNull_nullSupported() {
assertSetCount(null, 1);
}
@CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES)
public void testSetCount_addNull_nullUnsupported() {
try {
setCountNoCheckReturnValue(null, 1);
fail("adding null with setCount() should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullSupported() {
try {
assertSetCount(null, 0);
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullUnsupported() {
try {
assertSetCount(null, 0);
} catch (NullPointerException tolerated) {
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_existingNoNopNull_nullSupported() {
initCollectionWithNullElement();
try {
assertSetCount(null, 1);
} catch (UnsupportedOperationException tolerated) {
}
}
// Negative count.
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_negative_removeSupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_negative_removeUnsupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException or UnsupportedOperationException");
} catch (IllegalArgumentException expected) {
} catch (UnsupportedOperationException expected) {
}
}
// TODO: test adding element of wrong type
/**
* Returns {@link Method} instances for the {@code setCount()} tests that
* assume multisets support duplicates so that the test of {@code
* Multisets.forSet()} can suppress them.
*/
@GwtIncompatible("reflection")
public static List<Method> getSetCountDuplicateInitializingMethods() {
return Arrays.asList(
getMethod("testSetCount_threeToThree_removeSupported"),
getMethod("testSetCount_threeToZero_supported"),
getMethod("testSetCount_threeToOne_supported"));
}
@GwtIncompatible("reflection")
private static Method getMethod(String methodName) {
return Helpers.getMethod(AbstractMultisetSetCountTester.class, methodName);
}
}
| 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.google;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.AbstractCollectionTestSuiteBuilder;
import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
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.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.CollectionSerializationEqualTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a {@code Multiset} implementation.
*
* @author Jared Levy
* @author Louis Wasserman
*/
public class MultisetTestSuiteBuilder<E> extends
AbstractCollectionTestSuiteBuilder<MultisetTestSuiteBuilder<E>, E> {
public static <E> MultisetTestSuiteBuilder<E> using(
TestMultisetGenerator<E> generator) {
return new MultisetTestSuiteBuilder<E>().usingGenerator(generator);
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers
= Helpers.copyToList(super.getTesters());
testers.add(CollectionSerializationEqualTester.class);
testers.add(MultisetReadsTester.class);
testers.add(MultisetSetCountConditionallyTester.class);
testers.add(MultisetSetCountUnconditionallyTester.class);
testers.add(MultisetWritesTester.class);
testers.add(MultisetIteratorTester.class);
testers.add(MultisetSerializationTester.class);
return testers;
}
private static Set<Feature<?>> computeReserializedMultisetFeatures(
Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
derivedFeatures.addAll(features);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
@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.SERIALIZABLE)) {
derivedSuites.add(MultisetTestSuiteBuilder
.using(new ReserializedMultisetGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedMultisetFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
return derivedSuites;
}
static class ReserializedMultisetGenerator<E> implements TestMultisetGenerator<E>{
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedMultisetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public Multiset<E> create(Object... elements) {
return (Multiset<E>) SerializableTester.reserialize(gen.create(elements));
}
@Override
public E[] createArray(int length) {
return gen.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return gen.order(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.base.Preconditions.checkArgument;
import static com.google.common.collect.testing.Helpers.mapEntry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.CollectionTestSuiteBuilder;
import com.google.common.collect.testing.DerivedGenerator;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.PerCollectionSizeTestSuiteBuilder;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestCollectionGenerator;
import com.google.common.collect.testing.TestMapGenerator;
import com.google.common.collect.testing.TestSubjectGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
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 {@code Multimap} implementation.
*
* @author Louis Wasserman
*/
public class MultimapTestSuiteBuilder<K, V, M extends Multimap<K, V>> extends
PerCollectionSizeTestSuiteBuilder<
MultimapTestSuiteBuilder<K, V, M>,
TestMultimapGenerator<K, V, M>, M, Map.Entry<K, V>> {
public static <K, V, M extends Multimap<K, V>> MultimapTestSuiteBuilder<K, V, M> using(
TestMultimapGenerator<K, V, M> generator) {
return new MultimapTestSuiteBuilder<K, V, M>().usingGenerator(generator);
}
// Class parameters must be raw.
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
return ImmutableList.<Class<? extends AbstractTester>> of(
MultimapSizeTester.class,
MultimapContainsKeyTester.class,
MultimapContainsValueTester.class,
MultimapContainsEntryTester.class,
MultimapGetTester.class,
MultimapPutTester.class,
MultimapPutIterableTester.class,
MultimapRemoveEntryTester.class,
MultimapRemoveAllTester.class);
}
@Override
protected List<TestSuite> createDerivedSuites(
FeatureSpecificTestSuiteBuilder<
?,
? extends OneSizeTestContainerGenerator<M, Map.Entry<K, V>>>
parentBuilder) {
// TODO: Once invariant support is added, supply invariants to each of the
// derived suites, to check that mutations to the derived collections are
// reflected in the underlying map.
List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);
if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
derivedSuites.add(MultimapTestSuiteBuilder.using(
new ReserializedMultimapGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeReserializedMultimapFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + " reserialized")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
derivedSuites.add(MapTestSuiteBuilder.using(
new AsMapGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeAsMapFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".asMap")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
derivedSuites.add(computeEntriesTestSuite(parentBuilder));
derivedSuites.add(computeMultimapGetTestSuite(parentBuilder));
derivedSuites.add(computeKeysTestSuite(parentBuilder));
return derivedSuites;
}
TestSuite computeValuesTestSuite(
FeatureSpecificTestSuiteBuilder<?, ?
extends OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return CollectionTestSuiteBuilder.using(
new ValuesGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeValuesFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".entries")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
TestSuite computeEntriesTestSuite(
FeatureSpecificTestSuiteBuilder<?, ?
extends OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return CollectionTestSuiteBuilder.using(
new EntriesGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeEntriesFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".entries")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return CollectionTestSuiteBuilder.using(
new MultimapGetGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeMultimapGetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
TestSuite computeKeysTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<M, Map.Entry<K, V>>> parentBuilder) {
return MultisetTestSuiteBuilder.using(
new KeysGenerator<K, V, M>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeKeysFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".keys")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
static Set<Feature<?>> computeDerivedCollectionFeatures(Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
if (!derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
if (derivedFeatures.remove(MapFeature.ALLOWS_NULL_QUERIES)) {
derivedFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES);
}
if (derivedFeatures.remove(MapFeature.SUPPORTS_REMOVE)) {
derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE);
}
return derivedFeatures;
}
static Set<Feature<?>> computeEntriesFeatures(
Set<Feature<?>> multimapFeatures) {
return computeDerivedCollectionFeatures(multimapFeatures);
}
static Set<Feature<?>> computeValuesFeatures(
Set<Feature<?>> multimapFeatures) {
return computeDerivedCollectionFeatures(multimapFeatures);
}
static Set<Feature<?>> computeKeysFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> result = computeDerivedCollectionFeatures(multimapFeatures);
if (multimapFeatures.contains(MapFeature.ALLOWS_NULL_KEYS)) {
result.add(CollectionFeature.ALLOWS_NULL_VALUES);
}
return result;
}
private static Set<Feature<?>> computeReserializedMultimapFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
private static Set<Feature<?>> computeAsMapFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
derivedFeatures.remove(MapFeature.GENERAL_PURPOSE);
derivedFeatures.remove(MapFeature.SUPPORTS_PUT);
derivedFeatures.remove(MapFeature.ALLOWS_NULL_VALUES);
derivedFeatures.add(MapFeature.REJECTS_DUPLICATES_AT_CREATION);
if (!derivedFeatures.contains(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
return derivedFeatures;
}
private static final Multimap<Feature<?>, Feature<?>> GET_FEATURE_MAP = ImmutableMultimap
.<Feature<?>, Feature<?>> builder()
.put(
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION)
.put(MapFeature.GENERAL_PURPOSE, CollectionFeature.GENERAL_PURPOSE)
.put(MapFeature.ALLOWS_NULL_QUERIES, CollectionFeature.ALLOWS_NULL_QUERIES)
.put(MapFeature.ALLOWS_NULL_VALUES, CollectionFeature.ALLOWS_NULL_VALUES)
.put(MapFeature.SUPPORTS_REMOVE, CollectionFeature.SUPPORTS_REMOVE)
.put(MapFeature.SUPPORTS_PUT, CollectionFeature.SUPPORTS_ADD)
.build();
Set<Feature<?>> computeMultimapGetFeatures(
Set<Feature<?>> multimapFeatures) {
Set<Feature<?>> derivedFeatures = Helpers.copyToSet(multimapFeatures);
for (Map.Entry<Feature<?>, Feature<?>> entry : GET_FEATURE_MAP.entries()) {
if (derivedFeatures.contains(entry.getKey())) {
derivedFeatures.add(entry.getValue());
}
}
if (!derivedFeatures.contains(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
}
derivedFeatures.removeAll(GET_FEATURE_MAP.keySet());
return derivedFeatures;
}
private static class AsMapGenerator<K, V, M extends Multimap<K, V>> implements
TestMapGenerator<K, Collection<V>>, DerivedGenerator {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public AsMapGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public TestSubjectGenerator<?> getInnerGenerator() {
return multimapGenerator;
}
private Collection<V> createCollection(V v) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createCollection(Collections.singleton(v));
}
@Override
public SampleElements<Entry<K, Collection<V>>> samples() {
SampleElements<K> sampleKeys =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys();
SampleElements<V> sampleValues =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleValues();
return new SampleElements<Entry<K, Collection<V>>>(
mapEntry(sampleKeys.e0, createCollection(sampleValues.e0)),
mapEntry(sampleKeys.e1, createCollection(sampleValues.e1)),
mapEntry(sampleKeys.e2, createCollection(sampleValues.e2)),
mapEntry(sampleKeys.e3, createCollection(sampleValues.e3)),
mapEntry(sampleKeys.e4, createCollection(sampleValues.e4)));
}
@Override
public Map<K, Collection<V>> create(Object... elements) {
Set<K> keySet = new HashSet<K>();
List<Map.Entry<K, V>> builder = new ArrayList<Entry<K, V>>();
for (Object o : elements) {
Map.Entry<K, Collection<V>> entry = (Entry<K, Collection<V>>) o;
keySet.add(entry.getKey());
for (V v : entry.getValue()) {
builder.add(mapEntry(entry.getKey(), v));
}
}
checkArgument(keySet.size() == elements.length, "Duplicate keys");
return multimapGenerator.create(builder.toArray()).asMap();
}
@SuppressWarnings("unchecked")
@Override
public Entry<K, Collection<V>>[] createArray(int length) {
return new Entry[length];
}
@Override
public Iterable<Entry<K, Collection<V>>> order(List<Entry<K, Collection<V>>> insertionOrder) {
Map<K, Collection<V>> map = new HashMap<K, Collection<V>>();
List<Map.Entry<K, V>> builder = new ArrayList<Entry<K, V>>();
for (Entry<K, Collection<V>> entry : insertionOrder) {
for (V v : entry.getValue()) {
builder.add(mapEntry(entry.getKey(), v));
}
map.put(entry.getKey(), entry.getValue());
}
Iterable<Map.Entry<K, V>> ordered = multimapGenerator.order(builder);
LinkedHashMap<K, Collection<V>> orderedMap = new LinkedHashMap<K, Collection<V>>();
for (Map.Entry<K, V> entry : ordered) {
orderedMap.put(entry.getKey(), map.get(entry.getKey()));
}
return orderedMap.entrySet();
}
@Override
public K[] createKeyArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createKeyArray(length);
}
@SuppressWarnings("unchecked")
@Override
public Collection<V>[] createValueArray(int length) {
return new Collection[length];
}
}
static class EntriesGenerator<K, V, M extends Multimap<K, V>>
implements TestCollectionGenerator<Entry<K, V>>, DerivedGenerator {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public EntriesGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public TestSubjectGenerator<?> getInnerGenerator() {
return multimapGenerator;
}
@Override
public SampleElements<Entry<K, V>> samples() {
return multimapGenerator.samples();
}
@Override
public Collection<Entry<K, V>> create(Object... elements) {
return multimapGenerator.create(elements).entries();
}
@SuppressWarnings("unchecked")
@Override
public Entry<K, V>[] createArray(int length) {
return new Entry[length];
}
@Override
public Iterable<Entry<K, V>> order(List<Entry<K, V>> insertionOrder) {
return multimapGenerator.order(insertionOrder);
}
}
static class ValuesGenerator<K, V, M extends Multimap<K, V>>
implements TestCollectionGenerator<V> {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public ValuesGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public SampleElements<V> samples() {
return
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleValues();
}
@Override
public Collection<V> create(Object... elements) {
K k =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys().e0;
Entry<K, V>[] entries = new Entry[elements.length];
for (int i = 0; i < elements.length; i++) {
entries[i] = mapEntry(k, (V) elements[i]);
}
return multimapGenerator.create(entries).values();
}
@SuppressWarnings("unchecked")
@Override
public V[] createArray(int length) {
return ((TestMultimapGenerator<K, V, M>)
multimapGenerator.getInnerGenerator()).createValueArray(length);
}
@Override
public Iterable<V> order(List<V> insertionOrder) {
K k =
((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys().e0;
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (V v : insertionOrder) {
entries.add(mapEntry(k, v));
}
Iterable<Entry<K, V>> ordered = multimapGenerator.order(entries);
List<V> orderedValues = new ArrayList<V>();
for (Entry<K, V> entry : ordered) {
orderedValues.add(entry.getValue());
}
return orderedValues;
}
}
static class KeysGenerator<K, V, M extends Multimap<K, V>> implements
TestMultisetGenerator<K>, DerivedGenerator {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public KeysGenerator(
OneSizeTestContainerGenerator<M, Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public TestSubjectGenerator<?> getInnerGenerator() {
return multimapGenerator;
}
@Override
public SampleElements<K> samples() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator()).sampleKeys();
}
@Override
public Multiset<K> create(Object... elements) {
Iterator<V> valueIter = ((TestMultimapGenerator<K, V, M>) multimapGenerator
.getInnerGenerator()).sampleValues().iterator();
Entry<K, V>[] entries = new Entry[elements.length];
for (int i = 0; i < elements.length; i++) {
entries[i] = mapEntry((K) elements[i], valueIter.next());
}
return multimapGenerator.create(entries).keys();
}
@SuppressWarnings("unchecked")
@Override
public K[] createArray(int length) {
return ((TestMultimapGenerator<K, V, M>)
multimapGenerator.getInnerGenerator()).createKeyArray(length);
}
@Override
public Iterable<K> order(List<K> insertionOrder) {
Iterator<V> valueIter = ((TestMultimapGenerator<K, V, M>) multimapGenerator
.getInnerGenerator()).sampleValues().iterator();
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (K k : insertionOrder) {
entries.add(mapEntry(k, valueIter.next()));
}
Iterable<Entry<K, V>> ordered = multimapGenerator.order(entries);
List<K> orderedValues = new ArrayList<K>();
for (Entry<K, V> entry : ordered) {
orderedValues.add(entry.getKey());
}
return orderedValues;
}
}
static class MultimapGetGenerator<K, V, M extends Multimap<K, V>>
implements TestCollectionGenerator<V> {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public MultimapGetGenerator(
OneSizeTestContainerGenerator<
M, Map.Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public SampleElements<V> samples() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleValues();
}
@Override
public V[] createArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createValueArray(length);
}
@Override
public Iterable<V> order(List<V> insertionOrder) {
K k = ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleKeys().e0;
List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>();
for (V v : insertionOrder) {
entries.add(mapEntry(k, v));
}
Iterable<Entry<K, V>> orderedEntries = multimapGenerator.order(entries);
List<V> values = new ArrayList<V>();
for (Entry<K, V> entry : orderedEntries) {
values.add(entry.getValue());
}
return values;
}
@Override
public Collection<V> create(Object... elements) {
Entry<K, V>[] array = multimapGenerator.createArray(elements.length);
K k = ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleKeys().e0;
for (int i = 0; i < elements.length; i++) {
array[i] = mapEntry(k, (V) elements[i]);
}
return multimapGenerator.create(array).get(k);
}
}
private static class ReserializedMultimapGenerator<K, V, M extends Multimap<K, V>>
implements TestMultimapGenerator<K, V, M> {
private final OneSizeTestContainerGenerator<M, Map.Entry<K, V>> multimapGenerator;
public ReserializedMultimapGenerator(
OneSizeTestContainerGenerator<
M, Map.Entry<K, V>> multimapGenerator) {
this.multimapGenerator = multimapGenerator;
}
@Override
public SampleElements<Map.Entry<K, V>> samples() {
return multimapGenerator.samples();
}
@Override
public Map.Entry<K, V>[] createArray(int length) {
return multimapGenerator.createArray(length);
}
@Override
public Iterable<Map.Entry<K, V>> order(
List<Map.Entry<K, V>> insertionOrder) {
return multimapGenerator.order(insertionOrder);
}
@Override
public M create(Object... elements) {
return SerializableTester.reserialize(((TestMultimapGenerator<K, V, M>) multimapGenerator
.getInnerGenerator()).create(elements));
}
@Override
public K[] createKeyArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createKeyArray(length);
}
@Override
public V[] createValueArray(int length) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createValueArray(length);
}
@Override
public SampleElements<K> sampleKeys() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleKeys();
}
@Override
public SampleElements<V> sampleValues() {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.sampleValues();
}
@Override
public Collection<V> createCollection(Iterable<? extends V> values) {
return ((TestMultimapGenerator<K, V, M>) multimapGenerator.getInnerGenerator())
.createCollection(values);
}
}
}
| 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.AbstractMapTester;
import com.google.common.collect.testing.Helpers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
/**
* Skeleton for a tester of a {@code BiMap}.
*/
@GwtCompatible
public abstract class AbstractBiMapTester<K, V> extends AbstractMapTester<K, V> {
@Override
protected BiMap<K, V> getMap() {
return (BiMap<K, V>) super.getMap();
}
static <K, V> Entry<V, K> reverseEntry(Entry<K, V> entry) {
return Helpers.mapEntry(entry.getValue(), entry.getKey());
}
@Override
protected void expectContents(Collection<Entry<K, V>> expected) {
super.expectContents(expected);
List<Entry<V, K>> reversedEntries = new ArrayList<Entry<V, K>>();
for (Entry<K, V> entry : expected) {
reversedEntries.add(reverseEntry(entry));
}
Helpers.assertEqualIgnoringOrder(getMap().inverse().entrySet(), reversedEntries);
for (Entry<K, V> entry : expected) {
assertEquals("Wrong key for value " + entry.getValue(), entry.getKey(), getMap()
.inverse()
.get(entry.getValue()));
}
}
@Override
protected void expectMissing(Entry<K, V>... entries) {
super.expectMissing(entries);
for (Entry<K, V> entry : entries) {
Entry<V, K> reversed = reverseEntry(entry);
BiMap<V, K> inv = getMap().inverse();
assertFalse("Inverse should not contain entry " + reversed,
inv.entrySet().contains(entry));
assertFalse("Inverse should not contain key " + entry.getValue(),
inv.containsKey(entry.getValue()));
assertFalse("Inverse should not contain value " + entry.getKey(),
inv.containsValue(entry.getKey()));
assertNull("Inverse should not return a mapping for key " + entry.getValue(),
getMap().get(entry.getValue()));
}
}
}
| 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.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.AbstractCollectionTester;
/**
* Base class for multiset collection tests.
*
* @author Jared Levy
*/
@GwtCompatible
public class AbstractMultisetTester<E> extends AbstractCollectionTester<E> {
protected final Multiset<E> getMultiset() {
return (Multiset<E>) collection;
}
protected void initThreeCopies() {
collection =
getSubjectGenerator().create(samples.e0, samples.e0, 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.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A skeleton generator for a {@code ListMultimap} implementation.
*
* @author Louis Wasserman
*/
@GwtCompatible
public abstract class TestStringListMultimapGenerator
implements TestListMultimapGenerator<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 SampleElements<String> sampleKeys() {
return new SampleElements<String>("one", "two", "three", "four", "five");
}
@Override
public SampleElements<String> sampleValues() {
return new SampleElements<String>("January", "February", "March", "April", "May");
}
@Override
public Collection<String> createCollection(Iterable<? extends String> values) {
return Helpers.copyToList(values);
}
@Override
public final ListMultimap<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 ListMultimap<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) 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.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* Tester for {@code BiMap.put} and {@code BiMap.forcePut}.
*/
@GwtCompatible
public class BiMapPutTester<K, V> extends AbstractBiMapTester<K, V> {
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testPutWithSameValueFails() {
K k0 = samples.e0.getKey();
K k1 = samples.e1.getKey();
V v0 = samples.e0.getValue();
getMap().put(k0, v0);
try {
getMap().put(k1, v0);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// success
}
// verify that the bimap is unchanged
expectAdded(samples.e0);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testPutPresentKeyDifferentValue() {
K k0 = samples.e0.getKey();
V v0 = samples.e0.getValue();
V v1 = samples.e1.getValue();
getMap().put(k0, v0);
getMap().put(k0, v1);
// verify that the bimap is changed, and that the old inverse mapping
// from v1 -> v0 is deleted
expectContents(Helpers.mapEntry(k0, v1));
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void putDistinctKeysDistinctValues() {
getMap().put(samples.e0.getKey(), samples.e0.getValue());
getMap().put(samples.e1.getKey(), samples.e1.getValue());
expectAdded(samples.e0, samples.e1);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testForcePutOverwritesOldValueEntry() {
K k0 = samples.e0.getKey();
K k1 = samples.e1.getKey();
V v0 = samples.e0.getValue();
getMap().put(k0, v0);
getMap().forcePut(k1, v0);
// verify that the bimap is unchanged
expectAdded(Helpers.mapEntry(k1, v0));
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(ZERO)
public void testInversePut() {
K k0 = samples.e0.getKey();
V v0 = samples.e0.getValue();
K k1 = samples.e1.getKey();
V v1 = samples.e1.getValue();
getMap().put(k0, v0);
getMap().inverse().put(v1, k1);
expectAdded(samples.e0, samples.e1);
}
}
| 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.CollectionFeature.SERIALIZABLE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.testing.SerializableTester;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
/**
* Tests for the {@code inverse} view of a BiMap.
*
* <p>This assumes that {@code bimap.inverse().inverse() == bimap}, which is not technically
* required but is fulfilled by all current implementations.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class BiMapInverseTester<K, V> extends AbstractBiMapTester<K, V> {
public void testInverseSame() {
assertSame(getMap(), getMap().inverse().inverse());
}
@CollectionFeature.Require(SERIALIZABLE)
public void testInverseSerialization() {
BiMapPair<K, V> pair = new BiMapPair<K, V>(getMap());
BiMapPair<K, V> copy = SerializableTester.reserialize(pair);
assertEquals(pair.forward, copy.forward);
assertEquals(pair.backward, copy.backward);
assertSame(copy.backward, copy.forward.inverse());
assertSame(copy.forward, copy.backward.inverse());
}
private static class BiMapPair<K, V> implements Serializable {
final BiMap<K, V> forward;
final BiMap<V, K> backward;
BiMapPair(BiMap<K, V> original) {
this.forward = original;
this.backward = original.inverse();
}
private static final long serialVersionUID = 0;
}
/**
* Returns {@link Method} instances for the tests that assume that the inverse will be the same
* after serialization.
*/
@GwtIncompatible("reflection")
public static List<Method> getInverseSameAfterSerializingMethods() {
return Collections.singletonList(getMethod("testInverseSerialization"));
}
@GwtIncompatible("reflection")
private static Method getMethod(String methodName) {
return Helpers.getMethod(BiMapInverseTester.class, methodName);
}
}
| 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.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import com.google.common.collect.testing.TestStringMapGenerator;
import com.google.common.collect.testing.TestUnhashableCollectionGenerator;
import com.google.common.collect.testing.UnhashableObject;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Generators of different types of map and related collections, such as
* keys, entries and values.
*
* @author Hayward Chan
*/
@GwtCompatible
public class MapGenerators {
public static class ImmutableMapGenerator
extends TestStringMapGenerator {
@Override protected Map<String, String> create(Entry<String, String>[] entries) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Entry<String, String> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
}
}
public static class ImmutableMapUnhashableValuesGenerator
extends TestUnhashableCollectionGenerator<Collection<UnhashableObject>> {
@Override public Collection<UnhashableObject> create(
UnhashableObject[] elements) {
ImmutableMap.Builder<Integer, UnhashableObject> builder = ImmutableMap.builder();
int key = 1;
for (UnhashableObject value : elements) {
builder.put(key++, value);
}
return builder.build().values();
}
}
public static class ImmutableMapValueListGenerator
implements TestListGenerator<String> {
@Override
public SampleElements<String> samples() {
return new SampleElements.Strings();
}
@Override
public List<String> create(Object... elements) {
ImmutableMap.Builder<Integer, String> builder = ImmutableMap.builder();
for (int i = 0; i < elements.length; i++) {
builder.put(i, toStringOrNull(elements[i]));
}
return builder.build().values().asList();
}
@Override
public String[] createArray(int length) {
return new String[length];
}
@Override
public Iterable<String> order(List<String> insertionOrder) {
return insertionOrder;
}
}
private static String toStringOrNull(Object o) {
return (o == null) ? null : o.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.google;
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.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
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.Collections;
import java.util.Iterator;
/**
* A generic JUnit test which tests multiset-specific write operations.
* Can't be invoked directly; please see {@link MultisetTestSuiteBuilder}.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetWritesTester<E> extends AbstractMultisetTester<E> {
/**
* Returns the {@link Method} instance for
* {@link #testEntrySet_iterator()} so that tests of
* classes with unmodifiable iterators can suppress it.
*/
@GwtIncompatible("reflection")
public static Method getEntrySetIteratorMethod() {
return Helpers.getMethod(
MultisetWritesTester.class, "testEntrySet_iterator");
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOccurrencesZero() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().add(samples.e0, 0));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddOccurrences() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().add(samples.e0, 2));
assertEquals("old count", originalCount + 2, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddOccurrences_unsupported() {
try {
getMultiset().add(samples.e0, 2);
fail("unsupported multiset.add(E, int) didn't throw exception");
} catch (UnsupportedOperationException required) {}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAdd_occurrences_negative() {
try {
getMultiset().add(samples.e0, -1);
fail("multiset.add(E, -1) didn't throw an exception");
} catch (IllegalArgumentException required) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveZeroNoOp() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().remove(samples.e0, 0));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_present() {
assertEquals("multiset.remove(present, 2) didn't return the old count",
1, getMultiset().remove(samples.e0, 2));
assertFalse("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_absent() {
assertEquals("multiset.remove(absent, 0) didn't return 0",
0, getMultiset().remove(samples.e3, 2));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemove_occurrences_unsupported_absent() {
// notice: we don't care whether it succeeds, or fails with UOE
try {
assertEquals(
"multiset.remove(absent, 2) didn't return 0 or throw an exception",
0, getMultiset().remove(samples.e3, 2));
} catch (UnsupportedOperationException ok) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_0() {
int oldCount = getMultiset().count(samples.e0);
assertEquals("multiset.remove(E, 0) didn't return the old count",
oldCount, getMultiset().remove(samples.e0, 0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_negative() {
try {
getMultiset().remove(samples.e0, -1);
fail("multiset.remove(E, -1) didn't throw an exception");
} catch (IllegalArgumentException required) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_wrongType() {
assertEquals("multiset.remove(wrongType, 1) didn't return 0",
0, getMultiset().remove(WrongType.VALUE, 1));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_clear() {
getMultiset().entrySet().clear();
assertTrue("multiset not empty after entrySet().clear()",
getMultiset().isEmpty());
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_iterator() {
Iterator<Multiset.Entry<E>> iterator = getMultiset().entrySet().iterator();
assertTrue(
"non-empty multiset.entrySet() iterator.hasNext() returned false",
iterator.hasNext());
assertEquals("multiset.entrySet() iterator.next() returned incorrect entry",
Multisets.immutableEntry(samples.e0, 1), iterator.next());
assertFalse(
"size 1 multiset.entrySet() iterator.hasNext() returned true "
+ "after next()",
iterator.hasNext());
iterator.remove();
assertTrue(
"multiset isn't empty after multiset.entrySet() iterator.remove()",
getMultiset().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testEntrySet_iterator_remove_unsupported() {
Iterator<Multiset.Entry<E>> iterator = getMultiset().entrySet().iterator();
assertTrue(
"non-empty multiset.entrySet() iterator.hasNext() returned false",
iterator.hasNext());
try {
iterator.remove();
fail("multiset.entrySet() iterator.remove() didn't throw an exception");
} catch (UnsupportedOperationException expected) {}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_remove_present() {
assertTrue(
"multiset.entrySet.remove(presentEntry) returned false",
getMultiset().entrySet().remove(
Multisets.immutableEntry(samples.e0, 1)));
assertFalse(
"multiset contains element after removing its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_remove_missing() {
assertFalse(
"multiset.entrySet.remove(missingEntry) returned true",
getMultiset().entrySet().remove(
Multisets.immutableEntry(samples.e0, 2)));
assertTrue(
"multiset didn't contain element after removing a missing entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAll_present() {
assertTrue(
"multiset.entrySet.removeAll(presentEntry) returned false",
getMultiset().entrySet().removeAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 1))));
assertFalse(
"multiset contains element after removing its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAll_missing() {
assertFalse(
"multiset.entrySet.remove(missingEntry) returned true",
getMultiset().entrySet().removeAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 2))));
assertTrue(
"multiset didn't contain element after removing a missing entry",
getMultiset().contains(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_removeAll_null() {
try {
getMultiset().entrySet().removeAll(null);
fail("multiset.entrySet.removeAll(null) didn't throw an exception");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAll_present() {
assertFalse(
"multiset.entrySet.retainAll(presentEntry) returned false",
getMultiset().entrySet().retainAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 1))));
assertTrue(
"multiset doesn't contains element after retaining its entry",
getMultiset().contains(samples.e0));
}
@CollectionSize.Require(ONE)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAll_missing() {
assertTrue(
"multiset.entrySet.retainAll(missingEntry) returned true",
getMultiset().entrySet().retainAll(
Collections.singleton(Multisets.immutableEntry(samples.e0, 2))));
assertFalse(
"multiset contains element after retaining a different entry",
getMultiset().contains(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testEntrySet_retainAll_null() {
try {
getMultiset().entrySet().retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException expected) {}
}
}
| 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 static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
/**
* Tests for {@link Multimap#remove(Object, Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapRemoveEntryTester<K, V> extends AbstractMultimapTester<K, V> {
private static final Object[] EMPTY = new Object[0];
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAbsent() {
assertFalse(multimap().remove(sampleKeys().e0, sampleValues().e1));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemovePropagatesToGet() {
Collection<V> result = multimap().get(sampleKeys().e0);
assertTrue(multimap().remove(sampleKeys().e0, sampleValues().e0));
assertTrue(result.isEmpty());
assertFalse(multimap().containsKey(sampleKeys().e0));
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemovePresent() {
assertTrue(multimap().remove(sampleKeys().e0, sampleValues().e0));
expectMissing(samples.e0);
assertGet(sampleKeys().e0, EMPTY);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_KEYS })
public void testRemoveNullKeyPresent() {
initMultimapWithNullKey();
assertTrue(multimap().remove(null, getValueForNullKey()));
expectMissing(Maps.immutableEntry((K) null, getValueForNullKey()));
assertGet(getKeyForNullValue(), EMPTY);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_VALUES })
public void testRemoveNullValuePresent() {
initMultimapWithNullValue();
assertTrue(multimap().remove(getKeyForNullValue(), null));
expectMissing(Maps.immutableEntry(getKeyForNullValue(), (V) null));
assertGet(getKeyForNullValue(), EMPTY);
}
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES})
public void testRemoveNullKeyAbsent() {
assertFalse(multimap().remove(null, sampleValues().e0));
expectUnchanged();
}
@MapFeature.Require({ SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES})
public void testRemoveNullValueAbsent() {
assertFalse(multimap().remove(sampleKeys().e0, null));
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES)
public void testRemoveNullValueForbidden() {
try {
multimap().remove(sampleKeys().e0, null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
expectUnchanged();
}
@MapFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES)
public void testRemoveNullKeyForbidden() {
try {
multimap().remove(null, sampleValues().e0);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
expectUnchanged();
}
}
| 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_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
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 {@link Multimap#containsValue}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapContainsValueTester<K, V> extends AbstractMultimapTester<K, V> {
@CollectionSize.Require(absent = ZERO)
public void testContainsValueYes() {
assertTrue(multimap().containsValue(sampleValues().e0));
}
public void testContainsValueNo() {
assertFalse(multimap().containsValue(sampleValues().e3));
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContainsNullValueYes() {
initMultimapWithNullValue();
assertTrue(multimap().containsValue(null));
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testContainsNullValueNo() {
assertFalse(multimap().containsValue(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContainsNullValueFails() {
try {
multimap().containsValue(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| 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.google;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static java.util.Collections.nCopies;
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 conditional {@code setCount()} operations on
* a multiset. Can't be invoked directly; please see
* {@link MultisetTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@GwtCompatible
public class MultisetSetCountConditionallyTester<E> extends
AbstractMultisetSetCountTester<E> {
@Override void setCountCheckReturnValue(E element, int count) {
assertTrue(
"setCount() with the correct expected present count should return true",
setCount(element, count));
}
@Override void setCountNoCheckReturnValue(E element, int count) {
setCount(element, count);
}
private boolean setCount(E element, int count) {
return getMultiset().setCount(element, getMultiset().count(element), count);
}
private void assertSetCountNegativeOldCount() {
try {
getMultiset().setCount(samples.e3, -1, 1);
fail("calling setCount() with a negative oldCount should throw "
+ "IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
// Negative oldCount.
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_negativeOldCount_addSupported() {
assertSetCountNegativeOldCount();
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCountConditional_negativeOldCount_addUnsupported() {
try {
assertSetCountNegativeOldCount();
} catch (UnsupportedOperationException tolerated) {
}
}
// Incorrect expected present count.
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_oldCountTooLarge() {
assertFalse("setCount() with a too-large oldCount should return false",
getMultiset().setCount(samples.e0, 2, 3));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_oldCountTooSmallZero() {
assertFalse("setCount() with a too-small oldCount should return false",
getMultiset().setCount(samples.e0, 0, 2));
expectUnchanged();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCountConditional_oldCountTooSmallNonzero() {
initThreeCopies();
assertFalse("setCount() with a too-small oldCount should return false",
getMultiset().setCount(samples.e0, 1, 5));
expectContents(nCopies(3, samples.e0));
}
/*
* TODO: test that unmodifiable multisets either throw UOE or return false
* when both are valid options. Currently we test the UOE cases and the
* return-false cases but not their intersection
*/
}
| 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.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.testing.SerializableTester;
import java.util.Set;
/**
* A generic JUnit test which tests multiset-specific serialization. Can't be invoked directly;
* please see {@link com.google.common.collect.testing.MultisetTestSuiteBuilder}.
*
* @author Louis Wasserman
*/
@GwtCompatible // but no-op
public class MultisetSerializationTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testEntrySetSerialization() {
Set<Multiset.Entry<E>> expected = getMultiset().entrySet();
assertEquals(expected, SerializableTester.reserialize(expected));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testElementSetSerialization() {
Set<E> expected = getMultiset().elementSet();
assertEquals(expected, SerializableTester.reserialize(expected));
}
}
| 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.collect.SetMultimap;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestSetGenerator;
import junit.framework.TestSuite;
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 {@code SetMultimap} implementation.
*
* @author Louis Wasserman
*/
public class SetMultimapTestSuiteBuilder<K, V>
extends MultimapTestSuiteBuilder<K, V, SetMultimap<K, V>> {
public static <K, V> SetMultimapTestSuiteBuilder<K, V> using(
TestSetMultimapGenerator<K, V> generator) {
SetMultimapTestSuiteBuilder<K, V> result = new SetMultimapTestSuiteBuilder<K, V>();
result.usingGenerator(generator);
return result;
}
@Override
TestSuite computeMultimapGetTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>>> parentBuilder) {
return SetTestSuiteBuilder.using(
new MultimapGetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeMultimapGetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".get[key]")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
@Override
TestSuite computeEntriesTestSuite(
FeatureSpecificTestSuiteBuilder<?, ? extends
OneSizeTestContainerGenerator<SetMultimap<K, V>, Map.Entry<K, V>>> parentBuilder) {
return SetTestSuiteBuilder.using(
new EntriesGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeEntriesFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + ".entries")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
private static class EntriesGenerator<K, V>
extends MultimapTestSuiteBuilder.EntriesGenerator<K, V, SetMultimap<K, V>>
implements TestSetGenerator<Entry<K, V>> {
public EntriesGenerator(
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Set<Entry<K, V>> create(Object... elements) {
return (Set<Entry<K, V>>) super.create(elements);
}
}
private static class MultimapGetGenerator<K, V>
extends MultimapTestSuiteBuilder.MultimapGetGenerator<K, V, SetMultimap<K, V>>
implements TestSetGenerator<V> {
public MultimapGetGenerator(
OneSizeTestContainerGenerator<SetMultimap<K, V>, Entry<K, V>> multimapGenerator) {
super(multimapGenerator);
}
@Override
public Set<V> create(Object... elements) {
return (Set<V>) 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.google;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.fail;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.LinkedHashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* A series of tests that support asserting that collections cannot be
* modified, either through direct or indirect means.
*
* @author Robert Konigsberg
*/
@GwtCompatible
public class UnmodifiableCollectionTests {
public static void assertMapEntryIsUnmodifiable(Entry<?, ?> entry) {
try {
entry.setValue(null);
fail("setValue on unmodifiable Map.Entry succeeded");
} catch (UnsupportedOperationException expected) {
}
}
/**
* Verifies that an Iterator is unmodifiable.
*
* <p>This test only works with iterators that iterate over a finite set.
*/
public static void assertIteratorIsUnmodifiable(Iterator<?> iterator) {
while (iterator.hasNext()) {
iterator.next();
try {
iterator.remove();
fail("Remove on unmodifiable iterator succeeded");
} catch (UnsupportedOperationException expected) {
}
}
}
/**
* Asserts that two iterators contain elements in tandem.
*
* <p>This test only works with iterators that iterate over a finite set.
*/
public static void assertIteratorsInOrder(
Iterator<?> expectedIterator, Iterator<?> actualIterator) {
int i = 0;
while (expectedIterator.hasNext()) {
Object expected = expectedIterator.next();
assertTrue(
"index " + i + " expected <" + expected + "., actual is exhausted",
actualIterator.hasNext());
Object actual = actualIterator.next();
assertEquals("index " + i, expected, actual);
i++;
}
if (actualIterator.hasNext()) {
fail("index " + i
+ ", expected is exhausted, actual <" + actualIterator.next() + ">");
}
}
/**
* Verifies that a collection is immutable.
*
* <p>A collection is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* collection throw UnsupportedOperationException when those mutators
* are called.
* </ol>
*
* @param collection the presumed-immutable collection
* @param sampleElement an element of the same type as that contained by
* {@code collection}. {@code collection} may or may not have {@code
* sampleElement} as a member.
*/
public static <E> void assertCollectionIsUnmodifiable(
Collection<E> collection, E sampleElement) {
Collection<E> siblingCollection = new ArrayList<E>();
siblingCollection.add(sampleElement);
Collection<E> copy = new ArrayList<E>();
copy.addAll(collection);
try {
collection.add(sampleElement);
fail("add succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.addAll(siblingCollection);
fail("addAll succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.clear();
fail("clear succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
assertIteratorIsUnmodifiable(collection.iterator());
assertCollectionsAreEquivalent(copy, collection);
try {
collection.remove(sampleElement);
fail("remove succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.removeAll(siblingCollection);
fail("removeAll succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
try {
collection.retainAll(siblingCollection);
fail("retainAll succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(copy, collection);
}
/**
* Verifies that a set is immutable.
*
* <p>A set is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* set throw UnsupportedOperationException when those mutators
* are called.
* </ol>
*
* @param set the presumed-immutable set
* @param sampleElement an element of the same type as that contained by
* {@code set}. {@code set} may or may not have {@code sampleElement} as a
* member.
*/
public static <E> void assertSetIsUnmodifiable(
Set<E> set, E sampleElement) {
assertCollectionIsUnmodifiable(set, sampleElement);
}
/**
* Verifies that a multiset is immutable.
*
* <p>A multiset is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* multiset throw UnsupportedOperationException when those mutators
* are called.
* </ol>
*
* @param multiset the presumed-immutable multiset
* @param sampleElement an element of the same type as that contained by
* {@code multiset}. {@code multiset} may or may not have {@code
* sampleElement} as a member.
*/
public static <E> void assertMultisetIsUnmodifiable(Multiset<E> multiset,
final E sampleElement) {
Multiset<E> copy = LinkedHashMultiset.create(multiset);
assertCollectionsAreEquivalent(multiset, copy);
// Multiset is a collection, so we can use all those tests.
assertCollectionIsUnmodifiable(multiset, sampleElement);
assertCollectionsAreEquivalent(multiset, copy);
try {
multiset.add(sampleElement, 2);
fail("add(Object, int) succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(multiset, copy);
try {
multiset.remove(sampleElement, 2);
fail("remove(Object, int) succeeded on unmodifiable collection");
} catch (UnsupportedOperationException expected) {
}
assertCollectionsAreEquivalent(multiset, copy);
assertCollectionsAreEquivalent(multiset, copy);
assertSetIsUnmodifiable(multiset.elementSet(), sampleElement);
assertCollectionsAreEquivalent(multiset, copy);
assertSetIsUnmodifiable(
multiset.entrySet(), new Multiset.Entry<E>() {
@Override
public int getCount() {
return 1;
}
@Override
public E getElement() {
return sampleElement;
}
});
assertCollectionsAreEquivalent(multiset, copy);
}
/**
* Verifies that a multimap is immutable.
*
* <p>A multimap is considered immutable if:
* <ol>
* <li>All its mutation methods result in UnsupportedOperationException, and
* do not change the underlying contents.
* <li>All methods that return objects that can indirectly mutate the
* multimap throw UnsupportedOperationException when those mutators
* </ol>
*
* @param multimap the presumed-immutable multimap
* @param sampleKey a key of the same type as that contained by
* {@code multimap}. {@code multimap} may or may not have {@code sampleKey} as
* a key.
* @param sampleValue a key of the same type as that contained by
* {@code multimap}. {@code multimap} may or may not have {@code sampleValue}
* as a key.
*/
public static <K, V> void assertMultimapIsUnmodifiable(
Multimap<K, V> multimap, final K sampleKey, final V sampleValue) {
List<Entry<K, V>> originalEntries =
Collections.unmodifiableList(Lists.newArrayList(multimap.entries()));
assertMultimapRemainsUnmodified(multimap, originalEntries);
Collection<V> sampleValueAsCollection = Collections.singleton(sampleValue);
// Test #clear()
try {
multimap.clear();
fail("clear succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test asMap().entrySet()
assertSetIsUnmodifiable(
multimap.asMap().entrySet(),
Maps.immutableEntry(sampleKey, sampleValueAsCollection));
// Test #values()
assertMultimapRemainsUnmodified(multimap, originalEntries);
if (!multimap.isEmpty()) {
Collection<V> values =
multimap.asMap().entrySet().iterator().next().getValue();
assertCollectionIsUnmodifiable(values, sampleValue);
}
// Test #entries()
assertCollectionIsUnmodifiable(
multimap.entries(),
Maps.immutableEntry(sampleKey, sampleValue));
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Iterate over every element in the entry set
for (Entry<K, V> entry : multimap.entries()) {
assertMapEntryIsUnmodifiable(entry);
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #keys()
assertMultisetIsUnmodifiable(multimap.keys(), sampleKey);
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #keySet()
assertSetIsUnmodifiable(multimap.keySet(), sampleKey);
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #get()
if (!multimap.isEmpty()) {
K key = multimap.keySet().iterator().next();
assertCollectionIsUnmodifiable(multimap.get(key), sampleValue);
assertMultimapRemainsUnmodified(multimap, originalEntries);
}
// Test #put()
try {
multimap.put(sampleKey, sampleValue);
fail("put succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #putAll(K, Collection<V>)
try {
multimap.putAll(sampleKey, sampleValueAsCollection);
fail("putAll(K, Iterable) succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #putAll(Multimap<K, V>)
Multimap<K, V> multimap2 = ArrayListMultimap.create();
multimap2.put(sampleKey, sampleValue);
try {
multimap.putAll(multimap2);
fail("putAll(Multimap<K, V>) succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #remove()
try {
multimap.remove(sampleKey, sampleValue);
fail("remove succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #removeAll()
try {
multimap.removeAll(sampleKey);
fail("removeAll succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #replaceValues()
try {
multimap.replaceValues(sampleKey, sampleValueAsCollection);
fail("replaceValues succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
// Test #asMap()
try {
multimap.asMap().remove(sampleKey);
fail("asMap().remove() succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
if (!multimap.isEmpty()) {
K presentKey = multimap.keySet().iterator().next();
try {
multimap.asMap().get(presentKey).remove(sampleValue);
fail("asMap().get().remove() succeeded on unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
assertMultimapRemainsUnmodified(multimap, originalEntries);
try {
multimap.asMap().values().iterator().next().remove(sampleValue);
fail("asMap().values().iterator().next().remove() succeeded on " +
"unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
try {
((Collection<?>) multimap.asMap().values().toArray()[0]).clear();
fail("asMap().values().toArray()[0].clear() succeeded on " +
"unmodifiable multimap");
} catch (UnsupportedOperationException expected) {
}
}
assertCollectionIsUnmodifiable(multimap.values(), sampleValue);
assertMultimapRemainsUnmodified(multimap, originalEntries);
}
private static <E> void assertCollectionsAreEquivalent(
Collection<E> expected, Collection<E> actual) {
assertIteratorsInOrder(expected.iterator(), actual.iterator());
}
private static <K, V> void assertMultimapRemainsUnmodified(
Multimap<K, V> expected, List<Entry<K, V>> actual) {
assertIteratorsInOrder(
expected.entries().iterator(), actual.iterator());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import java.util.Map.Entry;
/**
* Generators of various {@link com.google.common.collect.BiMap}s and derived
* collections.
*
* @author Jared Levy
* @author Hayward Chan
*/
@GwtCompatible
public class BiMapGenerators {
public static class ImmutableBiMapGenerator extends TestStringBiMapGenerator {
@Override protected BiMap<String, String> create(Entry<String, String>[] entries) {
ImmutableBiMap.Builder<String, String> builder = ImmutableBiMap.builder();
for (Entry<String, String> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
return builder.build();
}
}
}
| 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 |
/*
* 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.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.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.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Tester to make sure the {@code iterator().remove()} implementation of {@code Multiset} works when
* there are multiple occurrences of elements.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class MultisetIteratorTester<E> extends AbstractMultisetTester<E> {
@SuppressWarnings("unchecked")
@CollectionFeature.Require({SUPPORTS_REMOVE, KNOWN_ORDER})
public void testRemovingIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = SUPPORTS_REMOVE, absent = KNOWN_ORDER)
public void testRemovingIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_REMOVE)
public void testIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(absent = {SUPPORTS_REMOVE, KNOWN_ORDER})
public void testIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
/**
* Returns {@link Method} instances for the tests that assume multisets support duplicates so that
* the test of {@code Multisets.forSet()} can suppress them.
*/
@GwtIncompatible("reflection")
public static List<Method> getIteratorDuplicateInitializingMethods() {
return Arrays.asList(
Helpers.getMethod(MultisetIteratorTester.class, "testIteratorKnownOrder"),
Helpers.getMethod(MultisetIteratorTester.class, "testIteratorUnknownOrder"),
Helpers.getMethod(MultisetIteratorTester.class, "testRemovingIteratorKnownOrder"),
Helpers.getMethod(MultisetIteratorTester.class, "testRemovingIteratorUnknownOrder"));
}
}
| 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.Helpers.assertContentsAnyOrder;
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 static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.junit.contrib.truth.Truth.ASSERT;
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;
import java.util.Collection;
/**
* Tests for {@link Multimap#get(Object)}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapGetTester<K, V> extends AbstractMultimapTester<K, V> {
public void testGetEmpty() {
Collection<V> result = multimap().get(sampleKeys().e3);
assertTrue(result.isEmpty());
assertEquals(0, result.size());
}
@CollectionSize.Require(absent = ZERO)
public void testGetNonEmpty() {
Collection<V> result = multimap().get(sampleKeys().e0);
assertFalse(result.isEmpty());
assertContentsAnyOrder(result, sampleValues().e0);
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(SUPPORTS_REMOVE)
public void testGetPropagatesRemove() {
Collection<V> result = multimap().get(sampleKeys().e0);
assertTrue(result.remove(sampleValues().e0));
assertFalse(multimap().containsKey(sampleKeys().e0));
assertTrue(result.isEmpty());
assertTrue(multimap().get(sampleKeys().e0).isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ SUPPORTS_REMOVE, SUPPORTS_PUT })
public void testGetRemoveThenAddPropagates() {
int oldSize = getNumElements();
K k0 = sampleKeys().e0;
V v0 = sampleValues().e0;
Collection<V> result = multimap().get(k0);
assertTrue(result.remove(v0));
assertFalse(multimap().containsKey(k0));
assertFalse(multimap().containsEntry(k0, v0));
ASSERT.that(result).isEmpty();
V v1 = sampleValues().e1;
V v2 = sampleValues().e2;
assertTrue(result.add(v1));
assertTrue(result.add(v2));
ASSERT.that(result).hasContentsAnyOrder(v1, v2);
ASSERT.that(multimap().get(k0)).hasContentsAnyOrder(v1, v2);
assertTrue(multimap().containsKey(k0));
assertFalse(multimap().containsEntry(k0, v0));
assertTrue(multimap().containsEntry(k0, v2));
assertEquals(oldSize + 1, multimap().size());
}
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testGetNullPresent() {
initMultimapWithNullKey();
ASSERT.that(multimap().get(null)).hasContentsInOrder(getValueForNullKey());
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testGetNullAbsent() {
ASSERT.that(multimap().get(null)).isEmpty();
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testGetNullForbidden() {
try {
multimap().get(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testGetWithNullValue() {
initMultimapWithNullValue();
ASSERT.that(multimap().get(getKeyForNullValue()))
.hasContentsInOrder((V) 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.google;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.testing.TestCollectionGenerator;
/**
* Creates multisets, containing sample elements, to be tested.
*
* @author Jared Levy
*/
@GwtCompatible
public interface TestMultisetGenerator<E> extends TestCollectionGenerator<E> {
@Override
Multiset<E> create(Object... elements);
}
| 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.junit.contrib.truth.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.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>
extends AbstractContainerTester<Multimap<K, V>, Map.Entry<K, V>> {
private Multimap<K, V> multimap;
protected Multimap<K, V> 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 Multimap<K, V> resetContainer(Multimap<K, V> 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, Object... values) {
ASSERT.that(multimap().get(key)).hasContentsAnyOrder(values);
if (values.length > 0) {
ASSERT.that(multimap().asMap().get(key)).hasContentsAnyOrder(values);
assertFalse(multimap().isEmpty());
} else {
ASSERT.that(multimap().asMap().get(key)).isNull();
}
// Truth+autoboxing == compile error. Cast int to long to fix:
ASSERT.that(multimap().get(key).size()).is((long) values.length);
assertEquals(values.length > 0, multimap().containsKey(key));
assertEquals(values.length > 0, multimap().keySet().contains(key));
assertEquals(values.length > 0, multimap().keys().contains(key));
}
}
| 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.SetMultimap;
/**
* A generator for {@code SetMultimap} implementations based on test data.
*
* @author Louis Wasserman
*/
@GwtCompatible
public interface TestSetMultimapGenerator<K, V>
extends TestMultimapGenerator<K, V, SetMultimap<K, V>> {
}
| 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.google;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.testing.TestCharacterListGenerator;
import com.google.common.collect.testing.TestListGenerator;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestUnhashableCollectionGenerator;
import com.google.common.collect.testing.UnhashableObject;
import com.google.common.primitives.Chars;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Common generators of different types of lists.
*
* @author Hayward Chan
*/
@GwtCompatible
public final class ListGenerators {
private ListGenerators() {}
public static class ImmutableListOfGenerator extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
return ImmutableList.copyOf(elements);
}
}
public static class BuilderAddListGenerator extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
ImmutableList.Builder<String> builder = ImmutableList.<String>builder();
for (String element : elements) {
builder.add(element);
}
return builder.build();
}
}
public static class BuilderAddAllListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
return ImmutableList.<String>builder()
.addAll(asList(elements))
.build();
}
}
public static class BuilderReversedListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
List<String> list = asList(elements);
Collections.reverse(list);
return ImmutableList.copyOf(list).reverse();
}
}
public static class ImmutableListHeadSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
String[] suffix = {"f", "g"};
String[] all = new String[elements.length + suffix.length];
System.arraycopy(elements, 0, all, 0, elements.length);
System.arraycopy(suffix, 0, all, elements.length, suffix.length);
return ImmutableList.copyOf(all)
.subList(0, elements.length);
}
}
public static class ImmutableListTailSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
String[] prefix = {"f", "g"};
String[] all = new String[elements.length + prefix.length];
System.arraycopy(prefix, 0, all, 0, 2);
System.arraycopy(elements, 0, all, 2, elements.length);
return ImmutableList.copyOf(all)
.subList(2, elements.length + 2);
}
}
public static class ImmutableListMiddleSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
String[] prefix = {"f", "g"};
String[] suffix = {"h", "i"};
String[] all = new String[2 + elements.length + 2];
System.arraycopy(prefix, 0, all, 0, 2);
System.arraycopy(elements, 0, all, 2, elements.length);
System.arraycopy(suffix, 0, all, 2 + elements.length, 2);
return ImmutableList.copyOf(all)
.subList(2, elements.length + 2);
}
}
public static class CharactersOfStringGenerator
extends TestCharacterListGenerator {
@Override public List<Character> create(Character[] elements) {
char[] chars = Chars.toArray(Arrays.asList(elements));
return Lists.charactersOf(String.copyValueOf(chars));
}
}
public static class CharactersOfCharSequenceGenerator
extends TestCharacterListGenerator {
@Override public List<Character> create(Character[] elements) {
char[] chars = Chars.toArray(Arrays.asList(elements));
StringBuilder str = new StringBuilder();
str.append(chars);
return Lists.charactersOf(str);
}
}
private abstract static class TestUnhashableListGenerator
extends TestUnhashableCollectionGenerator<List<UnhashableObject>>
implements TestListGenerator<UnhashableObject> {
}
public static class UnhashableElementsImmutableListGenerator
extends TestUnhashableListGenerator {
@Override
public List<UnhashableObject> create(UnhashableObject[] elements) {
return ImmutableList.copyOf(elements);
}
}
}
| 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.SUPPORTS_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Iterator;
/**
* Tester for {@code BiMap.remove}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class BiMapRemoveTester<K, V> extends AbstractBiMapTester<K, V> {
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveKeyRemovesFromInverse() {
getMap().remove(samples.e0.getKey());
expectMissing(samples.e0);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveKeyFromKeySetRemovesFromInverse() {
getMap().keySet().remove(samples.e0.getKey());
expectMissing(samples.e0);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveFromValuesRemovesFromInverse() {
getMap().values().remove(samples.e0.getValue());
expectMissing(samples.e0);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveFromInverseRemovesFromForward() {
getMap().inverse().remove(samples.e0.getValue());
expectMissing(samples.e0);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveFromInverseKeySetRemovesFromForward() {
getMap().inverse().keySet().remove(samples.e0.getValue());
expectMissing(samples.e0);
}
@SuppressWarnings("unchecked")
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemoveFromInverseValuesRemovesFromInverse() {
getMap().inverse().values().remove(samples.e0.getKey());
expectMissing(samples.e0);
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testKeySetIteratorRemove() {
int initialSize = getNumElements();
Iterator<K> iterator = getMap().keySet().iterator();
iterator.next();
iterator.remove();
assertEquals(initialSize - 1, getMap().size());
assertEquals(initialSize - 1, getMap().inverse().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.google;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newTreeSet;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST_2;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST_2;
import static junit.framework.Assert.assertEquals;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomains;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.testing.TestCollectionGenerator;
import com.google.common.collect.testing.TestCollidingSetGenerator;
import com.google.common.collect.testing.TestIntegerSortedSetGenerator;
import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.TestStringSortedSetGenerator;
import com.google.common.collect.testing.TestUnhashableCollectionGenerator;
import com.google.common.collect.testing.UnhashableObject;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
/**
* Generators of different types of sets and derived collections from sets.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
public class SetGenerators {
public static class ImmutableSetCopyOfGenerator extends TestStringSetGenerator {
@Override protected Set<String> create(String[] elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class ImmutableSetWithBadHashesGenerator
extends TestCollidingSetGenerator
// Work around a GWT compiler bug. Not explicitly listing this will
// cause the createArray() method missing in the generated javascript.
// TODO: Remove this once the GWT bug is fixed.
implements TestCollectionGenerator<Object> {
@Override
public Set<Object> create(Object... elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class DegeneratedImmutableSetGenerator
extends TestStringSetGenerator {
// Make sure we get what we think we're getting, or else this test
// is pointless
@SuppressWarnings("cast")
@Override protected Set<String> create(String[] elements) {
return (ImmutableSet<String>)
ImmutableSet.of(elements[0], elements[0]);
}
}
public static class ImmutableSortedSetCopyOfGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.copyOf(elements);
}
}
public static class ImmutableSortedSetHeadsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.headSet("zzy");
}
}
public static class ImmutableSortedSetTailsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
return ImmutableSortedSet.copyOf(list)
.tailSet("\0\0");
}
}
public static class ImmutableSortedSetSubsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.subSet("\0\0", "zzy");
}
}
@GwtIncompatible("NavigableSet")
public static class ImmutableSortedSetDescendingGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet
.<String>reverseOrder()
.add(elements)
.build()
.descendingSet();
}
}
public static class ImmutableSortedSetExplicitComparator
extends TestStringSetGenerator {
private static final Comparator<String> STRING_REVERSED
= Collections.reverseOrder();
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.orderedBy(STRING_REVERSED)
.add(elements)
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetExplicitSuperclassComparatorGenerator
extends TestStringSetGenerator {
private static final Comparator<Comparable<?>> COMPARABLE_REVERSED
= Collections.reverseOrder();
@Override protected SortedSet<String> create(String[] elements) {
return new ImmutableSortedSet.Builder<String>(COMPARABLE_REVERSED)
.add(elements)
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetReversedOrderGenerator
extends TestStringSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.<String>reverseOrder()
.addAll(Arrays.asList(elements).iterator())
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetUnhashableGenerator
extends TestUnhashableSetGenerator {
@Override public Set<UnhashableObject> create(
UnhashableObject[] elements) {
return ImmutableSortedSet.copyOf(elements);
}
}
public static class ImmutableSetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
return ImmutableSet.copyOf(elements).asList();
}
}
public static class ImmutableSortedSetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSet<String> set = ImmutableSortedSet.copyOf(
comparator, Arrays.asList(elements));
return set.asList();
}
}
public static class ImmutableSortedSetSubsetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(elements);
builder.add(AFTER_LAST);
return builder.build().subSet(BEFORE_FIRST_2,
AFTER_LAST).asList();
}
}
@GwtIncompatible("NavigableSet")
public static class ImmutableSortedSetDescendingAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements).reverse();
return ImmutableSortedSet
.orderedBy(comparator)
.add(elements)
.build()
.descendingSet()
.asList();
}
}
public static class ImmutableSortedSetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(elements);
builder.add(AFTER_LAST);
return builder.build().asList().subList(1, elements.length + 1);
}
}
public static class ImmutableSortedsetSubsetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(BEFORE_FIRST_2);
builder.add(elements);
builder.add(AFTER_LAST);
builder.add(AFTER_LAST_2);
return builder.build().subSet(BEFORE_FIRST_2,
AFTER_LAST_2)
.asList().subList(1, elements.length + 1);
}
}
public abstract static class TestUnhashableSetGenerator
extends TestUnhashableCollectionGenerator<Set<UnhashableObject>>
implements TestSetGenerator<UnhashableObject> {
}
private static Ordering<String> createExplicitComparator(
String[] elements) {
// Collapse equal elements, which Ordering.explicit() doesn't support, while
// maintaining the ordering by first occurrence.
Set<String> elementsPlus = Sets.newLinkedHashSet();
elementsPlus.add(BEFORE_FIRST);
elementsPlus.add(BEFORE_FIRST_2);
elementsPlus.addAll(Arrays.asList(elements));
elementsPlus.add(AFTER_LAST);
elementsPlus.add(AFTER_LAST_2);
return Ordering.explicit(Lists.newArrayList(elementsPlus));
}
/*
* All the ContiguousSet generators below manually reject nulls here. In principle, we'd like to
* defer that to Range, since it's Range.asSet() that's used to create the sets. However, that
* gets messy here, and we already have null tests for Range.
*/
/*
* These generators also rely on consecutive integer inputs (not necessarily in order, but no
* holes).
*/
// SetCreationTester has some tests that pass in duplicates. Dedup them.
private static <E extends Comparable<? super E>> SortedSet<E> nullCheckedTreeSet(E[] elements) {
SortedSet<E> set = newTreeSet();
for (E element : elements) {
// Explicit null check because TreeSet wrongly accepts add(null) when empty.
set.add(checkNotNull(element));
}
return set;
}
public static class ContiguousSetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
return checkedCreate(nullCheckedTreeSet(elements));
}
}
public static class ContiguousSetHeadsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooHigh = (set.isEmpty()) ? 0 : set.last() + 1;
set.add(tooHigh);
return checkedCreate(set).headSet(tooHigh);
}
}
public static class ContiguousSetTailsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooLow = (set.isEmpty()) ? 0 : set.first() - 1;
set.add(tooLow);
return checkedCreate(set).tailSet(tooLow + 1);
}
}
public static class ContiguousSetSubsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
if (set.isEmpty()) {
/*
* The (tooLow + 1, tooHigh) arguments below would be invalid because tooLow would be
* greater than tooHigh.
*/
return Range.openClosed(0, 1).asSet(DiscreteDomains.integers()).subSet(0, 1);
}
int tooHigh = set.last() + 1;
int tooLow = set.first() - 1;
set.add(tooHigh);
set.add(tooLow);
return checkedCreate(set).subSet(tooLow + 1, tooHigh);
}
}
@GwtIncompatible("NavigableSet")
public static class ContiguousSetDescendingGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
return checkedCreate(nullCheckedTreeSet(elements)).descendingSet();
}
/** Sorts the elements in reverse natural order. */
@Override public List<Integer> order(List<Integer> insertionOrder) {
Collections.sort(insertionOrder, Ordering.natural().reverse());
return insertionOrder;
}
}
private abstract static class AbstractContiguousSetGenerator
extends TestIntegerSortedSetGenerator {
protected final ContiguousSet<Integer> checkedCreate(SortedSet<Integer> elementsSet) {
List<Integer> elements = newArrayList(elementsSet);
/*
* A ContiguousSet can't have holes. If a test demands a hole, it should be changed so that it
* doesn't need one, or it should be suppressed for ContiguousSet.
*/
for (int i = 0; i < elements.size() - 1; i++) {
assertEquals(elements.get(i) + 1, (int) elements.get(i + 1));
}
Range<Integer> range =
(elements.isEmpty()) ? Range.closedOpen(0, 0) : Range.encloseAll(elements);
return range.asSet(DiscreteDomains.integers());
}
}
}
| 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.Helpers.mapEntry;
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 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;
import java.util.Collection;
import java.util.Map.Entry;
/**
* Tester for the {@code size} methods of {@code Multimap} and its views.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapSizeTester<K, V> extends AbstractMultimapTester<K, V> {
public void testSize() {
int expectedSize = getNumElements();
Multimap<K, V> multimap = multimap();
assertEquals(expectedSize, multimap.size());
int size = 0;
for (Entry<K, V> entry : multimap.entries()) {
assertTrue(multimap.containsEntry(entry.getKey(), entry.getValue()));
size++;
}
assertEquals(expectedSize, size);
int size2 = 0;
for (Entry<K, Collection<V>> entry2 : multimap.asMap().entrySet()) {
size2 += entry2.getValue().size();
}
assertEquals(expectedSize, size2);
}
@CollectionSize.Require(ZERO)
public void testIsEmptyYes() {
assertTrue(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
public void testIsEmptyNo() {
assertFalse(multimap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testSizeNullEntry() {
initMultimapWithNullKey();
assertEquals(getNumElements(), multimap().size());
assertFalse(multimap().isEmpty());
}
@CollectionSize.Require(SEVERAL)
public void testSizeMultipleValues() {
resetContainer(
mapEntry(sampleKeys().e0, sampleValues().e0),
mapEntry(sampleKeys().e0, sampleValues().e1),
mapEntry(sampleKeys().e0, sampleValues().e2));
assertEquals(3, multimap().size());
assertEquals(3, multimap().entries().size());
assertEquals(3, multimap().keys().size());
assertEquals(1, multimap().keySet().size());
assertEquals(1, multimap().asMap().size());
}
}
| 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 static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
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 {@link Multimap#containsEntry}.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MultimapContainsEntryTester<K, V> extends AbstractMultimapTester<K, V> {
@CollectionSize.Require(absent = ZERO)
public void testContainsEntryYes() {
assertTrue(multimap().containsEntry(sampleKeys().e0, sampleValues().e0));
}
public void testContainsEntryNo() {
assertFalse(multimap().containsEntry(sampleKeys().e3, sampleValues().e3));
}
public void testContainsEntryAgreesWithGet() {
for (K k : sampleKeys()) {
for (V v : sampleValues()) {
assertEquals(multimap().get(k).contains(v),
multimap().containsEntry(k, v));
}
}
}
@CollectionSize.Require(absent = ZERO)
@MapFeature.Require({ ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES })
public void testContainsEntryNullYes() {
initMultimapWithNullKeyAndValue();
assertTrue(multimap().containsEntry(null, null));
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testContainsEntryNullNo() {
assertFalse(multimap().containsEntry(null, null));
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContainsEntryNullDisallowed() {
try {
multimap().containsEntry(null, null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {
// success
}
}
}
| 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.collect.BiMap;
import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.OneSizeTestContainerGenerator;
import com.google.common.collect.testing.PerCollectionSizeTestSuiteBuilder;
import com.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.collect.testing.google.DerivedGoogleCollectionGenerators.BiMapValueSetGenerator;
import com.google.common.collect.testing.google.DerivedGoogleCollectionGenerators.InverseBiMapGenerator;
import com.google.common.collect.testing.google.DerivedGoogleCollectionGenerators.MapGenerator;
import com.google.common.collect.testing.testers.SetCreationTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests a {@code BiMap}
* implementation.
*
* @author Louis Wasserman
*/
public class BiMapTestSuiteBuilder<K, V>
extends PerCollectionSizeTestSuiteBuilder<BiMapTestSuiteBuilder<K, V>,
TestBiMapGenerator<K, V>, BiMap<K, V>, Map.Entry<K, V>> {
public static <K, V> BiMapTestSuiteBuilder<K, V> using(TestBiMapGenerator<K, V> generator) {
return new BiMapTestSuiteBuilder<K, V>().usingGenerator(generator);
}
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
new ArrayList<Class<? extends AbstractTester>>();
testers.add(BiMapPutTester.class);
testers.add(BiMapInverseTester.class);
testers.add(BiMapRemoveTester.class);
testers.add(BiMapClearTester.class);
return testers;
}
enum NoRecurse implements Feature<Void> {
INVERSE;
@Override
public Set<Feature<? super Void>> getImpliedFeatures() {
return Collections.emptySet();
}
}
@Override
protected
List<TestSuite>
createDerivedSuites(
FeatureSpecificTestSuiteBuilder<?,
? extends OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>>> parentBuilder) {
List<TestSuite> derived = super.createDerivedSuites(parentBuilder);
// TODO(cpovirk): consider using this approach (derived suites instead of extension) in
// ListTestSuiteBuilder, etc.?
derived.add(MapTestSuiteBuilder
.using(new MapGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(parentBuilder.getFeatures())
.named(parentBuilder.getName() + " [Map]")
.suppressing(parentBuilder.getSuppressedTests())
.suppressing(SetCreationTester.class.getMethods())
// BiMap.entrySet() duplicate-handling behavior is too confusing for SetCreationTester
.createTestSuite());
/*
* TODO(cpovirk): the Map tests duplicate most of this effort by using a
* CollectionTestSuiteBuilder on values(). It would be nice to avoid that
*/
derived.add(SetTestSuiteBuilder
.using(new BiMapValueSetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeValuesSetFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + " values [Set]")
.suppressing(parentBuilder.getSuppressedTests())
.suppressing(SetCreationTester.class.getMethods())
// BiMap.values() duplicate-handling behavior is too confusing for SetCreationTester
.createTestSuite());
if (!parentBuilder.getFeatures().contains(NoRecurse.INVERSE)) {
derived.add(BiMapTestSuiteBuilder
.using(new InverseBiMapGenerator<K, V>(parentBuilder.getSubjectGenerator()))
.withFeatures(computeInverseFeatures(parentBuilder.getFeatures()))
.named(parentBuilder.getName() + " inverse")
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
return derived;
}
private static Set<Feature<?>> computeInverseFeatures(Set<Feature<?>> mapFeatures) {
Set<Feature<?>> inverseFeatures = new HashSet<Feature<?>>(mapFeatures);
boolean nullKeys = inverseFeatures.remove(MapFeature.ALLOWS_NULL_KEYS);
boolean nullValues = inverseFeatures.remove(MapFeature.ALLOWS_NULL_VALUES);
if (nullKeys) {
inverseFeatures.add(MapFeature.ALLOWS_NULL_VALUES);
}
if (nullValues) {
inverseFeatures.add(MapFeature.ALLOWS_NULL_KEYS);
}
inverseFeatures.add(NoRecurse.INVERSE);
inverseFeatures.remove(CollectionFeature.KNOWN_ORDER);
inverseFeatures.add(MapFeature.REJECTS_DUPLICATES_AT_CREATION);
return inverseFeatures;
}
// TODO(user): can we eliminate the duplication from MapTestSuiteBuilder here?
private static Set<Feature<?>> computeValuesSetFeatures(
Set<Feature<?>> mapFeatures) {
Set<Feature<?>> valuesCollectionFeatures =
computeCommonDerivedCollectionFeatures(mapFeatures);
valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_QUERIES);
if (mapFeatures.contains(MapFeature.ALLOWS_NULL_VALUES)) {
valuesCollectionFeatures.add(CollectionFeature.ALLOWS_NULL_VALUES);
}
valuesCollectionFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION);
return valuesCollectionFeatures;
}
private static Set<Feature<?>> computeCommonDerivedCollectionFeatures(
Set<Feature<?>> mapFeatures) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
if (mapFeatures.contains(MapFeature.SUPPORTS_REMOVE)) {
derivedFeatures.add(CollectionFeature.SUPPORTS_REMOVE);
}
if (mapFeatures.contains(MapFeature.REJECTS_DUPLICATES_AT_CREATION)) {
derivedFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION);
}
// add the intersection of CollectionSize.values() and mapFeatures
for (CollectionSize size : CollectionSize.values()) {
if (mapFeatures.contains(size)) {
derivedFeatures.add(size);
}
}
return derivedFeatures;
}
}
| 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.google;
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.annotations.GwtIncompatible;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
* A generic JUnit test which tests multiset-specific read operations.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.SetTestSuiteBuilder}.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetReadsTester<E> extends AbstractMultisetTester<E> {
public void testCount_0() {
assertEquals("multiset.count(missing) didn't return 0",
0, getMultiset().count(samples.e3));
}
@CollectionSize.Require(absent = ZERO)
public void testCount_1() {
assertEquals("multiset.count(present) didn't return 1",
1, getMultiset().count(samples.e0));
}
@CollectionSize.Require(SEVERAL)
public void testCount_3() {
initThreeCopies();
assertEquals("multiset.count(thriceContained) didn't return 3",
3, getMultiset().count(samples.e0));
}
public void testCount_null() {
assertEquals("multiset.count(null) didn't return 0",
0, getMultiset().count(null));
}
public void testCount_wrongType() {
assertEquals("multiset.count(wrongType) didn't return 0",
0, getMultiset().count(WrongType.VALUE));
}
@CollectionSize.Require(absent = ZERO)
public void testElementSet_contains() {
assertTrue("multiset.elementSet().contains(present) returned false",
getMultiset().elementSet().contains(samples.e0));
}
@CollectionSize.Require(absent = ZERO)
public void testEntrySet_contains() {
assertTrue("multiset.entrySet() didn't contain [present, 1]",
getMultiset().entrySet().contains(
Multisets.immutableEntry(samples.e0, 1)));
}
public void testEntrySet_contains_count0() {
assertFalse("multiset.entrySet() contains [missing, 0]",
getMultiset().entrySet().contains(
Multisets.immutableEntry(samples.e3, 0)));
}
public void testEntrySet_contains_nonentry() {
assertFalse("multiset.entrySet() contains a non-entry",
getMultiset().entrySet().contains(samples.e0));
}
public void testEntrySet_twice() {
assertEquals("calling multiset.entrySet() twice returned unequal sets",
getMultiset().entrySet(), getMultiset().entrySet());
}
@CollectionSize.Require(ZERO)
public void testEntrySet_hashCode_size0() {
assertEquals("multiset.entrySet() has incorrect hash code",
0, getMultiset().entrySet().hashCode());
}
@CollectionSize.Require(ONE)
public void testEntrySet_hashCode_size1() {
assertEquals("multiset.entrySet() has incorrect hash code",
1 ^ samples.e0.hashCode(), getMultiset().entrySet().hashCode());
}
public void testEquals_yes() {
assertTrue("multiset doesn't equal a multiset with the same elements",
getMultiset().equals(HashMultiset.create(getSampleElements())));
}
public void testEquals_differentSize() {
Multiset<E> other = HashMultiset.create(getSampleElements());
other.add(samples.e0);
assertFalse("multiset equals a multiset with a different size",
getMultiset().equals(other));
}
@CollectionSize.Require(absent = ZERO)
public void testEquals_differentElements() {
Multiset<E> other = HashMultiset.create(getSampleElements());
other.remove(samples.e0);
other.add(samples.e3);
assertFalse("multiset equals a multiset with different elements",
getMultiset().equals(other));
}
@CollectionSize.Require(ZERO)
public void testHashCode_size0() {
assertEquals("multiset has incorrect hash code",
0, getMultiset().hashCode());
}
@CollectionSize.Require(ONE)
public void testHashCode_size1() {
assertEquals("multiset has incorrect hash code",
1 ^ samples.e0.hashCode(), getMultiset().hashCode());
}
/**
* Returns {@link Method} instances for the read tests that assume multisets
* support duplicates so that the test of {@code Multisets.forSet()} can
* suppress them.
*/
@GwtIncompatible("reflection")
public static List<Method> getReadsDuplicateInitializingMethods() {
return Arrays.asList(
Helpers.getMethod(MultisetReadsTester.class, "testCount_3"));
}
}
| 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 com.google.common.collect.BoundType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import com.google.common.collect.SortedMultiset;
import com.google.common.collect.testing.AbstractTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests a
* {@code SortedMultiset} implementation.
*
* <p><b>Warning</b>: expects that {@code E} is a String.
*
* @author Louis Wasserman
*/
public class SortedMultisetTestSuiteBuilder<E> extends
MultisetTestSuiteBuilder<E> {
public static <E> SortedMultisetTestSuiteBuilder<E> using(
TestMultisetGenerator<E> generator) {
SortedMultisetTestSuiteBuilder<E> result =
new SortedMultisetTestSuiteBuilder<E>();
result.usingGenerator(generator);
return result;
}
@Override
public TestSuite createTestSuite() {
TestSuite suite = super.createTestSuite();
for (TestSuite subSuite : createDerivedSuites(this)) {
suite.addTest(subSuite);
}
return suite;
}
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
Helpers.copyToList(super.getTesters());
testers.add(MultisetNavigationTester.class);
return testers;
}
/**
* To avoid infinite recursion, test suites with these marker features won't
* have derived suites created for them.
*/
enum NoRecurse implements Feature<Void> {
SUBMULTISET, DESCENDING;
@Override
public Set<Feature<? super Void>> getImpliedFeatures() {
return Collections.emptySet();
}
}
/**
* Two bounds (from and to) define how to build a subMultiset.
*/
enum Bound {
INCLUSIVE, EXCLUSIVE, NO_BOUND;
}
List<TestSuite> createDerivedSuites(
SortedMultisetTestSuiteBuilder<E> parentBuilder) {
List<TestSuite> derivedSuites = Lists.newArrayList();
if (!parentBuilder.getFeatures().contains(NoRecurse.DESCENDING)) {
derivedSuites.add(createDescendingSuite(parentBuilder));
}
if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
derivedSuites.add(createReserializedSuite(parentBuilder));
}
if (!parentBuilder.getFeatures().contains(NoRecurse.SUBMULTISET)) {
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.NO_BOUND,
Bound.EXCLUSIVE));
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.NO_BOUND,
Bound.INCLUSIVE));
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.EXCLUSIVE,
Bound.NO_BOUND));
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.EXCLUSIVE,
Bound.EXCLUSIVE));
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.EXCLUSIVE,
Bound.INCLUSIVE));
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.INCLUSIVE,
Bound.NO_BOUND));
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.INCLUSIVE,
Bound.EXCLUSIVE));
derivedSuites.add(createSubMultisetSuite(parentBuilder, Bound.INCLUSIVE,
Bound.INCLUSIVE));
}
return derivedSuites;
}
private TestSuite createSubMultisetSuite(
SortedMultisetTestSuiteBuilder<E> parentBuilder, final Bound from,
final Bound to) {
final TestMultisetGenerator<E> delegate =
(TestMultisetGenerator<E>) parentBuilder.getSubjectGenerator();
Set<Feature<?>> features = new HashSet<Feature<?>>();
features.add(NoRecurse.SUBMULTISET);
features.add(CollectionFeature.RESTRICTS_ELEMENTS);
features.addAll(parentBuilder.getFeatures());
if (!features.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
features.remove(CollectionFeature.SERIALIZABLE);
}
SortedMultiset<E> emptyMultiset = (SortedMultiset<E>) delegate.create();
final Comparator<? super E> comparator = emptyMultiset.comparator();
SampleElements<E> samples = delegate.samples();
@SuppressWarnings("unchecked")
List<E> samplesList =
Arrays.asList(samples.e0, samples.e1, samples.e2, samples.e3,
samples.e4);
Collections.sort(samplesList, comparator);
final E firstInclusive = samplesList.get(0);
final E lastInclusive = samplesList.get(samplesList.size() - 1);
return SortedMultisetTestSuiteBuilder
.using(new ForwardingTestMultisetGenerator<E>(delegate) {
@Override
public SortedMultiset<E> create(Object... entries) {
@SuppressWarnings("unchecked")
// we dangerously assume E is a string
List<E> extremeValues = (List) getExtremeValues();
@SuppressWarnings("unchecked")
// map generators must past entry objects
List<E> normalValues = (List) Arrays.asList(entries);
// prepare extreme values to be filtered out of view
Collections.sort(extremeValues, comparator);
E firstExclusive = extremeValues.get(1);
E lastExclusive = extremeValues.get(2);
if (from == Bound.NO_BOUND) {
extremeValues.remove(0);
extremeValues.remove(0);
}
if (to == Bound.NO_BOUND) {
extremeValues.remove(extremeValues.size() - 1);
extremeValues.remove(extremeValues.size() - 1);
}
// the regular values should be visible after filtering
List<E> allEntries = new ArrayList<E>();
allEntries.addAll(extremeValues);
allEntries.addAll(normalValues);
SortedMultiset<E> multiset =
(SortedMultiset<E>) delegate.create(allEntries.toArray());
// call the smallest subMap overload that filters out the extreme
// values
if (from == Bound.INCLUSIVE) {
multiset =
multiset.tailMultiset(firstInclusive, BoundType.CLOSED);
} else if (from == Bound.EXCLUSIVE) {
multiset = multiset.tailMultiset(firstExclusive, BoundType.OPEN);
}
if (to == Bound.INCLUSIVE) {
multiset = multiset.headMultiset(lastInclusive, BoundType.CLOSED);
} else if (to == Bound.EXCLUSIVE) {
multiset = multiset.headMultiset(lastExclusive, BoundType.OPEN);
}
return multiset;
}
})
.named(parentBuilder.getName() + " subMultiset " + from + "-" + to)
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
/**
* Returns an array of four bogus elements that will always be too high or too
* low for the display. This includes two values for each extreme.
*
* <p>
* This method (dangerously) assume that the strings {@code "!! a"} and
* {@code "~~ z"} will work for this purpose, which may cause problems for
* navigable maps with non-string or unicode generators.
*/
private List<String> getExtremeValues() {
List<String> result = new ArrayList<String>();
result.add("!! a");
result.add("!! b");
result.add("~~ y");
result.add("~~ z");
return result;
}
private TestSuite createDescendingSuite(
SortedMultisetTestSuiteBuilder<E> parentBuilder) {
final TestMultisetGenerator<E> delegate =
(TestMultisetGenerator<E>) parentBuilder.getSubjectGenerator();
Set<Feature<?>> features = new HashSet<Feature<?>>();
features.add(NoRecurse.DESCENDING);
features.addAll(parentBuilder.getFeatures());
if (!features.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) {
features.remove(CollectionFeature.SERIALIZABLE);
}
return SortedMultisetTestSuiteBuilder
.using(new ForwardingTestMultisetGenerator<E>(delegate) {
@Override
public SortedMultiset<E> create(Object... entries) {
return ((SortedMultiset<E>) super.create(entries))
.descendingMultiset();
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return ImmutableList.copyOf(super.order(insertionOrder)).reverse();
}
})
.named(parentBuilder.getName() + " descending")
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
private TestSuite createReserializedSuite(
SortedMultisetTestSuiteBuilder<E> parentBuilder) {
final TestMultisetGenerator<E> delegate =
(TestMultisetGenerator<E>) parentBuilder.getSubjectGenerator();
Set<Feature<?>> features = new HashSet<Feature<?>>();
features.addAll(parentBuilder.getFeatures());
features.remove(CollectionFeature.SERIALIZABLE);
features.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return SortedMultisetTestSuiteBuilder
.using(new ForwardingTestMultisetGenerator<E>(delegate) {
@Override
public SortedMultiset<E> create(Object... entries) {
return SerializableTester.reserialize(((SortedMultiset<E>) super.create(entries)));
}
})
.named(parentBuilder.getName() + " reserialized")
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
private static class ForwardingTestMultisetGenerator<E>
implements TestMultisetGenerator<E> {
private final TestMultisetGenerator<E> delegate;
ForwardingTestMultisetGenerator(TestMultisetGenerator<E> delegate) {
this.delegate = delegate;
}
@Override
public SampleElements<E> samples() {
return delegate.samples();
}
@Override
public E[] createArray(int length) {
return delegate.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return delegate.order(insertionOrder);
}
@Override
public Multiset<E> create(Object... elements) {
return delegate.create(elements);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.concurrent.ConcurrentMap;
/**
* Tests representing the contract of {@link ConcurrentMap}. Concrete
* subclasses of this base class test conformance of concrete
* {@link ConcurrentMap} subclasses to that contract.
*
* <p>This class is GWT compatible.
*
* <p>The tests in this class for null keys and values only check maps for
* which null keys and values are not allowed. There are currently no
* {@link ConcurrentMap} implementations that support nulls.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class ConcurrentMapInterfaceTest<K, V>
extends MapInterfaceTest<K, V> {
protected ConcurrentMapInterfaceTest(boolean allowsNullKeys,
boolean allowsNullValues, boolean supportsPut, boolean supportsRemove,
boolean supportsClear) {
super(allowsNullKeys, allowsNullValues, supportsPut, supportsRemove,
supportsClear);
}
/**
* Creates a new value that is not expected to be found in
* {@link #makePopulatedMap()} and differs from the value returned by
* {@link #getValueNotInPopulatedMap()}.
*
* @return a value
* @throws UnsupportedOperationException if it's not possible to make a value
* that will not be found in the map
*/
protected abstract V getSecondValueNotInPopulatedMap()
throws UnsupportedOperationException;
@Override protected abstract ConcurrentMap<K, V> makeEmptyMap()
throws UnsupportedOperationException;
@Override protected abstract ConcurrentMap<K, V> makePopulatedMap()
throws UnsupportedOperationException;
@Override protected ConcurrentMap<K, V> makeEitherMap() {
try {
return makePopulatedMap();
} catch (UnsupportedOperationException e) {
return makeEmptyMap();
}
}
public void testPutIfAbsentNewKey() {
final ConcurrentMap<K, V> map;
final K keyToPut;
final V valueToPut;
try {
map = makeEitherMap();
keyToPut = getKeyNotInPopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsPut) {
int initialSize = map.size();
V oldValue = map.putIfAbsent(keyToPut, valueToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
assertEquals(initialSize + 1, map.size());
assertNull(oldValue);
} else {
try {
map.putIfAbsent(keyToPut, valueToPut);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutIfAbsentExistingKey() {
final ConcurrentMap<K, V> map;
final K keyToPut;
final V valueToPut;
try {
map = makePopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToPut = map.keySet().iterator().next();
if (supportsPut) {
V oldValue = map.get(keyToPut);
int initialSize = map.size();
assertEquals(oldValue, map.putIfAbsent(keyToPut, valueToPut));
assertEquals(oldValue, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(oldValue));
assertFalse(map.containsValue(valueToPut));
assertEquals(initialSize, map.size());
} else {
try {
map.putIfAbsent(keyToPut, valueToPut);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutIfAbsentNullKey() {
if (allowsNullKeys) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final V valueToPut;
try {
map = makeEitherMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
try {
map.putIfAbsent(null, valueToPut);
fail("Expected NullPointerException");
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
map.putIfAbsent(null, valueToPut);
fail("Expected UnsupportedOperationException or NullPointerException");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testPutIfAbsentNewKeyNullValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToPut;
try {
map = makeEitherMap();
keyToPut = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
try {
map.putIfAbsent(keyToPut, null);
fail("Expected NullPointerException");
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
map.putIfAbsent(keyToPut, null);
fail("Expected UnsupportedOperationException or NullPointerException");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testPutIfAbsentExistingKeyNullValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToPut;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToPut = map.keySet().iterator().next();
int initialSize = map.size();
if (supportsPut) {
try {
assertNull(map.putIfAbsent(keyToPut, null));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
map.putIfAbsent(keyToPut, null);
fail("Expected UnsupportedOperationException or NullPointerException");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testRemoveKeyValueExisting() {
final ConcurrentMap<K, V> map;
final K keyToRemove;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToRemove = map.keySet().iterator().next();
V oldValue = map.get(keyToRemove);
if (supportsRemove) {
int initialSize = map.size();
assertTrue(map.remove(keyToRemove, oldValue));
assertFalse(map.containsKey(keyToRemove));
assertEquals(initialSize - 1, map.size());
} else {
try {
map.remove(keyToRemove, oldValue);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testRemoveKeyValueMissingKey() {
final ConcurrentMap<K, V> map;
final K keyToRemove;
final V valueToRemove;
try {
map = makePopulatedMap();
keyToRemove = getKeyNotInPopulatedMap();
valueToRemove = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsRemove) {
int initialSize = map.size();
assertFalse(map.remove(keyToRemove, valueToRemove));
assertEquals(initialSize, map.size());
} else {
try {
map.remove(keyToRemove, valueToRemove);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testRemoveKeyValueDifferentValue() {
final ConcurrentMap<K, V> map;
final K keyToRemove;
final V valueToRemove;
try {
map = makePopulatedMap();
valueToRemove = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToRemove = map.keySet().iterator().next();
if (supportsRemove) {
int initialSize = map.size();
V oldValue = map.get(keyToRemove);
assertFalse(map.remove(keyToRemove, valueToRemove));
assertEquals(oldValue, map.get(keyToRemove));
assertTrue(map.containsKey(keyToRemove));
assertEquals(initialSize, map.size());
} else {
try {
map.remove(keyToRemove, valueToRemove);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testRemoveKeyValueNullKey() {
if (allowsNullKeys) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final V valueToRemove;
try {
map = makeEitherMap();
valueToRemove = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsRemove) {
try {
assertFalse(map.remove(null, valueToRemove));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertFalse(map.remove(null, valueToRemove));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testRemoveKeyValueExistingKeyNullValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToRemove;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToRemove = map.keySet().iterator().next();
int initialSize = map.size();
if (supportsRemove) {
try {
assertFalse(map.remove(keyToRemove, null));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertFalse(map.remove(keyToRemove, null));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testRemoveKeyValueMissingKeyNullValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToRemove;
try {
map = makeEitherMap();
keyToRemove = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsRemove) {
try {
assertFalse(map.remove(keyToRemove, null));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertFalse(map.remove(keyToRemove, null));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
/* Replace2 tests call 2-parameter replace(key, value) */
public void testReplace2ExistingKey() {
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V newValue;
try {
map = makePopulatedMap();
newValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToReplace = map.keySet().iterator().next();
if (supportsPut) {
V oldValue = map.get(keyToReplace);
int initialSize = map.size();
assertEquals(oldValue, map.replace(keyToReplace, newValue));
assertEquals(newValue, map.get(keyToReplace));
assertTrue(map.containsKey(keyToReplace));
assertTrue(map.containsValue(newValue));
assertEquals(initialSize, map.size());
} else {
try {
map.replace(keyToReplace, newValue);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testReplace2MissingKey() {
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V newValue;
try {
map = makeEitherMap();
keyToReplace = getKeyNotInPopulatedMap();
newValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsPut) {
int initialSize = map.size();
assertNull(map.replace(keyToReplace, newValue));
assertNull(map.get(keyToReplace));
assertFalse(map.containsKey(keyToReplace));
assertFalse(map.containsValue(newValue));
assertEquals(initialSize, map.size());
} else {
try {
map.replace(keyToReplace, newValue);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testReplace2NullKey() {
if (allowsNullKeys) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final V valueToReplace;
try {
map = makeEitherMap();
valueToReplace = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
try {
assertNull(map.replace(null, valueToReplace));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertNull(map.replace(null, valueToReplace));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testReplace2ExistingKeyNullValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToReplace;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToReplace = map.keySet().iterator().next();
int initialSize = map.size();
if (supportsPut) {
try {
map.replace(keyToReplace, null);
fail("Expected NullPointerException");
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
map.replace(keyToReplace, null);
fail("Expected UnsupportedOperationException or NullPointerException");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testReplace2MissingKeyNullValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToReplace;
try {
map = makeEitherMap();
keyToReplace = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
try {
assertNull(map.replace(keyToReplace, null));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertNull(map.replace(keyToReplace, null));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
/*
* Replace3 tests call 3-parameter replace(key, oldValue, newValue)
*/
public void testReplace3ExistingKeyValue() {
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V oldValue;
final V newValue;
try {
map = makePopulatedMap();
newValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToReplace = map.keySet().iterator().next();
oldValue = map.get(keyToReplace);
if (supportsPut) {
int initialSize = map.size();
assertTrue(map.replace(keyToReplace, oldValue, newValue));
assertEquals(newValue, map.get(keyToReplace));
assertTrue(map.containsKey(keyToReplace));
assertTrue(map.containsValue(newValue));
assertFalse(map.containsValue(oldValue));
assertEquals(initialSize, map.size());
} else {
try {
map.replace(keyToReplace, oldValue, newValue);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testReplace3ExistingKeyDifferentValue() {
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V oldValue;
final V newValue;
try {
map = makePopulatedMap();
oldValue = getValueNotInPopulatedMap();
newValue = getSecondValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToReplace = map.keySet().iterator().next();
final V originalValue = map.get(keyToReplace);
int initialSize = map.size();
if (supportsPut) {
assertFalse(map.replace(keyToReplace, oldValue, newValue));
} else {
try {
map.replace(keyToReplace, oldValue, newValue);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertTrue(map.containsKey(keyToReplace));
assertFalse(map.containsValue(newValue));
assertFalse(map.containsValue(oldValue));
assertEquals(originalValue, map.get(keyToReplace));
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testReplace3MissingKey() {
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V oldValue;
final V newValue;
try {
map = makeEitherMap();
keyToReplace = getKeyNotInPopulatedMap();
oldValue = getValueNotInPopulatedMap();
newValue = getSecondValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
assertFalse(map.replace(keyToReplace, oldValue, newValue));
} else {
try {
map.replace(keyToReplace, oldValue, newValue);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertFalse(map.containsKey(keyToReplace));
assertFalse(map.containsValue(newValue));
assertFalse(map.containsValue(oldValue));
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testReplace3NullKey() {
if (allowsNullKeys) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final V oldValue;
final V newValue;
try {
map = makeEitherMap();
oldValue = getValueNotInPopulatedMap();
newValue = getSecondValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
try {
assertFalse(map.replace(null, oldValue, newValue));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertFalse(map.replace(null, oldValue, newValue));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testReplace3ExistingKeyNullOldValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V newValue;
try {
map = makePopulatedMap();
newValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToReplace = map.keySet().iterator().next();
final V originalValue = map.get(keyToReplace);
int initialSize = map.size();
if (supportsPut) {
try {
assertFalse(map.replace(keyToReplace, null, newValue));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertFalse(map.replace(keyToReplace, null, newValue));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertEquals(originalValue, map.get(keyToReplace));
assertInvariants(map);
}
public void testReplace3MissingKeyNullOldValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V newValue;
try {
map = makeEitherMap();
keyToReplace = getKeyNotInPopulatedMap();
newValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
try {
assertFalse(map.replace(keyToReplace, null, newValue));
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
assertFalse(map.replace(keyToReplace, null, newValue));
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testReplace3MissingKeyNullNewValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V oldValue;
try {
map = makeEitherMap();
keyToReplace = getKeyNotInPopulatedMap();
oldValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int initialSize = map.size();
if (supportsPut) {
try {
map.replace(keyToReplace, oldValue, null);
} catch (NullPointerException e) {
// Optional.
}
} else {
try {
map.replace(keyToReplace, oldValue, null);
} catch (UnsupportedOperationException e) {
// Optional.
} catch (NullPointerException e) {
// Optional.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testReplace3ExistingKeyValueNullNewValue() {
if (allowsNullValues) {
return; // Not yet implemented
}
final ConcurrentMap<K, V> map;
final K keyToReplace;
final V oldValue;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToReplace = map.keySet().iterator().next();
oldValue = map.get(keyToReplace);
int initialSize = map.size();
if (supportsPut) {
try {
map.replace(keyToReplace, oldValue, null);
fail("Expected NullPointerException");
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
map.replace(keyToReplace, oldValue, null);
fail("Expected UnsupportedOperationException or NullPointerException");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertEquals(initialSize, map.size());
assertEquals(oldValue, map.get(keyToReplace));
assertInvariants(map);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
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.
*
* <p>This class is GWT compatible.
*
* @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) 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.List;
import java.util.Queue;
/**
* Create queue of strings for tests.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestStringQueueGenerator
implements TestQueueGenerator<String>
{
@Override
public SampleElements<String> samples() {
return new Strings();
}
@Override
public Queue<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 Queue<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) 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.Collections;
import java.util.Iterator;
/**
* A utility for testing an Iterator implementation by comparing its behavior to
* that of a "known good" reference implementation. In order to accomplish this,
* it's important to test a great variety of sequences of the
* {@link Iterator#next}, {@link Iterator#hasNext} and {@link Iterator#remove}
* operations. This utility takes the brute-force approach of trying <i>all</i>
* possible sequences of these operations, up to a given number of steps. So, if
* the caller specifies to use <i>n</i> steps, a total of <i>3^n</i> tests are
* actually performed.
*
* <p>For instance, if <i>steps</i> is 5, one example sequence that will be
* tested is:
*
* <ol>
* <li>remove();
* <li>hasNext()
* <li>hasNext();
* <li>remove();
* <li>next();
* </ol>
*
* This particular order of operations may be unrealistic, and testing all 3^5
* of them may be thought of as overkill; however, it's difficult to determine
* which proper subset of this massive set would be sufficient to expose any
* possible bug. Brute force is simpler.
*
* <p>To use this class the concrete subclass must implement the
* {@link IteratorTester#newTargetIterator()} method. This is because it's
* impossible to test an Iterator without changing its state, so the tester
* needs a steady supply of fresh Iterators.
*
* <p>If your iterator supports modification through {@code remove()}, you may
* wish to override the verify() method, which is called <em>after</em>
* each sequence and is guaranteed to be called using the latest values
* obtained from {@link IteratorTester#newTargetIterator()}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
@GwtCompatible
public abstract class IteratorTester<E> extends
AbstractIteratorTester<E, Iterator<E>> {
/**
* Creates an IteratorTester.
*
* @param steps how many operations to test for each tested pair of iterators
* @param features the features supported by the iterator
*/
protected IteratorTester(int steps,
Iterable<? extends IteratorFeature> features,
Iterable<E> expectedElements, KnownOrder knownOrder) {
super(steps, Collections.<E>singleton(null), features, expectedElements,
knownOrder, 0);
}
@Override
protected final Iterable<Stimulus<E, Iterator<E>>> getStimulusValues() {
return iteratorStimuli();
}
}
| 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) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static java.util.Collections.disjoint;
import static java.util.logging.Level.FINER;
import com.google.common.collect.testing.features.ConflictingRequirementsException;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.FeatureUtil;
import com.google.common.collect.testing.features.TesterRequirements;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* the object generated by a G, selecting appropriate tests by matching them
* against specified features.
*
* @param <B> The concrete type of this builder (the 'self-type'). All the
* Builder methods of this class (such as {@link #named}) 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.
*
* @author George van den Driessche
*/
public abstract class FeatureSpecificTestSuiteBuilder<
B extends FeatureSpecificTestSuiteBuilder<B, G>, G> {
@SuppressWarnings("unchecked")
protected B self() {
return (B) this;
}
// Test Data
private G subjectGenerator;
// Gets run before every test.
private Runnable setUp;
// Gets run at the conclusion of every test.
private Runnable tearDown;
protected B usingGenerator(G subjectGenerator) {
this.subjectGenerator = subjectGenerator;
return self();
}
public G getSubjectGenerator() {
return subjectGenerator;
}
public B withSetUp(Runnable setUp) {
this.setUp = setUp;
return self();
}
protected Runnable getSetUp() {
return setUp;
}
public B withTearDown(Runnable tearDown) {
this.tearDown = tearDown;
return self();
}
protected Runnable getTearDown() {
return tearDown;
}
// Features
private Set<Feature<?>> features;
/**
* Configures this builder to produce tests appropriate for the given
* features.
*/
public B withFeatures(Feature<?>... features) {
return withFeatures(Arrays.asList(features));
}
public B withFeatures(Iterable<? extends Feature<?>> features) {
this.features = Helpers.copyToSet(features);
return self();
}
public Set<Feature<?>> getFeatures() {
return Collections.unmodifiableSet(features);
}
// Name
private String name;
/** Configures this builder produce a TestSuite with the given name. */
public B named(String name) {
if (name.contains("(")) {
throw new IllegalArgumentException("Eclipse hides all characters after "
+ "'('; please use '[]' or other characters instead of parentheses");
}
this.name = name;
return self();
}
public String getName() {
return name;
}
// Test suppression
private Set<Method> suppressedTests = new HashSet<Method>();
/**
* Prevents the given methods from being run as part of the test suite.
*
* <em>Note:</em> in principle this should never need to be used, but it
* might be useful if the semantics of an implementation disagree in
* unforeseen ways with the semantics expected by a test, or to keep dependent
* builds clean in spite of an erroneous test.
*/
public B suppressing(Method... methods) {
return suppressing(Arrays.asList(methods));
}
public B suppressing(Collection<Method> methods) {
suppressedTests.addAll(methods);
return self();
}
public Set<Method> getSuppressedTests() {
return suppressedTests;
}
private static final Logger logger = Logger.getLogger(
FeatureSpecificTestSuiteBuilder.class.getName());
/**
* Creates a runnable JUnit test suite based on the criteria already given.
*/
/*
* Class parameters must be raw. This annotation should go on testerClass in
* the for loop, but the 1.5 javac crashes on annotations in for loops:
* <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6294589>
*/
@SuppressWarnings("unchecked")
public TestSuite createTestSuite() {
checkCanCreate();
logger.fine(" Testing: " + name);
logger.fine("Features: " + formatFeatureSet(features));
FeatureUtil.addImpliedFeatures(features);
logger.fine("Expanded: " + formatFeatureSet(features));
// Class parameters must be raw.
List<Class<? extends AbstractTester>> testers = getTesters();
TestSuite suite = new TestSuite(name);
for (Class<? extends AbstractTester> testerClass : testers) {
final TestSuite testerSuite = makeSuiteForTesterClass(
(Class<? extends AbstractTester<?>>) testerClass);
if (testerSuite.countTestCases() > 0) {
suite.addTest(testerSuite);
}
}
return suite;
}
/**
* Throw {@link IllegalStateException} if {@link #createTestSuite()} can't
* be called yet.
*/
protected void checkCanCreate() {
if (subjectGenerator == null) {
throw new IllegalStateException("Call using() before createTestSuite().");
}
if (name == null) {
throw new IllegalStateException("Call named() before createTestSuite().");
}
if (features == null) {
throw new IllegalStateException(
"Call withFeatures() before createTestSuite().");
}
}
// Class parameters must be raw.
protected abstract List<Class<? extends AbstractTester>>
getTesters();
private boolean matches(Test test) {
final Method method;
try {
method = extractMethod(test);
} catch (IllegalArgumentException e) {
logger.finer(Platform.format(
"%s: including by default: %s", test, e.getMessage()));
return true;
}
if (suppressedTests.contains(method)) {
logger.finer(Platform.format(
"%s: excluding because it was explicitly suppressed.", test));
return false;
}
final TesterRequirements requirements;
try {
requirements = FeatureUtil.getTesterRequirements(method);
} catch (ConflictingRequirementsException e) {
throw new RuntimeException(e);
}
if (!features.containsAll(requirements.getPresentFeatures())) {
if (logger.isLoggable(FINER)) {
Set<Feature<?>> missingFeatures =
Helpers.copyToSet(requirements.getPresentFeatures());
missingFeatures.removeAll(features);
logger.finer(Platform.format(
"%s: skipping because these features are absent: %s",
method, missingFeatures));
}
return false;
}
if (intersect(features, requirements.getAbsentFeatures())) {
if (logger.isLoggable(FINER)) {
Set<Feature<?>> unwantedFeatures =
Helpers.copyToSet(requirements.getAbsentFeatures());
unwantedFeatures.retainAll(features);
logger.finer(Platform.format(
"%s: skipping because these features are present: %s",
method, unwantedFeatures));
}
return false;
}
return true;
}
private static boolean intersect(Set<?> a, Set<?> b) {
return !disjoint(a, b);
}
private static Method extractMethod(Test test) {
if (test instanceof AbstractTester) {
AbstractTester<?> tester = (AbstractTester<?>) test;
return Helpers.getMethod(tester.getClass(), tester.getTestMethodName());
} else if (test instanceof TestCase) {
TestCase testCase = (TestCase) test;
return Helpers.getMethod(testCase.getClass(), testCase.getName());
} else {
throw new IllegalArgumentException(
"unable to extract method from test: not a TestCase.");
}
}
protected TestSuite makeSuiteForTesterClass(
Class<? extends AbstractTester<?>> testerClass) {
final TestSuite candidateTests = new TestSuite(testerClass);
final TestSuite suite = filterSuite(candidateTests);
Enumeration<?> allTests = suite.tests();
while (allTests.hasMoreElements()) {
Object test = allTests.nextElement();
if (test instanceof AbstractTester) {
@SuppressWarnings("unchecked")
AbstractTester<? super G> tester = (AbstractTester<? super G>) test;
tester.init(subjectGenerator, name, setUp, tearDown);
}
}
return suite;
}
private TestSuite filterSuite(TestSuite suite) {
TestSuite filtered = new TestSuite(suite.getName());
final Enumeration<?> tests = suite.tests();
while (tests.hasMoreElements()) {
Test test = (Test) tests.nextElement();
if (matches(test)) {
filtered.addTest(test);
}
}
return filtered;
}
protected static String formatFeatureSet(Set<? extends Feature<?>> features) {
List<String> temp = new ArrayList<String>();
for (Feature<?> feature : features) {
Object featureAsObject = feature; // to work around bogus JDK warning
if (featureAsObject instanceof Enum) {
Enum<?> f = (Enum<?>) featureAsObject;
temp.add(Platform.classGetSimpleName(
f.getDeclaringClass()) + "." + feature);
} else {
temp.add(feature.toString());
}
}
return temp.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;
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Base class for testers of classes (including {@link Collection}
* and {@link java.util.Map Map}) that contain elements.
*
* <p>This class is GWT compatible.
*
* @param <C> the type of the container
* @param <E> the type of the container's contents
*
* @author George van den Driessche
*/
@GwtCompatible
public abstract class AbstractContainerTester<C, E>
extends AbstractTester<OneSizeTestContainerGenerator<C, E>> {
protected SampleElements<E> samples;
protected C container;
@Override public void setUp() throws Exception {
super.setUp();
samples = this.getSubjectGenerator().samples();
resetContainer();
}
/**
* @return the contents of the container under test, for use by
* {@link #expectContents(Object[]) expectContents(E...)} and its friends.
*/
protected abstract Collection<E> actualContents();
/**
* Replaces the existing container under test with a new container created
* by the subject generator.
*
* @see #resetContainer(Object) resetContainer(C)
*
* @return the new container instance.
*/
protected C resetContainer() {
return resetContainer(getSubjectGenerator().createTestSubject());
}
/**
* Replaces the existing container under test with a new container.
* This is useful when a single test method needs to create multiple
* containers while retaining the ability to use
* {@link #expectContents(Object[]) expectContents(E...)} and other
* convenience methods. The creation of multiple containers in a single
* method is discouraged in most cases, but it is vital to the iterator tests.
*
* @return the new container instance
* @param newValue the new container instance
*/
protected C resetContainer(C newValue) {
container = newValue;
return container;
}
/**
* @see #expectContents(java.util.Collection)
*
* @param elements expected contents of {@link #container}
*/
protected final void expectContents(E... elements) {
expectContents(Arrays.asList(elements));
}
/**
* Asserts that the collection under test contains exactly the given elements,
* respecting cardinality but not order. Subclasses may override this method
* to provide stronger assertions, e.g., to check ordering in lists, but
* realize that <strong>unless a test extends
* {@link com.google.common.collect.testing.testers.AbstractListTester
* AbstractListTester}, a call to {@code expectContents()} invokes this
* version</strong>.
*
* @param expected expected value of {@link #container}
*/
/*
* TODO: improve this and other implementations and move out of this framework
* for wider use
*
* TODO: could we incorporate the overriding logic from AbstractListTester, by
* examining whether the features include KNOWN_ORDER?
*/
protected void expectContents(Collection<E> expected) {
Helpers.assertEqualIgnoringOrder(expected, actualContents());
}
protected void expectUnchanged() {
expectContents(getSampleElements());
}
/**
* Asserts that the collection under test contains exactly the elements it was
* initialized with plus the given elements, according to
* {@link #expectContents(java.util.Collection)}. In other words, for the
* default {@code expectContents()} implementation, the number of occurrences
* of each given element has increased by one since the test collection was
* created, and the number of occurrences of all other elements has not
* changed.
*
* <p>Note: This means that a test like the following will fail if
* {@code collection} is a {@code Set}:
*
* <pre>
* collection.add(existingElement);
* expectAdded(existingElement);</pre>
*
* In this case, {@code collection} was not modified as a result of the
* {@code add()} call, and the test will fail because the number of
* occurrences of {@code existingElement} is unchanged.
*
* @param elements expected additional contents of {@link #container}
*/
protected final void expectAdded(E... elements) {
List<E> expected = Helpers.copyToList(getSampleElements());
expected.addAll(Arrays.asList(elements));
expectContents(expected);
}
protected final void expectAdded(int index, E... elements) {
expectAdded(index, Arrays.asList(elements));
}
protected final void expectAdded(int index, Collection<E> elements) {
List<E> expected = Helpers.copyToList(getSampleElements());
expected.addAll(index, elements);
expectContents(expected);
}
/*
* TODO: if we're testing a list, we could check indexOf(). (Doing it in
* AbstractListTester isn't enough because many tests that run on lists don't
* extends AbstractListTester.) We could also iterate over all elements to
* verify absence
*/
protected void expectMissing(E... elements) {
for (E element : elements) {
assertFalse("Should not contain " + element,
actualContents().contains(element));
}
}
protected E[] createSamplesArray() {
E[] array = getSubjectGenerator().createArray(getNumElements());
getSampleElements().toArray(array);
return array;
}
public static class ArrayWithDuplicate<E> {
public final E[] elements;
public final E duplicate;
private ArrayWithDuplicate(E[] elements, E duplicate) {
this.elements = elements;
this.duplicate = duplicate;
}
}
/**
* @return an array of the proper size with a duplicate element.
* The size must be at least three.
*/
protected ArrayWithDuplicate<E> createArrayWithDuplicateElement() {
E[] elements = createSamplesArray();
E duplicate = elements[(elements.length / 2) - 1];
elements[(elements.length / 2) + 1] = duplicate;
return new ArrayWithDuplicate<E>(elements, duplicate);
}
// Helper methods to improve readability of derived classes
protected int getNumElements() {
return getSubjectGenerator().getCollectionSize().getNumElements();
}
protected Collection<E> getSampleElements(int howMany) {
return getSubjectGenerator().getSampleElements(howMany);
}
protected Collection<E> getSampleElements() {
return getSampleElements(getNumElements());
}
/**
* Returns the {@linkplain #getSampleElements() sample elements} as ordered by
* {@link TestContainerGenerator#order(List)}. Tests should used this method
* only if they declare requirement {@link
* com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER}.
*/
protected List<E> getOrderedElements() {
List<E> list = new ArrayList<E>();
for (E e : getSubjectGenerator().order(
new ArrayList<E>(getSampleElements()))) {
list.add(e);
}
return Collections.unmodifiableList(list);
}
/**
* @return a suitable location for a null element, to use when initializing
* containers for tests that involve a null element being present.
*/
protected int getNullLocation() {
return getNumElements() / 2;
}
@SuppressWarnings("unchecked")
protected MinimalCollection<E> createDisjointCollection() {
return MinimalCollection.of(samples.e3, samples.e4);
}
@SuppressWarnings("unchecked")
protected MinimalCollection<E> emptyCollection() {
return MinimalCollection.<E>of();
}
}
| 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.features.CollectionSize;
import java.util.Collection;
/**
* The subject-generator interface accepted by Collection testers, for testing
* a Collection at one particular {@link CollectionSize}.
*
* <p>This interface should not be implemented outside this package;
* {@link PerCollectionSizeTestSuiteBuilder} constructs instances of it from
* a more general {@link TestCollectionGenerator}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface OneSizeTestContainerGenerator<T, E>
extends TestSubjectGenerator<T>, TestContainerGenerator<T, E> {
TestContainerGenerator<T, E> getInnerGenerator();
Collection<E> getSampleElements(int howMany);
CollectionSize getCollectionSize();
}
| 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;
import java.util.Collection;
/**
* Creates collections, containing sample elements, to be tested.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public interface TestCollectionGenerator<E>
extends TestContainerGenerator<Collection<E>, E> {
}
| 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 integer sets for testing collections that are sorted by natural
* ordering.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Jared Levy
*/
@GwtCompatible
public abstract class TestIntegerSortedSetGenerator
extends TestIntegerSetGenerator {
@Override protected abstract SortedSet<Integer> create(Integer[] elements);
/** Sorts the elements by their natural ordering. */
@Override public List<Integer> order(List<Integer> insertionOrder) {
Collections.sort(insertionOrder);
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.CollectionSerializationEqualTester;
import com.google.common.collect.testing.testers.SetAddAllTester;
import com.google.common.collect.testing.testers.SetAddTester;
import com.google.common.collect.testing.testers.SetCreationTester;
import com.google.common.collect.testing.testers.SetEqualsTester;
import com.google.common.collect.testing.testers.SetHashCodeTester;
import com.google.common.collect.testing.testers.SetRemoveTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a Set implementation.
*
* @author George van den Driessche
*/
public class SetTestSuiteBuilder<E>
extends AbstractCollectionTestSuiteBuilder<SetTestSuiteBuilder<E>, E> {
public static <E> SetTestSuiteBuilder<E> using(
TestSetGenerator<E> generator) {
return new SetTestSuiteBuilder<E>().usingGenerator(generator);
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers
= Helpers.copyToList(super.getTesters());
testers.add(CollectionSerializationEqualTester.class);
testers.add(SetAddAllTester.class);
testers.add(SetAddTester.class);
testers.add(SetCreationTester.class);
testers.add(SetHashCodeTester.class);
testers.add(SetEqualsTester.class);
testers.add(SetRemoveTester.class);
// SetRemoveAllTester doesn't exist because, Sets not permitting
// duplicate elements, there are no tests for Set.removeAll() that aren't
// covered by CollectionRemoveAllTester.
return testers;
}
@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.SERIALIZABLE)) {
derivedSuites.add(SetTestSuiteBuilder
.using(new ReserializedSetGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite());
}
return derivedSuites;
}
static class ReserializedSetGenerator<E> implements TestSetGenerator<E>{
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedSetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public Set<E> create(Object... elements) {
return (Set<E>) SerializableTester.reserialize(gen.create(elements));
}
@Override
public E[] createArray(int length) {
return gen.createArray(length);
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return gen.order(insertionOrder);
}
}
private static Set<Feature<?>> computeReserializedCollectionFeatures(
Set<Feature<?>> features) {
Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>();
derivedFeatures.addAll(features);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
return derivedFeatures;
}
}
| 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.Map;
/**
* A container class for the five sample elements we need for testing.
*
* <p>This class is GWT compatible.
*
* @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 Arrays.asList(e0, e1, e2, e3, e4).iterator();
}
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) 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) 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.features.CollectionFeature;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.SortedSetNavigationTester;
import junit.framework.TestSuite;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a SortedSet implementation.
*/
public class SortedSetTestSuiteBuilder<E> extends SetTestSuiteBuilder<E> {
public static <E> SortedSetTestSuiteBuilder<E> using(
TestSetGenerator<E> generator) {
SortedSetTestSuiteBuilder<E> builder =
new SortedSetTestSuiteBuilder<E>();
builder.usingGenerator(generator);
return builder;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
Helpers.copyToList(super.getTesters());
testers.add(SortedSetNavigationTester.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();
}
}
| 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.
*
* <p>This class is GWT compatible.
*/
@GwtCompatible
public enum WrongType {
VALUE
}
| 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.Map;
/**
* Creates maps, containing sample elements, to be tested.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface TestMapGenerator<K, V>
extends TestContainerGenerator<Map<K, V>, Map.Entry<K, V>> {
K[] createKeyArray(int length);
V[] createValueArray(int length);
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
/**
* A sample enumerated type we use for testing.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public enum AnEnum {
A, B, C, D, E, F
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.SetFeature;
import com.google.common.collect.testing.testers.CollectionIteratorTester;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Generates a test suite covering the {@link Set} implementations in the
* {@link java.util} package. Can be subclassed to specify tests that should
* be suppressed.
*
* @author Kevin Bourrillion
*/
public class TestsForSetsInJavaUtil {
public static Test suite() {
return new TestsForSetsInJavaUtil().allTests();
}
public Test allTests() {
TestSuite suite = new TestSuite("java.util Sets");
suite.addTest(testsForEmptySet());
suite.addTest(testsForSingletonSet());
suite.addTest(testsForHashSet());
suite.addTest(testsForLinkedHashSet());
suite.addTest(testsForEnumSet());
suite.addTest(testsForTreeSetNatural());
suite.addTest(testsForTreeSetWithComparator());
suite.addTest(testsForCopyOnWriteArraySet());
suite.addTest(testsForUnmodifiableSet());
suite.addTest(testsForCheckedSet());
suite.addTest(testsForAbstractSet());
suite.addTest(testsForBadlyCollidingHashSet());
suite.addTest(testsForConcurrentSkipListSetNatural());
suite.addTest(testsForConcurrentSkipListSetWithComparator());
return suite;
}
protected Collection<Method> suppressForEmptySet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForSingletonSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForHashSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForLinkedHashSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForEnumSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForTreeSetNatural() {
return Collections.emptySet();
}
protected Collection<Method> suppressForTreeSetWithComparator() {
return Collections.emptySet();
}
protected Collection<Method> suppressForCopyOnWriteArraySet() {
return Collections.singleton(CollectionIteratorTester
.getIteratorKnownOrderRemoveSupportedMethod());
}
protected Collection<Method> suppressForUnmodifiableSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForCheckedSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForAbstractSet() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentSkipListSetNatural() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentSkipListSetWithComparator() {
return Collections.emptySet();
}
public Test testsForEmptySet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator() {
@Override public Set<String> create(String[] elements) {
return Collections.emptySet();
}
})
.named("emptySet")
.withFeatures(
CollectionFeature.SERIALIZABLE,
CollectionSize.ZERO)
.suppressing(suppressForEmptySet())
.createTestSuite();
}
public Test testsForSingletonSet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator() {
@Override public Set<String> create(String[] elements) {
return Collections.singleton(elements[0]);
}
})
.named("singleton")
.withFeatures(
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ONE)
.suppressing(suppressForSingletonSet())
.createTestSuite();
}
public Test testsForHashSet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator() {
@Override public Set<String> create(String[] elements) {
return new HashSet<String>(MinimalCollection.of(elements));
}
})
.named("HashSet")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionSize.ANY)
.suppressing(suppressForHashSet())
.createTestSuite();
}
public Test testsForLinkedHashSet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator() {
@Override public Set<String> create(String[] elements) {
return new LinkedHashSet<String>(MinimalCollection.of(elements));
}
})
.named("LinkedHashSet")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionSize.ANY)
.suppressing(suppressForLinkedHashSet())
.createTestSuite();
}
public Test testsForEnumSet() {
return SetTestSuiteBuilder
.using(new TestEnumSetGenerator() {
@Override public Set<AnEnum> create(AnEnum[] elements) {
return (elements.length == 0)
? EnumSet.noneOf(AnEnum.class)
: EnumSet.copyOf(MinimalCollection.of(elements));
}
})
.named("EnumSet")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.RESTRICTS_ELEMENTS,
CollectionSize.ANY)
.suppressing(suppressForEnumSet())
.createTestSuite();
}
public Test testsForTreeSetNatural() {
return SetTestSuiteBuilder
.using(new TestStringSortedSetGenerator() {
@Override public SortedSet<String> create(String[] elements) {
return new TreeSet<String>(MinimalCollection.of(elements));
}
})
.named("TreeSet, natural")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionSize.ANY)
.suppressing(suppressForTreeSetNatural())
.createTestSuite();
}
public Test testsForTreeSetWithComparator() {
return SetTestSuiteBuilder
.using(new TestStringSortedSetGenerator() {
@Override public SortedSet<String> create(String[] elements) {
SortedSet<String> set
= new TreeSet<String>(arbitraryNullFriendlyComparator());
Collections.addAll(set, elements);
return set;
}
})
.named("TreeSet, with comparator")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionSize.ANY)
.suppressing(suppressForTreeSetWithComparator())
.createTestSuite();
}
public Test testsForCopyOnWriteArraySet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator() {
@Override public Set<String> create(String[] elements) {
return new CopyOnWriteArraySet<String>(
MinimalCollection.of(elements));
}
})
.named("CopyOnWriteArraySet")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForCopyOnWriteArraySet())
.createTestSuite();
}
public Test testsForUnmodifiableSet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator() {
@Override public Set<String> create(String[] elements) {
Set<String> innerSet = new HashSet<String>();
Collections.addAll(innerSet, elements);
return Collections.unmodifiableSet(innerSet);
}
})
.named("unmodifiableSet/HashSet")
.withFeatures(
CollectionFeature.NONE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.ANY)
.suppressing(suppressForUnmodifiableSet())
.createTestSuite();
}
public Test testsForCheckedSet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator() {
@Override public Set<String> create(String[] elements) {
Set<String> innerSet = new HashSet<String>();
Collections.addAll(innerSet, elements);
return Collections.checkedSet(innerSet, String.class);
}
})
.named("checkedSet/HashSet")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.RESTRICTS_ELEMENTS,
CollectionSize.ANY)
.suppressing(suppressForCheckedSet())
.createTestSuite();
}
public Test testsForAbstractSet() {
return SetTestSuiteBuilder
.using(new TestStringSetGenerator () {
@Override protected Set<String> create(String[] elements) {
final String[] deduped = dedupe(elements);
return new AbstractSet<String>() {
@Override public int size() {
return deduped.length;
}
@Override public Iterator<String> iterator() {
return MinimalCollection.of(deduped).iterator();
}
};
}
})
.named("AbstractSet")
.withFeatures(
CollectionFeature.NONE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.KNOWN_ORDER, // in this case, anyway
CollectionSize.ANY)
.suppressing(suppressForAbstractSet())
.createTestSuite();
}
public Test testsForBadlyCollidingHashSet() {
return SetTestSuiteBuilder
.using(new TestCollidingSetGenerator() {
@Override
public Set<Object> create(Object... elements) {
return new HashSet<Object>(MinimalCollection.of(elements));
}
})
.named("badly colliding HashSet")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionSize.SEVERAL)
.suppressing(suppressForHashSet())
.createTestSuite();
}
public Test testsForConcurrentSkipListSetNatural() {
return SetTestSuiteBuilder
.using(new TestStringSortedSetGenerator() {
@Override public SortedSet<String> create(String[] elements) {
return new ConcurrentSkipListSet<String>(MinimalCollection.of(elements));
}
})
.named("ConcurrentSkipListSet, natural")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListSetNatural())
.createTestSuite();
}
public Test testsForConcurrentSkipListSetWithComparator() {
return SetTestSuiteBuilder
.using(new TestStringSortedSetGenerator() {
@Override public SortedSet<String> create(String[] elements) {
SortedSet<String> set
= new ConcurrentSkipListSet<String>(arbitraryNullFriendlyComparator());
Collections.addAll(set, elements);
return set;
}
})
.named("ConcurrentSkipListSet, with comparator")
.withFeatures(
SetFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionFeature.KNOWN_ORDER,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListSetWithComparator())
.createTestSuite();
}
private static String[] dedupe(String[] elements) {
Set<String> tmp = new LinkedHashSet<String>();
Collections.addAll(tmp, elements);
return tmp.toArray(new String[0]);
}
static <T> Comparator<T> arbitraryNullFriendlyComparator() {
return new NullFriendlyComparator<T>();
}
private static final class NullFriendlyComparator<T>
implements Comparator<T>, Serializable {
@Override
public int compare(T left, T right) {
return String.valueOf(left).compareTo(String.valueOf(right));
}
}
}
| 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.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
/**
* Tests representing the contract of {@link SortedMap}. Concrete subclasses of
* this base class test conformance of concrete {@link SortedMap} subclasses to
* that contract.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
// TODO: Use this class to test classes besides ImmutableSortedMap.
@GwtCompatible
public abstract class SortedMapInterfaceTest<K, V>
extends MapInterfaceTest<K, V> {
/** A key type that is not assignable to any classes but Object. */
private static final class IncompatibleComparableKeyType
implements Comparable<IncompatibleComparableKeyType> {
@Override public String toString() {
return "IncompatibleComparableKeyType";
}
@Override
public int compareTo(IncompatibleComparableKeyType o) {
throw new ClassCastException();
}
}
protected SortedMapInterfaceTest(boolean allowsNullKeys,
boolean allowsNullValues, boolean supportsPut, boolean supportsRemove,
boolean supportsClear) {
super(allowsNullKeys, allowsNullValues, supportsPut, supportsRemove,
supportsClear);
}
@Override protected abstract SortedMap<K, V> makeEmptyMap()
throws UnsupportedOperationException;
@Override protected abstract SortedMap<K, V> makePopulatedMap()
throws UnsupportedOperationException;
@Override protected SortedMap<K, V> makeEitherMap() {
try {
return makePopulatedMap();
} catch (UnsupportedOperationException e) {
return makeEmptyMap();
}
}
@SuppressWarnings("unchecked") // Needed for null comparator
public void testOrdering() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Iterator<K> iterator = map.keySet().iterator();
K prior = iterator.next();
Comparator<? super K> comparator = map.comparator();
while (iterator.hasNext()) {
K current = iterator.next();
if (comparator == null) {
Comparable comparable = (Comparable) prior;
assertTrue(comparable.compareTo(current) < 0);
} else {
assertTrue(map.comparator().compare(prior, current) < 0);
}
current = prior;
}
}
public void testEntrySetContainsEntryIncompatibleComparableKey() {
final Map<K, V> map;
final Set<Entry<K, V>> entrySet;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
entrySet = map.entrySet();
final V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Entry<IncompatibleComparableKeyType, V> entry
= mapEntry(new IncompatibleComparableKeyType(), unmappedValue);
assertFalse(entrySet.contains(entry));
}
public void testFirstKeyEmpty() {
final SortedMap<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
try {
map.firstKey();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException expected) {}
assertInvariants(map);
}
public void testFirstKeyNonEmpty() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
K expected = map.keySet().iterator().next();
assertEquals(expected, map.firstKey());
assertInvariants(map);
}
public void testLastKeyEmpty() {
final SortedMap<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
try {
map.lastKey();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException expected) {}
assertInvariants(map);
}
public void testLastKeyNonEmpty() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
K expected = null;
for (K key : map.keySet()) {
expected = key;
}
assertEquals(expected, map.lastKey());
assertInvariants(map);
}
private static <E> List<E> toList(Collection<E> collection) {
return new ArrayList<E>(collection);
}
private static <E> List<E> subListSnapshot(
List<E> list, int fromIndex, int toIndex) {
List<E> subList = new ArrayList<E>();
for (int i = fromIndex; i < toIndex; i++) {
subList.add(list.get(i));
}
return Collections.unmodifiableList(subList);
}
public void testHeadMap() {
final SortedMap<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
List<Entry<K, V>> list = toList(map.entrySet());
for (int i = 0; i < list.size(); i++) {
List<Entry<K, V>> expected = subListSnapshot(list, 0, i);
SortedMap<K, V> headMap = map.headMap(list.get(i).getKey());
assertEquals(expected, toList(headMap.entrySet()));
}
}
public void testTailMap() {
final SortedMap<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
List<Entry<K, V>> list = toList(map.entrySet());
for (int i = 0; i < list.size(); i++) {
List<Entry<K, V>> expected = subListSnapshot(list, i, list.size());
SortedMap<K, V> tailMap = map.tailMap(list.get(i).getKey());
assertEquals(expected, toList(tailMap.entrySet()));
}
}
public void testSubMap() {
final SortedMap<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
List<Entry<K, V>> list = toList(map.entrySet());
for (int i = 0; i < list.size(); i++) {
for (int j = i; j < list.size(); j++) {
List<Entry<K, V>> expected = subListSnapshot(list, i, j);
SortedMap<K, V> subMap
= map.subMap(list.get(i).getKey(), list.get(j).getKey());
assertEquals(expected, toList(subMap.entrySet()));
}
}
}
public void testSubMapIllegal() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (map.size() < 2) {
return;
}
Iterator<K> iterator = map.keySet().iterator();
K first = iterator.next();
K second = iterator.next();
try {
map.subMap(second, first);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
public void testTailMapEntrySet() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (map.size() < 3) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
Entry<K, V> thirdEntry = iterator.next();
SortedMap<K, V> tail = map.tailMap(secondEntry.getKey());
Set<Entry<K, V>> tailEntrySet = tail.entrySet();
assertTrue(tailEntrySet.contains(thirdEntry));
assertTrue(tailEntrySet.contains(secondEntry));
assertFalse(tailEntrySet.contains(firstEntry));
assertEquals(tail.firstKey(), secondEntry.getKey());
}
public void testHeadMapEntrySet() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (map.size() < 3) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
Entry<K, V> thirdEntry = iterator.next();
SortedMap<K, V> head = map.headMap(secondEntry.getKey());
Set<Entry<K, V>> headEntrySet = head.entrySet();
assertFalse(headEntrySet.contains(thirdEntry));
assertFalse(headEntrySet.contains(secondEntry));
assertTrue(headEntrySet.contains(firstEntry));
assertEquals(head.firstKey(), firstEntry.getKey());
assertEquals(head.lastKey(), firstEntry.getKey());
}
public void testTailMapWriteThrough() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (map.size() < 2 || !supportsPut) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
K key = secondEntry.getKey();
SortedMap<K, V> subMap = map.tailMap(key);
V value = getValueNotInPopulatedMap();
subMap.put(key, value);
assertEquals(secondEntry.getValue(), value);
assertEquals(map.get(key), value);
try {
subMap.put(firstEntry.getKey(), value);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
public void testTailMapRemoveThrough() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int oldSize = map.size();
if (map.size() < 2 || !supportsRemove) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
K key = secondEntry.getKey();
SortedMap<K, V> subMap = map.tailMap(key);
subMap.remove(key);
assertNull(subMap.remove(firstEntry.getKey()));
assertEquals(map.size(), oldSize - 1);
assertFalse(map.containsKey(key));
assertEquals(subMap.size(), oldSize - 2);
}
public void testTailMapClearThrough() {
final SortedMap<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
int oldSize = map.size();
if (map.size() < 2 || !supportsClear) {
return;
}
Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
Entry<K, V> firstEntry = iterator.next();
Entry<K, V> secondEntry = iterator.next();
K key = secondEntry.getKey();
SortedMap<K, V> subMap = map.tailMap(key);
int subMapSize = subMap.size();
subMap.clear();
assertEquals(map.size(), oldSize - subMapSize);
assertTrue(subMap.isEmpty());
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
/**
* Generates a test suite covering the {@link Map} implementations in the
* {@link java.util} package. Can be subclassed to specify tests that should
* be suppressed.
*
* @author Kevin Bourrillion
*/
public class TestsForMapsInJavaUtil {
public static Test suite() {
return new TestsForMapsInJavaUtil().allTests();
}
public Test allTests() {
TestSuite suite = new TestSuite("java.util Maps");
suite.addTest(testsForEmptyMap());
suite.addTest(testsForSingletonMap());
suite.addTest(testsForHashMap());
suite.addTest(testsForLinkedHashMap());
suite.addTest(testsForTreeMapNatural());
suite.addTest(testsForTreeMapWithComparator());
suite.addTest(testsForEnumMap());
suite.addTest(testsForConcurrentHashMap());
suite.addTest(testsForConcurrentSkipListMapNatural());
suite.addTest(testsForConcurrentSkipListMapWithComparator());
return suite;
}
protected Collection<Method> suppressForEmptyMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForSingletonMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForHashMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForLinkedHashMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForTreeMapNatural() {
return Collections.emptySet();
}
protected Collection<Method> suppressForTreeMapWithComparator() {
return Collections.emptySet();
}
protected Collection<Method> suppressForEnumMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentHashMap() {
return Collections.emptySet();
}
protected Collection<Method> suppressForConcurrentSkipListMap() {
return Collections.emptySet();
}
public Test testsForEmptyMap() {
return MapTestSuiteBuilder
.using(new TestStringMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return Collections.emptyMap();
}
})
.named("emptyMap")
.withFeatures(
CollectionFeature.SERIALIZABLE,
CollectionSize.ZERO)
.suppressing(suppressForEmptyMap())
.createTestSuite();
}
public Test testsForSingletonMap() {
return MapTestSuiteBuilder
.using(new TestStringMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return Collections.singletonMap(
entries[0].getKey(), entries[0].getValue());
}
})
.named("singletonMap")
.withFeatures(
MapFeature.ALLOWS_NULL_KEYS,
MapFeature.ALLOWS_NULL_VALUES,
CollectionFeature.SERIALIZABLE,
CollectionSize.ONE)
.suppressing(suppressForSingletonMap())
.createTestSuite();
}
public Test testsForHashMap() {
return MapTestSuiteBuilder
.using(new TestStringMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return toHashMap(entries);
}
@Override public Iterable<Entry<String, String>> order(
List<Entry<String, String>> insertionOrder) {
/*
* For convenience, make this test double as a test that no tester
* calls order() on a container without the KNOWN_ORDER feature.
*/
throw new UnsupportedOperationException();
}
})
.named("HashMap")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_KEYS,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForHashMap())
.createTestSuite();
}
public Test testsForLinkedHashMap() {
return MapTestSuiteBuilder
.using(new TestStringMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return populate(new LinkedHashMap<String, String>(), entries);
}
})
.named("LinkedHashMap")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_KEYS,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForLinkedHashMap())
.createTestSuite();
}
public Test testsForTreeMapNatural() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
/*
* TODO(cpovirk): it would be nice to create an input Map and use
* the copy constructor here and in the other tests
*/
return populate(new TreeMap<String, String>(), entries);
}
})
.named("TreeMap, natural")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForTreeMapNatural())
.createTestSuite();
}
public Test testsForTreeMapWithComparator() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return populate(new TreeMap<String, String>(
arbitraryNullFriendlyComparator()), entries);
}
})
.named("TreeMap, with comparator")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_KEYS,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForTreeMapWithComparator())
.createTestSuite();
}
public Test testsForEnumMap() {
return MapTestSuiteBuilder
.using(new TestEnumMapGenerator() {
@Override protected Map<AnEnum, String> create(
Entry<AnEnum, String>[] entries) {
return populate(
new EnumMap<AnEnum, String>(AnEnum.class), entries);
}
})
.named("EnumMap")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
MapFeature.ALLOWS_NULL_VALUES,
MapFeature.RESTRICTS_KEYS,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForEnumMap())
.createTestSuite();
}
public Test testsForConcurrentHashMap() {
return MapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return populate(new ConcurrentHashMap<String, String>(), entries);
}
})
.named("ConcurrentHashMap")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForConcurrentHashMap())
.createTestSuite();
}
public Test testsForConcurrentSkipListMapNatural() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return populate(new ConcurrentSkipListMap<String, String>(), entries);
}
})
.named("ConcurrentSkipListMap, natural")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListMap())
.createTestSuite();
}
public Test testsForConcurrentSkipListMapWithComparator() {
return NavigableMapTestSuiteBuilder
.using(new TestStringSortedMapGenerator() {
@Override protected Map<String, String> create(
Entry<String, String>[] entries) {
return populate(new ConcurrentSkipListMap<String, String>(
arbitraryNullFriendlyComparator()), entries);
}
})
.named("ConcurrentSkipListMap, with comparator")
.withFeatures(
MapFeature.GENERAL_PURPOSE,
CollectionFeature.KNOWN_ORDER,
CollectionFeature.SERIALIZABLE,
CollectionSize.ANY)
.suppressing(suppressForConcurrentSkipListMap())
.createTestSuite();
}
// TODO: IdentityHashMap, AbstractMap
private static Map<String, String> toHashMap(
Entry<String, String>[] entries) {
return populate(new HashMap<String, String>(), entries);
}
// TODO: call conversion constructors or factory methods instead of using
// populate() on an empty map
private static <T> Map<T, String> populate(
Map<T, String> map, Entry<T, String>[] entries) {
for (Entry<T, String> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
static <T> Comparator<T> arbitraryNullFriendlyComparator() {
return new NullFriendlyComparator<T>();
}
private static final class NullFriendlyComparator<T> implements Comparator<T>, Serializable {
@Override
public int compare(T left, T right) {
return String.valueOf(left).compareTo(String.valueOf(right));
}
}
}
| 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 java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A wrapper around {@code TreeMap} that aggressively checks to see if keys are
* mutually comparable. This implementation passes the navigable map test
* suites.
*
* @author Louis Wasserman
*/
public final class SafeTreeMap<K, V>
implements Serializable, NavigableMap<K, V> {
@SuppressWarnings("unchecked")
private static final Comparator NATURAL_ORDER = new Comparator<Comparable>() {
@Override public int compare(Comparable o1, Comparable o2) {
return o1.compareTo(o2);
}
};
private final NavigableMap<K, V> delegate;
public SafeTreeMap() {
this(new TreeMap<K, V>());
}
public SafeTreeMap(Comparator<? super K> comparator) {
this(new TreeMap<K, V>(comparator));
}
public SafeTreeMap(Map<? extends K, ? extends V> map) {
this(new TreeMap<K, V>(map));
}
public SafeTreeMap(SortedMap<K, ? extends V> map) {
this(new TreeMap<K, V>(map));
}
private SafeTreeMap(NavigableMap<K, V> delegate) {
this.delegate = delegate;
if (delegate == null) {
throw new NullPointerException();
}
for (K k : keySet()) {
checkValid(k);
}
}
@Override public Entry<K, V> ceilingEntry(K key) {
return delegate.ceilingEntry(checkValid(key));
}
@Override public K ceilingKey(K key) {
return delegate.ceilingKey(checkValid(key));
}
@Override public void clear() {
delegate.clear();
}
@SuppressWarnings("unchecked")
@Override public Comparator<? super K> comparator() {
Comparator<? super K> comparator = delegate.comparator();
if (comparator == null) {
comparator = NATURAL_ORDER;
}
return comparator;
}
@Override public boolean containsKey(Object key) {
try {
return delegate.containsKey(checkValid(key));
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean containsValue(Object value) {
return delegate.containsValue(value);
}
@Override public NavigableSet<K> descendingKeySet() {
return delegate.descendingKeySet();
}
@Override public NavigableMap<K, V> descendingMap() {
return new SafeTreeMap<K, V>(delegate.descendingMap());
}
@Override public Set<Entry<K, V>> entrySet() {
return delegate.entrySet();
}
@Override public Entry<K, V> firstEntry() {
return delegate.firstEntry();
}
@Override public K firstKey() {
return delegate.firstKey();
}
@Override public Entry<K, V> floorEntry(K key) {
return delegate.floorEntry(checkValid(key));
}
@Override public K floorKey(K key) {
return delegate.floorKey(checkValid(key));
}
@Override public V get(Object key) {
return delegate.get(checkValid(key));
}
@Override public SortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
@Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return new SafeTreeMap<K, V>(
delegate.headMap(checkValid(toKey), inclusive));
}
@Override public Entry<K, V> higherEntry(K key) {
return delegate.higherEntry(checkValid(key));
}
@Override public K higherKey(K key) {
return delegate.higherKey(checkValid(key));
}
@Override public boolean isEmpty() {
return delegate.isEmpty();
}
@Override public NavigableSet<K> keySet() {
return navigableKeySet();
}
@Override public Entry<K, V> lastEntry() {
return delegate.lastEntry();
}
@Override public K lastKey() {
return delegate.lastKey();
}
@Override public Entry<K, V> lowerEntry(K key) {
return delegate.lowerEntry(checkValid(key));
}
@Override public K lowerKey(K key) {
return delegate.lowerKey(checkValid(key));
}
@Override public NavigableSet<K> navigableKeySet() {
return delegate.navigableKeySet();
}
@Override public Entry<K, V> pollFirstEntry() {
return delegate.pollFirstEntry();
}
@Override public Entry<K, V> pollLastEntry() {
return delegate.pollLastEntry();
}
@Override public V put(K key, V value) {
return delegate.put(checkValid(key), value);
}
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (K key : map.keySet()) {
checkValid(key);
}
delegate.putAll(map);
}
@Override public V remove(Object key) {
return delegate.remove(checkValid(key));
}
@Override public int size() {
return delegate.size();
}
@Override public NavigableMap<K, V> subMap(
K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return new SafeTreeMap<K, V>(delegate.subMap(
checkValid(fromKey), fromInclusive, checkValid(toKey), toInclusive));
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
@Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return new SafeTreeMap<K, V>(
delegate.tailMap(checkValid(fromKey), inclusive));
}
@Override public Collection<V> values() {
return delegate.values();
}
private <T> T checkValid(T t) {
// a ClassCastException is what's supposed to happen!
@SuppressWarnings("unchecked")
K k = (K) t;
comparator().compare(k, k);
return t;
}
@Override public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override public int hashCode() {
return delegate.hashCode();
}
@Override public String toString() {
return delegate.toString();
}
private static final long serialVersionUID = 0L;
}
| 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) 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 com.google.common.collect.testing.SampleElements.Unhashables;
import java.util.Collection;
import java.util.List;
/**
* Creates collections containing unhashable sample elements, to be tested.
*
* <p>This class is GWT compatible.
*
* @author Regina O'Dell
*/
@GwtCompatible
public abstract class
TestUnhashableCollectionGenerator<T extends Collection<UnhashableObject>>
implements TestCollectionGenerator<UnhashableObject> {
@Override
public SampleElements<UnhashableObject> samples() {
return new Unhashables();
}
@Override
public T create(Object... elements) {
UnhashableObject[] array = createArray(elements.length);
int i = 0;
for (Object e : elements) {
array[i++] = (UnhashableObject) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract T create(UnhashableObject[] elements);
@Override
public UnhashableObject[] createArray(int length) {
return new UnhashableObject[length];
}
@Override
public Iterable<UnhashableObject> order(
List<UnhashableObject> 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.Chars;
import java.util.List;
/**
* Generates {@code List<Character>} instances for test suites.
*
* <p>This class is GWT compatible.
*
* @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.Enums;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* An abstract TestSetGenerator for generating sets containing enum values.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public abstract class TestEnumSetGenerator implements TestSetGenerator<AnEnum> {
@Override
public SampleElements<AnEnum> samples() {
return new Enums();
}
@Override
public Set<AnEnum> create(Object... elements) {
AnEnum[] array = new AnEnum[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (AnEnum) e;
}
return create(array);
}
protected abstract Set<AnEnum> create(AnEnum[] elements);
@Override
public AnEnum[] createArray(int length) {
return new AnEnum[length];
}
/**
* Sorts the enums according to their natural ordering.
*/
@Override
public List<AnEnum> order(List<AnEnum> insertionOrder) {
Collections.sort(insertionOrder);
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.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) 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.
*
* <p>This class is GWT compatible.
*
* @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) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static java.util.Collections.singleton;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Tests representing the contract of {@link Map}. Concrete subclasses of this
* base class test conformance of concrete {@link Map} subclasses to that
* contract.
*
* TODO: Descriptive assertion messages, with hints as to probable
* fixes.
* TODO: Add another constructor parameter indicating whether the
* class under test is ordered, and check the order if so.
* TODO: Refactor to share code with SetTestBuilder &c.
*
* <p>This class is GWT compatible.
*
* @param <K> the type of keys used by the maps under test
* @param <V> the type of mapped values used the maps under test
*
* @author George van den Driessche
*/
@GwtCompatible
public abstract class MapInterfaceTest<K, V> extends TestCase {
/** A key type that is not assignable to any classes but Object. */
private static final class IncompatibleKeyType {
@Override public String toString() {
return "IncompatibleKeyType";
}
}
protected final boolean supportsPut;
protected final boolean supportsRemove;
protected final boolean supportsClear;
protected final boolean allowsNullKeys;
protected final boolean allowsNullValues;
protected final boolean supportsIteratorRemove;
/**
* Creates a new, empty instance of the class under test.
*
* @return a new, empty map instance.
* @throws UnsupportedOperationException if it's not possible to make an
* empty instance of the class under test.
*/
protected abstract Map<K, V> makeEmptyMap()
throws UnsupportedOperationException;
/**
* Creates a new, non-empty instance of the class under test.
*
* @return a new, non-empty map instance.
* @throws UnsupportedOperationException if it's not possible to make a
* non-empty instance of the class under test.
*/
protected abstract Map<K, V> makePopulatedMap()
throws UnsupportedOperationException;
/**
* Creates a new key that is not expected to be found
* in {@link #makePopulatedMap()}.
*
* @return a key.
* @throws UnsupportedOperationException if it's not possible to make a key
* that will not be found in the map.
*/
protected abstract K getKeyNotInPopulatedMap()
throws UnsupportedOperationException;
/**
* Creates a new value that is not expected to be found
* in {@link #makePopulatedMap()}.
*
* @return a value.
* @throws UnsupportedOperationException if it's not possible to make a value
* that will not be found in the map.
*/
protected abstract V getValueNotInPopulatedMap()
throws UnsupportedOperationException;
/**
* Constructor that assigns {@code supportsIteratorRemove} the same value as
* {@code supportsRemove}.
*/
protected MapInterfaceTest(
boolean allowsNullKeys,
boolean allowsNullValues,
boolean supportsPut,
boolean supportsRemove,
boolean supportsClear) {
this(allowsNullKeys, allowsNullValues, supportsPut, supportsRemove,
supportsClear, supportsRemove);
}
/**
* Constructor with an explicit {@code supportsIteratorRemove} parameter.
*/
protected MapInterfaceTest(
boolean allowsNullKeys,
boolean allowsNullValues,
boolean supportsPut,
boolean supportsRemove,
boolean supportsClear,
boolean supportsIteratorRemove) {
this.supportsPut = supportsPut;
this.supportsRemove = supportsRemove;
this.supportsClear = supportsClear;
this.allowsNullKeys = allowsNullKeys;
this.allowsNullValues = allowsNullValues;
this.supportsIteratorRemove = supportsIteratorRemove;
}
/**
* Used by tests that require a map, but don't care whether it's
* populated or not.
*
* @return a new map instance.
*/
protected Map<K, V> makeEitherMap() {
try {
return makePopulatedMap();
} catch (UnsupportedOperationException e) {
return makeEmptyMap();
}
}
protected final boolean supportsValuesHashCode(Map<K, V> map) {
// get the first non-null value
Collection<V> values = map.values();
for (V value : values) {
if (value != null) {
try {
value.hashCode();
} catch (Exception e) {
return false;
}
return true;
}
}
return true;
}
/**
* Checks all the properties that should always hold of a map. Also calls
* {@link #assertMoreInvariants} to check invariants that are peculiar to
* specific implementations.
*
* @see #assertMoreInvariants
* @param map the map to check.
*/
protected final void assertInvariants(Map<K, V> map) {
Set<K> keySet = map.keySet();
Collection<V> valueCollection = map.values();
Set<Entry<K, V>> entrySet = map.entrySet();
assertEquals(map.size() == 0, map.isEmpty());
assertEquals(map.size(), keySet.size());
assertEquals(keySet.size() == 0, keySet.isEmpty());
assertEquals(!keySet.isEmpty(), keySet.iterator().hasNext());
int expectedKeySetHash = 0;
for (K key : keySet) {
V value = map.get(key);
expectedKeySetHash += key != null ? key.hashCode() : 0;
assertTrue(map.containsKey(key));
assertTrue(map.containsValue(value));
assertTrue(valueCollection.contains(value));
assertTrue(valueCollection.containsAll(Collections.singleton(value)));
assertTrue(entrySet.contains(mapEntry(key, value)));
assertTrue(allowsNullKeys || (key != null));
}
assertEquals(expectedKeySetHash, keySet.hashCode());
assertEquals(map.size(), valueCollection.size());
assertEquals(valueCollection.size() == 0, valueCollection.isEmpty());
assertEquals(
!valueCollection.isEmpty(), valueCollection.iterator().hasNext());
for (V value : valueCollection) {
assertTrue(map.containsValue(value));
assertTrue(allowsNullValues || (value != null));
}
assertEquals(map.size(), entrySet.size());
assertEquals(entrySet.size() == 0, entrySet.isEmpty());
assertEquals(!entrySet.isEmpty(), entrySet.iterator().hasNext());
assertFalse(entrySet.contains("foo"));
boolean supportsValuesHashCode = supportsValuesHashCode(map);
if (supportsValuesHashCode) {
int expectedEntrySetHash = 0;
for (Entry<K, V> entry : entrySet) {
assertTrue(map.containsKey(entry.getKey()));
assertTrue(map.containsValue(entry.getValue()));
int expectedHash =
(entry.getKey() == null ? 0 : entry.getKey().hashCode()) ^
(entry.getValue() == null ? 0 : entry.getValue().hashCode());
assertEquals(expectedHash, entry.hashCode());
expectedEntrySetHash += expectedHash;
}
assertEquals(expectedEntrySetHash, entrySet.hashCode());
assertTrue(entrySet.containsAll(new HashSet<Entry<K, V>>(entrySet)));
assertTrue(entrySet.equals(new HashSet<Entry<K, V>>(entrySet)));
}
Object[] entrySetToArray1 = entrySet.toArray();
assertEquals(map.size(), entrySetToArray1.length);
assertTrue(Arrays.asList(entrySetToArray1).containsAll(entrySet));
Entry<?, ?>[] entrySetToArray2 = new Entry<?, ?>[map.size() + 2];
entrySetToArray2[map.size()] = mapEntry("foo", 1);
assertSame(entrySetToArray2, entrySet.toArray(entrySetToArray2));
assertNull(entrySetToArray2[map.size()]);
assertTrue(Arrays.asList(entrySetToArray2).containsAll(entrySet));
Object[] valuesToArray1 = valueCollection.toArray();
assertEquals(map.size(), valuesToArray1.length);
assertTrue(Arrays.asList(valuesToArray1).containsAll(valueCollection));
Object[] valuesToArray2 = new Object[map.size() + 2];
valuesToArray2[map.size()] = "foo";
assertSame(valuesToArray2, valueCollection.toArray(valuesToArray2));
assertNull(valuesToArray2[map.size()]);
assertTrue(Arrays.asList(valuesToArray2).containsAll(valueCollection));
if (supportsValuesHashCode) {
int expectedHash = 0;
for (Entry<K, V> entry : entrySet) {
expectedHash += entry.hashCode();
}
assertEquals(expectedHash, map.hashCode());
}
assertMoreInvariants(map);
}
/**
* Override this to check invariants which should hold true for a particular
* implementation, but which are not generally applicable to every instance
* of Map.
*
* @param map the map whose additional invariants to check.
*/
protected void assertMoreInvariants(Map<K, V> map) {
}
public void testClear() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsClear) {
map.clear();
assertTrue(map.isEmpty());
} else {
try {
map.clear();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testContainsKey() {
final Map<K, V> map;
final K unmappedKey;
try {
map = makePopulatedMap();
unmappedKey = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.containsKey(unmappedKey));
try {
assertFalse(map.containsKey(new IncompatibleKeyType()));
} catch (ClassCastException tolerated) {}
assertTrue(map.containsKey(map.keySet().iterator().next()));
if (allowsNullKeys) {
map.containsKey(null);
} else {
try {
map.containsKey(null);
} catch (NullPointerException optional) {
}
}
assertInvariants(map);
}
public void testContainsValue() {
final Map<K, V> map;
final V unmappedValue;
try {
map = makePopulatedMap();
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.containsValue(unmappedValue));
assertTrue(map.containsValue(map.values().iterator().next()));
if (allowsNullValues) {
map.containsValue(null);
} else {
try {
map.containsKey(null);
} catch (NullPointerException optional) {
}
}
assertInvariants(map);
}
public void testEntrySet() {
final Map<K, V> map;
final Set<Entry<K, V>> entrySet;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
entrySet = map.entrySet();
final K unmappedKey;
final V unmappedValue;
try {
unmappedKey = getKeyNotInPopulatedMap();
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
for (Entry<K, V> entry : entrySet) {
assertFalse(unmappedKey.equals(entry.getKey()));
assertFalse(unmappedValue.equals(entry.getValue()));
}
}
public void testEntrySetForEmptyMap() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
}
public void testEntrySetContainsEntryIncompatibleKey() {
final Map<K, V> map;
final Set<Entry<K, V>> entrySet;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
entrySet = map.entrySet();
final V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Entry<IncompatibleKeyType, V> entry
= mapEntry(new IncompatibleKeyType(), unmappedValue);
try {
assertFalse(entrySet.contains(entry));
} catch (ClassCastException tolerated) {}
}
public void testEntrySetContainsEntryNullKeyPresent() {
if (!allowsNullKeys || !supportsPut) {
return;
}
final Map<K, V> map;
final Set<Entry<K, V>> entrySet;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
entrySet = map.entrySet();
final V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
map.put(null, unmappedValue);
Entry<K, V> entry = mapEntry(null, unmappedValue);
assertTrue(entrySet.contains(entry));
assertFalse(entrySet.contains(mapEntry(null, null)));
}
public void testEntrySetContainsEntryNullKeyMissing() {
final Map<K, V> map;
final Set<Entry<K, V>> entrySet;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
entrySet = map.entrySet();
final V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Entry<K, V> entry = mapEntry(null, unmappedValue);
try {
assertFalse(entrySet.contains(entry));
} catch (NullPointerException e) {
assertFalse(allowsNullKeys);
}
try {
assertFalse(entrySet.contains(mapEntry(null, null)));
} catch (NullPointerException e) {
assertFalse(allowsNullKeys && allowsNullValues);
}
}
public void testEntrySetIteratorRemove() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Iterator<Entry<K, V>> iterator = entrySet.iterator();
if (supportsIteratorRemove) {
int initialSize = map.size();
Entry<K, V> entry = iterator.next();
Entry<K, V> entryCopy = Helpers.mapEntry(
entry.getKey(), entry.getValue());
iterator.remove();
assertEquals(initialSize - 1, map.size());
// Use "entryCopy" instead of "entry" because "entry" might be invalidated after
// iterator.remove().
assertFalse(entrySet.contains(entryCopy));
assertInvariants(map);
try {
iterator.remove();
fail("Expected IllegalStateException.");
} catch (IllegalStateException e) {
// Expected.
}
} else {
try {
iterator.next();
iterator.remove();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetRemove() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsRemove) {
int initialSize = map.size();
boolean didRemove = entrySet.remove(entrySet.iterator().next());
assertTrue(didRemove);
assertEquals(initialSize - 1, map.size());
} else {
try {
entrySet.remove(entrySet.iterator().next());
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetRemoveMissingKey() {
final Map<K, V> map;
final K key;
try {
map = makeEitherMap();
key = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entry
= mapEntry(key, getValueNotInPopulatedMap());
int initialSize = map.size();
if (supportsRemove) {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} else {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (UnsupportedOperationException optional) {}
}
assertEquals(initialSize, map.size());
assertFalse(map.containsKey(key));
assertInvariants(map);
}
public void testEntrySetRemoveDifferentValue() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
K key = map.keySet().iterator().next();
Entry<K, V> entry
= mapEntry(key, getValueNotInPopulatedMap());
int initialSize = map.size();
if (supportsRemove) {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} else {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (UnsupportedOperationException optional) {}
}
assertEquals(initialSize, map.size());
assertTrue(map.containsKey(key));
assertInvariants(map);
}
public void testEntrySetRemoveNullKeyPresent() {
if (!allowsNullKeys || !supportsPut || !supportsRemove) {
return;
}
final Map<K, V> map;
final Set<Entry<K, V>> entrySet;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
entrySet = map.entrySet();
final V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
map.put(null, unmappedValue);
assertEquals(unmappedValue, map.get(null));
assertTrue(map.containsKey(null));
Entry<K, V> entry = mapEntry(null, unmappedValue);
assertTrue(entrySet.remove(entry));
assertNull(map.get(null));
assertFalse(map.containsKey(null));
}
public void testEntrySetRemoveNullKeyMissing() {
final Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entry
= mapEntry(null, getValueNotInPopulatedMap());
int initialSize = map.size();
if (supportsRemove) {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (NullPointerException e) {
assertFalse(allowsNullKeys);
}
} else {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (UnsupportedOperationException optional) {}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testEntrySetRemoveAll() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entryToRemove = entrySet.iterator().next();
Set<Entry<K, V>> entriesToRemove = singleton(entryToRemove);
if (supportsRemove) {
// We use a copy of "entryToRemove" in the assertion because "entryToRemove" might be
// invalidated and have undefined behavior after entrySet.removeAll(entriesToRemove),
// for example entryToRemove.getValue() might be null.
Entry<K, V> entryToRemoveCopy = Helpers.mapEntry(
entryToRemove.getKey(), entryToRemove.getValue());
int initialSize = map.size();
boolean didRemove = entrySet.removeAll(entriesToRemove);
assertTrue(didRemove);
assertEquals(initialSize - entriesToRemove.size(), map.size());
// Use "entryToRemoveCopy" instead of "entryToRemove" because it might be invalidated and
// have undefined behavior after entrySet.removeAll(entriesToRemove),
assertFalse(entrySet.contains(entryToRemoveCopy));
} else {
try {
entrySet.removeAll(entriesToRemove);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetRemoveAllNullFromEmpty() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsRemove) {
try {
entrySet.removeAll(null);
fail("Expected NullPointerException.");
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
entrySet.removeAll(null);
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetRetainAll() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Set<Entry<K, V>> entriesToRetain =
singleton(entrySet.iterator().next());
if (supportsRemove) {
boolean shouldRemove = (entrySet.size() > entriesToRetain.size());
boolean didRemove = entrySet.retainAll(entriesToRetain);
assertEquals(shouldRemove, didRemove);
assertEquals(entriesToRetain.size(), map.size());
for (Entry<K, V> entry : entriesToRetain) {
assertTrue(entrySet.contains(entry));
}
} else {
try {
entrySet.retainAll(entriesToRetain);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetRetainAllNullFromEmpty() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsRemove) {
try {
entrySet.retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
entrySet.retainAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetClear() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsClear) {
entrySet.clear();
assertTrue(entrySet.isEmpty());
} else {
try {
entrySet.clear();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetAddAndAddAll() {
final Map<K, V> map = makeEitherMap();
Set<Entry<K, V>> entrySet = map.entrySet();
final Entry<K, V> entryToAdd = mapEntry(null, null);
try {
entrySet.add(entryToAdd);
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
assertInvariants(map);
try {
entrySet.addAll(singleton(entryToAdd));
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
assertInvariants(map);
}
public void testEntrySetSetValue() {
// TODO: Investigate the extent to which, in practice, maps that support
// put() also support Entry.setValue().
if (!supportsPut) {
return;
}
final Map<K, V> map;
final V valueToSet;
try {
map = makePopulatedMap();
valueToSet = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entry = entrySet.iterator().next();
final V oldValue = entry.getValue();
final V returnedValue = entry.setValue(valueToSet);
assertEquals(oldValue, returnedValue);
assertTrue(entrySet.contains(
mapEntry(entry.getKey(), valueToSet)));
assertEquals(valueToSet, map.get(entry.getKey()));
assertInvariants(map);
}
public void testEntrySetSetValueSameValue() {
// TODO: Investigate the extent to which, in practice, maps that support
// put() also support Entry.setValue().
if (!supportsPut) {
return;
}
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entry = entrySet.iterator().next();
final V oldValue = entry.getValue();
final V returnedValue = entry.setValue(oldValue);
assertEquals(oldValue, returnedValue);
assertTrue(entrySet.contains(
mapEntry(entry.getKey(), oldValue)));
assertEquals(oldValue, map.get(entry.getKey()));
assertInvariants(map);
}
public void testEqualsForEqualMap() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertEquals(map, map);
assertEquals(makePopulatedMap(), map);
assertFalse(map.equals(Collections.emptyMap()));
//no-inspection ObjectEqualsNull
assertFalse(map.equals(null));
}
public void testEqualsForLargerMap() {
if (!supportsPut) {
return;
}
final Map<K, V> map;
final Map<K, V> largerMap;
try {
map = makePopulatedMap();
largerMap = makePopulatedMap();
largerMap.put(getKeyNotInPopulatedMap(), getValueNotInPopulatedMap());
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.equals(largerMap));
}
public void testEqualsForSmallerMap() {
if (!supportsRemove) {
return;
}
final Map<K, V> map;
final Map<K, V> smallerMap;
try {
map = makePopulatedMap();
smallerMap = makePopulatedMap();
smallerMap.remove(smallerMap.keySet().iterator().next());
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.equals(smallerMap));
}
public void testEqualsForEmptyMap() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
assertEquals(map, map);
assertEquals(makeEmptyMap(), map);
assertEquals(Collections.emptyMap(), map);
assertFalse(map.equals(Collections.emptySet()));
//noinspection ObjectEqualsNull
assertFalse(map.equals(null));
}
public void testGet() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
for (Entry<K, V> entry : map.entrySet()) {
assertEquals(entry.getValue(), map.get(entry.getKey()));
}
K unmappedKey = null;
try {
unmappedKey = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertNull(map.get(unmappedKey));
}
public void testGetForEmptyMap() {
final Map<K, V> map;
K unmappedKey = null;
try {
map = makeEmptyMap();
unmappedKey = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertNull(map.get(unmappedKey));
}
public void testGetNull() {
Map<K, V> map = makeEitherMap();
if (allowsNullKeys) {
if (allowsNullValues) {
// TODO: decide what to test here.
} else {
assertEquals(map.containsKey(null), map.get(null) != null);
}
} else {
try {
map.get(null);
} catch (NullPointerException optional) {
}
}
assertInvariants(map);
}
public void testHashCode() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
}
public void testHashCodeForEmptyMap() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
}
public void testPutNewKey() {
final Map<K, V> map = makeEitherMap();
final K keyToPut;
final V valueToPut;
try {
keyToPut = getKeyNotInPopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsPut) {
int initialSize = map.size();
V oldValue = map.put(keyToPut, valueToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
assertEquals(initialSize + 1, map.size());
assertNull(oldValue);
} else {
try {
map.put(keyToPut, valueToPut);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutExistingKey() {
final Map<K, V> map;
final K keyToPut;
final V valueToPut;
try {
map = makePopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToPut = map.keySet().iterator().next();
if (supportsPut) {
int initialSize = map.size();
map.put(keyToPut, valueToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
assertEquals(initialSize, map.size());
} else {
try {
map.put(keyToPut, valueToPut);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutNullKey() {
if (!supportsPut) {
return;
}
final Map<K, V> map = makeEitherMap();
final V valueToPut;
try {
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (allowsNullKeys) {
final V oldValue = map.get(null);
final V returnedValue = map.put(null, valueToPut);
assertEquals(oldValue, returnedValue);
assertEquals(valueToPut, map.get(null));
assertTrue(map.containsKey(null));
assertTrue(map.containsValue(valueToPut));
} else {
try {
map.put(null, valueToPut);
fail("Expected RuntimeException");
} catch (RuntimeException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutNullValue() {
if (!supportsPut) {
return;
}
final Map<K, V> map = makeEitherMap();
final K keyToPut;
try {
keyToPut = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (allowsNullValues) {
int initialSize = map.size();
final V oldValue = map.get(keyToPut);
final V returnedValue = map.put(keyToPut, null);
assertEquals(oldValue, returnedValue);
assertNull(map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(null));
assertEquals(initialSize + 1, map.size());
} else {
try {
map.put(keyToPut, null);
fail("Expected RuntimeException");
} catch (RuntimeException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutNullValueForExistingKey() {
if (!supportsPut) {
return;
}
final Map<K, V> map;
final K keyToPut;
try {
map = makePopulatedMap();
keyToPut = map.keySet().iterator().next();
} catch (UnsupportedOperationException e) {
return;
}
if (allowsNullValues) {
int initialSize = map.size();
final V oldValue = map.get(keyToPut);
final V returnedValue = map.put(keyToPut, null);
assertEquals(oldValue, returnedValue);
assertNull(map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(null));
assertEquals(initialSize, map.size());
} else {
try {
map.put(keyToPut, null);
fail("Expected RuntimeException");
} catch (RuntimeException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutAllNewKey() {
final Map<K, V> map = makeEitherMap();
final K keyToPut;
final V valueToPut;
try {
keyToPut = getKeyNotInPopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
final Map<K, V> mapToPut = Collections.singletonMap(keyToPut, valueToPut);
if (supportsPut) {
int initialSize = map.size();
map.putAll(mapToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
assertEquals(initialSize + 1, map.size());
} else {
try {
map.putAll(mapToPut);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testPutAllExistingKey() {
final Map<K, V> map;
final K keyToPut;
final V valueToPut;
try {
map = makePopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToPut = map.keySet().iterator().next();
final Map<K, V> mapToPut = Collections.singletonMap(keyToPut, valueToPut);
int initialSize = map.size();
if (supportsPut) {
map.putAll(mapToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
} else {
try {
map.putAll(mapToPut);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testRemove() {
final Map<K, V> map;
final K keyToRemove;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
keyToRemove = map.keySet().iterator().next();
if (supportsRemove) {
int initialSize = map.size();
V expectedValue = map.get(keyToRemove);
V oldValue = map.remove(keyToRemove);
assertEquals(expectedValue, oldValue);
assertFalse(map.containsKey(keyToRemove));
assertEquals(initialSize - 1, map.size());
} else {
try {
map.remove(keyToRemove);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testRemoveMissingKey() {
final Map<K, V> map;
final K keyToRemove;
try {
map = makePopulatedMap();
keyToRemove = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsRemove) {
int initialSize = map.size();
assertNull(map.remove(keyToRemove));
assertEquals(initialSize, map.size());
} else {
try {
map.remove(keyToRemove);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testSize() {
assertInvariants(makeEitherMap());
}
public void testKeySetRemove() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keys = map.keySet();
K key = keys.iterator().next();
if (supportsRemove) {
int initialSize = map.size();
keys.remove(key);
assertEquals(initialSize - 1, map.size());
assertFalse(map.containsKey(key));
} else {
try {
keys.remove(key);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testKeySetRemoveAll() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keys = map.keySet();
K key = keys.iterator().next();
if (supportsRemove) {
int initialSize = map.size();
assertTrue(keys.removeAll(Collections.singleton(key)));
assertEquals(initialSize - 1, map.size());
assertFalse(map.containsKey(key));
} else {
try {
keys.removeAll(Collections.singleton(key));
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testKeySetRetainAll() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keys = map.keySet();
K key = keys.iterator().next();
if (supportsRemove) {
keys.retainAll(Collections.singleton(key));
assertEquals(1, map.size());
assertTrue(map.containsKey(key));
} else {
try {
keys.retainAll(Collections.singleton(key));
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testKeySetClear() {
final Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keySet = map.keySet();
if (supportsClear) {
keySet.clear();
assertTrue(keySet.isEmpty());
} else {
try {
keySet.clear();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testKeySetRemoveAllNullFromEmpty() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keySet = map.keySet();
if (supportsRemove) {
try {
keySet.removeAll(null);
fail("Expected NullPointerException.");
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
keySet.removeAll(null);
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testKeySetRetainAllNullFromEmpty() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keySet = map.keySet();
if (supportsRemove) {
try {
keySet.retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
keySet.retainAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValues() {
final Map<K, V> map;
final Collection<V> valueCollection;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
valueCollection = map.values();
final V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
for (V value : valueCollection) {
assertFalse(unmappedValue.equals(value));
}
}
public void testValuesIteratorRemove() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
Iterator<V> iterator = valueCollection.iterator();
if (supportsIteratorRemove) {
int initialSize = map.size();
iterator.next();
iterator.remove();
assertEquals(initialSize - 1, map.size());
// (We can't assert that the values collection no longer contains the
// removed value, because the underlying map can have multiple mappings
// to the same value.)
assertInvariants(map);
try {
iterator.remove();
fail("Expected IllegalStateException.");
} catch (IllegalStateException e) {
// Expected.
}
} else {
try {
iterator.next();
iterator.remove();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesRemove() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
if (supportsRemove) {
int initialSize = map.size();
valueCollection.remove(valueCollection.iterator().next());
assertEquals(initialSize - 1, map.size());
// (We can't assert that the values collection no longer contains the
// removed value, because the underlying map can have multiple mappings
// to the same value.)
} else {
try {
valueCollection.remove(valueCollection.iterator().next());
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesRemoveMissing() {
final Map<K, V> map;
final V valueToRemove;
try {
map = makeEitherMap();
valueToRemove = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
int initialSize = map.size();
if (supportsRemove) {
assertFalse(valueCollection.remove(valueToRemove));
} else {
try {
assertFalse(valueCollection.remove(valueToRemove));
} catch (UnsupportedOperationException e) {
// Tolerated.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testValuesRemoveAll() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
Set<V> valuesToRemove = singleton(valueCollection.iterator().next());
if (supportsRemove) {
valueCollection.removeAll(valuesToRemove);
for (V value : valuesToRemove) {
assertFalse(valueCollection.contains(value));
}
for (V value : valueCollection) {
assertFalse(valuesToRemove.contains(value));
}
} else {
try {
valueCollection.removeAll(valuesToRemove);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesRemoveAllNullFromEmpty() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> values = map.values();
if (supportsRemove) {
try {
values.removeAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
values.removeAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesRetainAll() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
Set<V> valuesToRetain = singleton(valueCollection.iterator().next());
if (supportsRemove) {
valueCollection.retainAll(valuesToRetain);
for (V value : valuesToRetain) {
assertTrue(valueCollection.contains(value));
}
for (V value : valueCollection) {
assertTrue(valuesToRetain.contains(value));
}
} else {
try {
valueCollection.retainAll(valuesToRetain);
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesRetainAllNullFromEmpty() {
final Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> values = map.values();
if (supportsRemove) {
try {
values.retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException e) {
// Expected.
}
} else {
try {
values.retainAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException e) {
// Expected.
} catch (NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesClear() {
final Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
if (supportsClear) {
valueCollection.clear();
assertTrue(valueCollection.isEmpty());
} else {
try {
valueCollection.clear();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) {
// Expected.
}
}
assertInvariants(map);
}
static <K, V> Entry<K, V> mapEntry(K key, V value) {
return Collections.singletonMap(key, value).entrySet().iterator().next();
}
}
| 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.features.CollectionSize;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Generator for collection of a particular size.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible
public final class OneSizeGenerator<T, E>
implements OneSizeTestContainerGenerator<T, E> {
private final TestContainerGenerator<T, E> generator;
private final CollectionSize collectionSize;
public OneSizeGenerator(TestContainerGenerator<T, E> generator,
CollectionSize collectionSize) {
this.generator = generator;
this.collectionSize = collectionSize;
}
@Override
public TestContainerGenerator<T, E> getInnerGenerator() {
return generator;
}
@Override
public SampleElements<E> samples() {
return generator.samples();
}
@Override
public T create(Object... elements) {
return generator.create(elements);
}
@Override
public E[] createArray(int length) {
return generator.createArray(length);
}
@Override
public T createTestSubject() {
Collection<E> elements = getSampleElements(
getCollectionSize().getNumElements());
return generator.create(elements.toArray());
}
@Override
public Collection<E> getSampleElements(int howMany) {
SampleElements<E> samples = samples();
@SuppressWarnings("unchecked")
List<E> allSampleElements = Arrays.asList(
samples.e0, samples.e1, samples.e2, samples.e3, samples.e4);
return new ArrayList<E>(allSampleElements.subList(0, howMany));
}
@Override
public CollectionSize getCollectionSize() {
return collectionSize;
}
@Override
public Iterable<E> order(List<E> insertionOrder) {
return generator.order(insertionOrder);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import junit.framework.TestSuite;
import java.util.List;
/**
* Given a test iterable generator, builds a test suite for the
* iterable's iterator, by delegating to a {@link IteratorTestSuiteBuilder}.
*
* @author George van den Driessche
*/
public class DerivedIteratorTestSuiteBuilder<E>
extends FeatureSpecificTestSuiteBuilder<
DerivedIteratorTestSuiteBuilder<E>,
TestSubjectGenerator<? extends Iterable<E>>> {
/**
* We rely entirely on the delegate builder for test creation, so this
* just throws UnsupportedOperationException.
*
* @return never.
*/
@Override protected List<Class<? extends AbstractTester>> getTesters() {
throw new UnsupportedOperationException();
}
@Override public TestSuite createTestSuite() {
checkCanCreate();
return new IteratorTestSuiteBuilder<E>()
.named(getName() + " iterator")
.usingGenerator(new DerivedTestIteratorGenerator<E>(
getSubjectGenerator()))
.withFeatures(getFeatures())
.createTestSuite();
}
}
| 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.AbstractCollection;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* A simplistic collection which implements only the bare minimum allowed by the
* spec, and throws exceptions whenever it can.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public class MinimalCollection<E> extends AbstractCollection<E> {
// TODO: expose allow nulls parameter?
public static <E> MinimalCollection<E> of(E... contents) {
return new MinimalCollection<E>(Object.class, true, contents);
}
// TODO: use this
public static <E> MinimalCollection<E> ofClassAndContents(
Class<? super E> type, E... contents) {
return new MinimalCollection<E>(type, true, contents);
}
private final E[] contents;
private final Class<? super E> type;
private final boolean allowNulls;
// Package-private so that it can be extended.
MinimalCollection(Class<? super E> type, boolean allowNulls, E... contents) {
// TODO: consider making it shuffle the contents to test iteration order.
this.contents = Platform.clone(contents);
this.type = type;
this.allowNulls = allowNulls;
if (!allowNulls) {
for (Object element : contents) {
if (element == null) {
throw new NullPointerException();
}
}
}
}
@Override public int size() {
return contents.length;
}
@Override public boolean contains(Object object) {
if (!allowNulls) {
// behave badly
if (object == null) {
throw new NullPointerException();
}
}
Platform.checkCast(type, object); // behave badly
return Arrays.asList(contents).contains(object);
}
@Override public boolean containsAll(Collection<?> collection) {
if (!allowNulls) {
for (Object object : collection) {
// behave badly
if (object == null) {
throw new NullPointerException();
}
}
}
return super.containsAll(collection);
}
@Override public Iterator<E> iterator() {
return Arrays.asList(contents).iterator();
}
@Override public Object[] toArray() {
Object[] result = new Object[contents.length];
System.arraycopy(contents, 0, result, 0, contents.length);
return result;
}
/*
* a "type A" unmodifiable collection freaks out proactively, even if there
* wasn't going to be any actual work to do anyway
*/
@Override public boolean addAll(Collection<? extends E> elementsToAdd) {
throw up();
}
@Override public boolean removeAll(Collection<?> elementsToRemove) {
throw up();
}
@Override public boolean retainAll(Collection<?> elementsToRetain) {
throw up();
}
@Override public void clear() {
throw up();
}
private static UnsupportedOperationException up() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
/**
* Creates iterators to be tested.
*
* @param <E> the element type of the iterator.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@GwtCompatible
public interface TestIteratorGenerator<E> {
Iterator<E> get();
}
| 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.List;
/**
* Creates sets, containing sample elements, to be tested.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
public interface TestListGenerator<E> extends TestCollectionGenerator<E> {
@Override
List<E> create(Object... elements);
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.