code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An implementation of {@link DataInput} that uses little-endian byte ordering
* for reading {@code short}, {@code int}, {@code float}, {@code double}, and
* {@code long} values.
* <p>
* <b>Note:</b> This class intentionally violates the specification of its
* supertype {@code DataInput}, which explicitly requires big-endian byte order.
*
* @author Chris Nokleberg
* @author Keith Bottner
* @since 8.0
*/
@Beta
public final class LittleEndianDataInputStream extends FilterInputStream
implements DataInput {
/**
* Creates a {@code LittleEndianDataInputStream} that wraps the given stream.
*
* @param in the stream to delegate to
*/
public LittleEndianDataInputStream(InputStream in) {
super(Preconditions.checkNotNull(in));
}
/**
* This method will throw an {@link UnsupportedOperationException}.
*/
@Override
public String readLine() {
throw new UnsupportedOperationException("readLine is not supported");
}
@Override
public void readFully(byte[] b) throws IOException {
ByteStreams.readFully(this, b);
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
ByteStreams.readFully(this, b, off, len);
}
@Override
public int skipBytes(int n) throws IOException {
return (int) in.skip(n);
}
@Override
public int readUnsignedByte() throws IOException {
int b1 = in.read();
if (0 > b1) {
throw new EOFException();
}
return b1;
}
/**
* Reads an unsigned {@code short} as specified by
* {@link DataInputStream#readUnsignedShort()}, except using little-endian
* byte order.
*
* @return the next two bytes of the input stream, interpreted as an
* unsigned 16-bit integer in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public int readUnsignedShort() throws IOException {
byte b1 = readAndCheckByte();
byte b2 = readAndCheckByte();
return Ints.fromBytes((byte) 0, (byte) 0, b2, b1);
}
/**
* Reads an integer as specified by {@link DataInputStream#readInt()}, except
* using little-endian byte order.
*
* @return the next four bytes of the input stream, interpreted as an
* {@code int} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public int readInt() throws IOException {
byte b1 = readAndCheckByte();
byte b2 = readAndCheckByte();
byte b3 = readAndCheckByte();
byte b4 = readAndCheckByte();
return Ints.fromBytes( b4, b3, b2, b1);
}
/**
* Reads a {@code long} as specified by {@link DataInputStream#readLong()},
* except using little-endian byte order.
*
* @return the next eight bytes of the input stream, interpreted as a
* {@code long} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public long readLong() throws IOException {
byte b1 = readAndCheckByte();
byte b2 = readAndCheckByte();
byte b3 = readAndCheckByte();
byte b4 = readAndCheckByte();
byte b5 = readAndCheckByte();
byte b6 = readAndCheckByte();
byte b7 = readAndCheckByte();
byte b8 = readAndCheckByte();
return Longs.fromBytes(b8, b7, b6, b5, b4, b3, b2, b1);
}
/**
* Reads a {@code float} as specified by {@link DataInputStream#readFloat()},
* except using little-endian byte order.
*
* @return the next four bytes of the input stream, interpreted as a
* {@code float} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
/**
* Reads a {@code double} as specified by
* {@link DataInputStream#readDouble()}, except using little-endian byte
* order.
*
* @return the next eight bytes of the input stream, interpreted as a
* {@code double} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
@Override
public String readUTF() throws IOException {
return new DataInputStream(in).readUTF();
}
/**
* Reads a {@code short} as specified by {@link DataInputStream#readShort()},
* except using little-endian byte order.
*
* @return the next two bytes of the input stream, interpreted as a
* {@code short} in little-endian byte order.
* @throws IOException if an I/O error occurs.
*/
@Override
public short readShort() throws IOException {
return (short) readUnsignedShort();
}
/**
* Reads a char as specified by {@link DataInputStream#readChar()}, except
* using little-endian byte order.
*
* @return the next two bytes of the input stream, interpreted as a
* {@code char} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public char readChar() throws IOException {
return (char) readUnsignedShort();
}
@Override
public byte readByte() throws IOException {
return (byte) readUnsignedByte();
}
@Override
public boolean readBoolean() throws IOException {
return readUnsignedByte() != 0;
}
/**
* Reads a byte from the input stream checking that the end of file (EOF)
* has not been encountered.
*
* @return byte read from input
* @throws IOException if an error is encountered while reading
* @throws EOFException if the end of file (EOF) is encountered.
*/
private byte readAndCheckByte() throws IOException, EOFException {
int b1 = in.read();
if (-1 == b1) {
throw new EOFException();
}
return (byte) b1;
}
}
| 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.io;
import java.io.DataOutput;
import java.io.IOException;
/**
* An extension of {@code DataOutput} for writing to in-memory byte arrays; its
* methods offer identical functionality but do not throw {@link IOException}.
*
* @author Jayaprabhakar Kadarkarai
* @since 1.0
*/
public interface ByteArrayDataOutput extends DataOutput {
@Override void write(int b);
@Override void write(byte b[]);
@Override void write(byte b[], int off, int len);
@Override void writeBoolean(boolean v);
@Override void writeByte(int v);
@Override void writeShort(int v);
@Override void writeChar(int v);
@Override void writeInt(int v);
@Override void writeLong(long v);
@Override void writeFloat(float v);
@Override void writeDouble(double v);
@Override void writeChars(String s);
@Override void writeUTF(String s);
/**
* @deprecated This method is dangerous as it discards the high byte of
* every character. For UTF-8, use {@code write(s.getBytes(Charsets.UTF_8))}.
*/
@Deprecated @Override void writeBytes(String s);
/**
* Returns the contents that have been written to this instance,
* as a byte array.
*/
byte[] toByteArray();
}
| 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.io;
import com.google.common.annotations.Beta;
import java.io.Flushable;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utility methods for working with {@link Flushable} objects.
*
* @author Michael Lancaster
* @since 1.0
*/
@Beta
public final class Flushables {
private static final Logger logger
= Logger.getLogger(Flushables.class.getName());
private Flushables() {}
/**
* Flush a {@link Flushable}, with control over whether an
* {@code IOException} may be thrown.
*
* <p>If {@code swallowIOException} is true, then we don't rethrow
* {@code IOException}, but merely log it.
*
* @param flushable the {@code Flushable} object to be flushed.
* @param swallowIOException if true, don't propagate IO exceptions
* thrown by the {@code flush} method
* @throws IOException if {@code swallowIOException} is false and
* {@link Flushable#flush} throws an {@code IOException}.
* @see Closeables#close
*/
public static void flush(Flushable flushable, boolean swallowIOException)
throws IOException {
try {
flushable.flush();
} catch (IOException e) {
if (swallowIOException) {
logger.log(Level.WARNING,
"IOException thrown while flushing Flushable.", e);
} else {
throw e;
}
}
}
/**
* Equivalent to calling {@code flush(flushable, true)}, but with no
* {@code IOException} in the signature.
*
* @param flushable the {@code Flushable} object to be flushed.
*/
public static void flushQuietly(Flushable flushable) {
try {
flush(flushable, true);
} catch (IOException e) {
logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
}
}
}
| 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.io;
import com.google.common.annotations.Beta;
import java.io.IOException;
/**
* A callback to be used with the streaming {@code readLines} methods.
*
* <p>{@link #processLine} will be called for each line that is read, and
* should return {@code false} when you want to stop processing.
*
* @author Miles Barr
* @since 1.0
*/
@Beta
public interface LineProcessor<T> {
/**
* This method will be called once for each line.
*
* @param line the line read from the input, without delimiter
* @return true to continue processing, false to stop
*/
boolean processLine(String line) throws IOException;
/** Return the result of processing all the lines. */
T getResult();
}
| 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 java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Implementation helper for {@link TestMapGenerator} for use with enum maps.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public abstract class TestEnumMapGenerator
implements TestMapGenerator<AnEnum, String> {
@Override
public SampleElements<Entry<AnEnum, String>> samples() {
return new SampleElements<Entry<AnEnum, String>>(
Helpers.mapEntry(AnEnum.A, "January"),
Helpers.mapEntry(AnEnum.B, "February"),
Helpers.mapEntry(AnEnum.C, "March"),
Helpers.mapEntry(AnEnum.D, "April"),
Helpers.mapEntry(AnEnum.E, "May")
);
}
@Override
public final Map<AnEnum, String> create(Object... entries) {
@SuppressWarnings("unchecked")
Entry<AnEnum, String>[] array = new Entry[entries.length];
int i = 0;
for (Object o : entries) {
@SuppressWarnings("unchecked")
Entry<AnEnum, String> e = (Entry<AnEnum, String>) o;
array[i++] = e;
}
return create(array);
}
protected abstract Map<AnEnum, String> create(
Entry<AnEnum, String>[] entries);
@Override
@SuppressWarnings("unchecked")
public final Entry<AnEnum, String>[] createArray(int length) {
return new Entry[length];
}
@Override
public final AnEnum[] createKeyArray(int length) {
return new AnEnum[length];
}
@Override
public final String[] createValueArray(int length) {
return new String[length];
}
/** Returns the original element list, unchanged. */
@Override
public Iterable<Entry<AnEnum, String>> order(
List<Entry<AnEnum, String>> insertionOrder) {
return insertionOrder;
}
} | Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import 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
*/
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 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
*/
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) 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.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;
/**
* Concrete instantiation of {@link AbstractCollectionTestSuiteBuilder} for
* testing collections that do not have a more specific tester like
* {@link ListTestSuiteBuilder} or {@link SetTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Louis Wasserman
*/
public class CollectionTestSuiteBuilder<E>
extends AbstractCollectionTestSuiteBuilder<
CollectionTestSuiteBuilder<E>, E> {
public static <E> CollectionTestSuiteBuilder<E> using(
TestCollectionGenerator<E> generator) {
return new CollectionTestSuiteBuilder<E>().usingGenerator(generator);
}
@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(CollectionTestSuiteBuilder
.using(new ReserializedCollectionGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.createTestSuite());
}
return derivedSuites;
}
static class ReserializedCollectionGenerator<E> implements TestCollectionGenerator<E> {
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedCollectionGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public Collection<E> create(Object... elements) {
return 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 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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
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 Platform.getMethod(tester.getClass(), tester.getTestMethodName());
} else if (test instanceof TestCase) {
TestCase testCase = (TestCase) test;
return Platform.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 = getTemplateSuite(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 static final Map<Class<? extends AbstractTester<?>>, TestSuite>
templateSuiteForClass =
new HashMap<Class<? extends AbstractTester<?>>, TestSuite>();
private static TestSuite getTemplateSuite(
Class<? extends AbstractTester<?>> testerClass) {
synchronized (templateSuiteForClass) {
TestSuite suite = templateSuiteForClass.get(testerClass);
if (suite == null) {
suite = new TestSuite(testerClass);
templateSuiteForClass.put(testerClass, suite);
}
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.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.ListAddAllAtIndexTester;
import com.google.common.collect.testing.testers.ListAddAllTester;
import com.google.common.collect.testing.testers.ListAddAtIndexTester;
import com.google.common.collect.testing.testers.ListAddTester;
import com.google.common.collect.testing.testers.ListCreationTester;
import com.google.common.collect.testing.testers.ListEqualsTester;
import com.google.common.collect.testing.testers.ListGetTester;
import com.google.common.collect.testing.testers.ListHashCodeTester;
import com.google.common.collect.testing.testers.ListIndexOfTester;
import com.google.common.collect.testing.testers.ListLastIndexOfTester;
import com.google.common.collect.testing.testers.ListListIteratorTester;
import com.google.common.collect.testing.testers.ListRemoveAllTester;
import com.google.common.collect.testing.testers.ListRemoveAtIndexTester;
import com.google.common.collect.testing.testers.ListRemoveTester;
import com.google.common.collect.testing.testers.ListRetainAllTester;
import com.google.common.collect.testing.testers.ListSetTester;
import com.google.common.collect.testing.testers.ListSubListTester;
import com.google.common.collect.testing.testers.ListToArrayTester;
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 List implementation.
*
* @author George van den Driessche
*/
public final class ListTestSuiteBuilder<E> extends
AbstractCollectionTestSuiteBuilder<ListTestSuiteBuilder<E>, E> {
public static <E> ListTestSuiteBuilder<E> using(
TestListGenerator<E> generator) {
return new ListTestSuiteBuilder<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(ListAddAllAtIndexTester.class);
testers.add(ListAddAllTester.class);
testers.add(ListAddAtIndexTester.class);
testers.add(ListAddTester.class);
testers.add(ListCreationTester.class);
testers.add(ListEqualsTester.class);
testers.add(ListGetTester.class);
testers.add(ListHashCodeTester.class);
testers.add(ListIndexOfTester.class);
testers.add(ListLastIndexOfTester.class);
testers.add(ListListIteratorTester.class);
testers.add(ListRemoveAllTester.class);
testers.add(ListRemoveAtIndexTester.class);
testers.add(ListRemoveTester.class);
testers.add(ListRetainAllTester.class);
testers.add(ListSetTester.class);
testers.add(ListSubListTester.class);
testers.add(ListToArrayTester.class);
return testers;
}
/**
* Specifies {@link CollectionFeature#KNOWN_ORDER} for all list tests, since
* lists have an iteration ordering corresponding to the insertion order.
*/
@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<Collection<E>, E>> parentBuilder) {
List<TestSuite> derivedSuites = new ArrayList<TestSuite>(
super.createDerivedSuites(parentBuilder));
if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
derivedSuites.add(ListTestSuiteBuilder
.using(new ReserializedListGenerator<E>(parentBuilder.getSubjectGenerator()))
.named(getName() + " reserialized")
.withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures()))
.createTestSuite());
}
return derivedSuites;
}
static class ReserializedListGenerator<E> implements TestListGenerator<E>{
final OneSizeTestContainerGenerator<Collection<E>, E> gen;
private ReserializedListGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) {
this.gen = gen;
}
@Override
public SampleElements<E> samples() {
return gen.samples();
}
@Override
public List<E> create(Object... elements) {
return (List<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;
/**
* To be implemented by test generators that can produce test subjects without
* requiring any parameters.
*
* <p>This class is GWT compatible.
*
* @param <T> the type created by this generator.
*
* @author George van den Driessche
*/
public interface TestSubjectGenerator<T> {
T createTestSubject();
}
| 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 junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
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;
// This class is GWT compatible.
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
public int compare(Entry<K, V> a, Entry<K, V> b) {
return 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();
}
};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
import junit.framework.AssertionFailedError;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
/**
* Most of the logic for {@link IteratorTester} and {@link ListIteratorTester}.
*
* <p>This class is GWT compatible.
*
* @param <E> the type of element returned by the iterator
* @param <I> the type of the iterator ({@link Iterator} or
* {@link ListIterator})
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
abstract class AbstractIteratorTester<E, I extends Iterator<E>> {
private boolean whenNextThrowsExceptionStopTestingCallsToRemove;
private boolean whenAddThrowsExceptionStopTesting;
/**
* Don't verify iterator behavior on remove() after a call to next()
* throws an exception.
*
* <p>JDK 6 currently has a bug where some iterators get into a undefined
* state when next() throws a NoSuchElementException. The correct
* behavior is for remove() to remove the last element returned by
* next, even if a subsequent next() call threw an exception; however
* JDK 6's HashMap and related classes throw an IllegalStateException
* in this case.
*
* <p>Calling this method causes the iterator tester to skip testing
* any remove() in a stimulus sequence after the reference iterator
* throws an exception in next().
*
* <p>TODO: remove this once we're on 6u5, which has the fix.
*
* @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6529795">
* Sun Java Bug 6529795</a>
*/
public void ignoreSunJavaBug6529795() {
whenNextThrowsExceptionStopTestingCallsToRemove = true;
}
/**
* Don't verify iterator behavior after a call to add() throws an exception.
*
* <p>AbstractList's ListIterator implementation gets into a undefined state
* when add() throws an UnsupportedOperationException. Instead of leaving the
* iterator's position unmodified, it increments it, skipping an element or
* even moving past the end of the list.
*
* <p>Calling this method causes the iterator tester to skip testing in a
* stimulus sequence after the iterator under test throws an exception in
* add().
*
* <p>TODO: remove this once the behavior is fixed.
*
* @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6533203">
* Sun Java Bug 6533203</a>
*/
public void stopTestingWhenAddThrowsException() {
whenAddThrowsExceptionStopTesting = true;
}
private Stimulus<E, ? super I>[] stimuli;
private final Iterator<E> elementsToInsert;
private final Set<IteratorFeature> features;
private final List<E> expectedElements;
private final int startIndex;
private final KnownOrder knownOrder;
/**
* Meta-exception thrown by
* {@link AbstractIteratorTester.MultiExceptionListIterator} instead of
* throwing any particular exception type.
*/
// This class is accessible but not supported in GWT.
private static final class PermittedMetaException extends RuntimeException {
final Set<? extends Class<? extends RuntimeException>> exceptionClasses;
PermittedMetaException(
Set<? extends Class<? extends RuntimeException>> exceptionClasses) {
super("one of " + exceptionClasses);
this.exceptionClasses = exceptionClasses;
}
PermittedMetaException(Class<? extends RuntimeException> exceptionClass) {
this(Collections.singleton(exceptionClass));
}
// It's not supported In GWT, it always returns true.
boolean isPermitted(RuntimeException exception) {
for (Class<? extends RuntimeException> clazz : exceptionClasses) {
if (Platform.checkIsInstance(clazz, exception)) {
return true;
}
}
return false;
}
// It's not supported in GWT, it always passes.
void assertPermitted(RuntimeException exception) {
if (!isPermitted(exception)) {
// TODO: use simple class names
String message = "Exception " + exception.getClass()
+ " was thrown; expected " + this;
Helpers.fail(exception, message);
}
}
@Override public String toString() {
return getMessage();
}
private static final long serialVersionUID = 0;
}
private static final class UnknownElementException extends RuntimeException {
private UnknownElementException(Collection<?> expected, Object actual) {
super("Returned value '"
+ actual + "' not found. Remaining elements: " + expected);
}
private static final long serialVersionUID = 0;
}
/**
* Quasi-implementation of {@link ListIterator} that works from a list of
* elements and a set of features to support (from the enclosing
* {@link AbstractIteratorTester} instance). Instead of throwing exceptions
* like {@link NoSuchElementException} at the appropriate times, it throws
* {@link PermittedMetaException} instances, which wrap a set of all
* exceptions that the iterator could throw during the invocation of that
* method. This is necessary because, e.g., a call to
* {@code iterator().remove()} of an unmodifiable list could throw either
* {@link IllegalStateException} or {@link UnsupportedOperationException}.
* Note that iterator implementations should always throw one of the
* exceptions in a {@code PermittedExceptions} instance, since
* {@code PermittedExceptions} is thrown only when a method call is invalid.
*
* <p>This class is accessible but not supported in GWT as it references
* {@link PermittedMetaException}.
*/
protected final class MultiExceptionListIterator implements ListIterator<E> {
// TODO: track seen elements when order isn't guaranteed
// TODO: verify contents afterward
// TODO: something shiny and new instead of Stack
// TODO: test whether null is supported (create a Feature)
/**
* The elements to be returned by future calls to {@code next()}, with the
* first at the top of the stack.
*/
final Stack<E> nextElements = new Stack<E>();
/**
* The elements to be returned by future calls to {@code previous()}, with
* the first at the top of the stack.
*/
final Stack<E> previousElements = new Stack<E>();
/**
* {@link #nextElements} if {@code next()} was called more recently then
* {@code previous}, {@link #previousElements} if the reverse is true, or --
* overriding both of these -- {@code null} if {@code remove()} or
* {@code add()} has been called more recently than either. We use this to
* determine which stack to pop from on a call to {@code remove()} (or to
* pop from and push to on a call to {@code set()}.
*/
Stack<E> stackWithLastReturnedElementAtTop = null;
MultiExceptionListIterator(List<E> expectedElements) {
Helpers.addAll(nextElements, Helpers.reverse(expectedElements));
for (int i = 0; i < startIndex; i++) {
previousElements.push(nextElements.pop());
}
}
@Override
public void add(E e) {
if (!features.contains(IteratorFeature.SUPPORTS_ADD)) {
throw new PermittedMetaException(UnsupportedOperationException.class);
}
previousElements.push(e);
stackWithLastReturnedElementAtTop = null;
}
@Override
public boolean hasNext() {
return !nextElements.isEmpty();
}
@Override
public boolean hasPrevious() {
return !previousElements.isEmpty();
}
@Override
public E next() {
return transferElement(nextElements, previousElements);
}
@Override
public int nextIndex() {
return previousElements.size();
}
@Override
public E previous() {
return transferElement(previousElements, nextElements);
}
@Override
public int previousIndex() {
return nextIndex() - 1;
}
@Override
public void remove() {
throwIfInvalid(IteratorFeature.SUPPORTS_REMOVE);
stackWithLastReturnedElementAtTop.pop();
stackWithLastReturnedElementAtTop = null;
}
@Override
public void set(E e) {
throwIfInvalid(IteratorFeature.SUPPORTS_SET);
stackWithLastReturnedElementAtTop.pop();
stackWithLastReturnedElementAtTop.push(e);
}
/**
* Moves the given element from its current position in
* {@link #nextElements} to the top of the stack so that it is returned by
* the next call to {@link Iterator#next()}. If the element is not in
* {@link #nextElements}, this method throws an
* {@link UnknownElementException}.
*
* <p>This method is used when testing iterators without a known ordering.
* We poll the target iterator's next element and pass it to the reference
* iterator through this method so it can return the same element. This
* enables the assertion to pass and the reference iterator to properly
* update its state.
*/
void promoteToNext(E e) {
if (nextElements.remove(e)) {
nextElements.push(e);
} else {
throw new UnknownElementException(nextElements, e);
}
}
private E transferElement(Stack<E> source, Stack<E> destination) {
if (source.isEmpty()) {
throw new PermittedMetaException(NoSuchElementException.class);
}
destination.push(source.pop());
stackWithLastReturnedElementAtTop = destination;
return destination.peek();
}
private void throwIfInvalid(IteratorFeature methodFeature) {
Set<Class<? extends RuntimeException>> exceptions
= new HashSet<Class<? extends RuntimeException>>();
if (!features.contains(methodFeature)) {
exceptions.add(UnsupportedOperationException.class);
}
if (stackWithLastReturnedElementAtTop == null) {
exceptions.add(IllegalStateException.class);
}
if (!exceptions.isEmpty()) {
throw new PermittedMetaException(exceptions);
}
}
private List<E> getElements() {
List<E> elements = new ArrayList<E>();
Helpers.addAll(elements, previousElements);
Helpers.addAll(elements, Helpers.reverse(nextElements));
return elements;
}
}
public enum KnownOrder { KNOWN_ORDER, UNKNOWN_ORDER }
@SuppressWarnings("unchecked") // creating array of generic class Stimulus
AbstractIteratorTester(int steps, Iterable<E> elementsToInsertIterable,
Iterable<? extends IteratorFeature> features,
Iterable<E> expectedElements, KnownOrder knownOrder, int startIndex) {
// periodically we should manually try (steps * 3 / 2) here; all tests but
// one should still pass (testVerifyGetsCalled()).
stimuli = new Stimulus[steps];
if (!elementsToInsertIterable.iterator().hasNext()) {
throw new IllegalArgumentException();
}
elementsToInsert = Helpers.cycle(elementsToInsertIterable);
this.features = Helpers.copyToSet(features);
this.expectedElements = Helpers.copyToList(expectedElements);
this.knownOrder = knownOrder;
this.startIndex = startIndex;
}
/**
* I'd like to make this a parameter to the constructor, but I can't because
* the stimulus instances refer to {@code this}.
*/
protected abstract Iterable<? extends Stimulus<E, ? super I>>
getStimulusValues();
/**
* Returns a new target iterator each time it's called. This is the iterator
* you are trying to test. This must return an Iterator that returns the
* expected elements passed to the constructor in the given order. Warning: it
* is not enough to simply pull multiple iterators from the same source
* Iterable, unless that Iterator is unmodifiable.
*/
protected abstract I newTargetIterator();
/**
* Override this to verify anything after running a list of Stimuli.
*
* <p>For example, verify that calls to remove() actually removed
* the correct elements.
*
* @param elements the expected elements passed to the constructor, as mutated
* by {@code remove()}, {@code set()}, and {@code add()} calls
*/
protected void verify(List<E> elements) {}
/**
* Executes the test.
*/
public final void test() {
try {
recurse(0);
} catch (RuntimeException e) {
throw new RuntimeException(Arrays.toString(stimuli), e);
}
}
private void recurse(int level) {
// We're going to reuse the stimuli array 3^steps times by overwriting it
// in a recursive loop. Sneaky.
if (level == stimuli.length) {
// We've filled the array.
compareResultsForThisListOfStimuli();
} else {
// Keep recursing to fill the array.
for (Stimulus<E, ? super I> stimulus : getStimulusValues()) {
stimuli[level] = stimulus;
recurse(level + 1);
}
}
}
private void compareResultsForThisListOfStimuli() {
MultiExceptionListIterator reference =
new MultiExceptionListIterator(expectedElements);
I target = newTargetIterator();
boolean shouldStopTestingCallsToRemove = false;
for (int i = 0; i < stimuli.length; i++) {
Stimulus<E, ? super I> stimulus = stimuli[i];
if (stimulus.equals(remove) && shouldStopTestingCallsToRemove) {
break;
}
try {
boolean threwException = stimulus.executeAndCompare(reference, target);
if (threwException
&& stimulus.equals(next)
&& whenNextThrowsExceptionStopTestingCallsToRemove) {
shouldStopTestingCallsToRemove = true;
}
if (threwException
&& stimulus.equals(add)
&& whenAddThrowsExceptionStopTesting) {
break;
}
List<E> elements = reference.getElements();
verify(elements);
} catch (AssertionFailedError cause) {
Helpers.fail(cause,
"failed with stimuli " + subListCopy(stimuli, i + 1));
}
}
}
private static List<Object> subListCopy(Object[] source, int size) {
final Object[] copy = new Object[size];
Platform.unsafeArrayCopy(source, 0, copy, 0, size);
return Arrays.asList(copy);
}
private interface IteratorOperation {
Object execute(Iterator<?> iterator);
}
/**
* Apply this method to both iterators and return normally only if both
* produce the same response.
*
* @return {@code true} if an exception was thrown by the iterators.
*
* @see Stimulus#executeAndCompare(ListIterator, Iterator)
*/
private <T extends Iterator<E>> boolean internalExecuteAndCompare(
T reference, T target, IteratorOperation method)
throws AssertionFailedError {
Object referenceReturnValue = null;
PermittedMetaException referenceException = null;
Object targetReturnValue = null;
RuntimeException targetException = null;
try {
targetReturnValue = method.execute(target);
} catch (RuntimeException e) {
targetException = e;
}
try {
if (method == NEXT_METHOD && targetException == null
&& knownOrder == KnownOrder.UNKNOWN_ORDER) {
/*
* We already know the iterator is an Iterator<E>, and now we know that
* we called next(), so the returned element must be of type E.
*/
@SuppressWarnings("unchecked")
E targetReturnValueFromNext = (E) targetReturnValue;
/*
* We have an Iterator<E> and want to cast it to
* MultiExceptionListIterator. Because we're inside an
* AbstractIteratorTester<E>, that's implicitly a cast to
* AbstractIteratorTester<E>.MultiExceptionListIterator. The runtime
* won't be able to verify the AbstractIteratorTester<E> part, so it's
* an unchecked cast. We know, however, that the only possible value for
* the type parameter is <E>, since otherwise the
* MultiExceptionListIterator wouldn't be an Iterator<E>. The cast is
* safe, even though javac can't tell.
*
* Sun bug 6665356 is an additional complication. Until OpenJDK 7, javac
* doesn't recognize this kind of cast as unchecked cast. Neither does
* Eclipse 3.4. Right now, this suppression is mostly unecessary.
*/
MultiExceptionListIterator multiExceptionListIterator =
(MultiExceptionListIterator) reference;
multiExceptionListIterator.promoteToNext(targetReturnValueFromNext);
}
referenceReturnValue = method.execute(reference);
} catch (PermittedMetaException e) {
referenceException = e;
} catch (UnknownElementException e) {
Helpers.fail(e, e.getMessage());
}
if (referenceException == null) {
if (targetException != null) {
Helpers.fail(targetException,
"Target threw exception when reference did not");
}
/*
* Reference iterator returned a value, so we should expect the
* same value from the target
*/
assertEquals(referenceReturnValue, targetReturnValue);
return false;
}
if (targetException == null) {
fail("Target failed to throw " + referenceException);
}
/*
* Reference iterator threw an exception, so we should expect an acceptable
* exception from the target.
*/
referenceException.assertPermitted(targetException);
return true;
}
private static final IteratorOperation REMOVE_METHOD =
new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
iterator.remove();
return null;
}
};
private static final IteratorOperation NEXT_METHOD =
new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
return iterator.next();
}
};
private static final IteratorOperation PREVIOUS_METHOD =
new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
return ((ListIterator<?>) iterator).previous();
}
};
private final IteratorOperation newAddMethod() {
final Object toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<Object> rawIterator = (ListIterator<Object>) iterator;
rawIterator.add(toInsert);
return null;
}
};
}
private final IteratorOperation newSetMethod() {
final E toInsert = elementsToInsert.next();
return new IteratorOperation() {
@Override
public Object execute(Iterator<?> iterator) {
@SuppressWarnings("unchecked")
ListIterator<E> li = (ListIterator<E>) iterator;
li.set(toInsert);
return null;
}
};
}
abstract static class Stimulus<E, T extends Iterator<E>> {
private final String toString;
protected Stimulus(String toString) {
this.toString = toString;
}
/**
* Send this stimulus to both iterators and return normally only if both
* produce the same response.
*
* @return {@code true} if an exception was thrown by the iterators.
*/
abstract boolean executeAndCompare(ListIterator<E> reference, T target);
@Override public String toString() {
return toString;
}
}
Stimulus<E, Iterator<E>> hasNext = new Stimulus<E, Iterator<E>>("hasNext") {
@Override boolean
executeAndCompare(ListIterator<E> reference, Iterator<E> target) {
// return only if both are true or both are false
assertEquals(reference.hasNext(), target.hasNext());
return false;
}
};
Stimulus<E, Iterator<E>> next = new Stimulus<E, Iterator<E>>("next") {
@Override boolean
executeAndCompare(ListIterator<E> reference, Iterator<E> target) {
return internalExecuteAndCompare(reference, target, NEXT_METHOD);
}
};
Stimulus<E, Iterator<E>> remove = new Stimulus<E, Iterator<E>>("remove") {
@Override boolean
executeAndCompare(ListIterator<E> reference, Iterator<E> target) {
return internalExecuteAndCompare(reference, target, REMOVE_METHOD);
}
};
@SuppressWarnings("unchecked")
List<Stimulus<E, Iterator<E>>> iteratorStimuli() {
return Arrays.asList(hasNext, next, remove);
}
Stimulus<E, ListIterator<E>> hasPrevious =
new Stimulus<E, ListIterator<E>>("hasPrevious") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
// return only if both are true or both are false
assertEquals(reference.hasPrevious(), target.hasPrevious());
return false;
}
};
Stimulus<E, ListIterator<E>> nextIndex =
new Stimulus<E, ListIterator<E>>("nextIndex") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
assertEquals(reference.nextIndex(), target.nextIndex());
return false;
}
};
Stimulus<E, ListIterator<E>> previousIndex =
new Stimulus<E, ListIterator<E>>("previousIndex") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
assertEquals(reference.previousIndex(), target.previousIndex());
return false;
}
};
Stimulus<E, ListIterator<E>> previous =
new Stimulus<E, ListIterator<E>>("previous") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
return internalExecuteAndCompare(reference, target, PREVIOUS_METHOD);
}
};
Stimulus<E, ListIterator<E>> add = new Stimulus<E, ListIterator<E>>("add") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
return internalExecuteAndCompare(reference, target, newAddMethod());
}
};
Stimulus<E, ListIterator<E>> set = new Stimulus<E, ListIterator<E>>("set") {
@Override boolean executeAndCompare(
ListIterator<E> reference, ListIterator<E> target) {
return internalExecuteAndCompare(reference, target, newSetMethod());
}
};
@SuppressWarnings("unchecked")
List<Stimulus<E, ListIterator<E>>> listIteratorStimuli() {
return Arrays.asList(
hasPrevious, nextIndex, previousIndex, previous, add, set);
}
}
| Java |
/*
* Copyright (C) 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.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
*/
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.collect.testing.SampleElements.Strings;
import java.util.List;
import java.util.Set;
/**
* Create string sets for collection tests.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public abstract class TestStringSetGenerator implements TestSetGenerator<String>
{
@Override
public SampleElements<String> samples() {
return new Strings();
}
@Override
public Set<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 Set<String> create(String[] elements);
@Override
public String[] createArray(int length) {
return new String[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<String> order(List<String> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.Iterator;
/**
* Adapts a test iterable generator to give a TestIteratorGenerator.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public final class DerivedTestIteratorGenerator<E>
implements TestIteratorGenerator<E> {
private final TestSubjectGenerator<? extends Iterable<E>>
collectionGenerator;
public DerivedTestIteratorGenerator(
TestSubjectGenerator<? extends Iterable<E>> collectionGenerator) {
this.collectionGenerator = collectionGenerator;
}
public TestSubjectGenerator<? extends Iterable<E>> getCollectionGenerator() {
return collectionGenerator;
}
@Override
public Iterator<E> get() {
return collectionGenerator.createTestSubject().iterator();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.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()))
.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.features;
import com.google.common.collect.testing.Helpers;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
/**
* When describing the features of the collection produced by a given generator
* (i.e. in a call to {@link
* com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder#withFeatures(Feature...)}),
* this annotation specifies each of the different sizes for which a test suite
* should be built. (In a typical case, the features should include {@link
* CollectionSize#ANY}.) These semantics are thus a little different
* from those of other Collection-related features such as {@link
* CollectionFeature} or {@link SetFeature}.
* <p>
* However, when {@link CollectionSize.Require} is used to annotate a test it
* behaves normally (i.e. it requires the collection instance under test to be
* a certain size for the test to run). Note that this means a test should not
* require more than one CollectionSize, since a particular collection instance
* can only be one size at once.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
// Enum values use constructors with generic varargs.
@SuppressWarnings("unchecked")
public enum CollectionSize implements Feature<Collection>,
Comparable<CollectionSize> {
/** Test an empty collection. */
ZERO(0),
/** Test a one-element collection. */
ONE(1),
/** Test a three-element collection. */
SEVERAL(3),
/*
* TODO: add VERY_LARGE, noting that we currently assume that the fourth
* sample element is not in any collection
*/
ANY(
ZERO,
ONE,
SEVERAL
);
private final Set<Feature<? super Collection>> implied;
private final Integer numElements;
CollectionSize(int numElements) {
this.implied = Collections.emptySet();
this.numElements = numElements;
}
CollectionSize(Feature<? super Collection> ... implied) {
// Keep the order here, so that PerCollectionSizeTestSuiteBuilder
// gives a predictable order of test suites.
this.implied = Helpers.copyToSet(implied);
this.numElements = null;
}
@Override
public Set<Feature<? super Collection>> getImpliedFeatures() {
return implied;
}
public int getNumElements() {
if (numElements == null) {
throw new IllegalStateException(
"A compound CollectionSize doesn't specify a number of elements.");
}
return numElements;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
CollectionSize[] value() default {};
CollectionSize[] absent() default {};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import java.util.Set;
/**
* Base class for enumerating the features of an interface to be tested.
*
* <p>This class is GWT compatible.
*
* @param <T> The interface whose features are to be enumerated.
* @author George van den Driessche
*/
public interface Feature<T> {
/** Returns the set of features that are implied by this feature. */
Set<Feature<? super T>> getImpliedFeatures();
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import com.google.common.collect.testing.Helpers;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Map;
import java.util.Set;
/**
* Optional features of classes derived from {@code Map}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
// Enum values use constructors with generic varargs.
@SuppressWarnings("unchecked")
public enum MapFeature implements Feature<Map> {
/**
* The map does not throw {@code NullPointerException} on calls such as
* {@code containsKey(null)}, {@code get(null)}, or {@code remove(null)}.
*/
ALLOWS_NULL_QUERIES,
ALLOWS_NULL_KEYS (ALLOWS_NULL_QUERIES),
ALLOWS_NULL_VALUES,
RESTRICTS_KEYS,
RESTRICTS_VALUES,
SUPPORTS_PUT,
SUPPORTS_PUT_ALL,
SUPPORTS_REMOVE,
SUPPORTS_CLEAR,
FAILS_FAST_ON_CONCURRENT_MODIFICATION,
/**
* Indicates that the constructor or factory method of a map, usually an
* immutable map, throws an {@link IllegalArgumentException} when presented
* with duplicate keys instead of discarding all but one.
*/
REJECTS_DUPLICATES_AT_CREATION,
GENERAL_PURPOSE(
SUPPORTS_PUT,
SUPPORTS_PUT_ALL,
SUPPORTS_REMOVE,
SUPPORTS_CLEAR
),
/** Features supported by maps where only removal is allowed. */
REMOVE_OPERATIONS(
SUPPORTS_REMOVE,
SUPPORTS_CLEAR
);
private final Set<Feature<? super Map>> implied;
MapFeature(Feature<? super Map> ... implied) {
this.implied = Helpers.copyToSet(implied);
}
@Override
public Set<Feature<? super Map>> getImpliedFeatures() {
return implied;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
public abstract MapFeature[] value() default {};
public abstract MapFeature[] absent() default {};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import java.util.Set;
/**
* Thrown when requirements on a tester method or class conflict with
* each other.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class ConflictingRequirementsException extends Exception {
private Set<Feature<?>> conflicts;
private Object source;
public ConflictingRequirementsException(
String message, Set<Feature<?>> conflicts, Object source) {
super(message);
this.conflicts = conflicts;
this.source = source;
}
public Set<Feature<?>> getConflicts() {
return conflicts;
}
public Object getSource() {
return source;
}
@Override public String getMessage() {
return super.getMessage() + " (source: " + source + ")";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import com.google.common.collect.testing.Helpers;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.SortedSet;
/**
* Optional features of classes derived from {@code Collection}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
// Enum values use constructors with generic varargs.
@SuppressWarnings("unchecked")
public enum CollectionFeature implements Feature<Collection> {
/**
* The collection must not throw {@code NullPointerException} on calls
* such as {@code contains(null)} or {@code remove(null)}, but instead
* must return a simple {@code false}.
*/
ALLOWS_NULL_QUERIES,
ALLOWS_NULL_VALUES (ALLOWS_NULL_QUERIES),
/**
* Indicates that a collection disallows certain elements (other than
* {@code null}, whose validity as an element is indicated by the presence
* or absence of {@link #ALLOWS_NULL_VALUES}).
* From the documentation for {@link Collection}:
* <blockquote>"Some collection implementations have restrictions on the
* elements that they may contain. For example, some implementations
* prohibit null elements, and some have restrictions on the types of their
* elements."</blockquote>
*/
RESTRICTS_ELEMENTS,
/**
* Indicates that a collection has a well-defined ordering of its elements.
* The ordering may depend on the element values, such as a {@link SortedSet},
* or on the insertion ordering, such as a {@link LinkedHashSet}. All list
* tests automatically specify this feature.
*/
KNOWN_ORDER,
/**
* Indicates that a collection has a different {@link Object#toString}
* representation than most collections. If not specified, the collection
* tests will examine the value returned by {@link Object#toString}.
*/
NON_STANDARD_TOSTRING,
/**
* Indicates that the constructor or factory method of a collection, usually
* an immutable set, throws an {@link IllegalArgumentException} when presented
* with duplicate elements instead of collapsing them to a single element or
* including duplicate instances in the collection.
*/
REJECTS_DUPLICATES_AT_CREATION,
SUPPORTS_ADD,
SUPPORTS_REMOVE,
SUPPORTS_ADD_ALL,
SUPPORTS_REMOVE_ALL,
SUPPORTS_RETAIN_ALL,
SUPPORTS_CLEAR,
FAILS_FAST_ON_CONCURRENT_MODIFICATION,
/**
* Features supported by general-purpose collections -
* everything but {@link #RESTRICTS_ELEMENTS}.
* @see java.util.Collection the definition of general-purpose collections.
*/
GENERAL_PURPOSE(
SUPPORTS_ADD,
SUPPORTS_REMOVE,
SUPPORTS_ADD_ALL,
SUPPORTS_REMOVE_ALL,
SUPPORTS_RETAIN_ALL,
SUPPORTS_CLEAR),
/** Features supported by collections where only removal is allowed. */
REMOVE_OPERATIONS(
SUPPORTS_REMOVE,
SUPPORTS_REMOVE_ALL,
SUPPORTS_RETAIN_ALL,
SUPPORTS_CLEAR),
SERIALIZABLE, SERIALIZABLE_INCLUDING_VIEWS(SERIALIZABLE),
/**
* For documenting collections that support no optional features, such as
* {@link java.util.Collections#emptySet}
*/
NONE();
private final Set<Feature<? super Collection>> implied;
CollectionFeature(Feature<? super Collection> ... implied) {
this.implied = Helpers.copyToSet(implied);
}
@Override
public Set<Feature<? super Collection>> getImpliedFeatures() {
return implied;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
CollectionFeature[] value() default {};
CollectionFeature[] absent() default {};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import com.google.common.collect.testing.Helpers;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Set;
/**
* Optional features of classes derived from {@code List}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
// Enum values use constructors with generic varargs.
@SuppressWarnings("unchecked")
public enum ListFeature implements Feature<List> {
SUPPORTS_SET,
SUPPORTS_ADD_WITH_INDEX,
SUPPORTS_ADD_ALL_WITH_INDEX,
SUPPORTS_REMOVE_WITH_INDEX,
GENERAL_PURPOSE(
CollectionFeature.GENERAL_PURPOSE,
SUPPORTS_SET,
SUPPORTS_ADD_WITH_INDEX,
SUPPORTS_ADD_ALL_WITH_INDEX,
SUPPORTS_REMOVE_WITH_INDEX
),
/** Features supported by lists where only removal is allowed. */
REMOVE_OPERATIONS(
CollectionFeature.REMOVE_OPERATIONS,
SUPPORTS_REMOVE_WITH_INDEX
);
private final Set<Feature<? super List>> implied;
ListFeature(Feature<? super List> ... implied) {
this.implied = Helpers.copyToSet(implied);
}
@Override
public Set<Feature<? super List>> getImpliedFeatures() {
return implied;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
ListFeature[] value() default {};
ListFeature[] absent() default {};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import com.google.common.collect.testing.Helpers;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Set;
/**
* Optional features of classes derived from {@code Set}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
// Enum values use constructors with generic varargs.
@SuppressWarnings("unchecked")
public enum SetFeature implements Feature<Set> {
GENERAL_PURPOSE(
CollectionFeature.GENERAL_PURPOSE
);
private final Set<Feature<? super Set>> implied;
SetFeature(Feature<? super Set> ... implied) {
this.implied = Helpers.copyToSet(implied);
}
@Override
public Set<Feature<? super Set>> getImpliedFeatures() {
return implied;
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @interface Require {
public abstract SetFeature[] value() default {};
public abstract SetFeature[] absent() default {};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import com.google.common.collect.testing.Helpers;
import java.util.Collections;
import java.util.Set;
/**
* Encapsulates the constraints that a class under test must satisfy in order
* for a tester method to be run against that class.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public final class TesterRequirements {
private final Set<Feature<?>> presentFeatures;
private final Set<Feature<?>> absentFeatures;
public TesterRequirements(
Set<Feature<?>> presentFeatures, Set<Feature<?>> absentFeatures) {
this.presentFeatures = Helpers.copyToSet(presentFeatures);
this.absentFeatures = Helpers.copyToSet(absentFeatures);
}
public TesterRequirements(TesterRequirements tr) {
this(tr.getPresentFeatures(), tr.getAbsentFeatures());
}
public TesterRequirements() {
this(Collections.<Feature<?>>emptySet(),
Collections.<Feature<?>>emptySet());
}
public final Set<Feature<?>> getPresentFeatures() {
return presentFeatures;
}
public final Set<Feature<?>> getAbsentFeatures() {
return absentFeatures;
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof TesterRequirements) {
TesterRequirements that = (TesterRequirements) object;
return this.presentFeatures.equals(that.presentFeatures)
&& this.absentFeatures.equals(that.absentFeatures);
}
return false;
}
@Override public int hashCode() {
return presentFeatures.hashCode() * 31 + absentFeatures.hashCode();
}
@Override public String toString() {
return "{TesterRequirements: present="
+ presentFeatures + ", absent=" + absentFeatures + "}";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import com.google.common.collect.testing.Helpers;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Utilities for collecting and validating tester requirements from annotations.
*
* <p>This class can be referenced in GWT tests.
*
* @author George van den Driessche
*/
public class FeatureUtil {
/**
* A cache of annotated objects (typically a Class or Method) to its
* set of annotations.
*/
private static Map<AnnotatedElement, Annotation[]> annotationCache =
new HashMap<AnnotatedElement, Annotation[]>();
private static final Map<Class<?>, TesterRequirements>
classTesterRequirementsCache =
new HashMap<Class<?>, TesterRequirements>();
/**
* Given a set of features, add to it all the features directly or indirectly
* implied by any of them, and return it.
* @param features the set of features to expand
* @return the same set of features, expanded with all implied features
*/
public static Set<Feature<?>> addImpliedFeatures(Set<Feature<?>> features) {
// The base case of the recursion is an empty set of features, which will
// occur when the previous set contained only simple features.
if (!features.isEmpty()) {
features.addAll(impliedFeatures(features));
}
return features;
}
/**
* Given a set of features, return a new set of all features directly or
* indirectly implied by any of them.
* @param features the set of features whose implications to find
* @return the implied set of features
*/
public static Set<Feature<?>> impliedFeatures(Set<Feature<?>> features) {
Set<Feature<?>> implied = new LinkedHashSet<Feature<?>>();
for (Feature<?> feature : features) {
implied.addAll(feature.getImpliedFeatures());
}
addImpliedFeatures(implied);
return implied;
}
/**
* Get the full set of requirements for a tester class.
* @param testerClass a tester class
* @return all the constraints implicitly or explicitly required by the class
* or any of its superclasses.
* @throws ConflictingRequirementsException if the requirements are mutually
* inconsistent.
*/
public static TesterRequirements getTesterRequirements(Class<?> testerClass)
throws ConflictingRequirementsException {
synchronized (classTesterRequirementsCache) {
TesterRequirements requirements =
classTesterRequirementsCache.get(testerClass);
if (requirements == null) {
requirements = buildTesterRequirements(testerClass);
classTesterRequirementsCache.put(testerClass, requirements);
}
return requirements;
}
}
/**
* Get the full set of requirements for a tester class.
* @param testerMethod a test method of a tester class
* @return all the constraints implicitly or explicitly required by the
* method, its declaring class, or any of its superclasses.
* @throws ConflictingRequirementsException if the requirements are
* mutually inconsistent.
*/
public static TesterRequirements getTesterRequirements(Method testerMethod)
throws ConflictingRequirementsException {
return buildTesterRequirements(testerMethod);
}
/**
* Construct the full set of requirements for a tester class.
* @param testerClass a tester class
* @return all the constraints implicitly or explicitly required by the class
* or any of its superclasses.
* @throws ConflictingRequirementsException if the requirements are mutually
* inconsistent.
*/
static TesterRequirements buildTesterRequirements(Class<?> testerClass)
throws ConflictingRequirementsException {
final TesterRequirements declaredRequirements =
buildDeclaredTesterRequirements(testerClass);
Class<?> baseClass = testerClass.getSuperclass();
if (baseClass == null) {
return declaredRequirements;
} else {
final TesterRequirements clonedBaseRequirements =
new TesterRequirements(getTesterRequirements(baseClass));
return incorporateRequirements(
clonedBaseRequirements, declaredRequirements, testerClass);
}
}
/**
* Construct the full set of requirements for a tester method.
* @param testerMethod a test method of a tester class
* @return all the constraints implicitly or explicitly required by the
* method, its declaring class, or any of its superclasses.
* @throws ConflictingRequirementsException if the requirements are mutually
* inconsistent.
*/
static TesterRequirements buildTesterRequirements(Method testerMethod)
throws ConflictingRequirementsException {
TesterRequirements clonedClassRequirements = new TesterRequirements(
getTesterRequirements(testerMethod.getDeclaringClass()));
TesterRequirements declaredRequirements =
buildDeclaredTesterRequirements(testerMethod);
return incorporateRequirements(
clonedClassRequirements, declaredRequirements, testerMethod);
}
/**
* Construct the set of requirements specified by annotations
* directly on a tester class or method.
* @param classOrMethod a tester class or a test method thereof
* @return all the constraints implicitly or explicitly required by
* annotations on the class or method.
* @throws ConflictingRequirementsException if the requirements are mutually
* inconsistent.
*/
public static TesterRequirements buildDeclaredTesterRequirements(
AnnotatedElement classOrMethod)
throws ConflictingRequirementsException {
TesterRequirements requirements = new TesterRequirements();
Iterable<Annotation> testerAnnotations =
getTesterAnnotations(classOrMethod);
for (Annotation testerAnnotation : testerAnnotations) {
TesterRequirements moreRequirements =
buildTesterRequirements(testerAnnotation);
incorporateRequirements(
requirements, moreRequirements, testerAnnotation);
}
return requirements;
}
/**
* Find all the tester annotations declared on a tester class or method.
* @param classOrMethod a class or method whose tester annotations to find
* @return an iterable sequence of tester annotations on the class
*/
public static Iterable<Annotation> getTesterAnnotations(
AnnotatedElement classOrMethod) {
List<Annotation> result = new ArrayList<Annotation>();
Annotation[] annotations;
synchronized (annotationCache) {
annotations = annotationCache.get(classOrMethod);
if (annotations == null) {
annotations = classOrMethod.getDeclaredAnnotations();
annotationCache.put(classOrMethod, annotations);
}
}
for (Annotation a : annotations) {
Class<? extends Annotation> annotationClass = a.annotationType();
if (annotationClass.isAnnotationPresent(TesterAnnotation.class)) {
result.add(a);
}
}
return result;
}
/**
* Find all the constraints explicitly or implicitly specified by a single
* tester annotation.
* @param testerAnnotation a tester annotation
* @return the requirements specified by the annotation
* @throws ConflictingRequirementsException if the requirements are mutually
* inconsistent.
*/
private static TesterRequirements buildTesterRequirements(
Annotation testerAnnotation)
throws ConflictingRequirementsException {
Class<? extends Annotation> annotationClass = testerAnnotation.getClass();
final Feature<?>[] presentFeatures;
final Feature<?>[] absentFeatures;
try {
presentFeatures = (Feature[]) annotationClass.getMethod("value")
.invoke(testerAnnotation);
absentFeatures = (Feature[]) annotationClass.getMethod("absent")
.invoke(testerAnnotation);
} catch (Exception e) {
throw new IllegalArgumentException(
"Error extracting features from tester annotation.", e);
}
Set<Feature<?>> allPresentFeatures =
addImpliedFeatures(Helpers.<Feature<?>>copyToSet(presentFeatures));
Set<Feature<?>> allAbsentFeatures =
addImpliedFeatures(Helpers.<Feature<?>>copyToSet(absentFeatures));
Set<Feature<?>> conflictingFeatures =
intersection(allPresentFeatures, allAbsentFeatures);
if (!conflictingFeatures.isEmpty()) {
throw new ConflictingRequirementsException("Annotation explicitly or " +
"implicitly requires one or more features to be both present " +
"and absent.",
conflictingFeatures, testerAnnotation);
}
return new TesterRequirements(allPresentFeatures, allAbsentFeatures);
}
/**
* Incorporate additional requirements into an existing requirements object.
* @param requirements the existing requirements object
* @param moreRequirements more requirements to incorporate
* @param source the source of the additional requirements
* (used only for error reporting)
* @return the existing requirements object, modified to include the
* additional requirements
* @throws ConflictingRequirementsException if the additional requirements
* are inconsistent with the existing requirements
*/
private static TesterRequirements incorporateRequirements(
TesterRequirements requirements, TesterRequirements moreRequirements,
Object source) throws ConflictingRequirementsException {
Set<Feature<?>> presentFeatures = requirements.getPresentFeatures();
Set<Feature<?>> absentFeatures = requirements.getAbsentFeatures();
Set<Feature<?>> morePresentFeatures = moreRequirements.getPresentFeatures();
Set<Feature<?>> moreAbsentFeatures = moreRequirements.getAbsentFeatures();
checkConflict(
"absent", absentFeatures,
"present", morePresentFeatures, source);
checkConflict(
"present", presentFeatures,
"absent", moreAbsentFeatures, source);
presentFeatures.addAll(morePresentFeatures);
absentFeatures.addAll(moreAbsentFeatures);
return requirements;
}
// Used by incorporateRequirements() only
private static void checkConflict(
String earlierRequirement, Set<Feature<?>> earlierFeatures,
String newRequirement, Set<Feature<?>> newFeatures,
Object source) throws ConflictingRequirementsException {
Set<Feature<?>> conflictingFeatures;
conflictingFeatures = intersection(newFeatures, earlierFeatures);
if (!conflictingFeatures.isEmpty()) {
throw new ConflictingRequirementsException(String.format(
"Annotation requires to be %s features that earlier " +
"annotations required to be %s.",
newRequirement, earlierRequirement),
conflictingFeatures, source);
}
}
/**
* Construct a new {@link java.util.Set} that is the intersection
* of the given sets.
*/
// Calls generic varargs method.
@SuppressWarnings("unchecked")
public static <T> Set<T> intersection(
Set<? extends T> set1, Set<? extends T> set2) {
return intersection(new Set[] {set1, set2});
}
/**
* Construct a new {@link java.util.Set} that is the intersection
* of all the given sets.
* @param sets the sets to intersect
* @return the intersection of the sets
* @throws java.lang.IllegalArgumentException if there are no sets to
* intersect
*/
public static <T> Set<T> intersection(Set<? extends T> ... sets) {
if (sets.length == 0) {
throw new IllegalArgumentException(
"Can't intersect no sets; would have to return the universe.");
}
Set<T> results = Helpers.copyToSet(sets[0]);
for (int i = 1; i < sets.length; i++) {
Set<? extends T> set = sets[i];
results.retainAll(set);
}
return results;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.features;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this to meta-annotate XxxFeature.Require annotations, so that those
* annotations can be used to decide whether to apply a test to a given
* class-under-test.
* <br>
* This is needed because annotations can't implement interfaces, which is also
* why reflection is used to extract values from the properties of the various
* annotations.
*
* <p>This class is GWT compatible.
*
* @see CollectionFeature.Require
*
* @author George van den Driessche
*/
@Target(value = {java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface TesterAnnotation {
}
| 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) 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 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
*/
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 java.util.Queue;
/**
* Creates queues, containing sample elements, to be tested.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
public interface TestQueueGenerator<E> extends TestCollectionGenerator<E> {
@Override
Queue<E> create(Object... elements);
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.Set;
/**
* Reserializes the sets created by another test set generator.
*
* TODO: make CollectionTestSuiteBuilder test reserialized collections
*
* @author Jesse Wilson
*/
public class ReserializingTestSetGenerator<E>
extends ReserializingTestCollectionGenerator<E>
implements TestSetGenerator<E> {
ReserializingTestSetGenerator(TestSetGenerator<E> delegate) {
super(delegate);
}
public static <E> TestSetGenerator<E> newInstance(
TestSetGenerator<E> delegate) {
return new ReserializingTestSetGenerator<E>(delegate);
}
@Override public Set<E> create(Object... elements) {
return (Set<E>) super.create(elements);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
/**
* 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.
*/
public enum WrongType {
VALUE
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.io.Serializable;
/**
* Simple base class to verify that we handle generics correctly.
*
* @author Kevin Bourrillion
*/
public class BaseComparable implements Comparable<BaseComparable>, Serializable {
private final String s;
public BaseComparable(String s) {
this.s = s;
}
@Override public int hashCode() { // delegate to 's'
return s.hashCode();
}
@Override public boolean equals(Object other) {
if (other == null) {
return false;
} else if (other instanceof BaseComparable) {
return s.equals(((BaseComparable) other).s);
} else {
return false;
}
}
@Override
public int compareTo(BaseComparable o) {
return s.compareTo(o.s);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.features.FeatureUtil;
import junit.framework.TestSuite;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* This builder creates a composite test suite, containing a separate test suite
* for each {@link CollectionSize} present in the features specified
* by {@link #withFeatures(Feature...)}.
*
* @param <B> The concrete type of this builder (the 'self-type'). All the
* Builder methods of this class (such as {@link #named(String)}) return this
* type, so that Builder methods of more derived classes can be chained onto
* them without casting.
* @param <G> The type of the generator to be passed to testers in the
* generated test suite. An instance of G should somehow provide an
* instance of the class under test, plus any other information required
* to parameterize the test.
*
* @see FeatureSpecificTestSuiteBuilder
*
* @author George van den Driessche
*/
public abstract class PerCollectionSizeTestSuiteBuilder<
B extends PerCollectionSizeTestSuiteBuilder<B, G, T, E>,
G extends TestContainerGenerator<T, E>,
T,
E>
extends FeatureSpecificTestSuiteBuilder<B, G> {
private static final Logger logger = Logger.getLogger(
PerCollectionSizeTestSuiteBuilder.class.getName());
/**
* Creates a runnable JUnit test suite based on the criteria already given.
*/
@Override public TestSuite createTestSuite() {
checkCanCreate();
String name = getName();
// Copy this set, so we can modify it.
Set<Feature<?>> features = Helpers.copyToSet(getFeatures());
List<Class<? extends AbstractTester>> testers = getTesters();
logger.fine(" Testing: " + name);
// Split out all the specified sizes.
Set<Feature<?>> sizesToTest =
Helpers.<Feature<?>>copyToSet(CollectionSize.values());
sizesToTest.retainAll(features);
features.removeAll(sizesToTest);
FeatureUtil.addImpliedFeatures(sizesToTest);
sizesToTest.retainAll(Arrays.asList(
CollectionSize.ZERO, CollectionSize.ONE, CollectionSize.SEVERAL));
logger.fine(" Sizes: " + formatFeatureSet(sizesToTest));
if (sizesToTest.isEmpty()) {
throw new IllegalStateException(name
+ ": no CollectionSizes specified (check the argument to "
+ "FeatureSpecificTestSuiteBuilder.withFeatures().)");
}
TestSuite suite = new TestSuite(name);
for (Feature<?> collectionSize : sizesToTest) {
String oneSizeName = Platform.format("%s [collection size: %s]",
name, collectionSize.toString().toLowerCase());
OneSizeGenerator<T, E> oneSizeGenerator = new OneSizeGenerator<T, E>(
getSubjectGenerator(), (CollectionSize) collectionSize);
Set<Feature<?>> oneSizeFeatures = Helpers.copyToSet(features);
oneSizeFeatures.add(collectionSize);
Set<Method> oneSizeSuppressedTests = getSuppressedTests();
OneSizeTestSuiteBuilder<T, E> oneSizeBuilder =
new OneSizeTestSuiteBuilder<T, E>(testers)
.named(oneSizeName)
.usingGenerator(oneSizeGenerator)
.withFeatures(oneSizeFeatures)
.withSetUp(getSetUp())
.withTearDown(getTearDown())
.suppressing(oneSizeSuppressedTests);
TestSuite oneSizeSuite = oneSizeBuilder.createTestSuite();
suite.addTest(oneSizeSuite);
for (TestSuite derivedSuite : createDerivedSuites(oneSizeBuilder)) {
oneSizeSuite.addTest(derivedSuite);
}
}
return suite;
}
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<
?, ? extends OneSizeTestContainerGenerator<T, E>> parentBuilder) {
return new ArrayList<TestSuite>();
}
/** Builds a test suite for one particular {@link CollectionSize}. */
private static final class OneSizeTestSuiteBuilder<T, E> extends
FeatureSpecificTestSuiteBuilder<
OneSizeTestSuiteBuilder<T, E>, OneSizeGenerator<T, E>> {
private final List<Class<? extends AbstractTester>> testers;
public OneSizeTestSuiteBuilder(
List<Class<? extends AbstractTester>> testers) {
this.testers = testers;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
return testers;
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
/**
* Create string sets for testing collections that are sorted by natural
* ordering.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
public abstract class TestStringSortedSetGenerator
extends TestStringSetGenerator {
@Override protected abstract SortedSet<String> create(String[] elements);
/** Sorts the elements by their natural ordering. */
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder);
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 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.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Implementation helper for {@link TestMapGenerator} for use with maps of
* strings.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Jared Levy
* @author George van den Driessche
*/
public abstract class TestStringMapGenerator
implements TestMapGenerator<String, String> {
@Override
public SampleElements<Map.Entry<String, String>> samples() {
return new SampleElements<Map.Entry<String, String>>(
Helpers.mapEntry("one", "January"),
Helpers.mapEntry("two", "February"),
Helpers.mapEntry("three", "March"),
Helpers.mapEntry("four", "April"),
Helpers.mapEntry("five", "May")
);
}
@Override
public final Map<String, String> create(Object... entries) {
@SuppressWarnings("unchecked")
Entry<String, String>[] array = new Entry[entries.length];
int i = 0;
for (Object o : entries) {
@SuppressWarnings("unchecked")
Entry<String, String> e = (Entry<String, String>) o;
array[i++] = e;
}
return create(array);
}
protected abstract Map<String, String> create(
Entry<String, String>[] entries);
@Override
@SuppressWarnings("unchecked")
public final Entry<String, String>[] createArray(int length) {
return new Entry[length];
}
@Override
public final String[] createKeyArray(int length) {
return new String[length];
}
@Override
public final String[] createValueArray(int length) {
return new String[length];
}
/** Returns the original element list, unchanged. */
@Override
public Iterable<Entry<String, String>> order(
List<Entry<String, String>> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 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 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
*/
public abstract class ListIteratorTester<E> extends
AbstractIteratorTester<E, ListIterator<E>> {
protected ListIteratorTester(int steps, Iterable<E> elementsToInsert,
Iterable<? extends IteratorFeature> features,
Iterable<E> expectedElements, int startIndex) {
super(steps, elementsToInsert, features, expectedElements,
KnownOrder.KNOWN_ORDER, startIndex);
}
@Override
protected final Iterable<? extends Stimulus<E, ? super ListIterator<E>>>
getStimulusValues() {
List<Stimulus<E, ? super ListIterator<E>>> list =
new ArrayList<Stimulus<E, ? super ListIterator<E>>>();
Helpers.addAll(list, iteratorStimuli());
Helpers.addAll(list, listIteratorStimuli());
return list;
}
@Override protected abstract ListIterator<E> newTargetIterator();
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.features.Feature;
import com.google.common.collect.testing.testers.MapNavigationTester;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Set;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a NavigableMap implementation.
*/
public class NavigableMapTestSuiteBuilder<K, V> extends MapTestSuiteBuilder<K, V> {
public static <K, V> NavigableMapTestSuiteBuilder<K, V> using(
TestMapGenerator<K, V> generator) {
NavigableMapTestSuiteBuilder<K, V> result = new NavigableMapTestSuiteBuilder<K, V>();
result.usingGenerator(generator);
return result;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.add(MapNavigationTester.class);
return testers;
}
@Override
protected List<TestSuite> createDerivedSuites(FeatureSpecificTestSuiteBuilder<?,
? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>> parentBuilder) {
List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);
if (!parentBuilder.getFeatures().contains(NoRecurse.DESCENDING)) {
derivedSuites.add(createDescendingSuite(parentBuilder));
}
if (!parentBuilder.getFeatures().contains(NoRecurse.SUBMAP)) {
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.EXCLUSIVE));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.NO_BOUND, Bound.INCLUSIVE));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.NO_BOUND));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.EXCLUSIVE));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.EXCLUSIVE, Bound.INCLUSIVE));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.NO_BOUND));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.EXCLUSIVE));
derivedSuites.add(createSubmapSuite(parentBuilder, Bound.INCLUSIVE, Bound.INCLUSIVE));
}
return derivedSuites;
}
@Override protected SetTestSuiteBuilder<K> createDerivedKeySetSuite(
TestSetGenerator<K> keySetGenerator) {
return NavigableSetTestSuiteBuilder.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();
}
}
/**
* Two bounds (from and to) define how to build a subMap.
*/
enum Bound {
INCLUSIVE,
EXCLUSIVE,
NO_BOUND;
}
/**
* 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.
*/
private 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());
NavigableMap<K, V> emptyMap = (NavigableMap<K, V>) delegate.create();
final Comparator<Entry<K, V>> entryComparator = Helpers.entryComparator(emptyMap.comparator());
// derive values for inclusive filtering from the input samples
SampleElements<Entry<K, V>> samples = delegate.samples();
@SuppressWarnings("unchecked") // no elements are inserted into the array
List<Entry<K, V>> samplesList = Arrays.asList(
samples.e0, samples.e1, samples.e2, samples.e3, samples.e4);
Collections.sort(samplesList, entryComparator);
final K firstInclusive = samplesList.get(0).getKey();
final K lastInclusive = samplesList.get(samplesList.size() - 1).getKey();
return NavigableMapTestSuiteBuilder
.using(new ForwardingTestMapGenerator<K, V>(delegate) {
@Override public Map<K, V> create(Object... entries) {
@SuppressWarnings("unchecked") // we dangerously assume K and V are both strings
List<Entry<K, V>> extremeValues = (List) getExtremeValues();
@SuppressWarnings("unchecked") // map generators must past entry objects
List<Entry<K, V>> normalValues = (List) Arrays.asList(entries);
// prepare extreme values to be filtered out of view
Collections.sort(extremeValues, entryComparator);
K firstExclusive = extremeValues.get(1).getKey();
K lastExclusive = extremeValues.get(2).getKey();
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<Entry<K, V>> allEntries = new ArrayList<Entry<K, V>>();
allEntries.addAll(extremeValues);
allEntries.addAll(normalValues);
NavigableMap<K, V> map = (NavigableMap<K, V>)
delegate.create((Object[])
allEntries.toArray(new Entry[allEntries.size()]));
// call the smallest subMap overload that filters out the extreme values
if (from == Bound.NO_BOUND && to == Bound.EXCLUSIVE) {
return map.headMap(lastExclusive);
} else if (from == Bound.NO_BOUND && to == Bound.INCLUSIVE) {
return map.headMap(lastInclusive, true);
} else if (from == Bound.EXCLUSIVE && to == Bound.NO_BOUND) {
return map.tailMap(firstExclusive, false);
} else if (from == Bound.EXCLUSIVE && to == Bound.EXCLUSIVE) {
return map.subMap(firstExclusive, false, lastExclusive, false);
} else if (from == Bound.EXCLUSIVE && to == Bound.INCLUSIVE) {
return map.subMap(firstExclusive, false, lastInclusive, true);
} else if (from == Bound.INCLUSIVE && to == Bound.NO_BOUND) {
return map.tailMap(firstInclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.EXCLUSIVE) {
return map.subMap(firstInclusive, lastExclusive);
} else if (from == Bound.INCLUSIVE && to == Bound.INCLUSIVE) {
return map.subMap(firstInclusive, true, lastInclusive, true);
} else {
throw new IllegalArgumentException();
}
}
})
.named(parentBuilder.getName() + " subMap " + 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<Entry<String, String>> getExtremeValues() {
List<Entry<String, String>> result = new ArrayList<Entry<String, String>>();
result.add(Helpers.mapEntry("!! a", "below view"));
result.add(Helpers.mapEntry("!! b", "below view"));
result.add(Helpers.mapEntry("~~ y", "above view"));
result.add(Helpers.mapEntry("~~ z", "above view"));
return result;
}
/**
* Create a suite whose maps are descending views of other maps.
*/
private TestSuite createDescendingSuite(final FeatureSpecificTestSuiteBuilder<?,
? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>> parentBuilder) {
final TestMapGenerator<K, V> delegate
= (TestMapGenerator<K, V>) parentBuilder.getSubjectGenerator().getInnerGenerator();
List<Feature<?>> features = new ArrayList<Feature<?>>();
features.add(NoRecurse.DESCENDING);
features.addAll(parentBuilder.getFeatures());
return NavigableMapTestSuiteBuilder
.using(new ForwardingTestMapGenerator<K, V>(delegate) {
@Override public Map<K, V> create(Object... entries) {
NavigableMap<K, V> map = (NavigableMap<K, V>) delegate.create(entries);
return map.descendingMap();
}
})
.named(parentBuilder.getName() + " descending")
.withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests())
.createTestSuite();
}
static class ForwardingTestMapGenerator<K, V> implements TestMapGenerator<K, V> {
private TestMapGenerator<K, V> delegate;
ForwardingTestMapGenerator(TestMapGenerator<K, V> delegate) {
this.delegate = delegate;
}
@Override
public Iterable<Entry<K, V>> order(List<Entry<K, V>> insertionOrder) {
return delegate.order(insertionOrder);
}
@Override
public K[] createKeyArray(int length) {
return delegate.createKeyArray(length);
}
@Override
public V[] createValueArray(int length) {
return delegate.createValueArray(length);
}
@Override
public SampleElements<Entry<K, V>> samples() {
return delegate.samples();
}
@Override
public Map<K, V> create(Object... elements) {
return delegate.create(elements);
}
@Override
public Entry<K, V>[] createArray(int length) {
return delegate.createArray(length);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.Map;
/**
* A container class for the five sample elements we need for testing.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public class SampleElements<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;
}
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 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 <K, V> SampleElements<Map.Entry<K, V>> mapEntries(
SampleElements<K> keys, SampleElements<V> values) {
return new SampleElements<Map.Entry<K, V>>(
Helpers.mapEntry(keys.e0, values.e0),
Helpers.mapEntry(keys.e1, values.e1),
Helpers.mapEntry(keys.e2, values.e2),
Helpers.mapEntry(keys.e3, values.e3),
Helpers.mapEntry(keys.e4, values.e4));
}
public static class Unhashables extends SampleElements<UnhashableObject> {
public Unhashables() {
super(new UnhashableObject(1),
new UnhashableObject(2),
new UnhashableObject(3),
new UnhashableObject(4),
new UnhashableObject(5));
}
}
public static class Colliders extends SampleElements<Object> {
public Colliders() {
super(new Collider(1),
new Collider(2),
new Collider(3),
new Collider(4),
new Collider(5));
}
}
private static class Collider {
final int value;
Collider(int value) {
this.value = value;
}
@Override public boolean equals(Object obj) {
return obj instanceof Collider && ((Collider) obj).value == value;
}
@Override public int hashCode() {
return 1; // evil!
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.lang.reflect.Method;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* <p>This class is emulated in GWT.
*
* @author Hayward Chan
*/
class Platform {
/**
* Calls {@link Class#isInstance(Object)}. Factored out so that it can be
* emulated in GWT.
*
* <p>This method always returns {@code true} in GWT.
*/
static boolean checkIsInstance(Class<?> clazz, Object obj) {
return clazz.isInstance(obj);
}
static <T> T[] clone(T[] array) {
return array.clone();
}
// Class.cast is not supported in GWT. This method is a no-op in GWT.
static void checkCast(Class<?> clazz, Object obj) {
clazz.cast(obj);
}
static String format(String template, Object... args) {
return String.format(template, args);
}
/**
* Wrapper around {@link System#arraycopy} so that it can be emulated
* correctly in GWT.
*
* <p>It is only intended for the case {@code src} and {@code dest} are
* different. It also doesn't validate the types and indices.
*
* <p>As of GWT 2.0, The built-in {@link System#arraycopy} doesn't work
* in general case. See
* http://code.google.com/p/google-web-toolkit/issues/detail?id=3621
* for more details.
*/
static void unsafeArrayCopy(
Object[] src, int srcPos, Object[] dest, int destPos, int length) {
System.arraycopy(src, srcPos, dest, destPos, length);
}
static Method getMethod(Class<?> clazz, String name) {
try {
return clazz.getMethod(name);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
static String classGetSimpleName(Class<?> clazz) {
return clazz.getSimpleName();
}
private Platform() {}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Set;
/**
* A method supported by implementations of the {@link Iterator} or
* {@link ListIterator} interface.
*
* <p>This enum is GWT compatible.
*
* @author Chris Povirk
*/
public enum IteratorFeature {
/**
* Support for {@link Iterator#remove()}.
*/
SUPPORTS_REMOVE,
/**
* Support for {@link ListIterator#add(Object)}; ignored for plain
* {@link Iterator} implementations.
*/
SUPPORTS_ADD,
/**
* Support for {@link ListIterator#set(Object)}; ignored for plain
* {@link Iterator} implementations.
*/
SUPPORTS_SET;
/**
* A set containing none of the optional features of the {@link Iterator} or
* {@link ListIterator} interfaces.
*/
public static final Set<IteratorFeature> UNMODIFIABLE =
Collections.emptySet();
/**
* A set containing all of the optional features of the {@link Iterator} and
* {@link ListIterator} interfaces.
*/
public static final Set<IteratorFeature> MODIFIABLE =
Collections.unmodifiableSet(EnumSet.allOf(IteratorFeature.class));
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* A simplistic set which implements the bare minimum so that it can be used in
* tests without relying on any specific Set implementations. Slow. Explicitly
* allows null elements so that they can be used in the testers.
*
* <p>This class is GWT compatible.
*
* @author Regina O'Dell
*/
public class MinimalSet<E> extends MinimalCollection<E> implements Set<E> {
@SuppressWarnings("unchecked") // empty Object[] as E[]
public static <E> MinimalSet<E> of(E... contents) {
return ofClassAndContents(
Object.class, (E[]) new Object[0], Arrays.asList(contents));
}
@SuppressWarnings("unchecked") // empty Object[] as E[]
public static <E> MinimalSet<E> from(Collection<? extends E> contents) {
return ofClassAndContents(Object.class, (E[]) new Object[0], contents);
}
public static <E> MinimalSet<E> ofClassAndContents(
Class<? super E> type, E[] emptyArrayForContents,
Iterable<? extends E> contents) {
List<E> setContents = new ArrayList<E>();
for (E e : contents) {
if (!setContents.contains(e)) {
setContents.add(e);
}
}
return new MinimalSet<E>(type, setContents.toArray(emptyArrayForContents));
}
private MinimalSet(Class<? super E> type, E... contents) {
super(type, true, contents);
}
/*
* equals() and hashCode() are more specific in the Set contract.
*/
@Override public boolean equals(Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return (this.size() == that.size()) && this.containsAll(that);
}
return false;
}
@Override public int hashCode() {
int hashCodeSum = 0;
for (Object o : this) {
hashCodeSum += (o == null) ? 0 : o.hashCode();
}
return hashCodeSum;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import 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
*/
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) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.testers.QueueElementTester;
import com.google.common.collect.testing.testers.QueueOfferTester;
import com.google.common.collect.testing.testers.QueuePeekTester;
import com.google.common.collect.testing.testers.QueuePollTester;
import com.google.common.collect.testing.testers.QueueRemoveTester;
import java.util.ArrayList;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a queue implementation.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
public final class QueueTestSuiteBuilder<E>
extends AbstractCollectionTestSuiteBuilder<QueueTestSuiteBuilder<E>, E> {
public static <E> QueueTestSuiteBuilder<E> using(
TestQueueGenerator<E> generator) {
return new QueueTestSuiteBuilder<E>().usingGenerator(generator);
}
private boolean runCollectionTests = true;
/**
* Specify whether to skip the general collection tests. Call this method when
* testing a collection that's both a queue and a list, to avoid running the
* common collection tests twice. By default, collection tests do run.
*/
public QueueTestSuiteBuilder<E> skipCollectionTests() {
runCollectionTests = false;
return this;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
new ArrayList<Class<? extends AbstractTester>>();
if (runCollectionTests) {
testers.addAll(super.getTesters());
}
testers.add(QueueElementTester.class);
testers.add(QueueOfferTester.class);
testers.add(QueuePeekTester.class);
testers.add(QueuePollTester.class);
testers.add(QueueRemoveTester.class);
return testers;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.Collections;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* an Iterator implementation.
*
* <p>At least, it will do when it's finished.
*
* @author George van den Driessche
*/
public class IteratorTestSuiteBuilder<E>
extends FeatureSpecificTestSuiteBuilder<
IteratorTestSuiteBuilder<E>, TestIteratorGenerator<?>> {
@Override protected List<Class<? extends AbstractTester>> getTesters() {
return Collections.<Class<? extends AbstractTester>>singletonList(
ExampleIteratorTester.class);
}
}
| Java |
/*
* Copyright (C) 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.SampleElements.Strings;
import java.util.Collection;
import java.util.List;
/**
* String creation for testing arbitrary collections.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
public abstract class TestStringCollectionGenerator
implements TestCollectionGenerator<String> {
@Override
public SampleElements<String> samples() {
return new Strings();
}
@Override
public Collection<String> create(Object... elements) {
String[] array = new String[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (String) e;
}
return create(array);
}
protected abstract Collection<String> create(String[] elements);
@Override
public String[] createArray(int length) {
return new String[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<String> order(List<String> insertionOrder) {
return insertionOrder;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.collect.testing.testers.SetNavigationTester;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a NavigableSet implementation.
*/
public final class NavigableSetTestSuiteBuilder<E>
extends SetTestSuiteBuilder<E> {
public static <E> NavigableSetTestSuiteBuilder<E> using(
TestSetGenerator<E> generator) {
NavigableSetTestSuiteBuilder<E> builder =
new NavigableSetTestSuiteBuilder<E>();
builder.usingGenerator(generator);
return builder;
}
@Override protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers =
Helpers.copyToList(super.getTesters());
testers.add(SetNavigationTester.class);
return testers;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests remove operations on a set. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class SetRemoveTester<E> extends AbstractSetTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemove_present() {
getSet().remove(samples.e0);
assertFalse("After remove(present) a set should not contain "
+ "the removed element.",
getSet().contains(samples.e0));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
/**
* A generic JUnit test which tests add operations on a set. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.SetTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public class SetAddTester<E> extends AbstractSetTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedPresent() {
assertFalse("add(present) should return false", getSet().add(samples.e0));
expectUnchanged();
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedNullPresent() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
assertFalse("add(nullPresent) should return false", getSet().add(null));
expectContents(array);
}
/**
* Returns the {@link Method} instance for
* {@link #testAdd_supportedNullPresent()} so that tests can suppress it. See
* {@link CollectionAddTester#getAddNullSupportedMethod()} for details.
*/
public static Method getAddSupportedNullPresentMethod() {
return Platform.getMethod(SetAddTester.class, "testAdd_supportedNullPresent");
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Arrays;
import java.util.List;
/**
* A generic JUnit test which tests creation (typically through a constructor or
* static factory method) of a set. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.SetTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
public class SetCreationTester<E> extends AbstractSetTester<E> {
@CollectionFeature.Require(value = ALLOWS_NULL_VALUES,
absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesNotRejected() {
E[] array = createArrayWithNullElement();
array[0] = null;
collection = getSubjectGenerator().create(array);
List<E> expectedWithDuplicateRemoved =
Arrays.asList(array).subList(1, getNumElements());
expectContents(expectedWithDuplicateRemoved);
}
@CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() {
E[] array = createSamplesArray();
array[1] = samples.e0;
collection = getSubjectGenerator().create(array);
List<E> expectedWithDuplicateRemoved =
Arrays.asList(array).subList(1, getNumElements());
expectContents(expectedWithDuplicateRemoved);
}
@CollectionFeature.Require(
{ALLOWS_NULL_VALUES, REJECTS_DUPLICATES_AT_CREATION})
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesRejected() {
E[] array = createArrayWithNullElement();
array[0] = null;
try {
collection = getSubjectGenerator().create(array);
fail("Should reject duplicate null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
@CollectionFeature.Require(REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesRejected() {
E[] array = createSamplesArray();
array[1] = samples.e0;
try {
collection = getSubjectGenerator().create(array);
fail("Should reject duplicate non-null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* A generic JUnit test which tests {@code toArray()} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
public class CollectionToArrayTester<E> extends AbstractCollectionTester<E> {
public void testToArray_noArgs() {
Object[] array = collection.toArray();
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
/**
* {@link Collection#toArray(Object[])} says: "Note that
* <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>."
*
* <p>For maximum effect, the collection under test should be created from an
* element array of a type other than {@code Object[]}.
*/
public void testToArray_isPlainObjectArray() {
Object[] array = collection.toArray();
assertEquals(Object[].class, array.getClass());
}
public void testToArray_emptyArray() {
E[] empty = getSubjectGenerator().createArray(0);
E[] array = collection.toArray(empty);
assertEquals("toArray(emptyT[]) should return an array of type T",
empty.getClass(), array.getClass());
assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_emptyArray_ordered() {
E[] empty = getSubjectGenerator().createArray(0);
E[] array = collection.toArray(empty);
assertEquals("toArray(emptyT[]) should return an array of type T",
empty.getClass(), array.getClass());
assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_emptyArrayOfObject() {
Object[] in = new Object[0];
Object[] array = collection.toArray(in);
assertEquals("toArray(emptyObject[]) should return an array of type Object",
Object[].class, array.getClass());
assertEquals("toArray(emptyObject[]).length",
getNumElements(), array.length);
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
public void testToArray_rightSizedArray() {
E[] array = getSubjectGenerator().createArray(getNumElements());
assertSame("toArray(sameSizeE[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_rightSizedArray_ordered() {
E[] array = getSubjectGenerator().createArray(getNumElements());
assertSame("toArray(sameSizeE[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_rightSizedArrayOfObject() {
Object[] array = new Object[getNumElements()];
assertSame("toArray(sameSizeObject[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_rightSizedArrayOfObject_ordered() {
Object[] array = new Object[getNumElements()];
assertSame("toArray(sameSizeObject[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_oversizedArray() {
E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
array[getNumElements()] = samples.e3;
array[getNumElements() + 1] = samples.e3;
assertSame("toArray(overSizedE[]) should return the given array",
array, collection.toArray(array));
List<E> subArray = Arrays.asList(array).subList(0, getNumElements());
E[] expectedSubArray = createSamplesArray();
for (int i = 0; i < getNumElements(); i++) {
assertTrue(
"toArray(overSizedE[]) should contain element " + expectedSubArray[i],
subArray.contains(expectedSubArray[i]));
}
assertNull("The array element "
+ "immediately following the end of the collection should be nulled",
array[getNumElements()]);
// array[getNumElements() + 1] might or might not have been nulled
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_oversizedArray_ordered() {
E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
array[getNumElements()] = samples.e3;
array[getNumElements() + 1] = samples.e3;
assertSame("toArray(overSizedE[]) should return the given array",
array, collection.toArray(array));
List<E> expected = getOrderedElements();
for (int i = 0; i < getNumElements(); i++) {
assertEquals(expected.get(i), array[i]);
}
assertNull("The array element "
+ "immediately following the end of the collection should be nulled",
array[getNumElements()]);
// array[getNumElements() + 1] might or might not have been nulled
}
@CollectionSize.Require(absent = ZERO)
public void testToArray_emptyArrayOfWrongTypeForNonEmptyCollection() {
try {
WrongType[] array = new WrongType[0];
collection.toArray(array);
fail("toArray(notAssignableTo[]) should throw");
} catch (ArrayStoreException expected) {
}
}
@CollectionSize.Require(ZERO)
public void testToArray_emptyArrayOfWrongTypeForEmptyCollection() {
WrongType[] array = new WrongType[0];
assertSame(
"toArray(sameSizeNotAssignableTo[]) should return the given array",
array, collection.toArray(array));
}
private void expectArrayContentsAnyOrder(Object[] expected, Object[] actual) {
Helpers.assertEqualIgnoringOrder(
Arrays.asList(expected), Arrays.asList(actual));
}
private void expectArrayContentsInOrder(List<E> expected, Object[] actual) {
assertEquals("toArray() ordered contents: ",
expected, Arrays.asList(actual));
}
/**
* Returns the {@link Method} instance for
* {@link #testToArray_isPlainObjectArray()} so that tests of
* {@link Arrays#asList(Object[])} can suppress it with {@code
* FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6260652">Sun bug
* 6260652</a> is fixed.
*/
public static Method getToArrayIsPlainObjectArrayMethod() {
return Platform.getMethod(CollectionToArrayTester.class, "testToArray_isPlainObjectArray");
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code add} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class CollectionAddTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAdd_supportedNotPresent() {
assertTrue("add(notPresent) should return true",
collection.add(samples.e3));
expectAdded(samples.e3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAdd_unsupportedNotPresent() {
try {
collection.add(samples.e3);
fail("add(notPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_unsupportedPresent() {
try {
assertFalse("add(present) should return false or throw",
collection.add(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(
value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testAdd_nullSupported() {
assertTrue("add(null) should return true", collection.add(null));
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD,
absent = ALLOWS_NULL_VALUES)
public void testAdd_nullUnsupported() {
try {
collection.add(null);
fail("add(null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported add(null)");
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testAddConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.add(samples.e3));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
/**
* Returns the {@link Method} instance for {@link #testAdd_nullSupported()} so
* that tests of {@link
* java.util.Collections#checkedCollection(java.util.Collection, Class)} can
* suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()}
* until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6409434">Sun bug
* 6409434</a> is fixed. It's unclear whether nulls were to be permitted or
* forbidden, but presumably the eventual fix will be to permit them, as it
* seems more likely that code would depend on that behavior than on the
* other. Thus, we say the bug is in add(), which fails to support null.
*/
public static Method getAddNullSupportedMethod() {
return Platform.getMethod(CollectionAddTester.class, "testAdd_nullSupported");
}
/**
* Returns the {@link Method} instance for {@link #testAdd_nullSupported()} so
* that tests of {@link
* java.util.Collections#checkedCollection(java.util.Collection, Class)} can
* suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()}
* until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun
* bug 5045147</a> is fixed.
*/
public static Method getAddNullUnsupportedMethod() {
return Platform.getMethod(CollectionAddTester.class, "testAdd_nullUnsupported");
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import static com.google.common.collect.testing.testers.Platform.listListIteratorTesterNumIterations;
import static java.util.Collections.singleton;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.ListIteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.ListFeature;
import java.lang.reflect.Method;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* A generic JUnit test which tests {@code listIterator} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
public class ListListIteratorTester<E> extends AbstractListTester<E> {
// TODO: switch to DerivedIteratorTestSuiteBuilder
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
@ListFeature.Require(absent = {SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX})
public void testListIterator_unmodifiable() {
runListIteratorTest(UNMODIFIABLE);
}
/*
* For now, we don't cope with testing this when the list supports only some
* modification operations.
*/
@CollectionFeature.Require(SUPPORTS_REMOVE)
@ListFeature.Require({SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX})
public void testListIterator_fullyModifiable() {
runListIteratorTest(MODIFIABLE);
}
private void runListIteratorTest(Set<IteratorFeature> features) {
new ListIteratorTester<E>(
listListIteratorTesterNumIterations(), singleton(samples.e4), features,
Helpers.copyToList(getSampleElements()), 0) {
{
// TODO: don't set this universally
stopTestingWhenAddThrowsException();
}
@Override protected ListIterator<E> newTargetIterator() {
resetCollection();
return getList().listIterator();
}
@Override protected void verify(List<E> elements) {
expectContents(elements);
}
}.test();
}
public void testListIterator_tooLow() {
try {
getList().listIterator(-1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testListIterator_tooHigh() {
try {
getList().listIterator(getNumElements() + 1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testListIterator_atSize() {
getList().listIterator(getNumElements());
// TODO: run the iterator through ListIteratorTester
}
/**
* Returns the {@link Method} instance for
* {@link #testListIterator_fullyModifiable()} so that tests of
* {@link CopyOnWriteArraySet} can suppress it with
* {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570575">Sun bug
* 6570575</a> is fixed.
*/
public static Method getListIteratorFullyModifiableMethod() {
return Platform.getMethod(
ListListIteratorTester.class, "testListIterator_fullyModifiable");
}
/**
* Returns the {@link Method} instance for
* {@link #testListIterator_unmodifiable()} so that it can be suppressed in
* GWT tests.
*/
public static Method getListIteratorUnmodifiableMethod() {
return Platform.getMethod(
ListListIteratorTester.class, "testListIterator_unmodifiable");
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
/**
* A generic JUnit test which tests operations on a NavigableSet. Can't be
* invoked directly; please see {@code SetTestSuiteBuilder}.
*
* @author Jesse Wilson
* @author Louis Wasserman
*/
public class SetNavigationTester<E> extends AbstractSetTester<E> {
private NavigableSet<E> navigableSet;
private List<E> values;
private E a;
private E b;
private E c;
@Override public void setUp() throws Exception {
super.setUp();
navigableSet = (NavigableSet<E>) getSet();
values = Helpers.copyToList(getSubjectGenerator().getSampleElements(
getSubjectGenerator().getCollectionSize().getNumElements()));
Collections.sort(values, navigableSet.comparator());
// some tests assume SEVERAL == 3
if (values.size() >= 1) {
a = values.get(0);
if (values.size() >= 3) {
b = values.get(1);
c = values.get(2);
}
}
}
/**
* Resets the contents of navigableSet to have elements a, c, for the
* navigation tests.
*/
protected void resetWithHole() {
super.resetContainer(getSubjectGenerator().create(a, c));
navigableSet = (NavigableSet<E>) getSet();
}
@CollectionSize.Require(ZERO)
public void testEmptySetFirst() {
try {
navigableSet.first();
fail();
} catch (NoSuchElementException e) {
}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptySetPollFirst() {
assertNull(navigableSet.pollFirst());
}
@CollectionSize.Require(ZERO)
public void testEmptySetNearby() {
assertNull(navigableSet.lower(samples.e0));
assertNull(navigableSet.floor(samples.e0));
assertNull(navigableSet.ceiling(samples.e0));
assertNull(navigableSet.higher(samples.e0));
}
@CollectionSize.Require(ZERO)
public void testEmptySetLast() {
try {
navigableSet.last();
fail();
} catch (NoSuchElementException e) {
}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptySetPollLast() {
assertNull(navigableSet.pollLast());
}
@CollectionSize.Require(ONE)
public void testSingletonSetFirst() {
assertEquals(a, navigableSet.first());
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonSetPollFirst() {
assertEquals(a, navigableSet.pollFirst());
assertTrue(navigableSet.isEmpty());
}
@CollectionSize.Require(ONE)
public void testSingletonSetNearby() {
assertNull(navigableSet.lower(samples.e0));
assertEquals(a, navigableSet.floor(samples.e0));
assertEquals(a, navigableSet.ceiling(samples.e0));
assertNull(navigableSet.higher(samples.e0));
}
@CollectionSize.Require(ONE)
public void testSingletonSetLast() {
assertEquals(a, navigableSet.last());
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonSetPollLast() {
assertEquals(a, navigableSet.pollLast());
assertTrue(navigableSet.isEmpty());
}
@CollectionSize.Require(SEVERAL)
public void testFirst() {
assertEquals(a, navigableSet.first());
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollFirst() {
assertEquals(a, navigableSet.pollFirst());
assertEquals(
values.subList(1, values.size()), Helpers.copyToList(navigableSet));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testPollFirstUnsupported() {
try {
navigableSet.pollFirst();
fail();
} catch (UnsupportedOperationException e) {
}
}
@CollectionSize.Require(SEVERAL)
public void testLower() {
resetWithHole();
assertEquals(null, navigableSet.lower(a));
assertEquals(a, navigableSet.lower(b));
assertEquals(a, navigableSet.lower(c));
}
@CollectionSize.Require(SEVERAL)
public void testFloor() {
resetWithHole();
assertEquals(a, navigableSet.floor(a));
assertEquals(a, navigableSet.floor(b));
assertEquals(c, navigableSet.floor(c));
}
@CollectionSize.Require(SEVERAL)
public void testCeiling() {
resetWithHole();
assertEquals(a, navigableSet.ceiling(a));
assertEquals(c, navigableSet.ceiling(b));
assertEquals(c, navigableSet.ceiling(c));
}
@CollectionSize.Require(SEVERAL)
public void testHigher() {
resetWithHole();
assertEquals(c, navigableSet.higher(a));
assertEquals(c, navigableSet.higher(b));
assertEquals(null, navigableSet.higher(c));
}
@CollectionSize.Require(SEVERAL)
public void testLast() {
assertEquals(c, navigableSet.last());
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollLast() {
assertEquals(c, navigableSet.pollLast());
assertEquals(
values.subList(0, values.size() - 1), Helpers.copyToList(navigableSet));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testPollLastUnsupported() {
try {
navigableSet.pollLast();
fail();
} catch (UnsupportedOperationException e) {
}
}
@CollectionSize.Require(SEVERAL)
public void testDescendingNavigation() {
List<E> descending = new ArrayList<E>();
for (Iterator<E> i = navigableSet.descendingIterator(); i.hasNext();) {
descending.add(i.next());
}
Collections.reverse(descending);
assertEquals(values, descending);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_RETAIN_ALL;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* A generic JUnit test which tests {@code retainAll} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class CollectionRetainAllTester<E> extends AbstractCollectionTester<E> {
/**
* A collection of elements to retain, along with a description for use in
* failure messages.
*/
private class Target {
private final Collection<E> toRetain;
private final String description;
private Target(Collection<E> toRetain, String description) {
this.toRetain = toRetain;
this.description = description;
}
@Override public String toString() {
return description;
}
}
private Target empty;
private Target disjoint;
private Target superset;
private Target nonEmptyProperSubset;
private Target sameElements;
private Target partialOverlap;
private Target containsDuplicates;
private Target nullSingleton;
@Override public void setUp() throws Exception {
super.setUp();
empty = new Target(emptyCollection(), "empty");
/*
* We test that nullSingleton.retainAll(disjointList) does NOT throw a
* NullPointerException when disjointList does not, so we can't use
* MinimalCollection, which throws NullPointerException on calls to
* contains(null).
*/
List<E> disjointList = Arrays.asList(samples.e3, samples.e4);
disjoint
= new Target(disjointList, "disjoint");
superset
= new Target(MinimalCollection.of(
samples.e0, samples.e1, samples.e2, samples.e3, samples.e4),
"superset");
nonEmptyProperSubset
= new Target(MinimalCollection.of(samples.e1), "subset");
sameElements
= new Target(Arrays.asList(createSamplesArray()), "sameElements");
containsDuplicates = new Target(
MinimalCollection.of(samples.e0, samples.e0, samples.e3, samples.e3),
"containsDuplicates");
partialOverlap
= new Target(MinimalCollection.of(samples.e2, samples.e3),
"partialOverlap");
nullSingleton
= new Target(Collections.<E>singleton(null), "nullSingleton");
}
// retainAll(empty)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(ZERO)
public void testRetainAll_emptyPreviouslyEmpty() {
expectReturnsFalse(empty);
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(ZERO)
public void testRetainAll_emptyPreviouslyEmptyUnsupported() {
expectReturnsFalseOrThrows(empty);
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRetainAll_emptyPreviouslyNonEmpty() {
expectReturnsTrue(empty);
expectContents();
expectMissing(samples.e0, samples.e1, samples.e2);
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRetainAll_emptyPreviouslyNonEmptyUnsupported() {
expectThrows(empty);
expectUnchanged();
}
// retainAll(disjoint)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(ZERO)
public void testRetainAll_disjointPreviouslyEmpty() {
expectReturnsFalse(disjoint);
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(ZERO)
public void testRetainAll_disjointPreviouslyEmptyUnsupported() {
expectReturnsFalseOrThrows(disjoint);
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRetainAll_disjointPreviouslyNonEmpty() {
expectReturnsTrue(disjoint);
expectContents();
expectMissing(samples.e0, samples.e1, samples.e2);
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRetainAll_disjointPreviouslyNonEmptyUnsupported() {
expectThrows(disjoint);
expectUnchanged();
}
// retainAll(superset)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
public void testRetainAll_superset() {
expectReturnsFalse(superset);
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
public void testRetainAll_supersetUnsupported() {
expectReturnsFalseOrThrows(superset);
expectUnchanged();
}
// retainAll(subset)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRetainAll_subset() {
expectReturnsTrue(nonEmptyProperSubset);
expectContents(nonEmptyProperSubset.toRetain);
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRetainAll_subsetUnsupported() {
expectThrows(nonEmptyProperSubset);
expectUnchanged();
}
// retainAll(sameElements)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
public void testRetainAll_sameElements() {
expectReturnsFalse(sameElements);
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
public void testRetainAll_sameElementsUnsupported() {
expectReturnsFalseOrThrows(sameElements);
expectUnchanged();
}
// retainAll(partialOverlap)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRetainAll_partialOverlap() {
expectReturnsTrue(partialOverlap);
expectContents(samples.e2);
}
@CollectionFeature.Require(absent = SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRetainAll_partialOverlapUnsupported() {
expectThrows(partialOverlap);
expectUnchanged();
}
// retainAll(containsDuplicates)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(ONE)
public void testRetainAll_containsDuplicatesSizeOne() {
expectReturnsFalse(containsDuplicates);
expectContents(samples.e0);
}
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRetainAll_containsDuplicatesSizeSeveral() {
expectReturnsTrue(containsDuplicates);
expectContents(samples.e0);
}
// retainAll(nullSingleton)
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(ZERO)
public void testRetainAll_nullSingletonPreviouslyEmpty() {
expectReturnsFalse(nullSingleton);
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRetainAll_nullSingletonPreviouslyNonEmpty() {
expectReturnsTrue(nullSingleton);
expectContents();
}
@CollectionFeature.Require({SUPPORTS_RETAIN_ALL, ALLOWS_NULL_VALUES})
@CollectionSize.Require(ONE)
public void testRetainAll_nullSingletonPreviouslySingletonWithNull() {
initCollectionWithNullElement();
expectReturnsFalse(nullSingleton);
expectContents(createArrayWithNullElement());
}
@CollectionFeature.Require({SUPPORTS_RETAIN_ALL, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRetainAll_nullSingletonPreviouslySeveralWithNull() {
initCollectionWithNullElement();
expectReturnsTrue(nullSingleton);
expectContents(nullSingleton.toRetain);
}
// nullSingleton.retainAll()
@CollectionFeature.Require({SUPPORTS_RETAIN_ALL, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testRetainAll_containsNonNullWithNull() {
initCollectionWithNullElement();
expectReturnsTrue(disjoint);
expectContents();
}
// retainAll(null)
/*
* AbstractCollection fails the retainAll(null) test when the subject
* collection is empty, but we'd still like to test retainAll(null) when we
* can. We split the test into empty and non-empty cases. This allows us to
* suppress only the former.
*/
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(ZERO)
public void testRetainAll_nullCollectionReferenceEmptySubject() {
try {
collection.retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException expected) {
}
}
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRetainAll_nullCollectionReferenceNonEmptySubject() {
try {
collection.retainAll(null);
fail("retainAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
private void expectReturnsTrue(Target target) {
String message
= Platform.format("retainAll(%s) should return true", target);
assertTrue(message, collection.retainAll(target.toRetain));
}
private void expectReturnsFalse(Target target) {
String message
= Platform.format("retainAll(%s) should return false", target);
assertFalse(message, collection.retainAll(target.toRetain));
}
private void expectThrows(Target target) {
try {
collection.retainAll(target.toRetain);
String message = Platform.format("retainAll(%s) should throw", target);
fail(message);
} catch (UnsupportedOperationException expected) {
}
}
private void expectReturnsFalseOrThrows(Target target) {
String message
= Platform.format("retainAll(%s) should return false or throw", target);
try {
assertFalse(message, collection.retainAll(target.toRetain));
} catch (UnsupportedOperationException tolerated) {
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import static java.util.Collections.emptyList;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import com.google.common.testing.SerializableTester;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A generic JUnit test which tests {@code subList()} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class ListSubListTester<E> extends AbstractListTester<E> {
public void testSubList_startNegative() {
try {
getList().subList(-1, 0);
fail("subList(-1, 0) should throw");
} catch (IndexOutOfBoundsException expected) {
}
}
public void testSubList_endTooLarge() {
try {
getList().subList(0, getNumElements() + 1);
fail("subList(0, size + 1) should throw");
} catch (IndexOutOfBoundsException expected) {
}
}
public void testSubList_startGreaterThanEnd() {
try {
getList().subList(1, 0);
fail("subList(1, 0) should throw");
} catch (IndexOutOfBoundsException expected) {
} catch (IllegalArgumentException expected) {
/*
* The subList() docs claim that this should be an
* IndexOutOfBoundsException, but many JDK implementations throw
* IllegalArgumentException:
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4506427
*/
}
}
public void testSubList_empty() {
assertEquals("subList(0, 0) should be empty",
emptyList(), getList().subList(0, 0));
}
public void testSubList_entireList() {
assertEquals("subList(0, size) should be equal to the original list",
getList(), getList().subList(0, getNumElements()));
}
@ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListRemoveAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.remove(0);
List<E> expected =
Arrays.asList(createSamplesArray()).subList(1, getNumElements());
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testSubList_subListAddAffectsOriginal() {
List<E> subList = getList().subList(0, 0);
subList.add(samples.e3);
expectAdded(0, samples.e3);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListSetAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.set(0, samples.e3);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.set(0, samples.e3);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSubList_originalListSetAffectsSubList() {
List<E> subList = getList().subList(0, 1);
getList().set(0, samples.e3);
assertEquals("A set() call to a list after a sublist has been created "
+ "should be reflected in the sublist",
Collections.singletonList(samples.e3), subList);
}
@ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListRemoveAffectsOriginalLargeList() {
List<E> subList = getList().subList(1, 3);
subList.remove(samples.e2);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.remove(2);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListAddAtIndexAffectsOriginalLargeList() {
List<E> subList = getList().subList(2, 3);
subList.add(0, samples.e3);
expectAdded(2, samples.e3);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListSetAffectsOriginalLargeList() {
List<E> subList = getList().subList(1, 2);
subList.set(0, samples.e3);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.set(1, samples.e3);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_originalListSetAffectsSubListLargeList() {
List<E> subList = getList().subList(1, 3);
getList().set(1, samples.e3);
assertEquals("A set() call to a list after a sublist has been created "
+ "should be reflected in the sublist",
Arrays.asList(samples.e3, samples.e2), subList);
}
public void testSubList_ofSubListEmpty() {
List<E> subList = getList().subList(0, 0).subList(0, 0);
assertEquals("subList(0, 0).subList(0, 0) should be an empty list",
emptyList(), subList);
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_ofSubListNonEmpty() {
List<E> subList = getList().subList(0, 2).subList(1, 2);
assertEquals("subList(0, 2).subList(1, 2) "
+ "should be a single-element list of the element at index 1",
Collections.singletonList(samples.e1), subList);
}
@CollectionSize.Require(absent = {ZERO})
public void testSubList_size() {
List<E> list = getList();
int size = getNumElements();
assertEquals(list.subList(0, size).size(),
size);
assertEquals(list.subList(0, size - 1).size(),
size - 1);
assertEquals(list.subList(1, size).size(),
size - 1);
assertEquals(list.subList(size, size).size(),
0);
assertEquals(list.subList(0, 0).size(),
0);
}
@CollectionSize.Require(absent = {ZERO})
public void testSubList_isEmpty() {
List<E> list = getList();
int size = getNumElements();
for (List<E> subList : Arrays.asList(
list.subList(0, size),
list.subList(0, size - 1),
list.subList(1, size),
list.subList(0, 0),
list.subList(size, size))) {
assertEquals(subList.isEmpty(), subList.size() == 0);
}
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_get() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(list.get(0), copy.get(0));
assertEquals(list.get(size - 1), copy.get(size - 1));
assertEquals(list.get(1), tail.get(0));
assertEquals(list.get(size - 1), tail.get(size - 2));
assertEquals(list.get(0), head.get(0));
assertEquals(list.get(size - 2), head.get(size - 2));
for (List<E> subList : Arrays.asList(copy, head, tail)) {
for (int index : Arrays.asList(-1, subList.size())) {
try {
subList.get(index);
fail("expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
}
}
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_contains() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertTrue(copy.contains(list.get(0)));
assertTrue(head.contains(list.get(0)));
assertTrue(tail.contains(list.get(1)));
// The following assumes all elements are distinct.
assertTrue(copy.contains(list.get(size - 1)));
assertTrue(head.contains(list.get(size - 2)));
assertTrue(tail.contains(list.get(size - 1)));
assertFalse(head.contains(list.get(size - 1)));
assertFalse(tail.contains(list.get(0)));
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_indexOf() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(copy.indexOf(list.get(0)),
0);
assertEquals(head.indexOf(list.get(0)),
0);
assertEquals(tail.indexOf(list.get(1)),
0);
// The following assumes all elements are distinct.
assertEquals(copy.indexOf(list.get(size - 1)),
size - 1);
assertEquals(head.indexOf(list.get(size - 2)),
size - 2);
assertEquals(tail.indexOf(list.get(size - 1)),
size - 2);
assertEquals(head.indexOf(list.get(size - 1)),
-1);
assertEquals(tail.indexOf(list.get(0)),
-1);
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_lastIndexOf() {
List<E> list = getList();
int size = list.size();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(copy.lastIndexOf(list.get(size - 1)),
size - 1);
assertEquals(head.lastIndexOf(list.get(size - 2)),
size - 2);
assertEquals(tail.lastIndexOf(list.get(size - 1)),
size - 2);
// The following assumes all elements are distinct.
assertEquals(copy.lastIndexOf(list.get(0)),
0);
assertEquals(head.lastIndexOf(list.get(0)),
0);
assertEquals(tail.lastIndexOf(list.get(1)),
0);
assertEquals(head.lastIndexOf(list.get(size - 1)),
-1);
assertEquals(tail.lastIndexOf(list.get(0)),
-1);
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testReserializeWholeSubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements()));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testReserializeEmptySubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, 0));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testReserializeSubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, 2));
}
/**
* Returns the {@link Method} instance for
* {@link #testSubList_originalListSetAffectsSubList()} so that tests
* of {@link CopyOnWriteArrayList} can suppress them with
* {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570631">Sun bug
* 6570631</a> is fixed.
*/
public static Method getSubListOriginalListSetAffectsSubListMethod() {
return Platform
.getMethod(ListSubListTester.class, "testSubList_originalListSetAffectsSubList");
}
/**
* Returns the {@link Method} instance for
* {@link #testSubList_originalListSetAffectsSubListLargeList()} ()} so that
* tests of {@link CopyOnWriteArrayList} can suppress them with
* {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570631">Sun bug
* 6570631</a> is fixed.
*/
public static Method
getSubListOriginalListSetAffectsSubListLargeListMethod() {
return Platform
.getMethod(ListSubListTester.class, "testSubList_originalListSetAffectsSubListLargeList");
}
/**
* Returns the {@link Method} instance for
* {@link #testSubList_subListRemoveAffectsOriginalLargeList()} so that tests
* of {@link CopyOnWriteArrayList} can suppress it with
* {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570575">Sun bug
* 6570575</a> is fixed.
*/
public static Method getSubListSubListRemoveAffectsOriginalLargeListMethod() {
return Platform.getMethod(
ListSubListTester.class, "testSubList_subListRemoveAffectsOriginalLargeList");
}
/*
* TODO: perform all List tests on subList(), but beware infinite recursion
*/
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_ALL_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static java.util.Collections.singletonList;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import java.util.List;
/**
* A generic JUnit test which tests {@code addAll(int, Collection)} operations
* on a list. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class ListAddAllAtIndexTester<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_supportedAllPresent() {
assertTrue("addAll(n, allPresent) should return true",
getList().addAll(0, MinimalCollection.of(samples.e0)));
expectAdded(0, samples.e0);
}
@ListFeature.Require(absent = SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_unsupportedAllPresent() {
try {
getList().addAll(0, MinimalCollection.of(samples.e0));
fail("addAll(n, allPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_supportedSomePresent() {
assertTrue("addAll(n, allPresent) should return true",
getList().addAll(0, MinimalCollection.of(samples.e0, samples.e3)));
expectAdded(0, samples.e0, samples.e3);
}
@ListFeature.Require(absent = SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_unsupportedSomePresent() {
try {
getList().addAll(0, MinimalCollection.of(samples.e0, samples.e3));
fail("addAll(n, allPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
public void testAddAllAtIndex_supportedNothing() {
assertFalse("addAll(n, nothing) should return false",
getList().addAll(0, emptyCollection()));
expectUnchanged();
}
@ListFeature.Require(absent = SUPPORTS_ADD_ALL_WITH_INDEX)
public void testAddAllAtIndex_unsupportedNothing() {
try {
assertFalse("addAll(n, nothing) should return false or throw",
getList().addAll(0, emptyCollection()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
public void testAddAllAtIndex_withDuplicates() {
MinimalCollection<E> elementsToAdd
= MinimalCollection.of(samples.e0, samples.e1, samples.e0, samples.e1);
assertTrue("addAll(n, hasDuplicates) should return true",
getList().addAll(0, elementsToAdd));
expectAdded(0, samples.e0, samples.e1, samples.e0, samples.e1);
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testAddAllAtIndex_nullSupported() {
List<E> containsNull = singletonList(null);
assertTrue("addAll(n, containsNull) should return true",
getList().addAll(0, containsNull));
/*
* We need (E) to force interpretation of null as the single element of a
* varargs array, not the array itself
*/
expectAdded(0, (E) null);
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testAddAllAtIndex_nullUnsupported() {
List<E> containsNull = singletonList(null);
try {
getList().addAll(0, containsNull);
fail("addAll(n, containsNull) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported addAll(n, containsNull)");
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testAddAllAtIndex_middle() {
assertTrue("addAll(middle, disjoint) should return true",
getList().addAll(getNumElements() / 2, createDisjointCollection()));
expectAdded(getNumElements() / 2, createDisjointCollection());
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAllAtIndex_end() {
assertTrue("addAll(end, disjoint) should return true",
getList().addAll(getNumElements(), createDisjointCollection()));
expectAdded(getNumElements(), createDisjointCollection());
}
@ListFeature.Require(SUPPORTS_ADD_ALL_WITH_INDEX)
public void testAddAllAtIndex_nullCollectionReference() {
try {
getList().addAll(0, null);
fail("addAll(n, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_negative() {
try {
getList().addAll(-1, MinimalCollection.of(samples.e3));
fail("addAll(-1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAllAtIndex_tooLarge() {
try {
getList().addAll(getNumElements() + 1, MinimalCollection.of(samples.e3));
fail("addAll(size + 1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE_ALL;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests removeAll operations on a list. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class ListRemoveAllTester<E> extends AbstractListTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRemoveAll_duplicate() {
ArrayWithDuplicate<E> arrayAndDuplicate = createArrayWithDuplicateElement();
collection = getSubjectGenerator().create(arrayAndDuplicate.elements);
E duplicate = arrayAndDuplicate.duplicate;
assertTrue("removeAll(intersectingCollection) should return true",
getList().removeAll(MinimalCollection.of(duplicate)));
assertFalse("after removeAll(e), a collection should not contain e even " +
"if it initially contained e more than once.",
getList().contains(duplicate));
}
// All other cases are covered by CollectionRemoveAllTester.
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.REJECTS_DUPLICATES_AT_CREATION;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code indexOf()} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
public class ListIndexOfTester<E> extends AbstractListIndexOfTester<E> {
@Override protected int find(Object o) {
return getList().indexOf(o);
}
@Override protected String getMethodName() {
return "indexOf";
}
@CollectionFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testIndexOf_duplicate() {
E[] array = createSamplesArray();
array[getNumElements() / 2] = samples.e0;
collection = getSubjectGenerator().create(array);
assertEquals("indexOf(duplicate) should return index of first occurrence",
0, getList().indexOf(samples.e0));
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* A generic JUnit test which tests {@code iterator} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
public class CollectionIteratorTester<E> extends AbstractCollectionTester<E> {
public void testIterator() {
List<E> iteratorElements = new ArrayList<E>();
for (E element : collection) { // uses iterator()
iteratorElements.add(element);
}
Helpers.assertEqualIgnoringOrder(
Arrays.asList(createSamplesArray()), iteratorElements);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testIterationOrdering() {
List<E> iteratorElements = new ArrayList<E>();
for (E element : collection) { // uses iterator()
iteratorElements.add(element);
}
List<E> expected = Helpers.copyToList(getOrderedElements());
assertEquals("Different ordered iteration", expected, iteratorElements);
}
// TODO: switch to DerivedIteratorTestSuiteBuilder
@CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE})
public void testIterator_knownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_REMOVE)
public void testIterator_knownOrderRemoveUnsupported() {
runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_REMOVE)
public void testIterator_unknownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER,
getSampleElements());
}
@CollectionFeature.Require(absent = {KNOWN_ORDER, SUPPORTS_REMOVE})
public void testIterator_unknownOrderRemoveUnsupported() {
runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER,
getSampleElements());
}
private void runIteratorTest(Set<IteratorFeature> features,
IteratorTester.KnownOrder knownOrder, Iterable<E> elements) {
new IteratorTester<E>(Platform.collectionIteratorTesterNumIterations(), features, elements,
knownOrder) {
{
// TODO: don't set this universally
ignoreSunJavaBug6529795();
}
@Override protected Iterator<E> newTargetIterator() {
resetCollection();
return collection.iterator();
}
@Override protected void verify(List<E> elements) {
expectContents(elements);
}
}.test();
}
/**
* Returns the {@link Method} instance for
* {@link #testIterator_knownOrderRemoveSupported()} so that tests of
* {@link CopyOnWriteArraySet} and {@link CopyOnWriteArrayList} can suppress
* it with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6570575">Sun bug
* 6570575</a> is fixed.
*/
public static Method getIteratorKnownOrderRemoveSupportedMethod() {
return Platform.getMethod(
CollectionIteratorTester.class, "testIterator_knownOrderRemoveSupported");
}
/**
* Returns the {@link Method} instance for
* {@link #testIterator_unknownOrderRemoveSupported()} so that tests of
* classes with unmodifiable iterators can suppress it.
*/
public static Method getIteratorUnknownOrderRemoveSupportedMethod() {
return Platform.getMethod(
CollectionIteratorTester.class, "testIterator_unknownOrderRemoveSupported");
}
public void testIteratorNoSuchElementException() {
Iterator<E> iterator = collection.iterator();
while (iterator.hasNext()) {
iterator.next();
}
try {
iterator.next();
fail("iterator.next() should throw NoSuchElementException");
} catch (NoSuchElementException expected) {}
}
/**
* Returns the {@link Method} instance for
* {@link #testIterator_knownOrderRemoveUnsupported()} so that tests of
* {@code ArrayStack} can suppress it with
* {@code FeatureSpecificTestSuiteBuilder.suppressing()}. {@code ArrayStack}
* supports {@code remove()} on only the first element, and the iterator
* tester can't handle that.
*/
public static Method getIteratorKnownOrderRemoveUnsupportedMethod() {
return Platform.getMethod(
CollectionIteratorTester.class, "testIterator_knownOrderRemoveUnsupported");
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import com.google.common.collect.testing.AbstractCollectionTester;
/**
* Tests {@link java.util.Collection#equals}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class CollectionEqualsTester<E> extends AbstractCollectionTester<E> {
public void testEquals_self() {
assertTrue("An Object should be equal to itself.",
collection.equals(collection));
}
public void testEquals_null() {
//noinspection ObjectEqualsNull
assertFalse("An object should not be equal to null.",
collection.equals(null));
}
public void testEquals_notACollection() {
//noinspection EqualsBetweenInconvertibleTypes
assertFalse("A Collection should never equal an "
+ "object that is not a Collection.",
collection.equals("huh?"));
}
} | Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code remove(Object)} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class ListRemoveTester<E> extends AbstractListTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRemove_duplicate() {
ArrayWithDuplicate<E> arrayAndDuplicate = createArrayWithDuplicateElement();
collection = getSubjectGenerator().create(arrayAndDuplicate.elements);
E duplicate = arrayAndDuplicate.duplicate;
int firstIndex = getList().indexOf(duplicate);
int initialSize = getList().size();
assertTrue("remove(present) should return true",
getList().remove(duplicate));
assertTrue("After remove(duplicate), a list should still contain "
+ "the duplicate element", getList().contains(duplicate));
assertFalse("remove(duplicate) should remove the first instance of the "
+ "duplicate element in the list",
firstIndex == getList().indexOf(duplicate));
assertEquals("remove(present) should decrease the size of a list by one.",
initialSize - 1, getList().size());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_CLEAR;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code clear()} operations on a map.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
* @author Chris Povirk
*/
public class MapClearTester<K, V> extends AbstractMapTester<K, V> {
@MapFeature.Require(SUPPORTS_CLEAR)
public void testClear() {
getMap().clear();
assertTrue("After clear(), a map should be empty.",
getMap().isEmpty());
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_CLEAR})
@CollectionSize.Require(absent = ZERO)
public void testClearConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
getMap().clear();
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_CLEAR})
@CollectionSize.Require(absent = ZERO)
public void testClearConcurrentWithKeySetIteration() {
try {
Iterator<K> iterator = getMap().keySet().iterator();
getMap().clear();
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_CLEAR})
@CollectionSize.Require(absent = ZERO)
public void testClearConcurrentWithValuesIteration() {
try {
Iterator<V> iterator = getMap().values().iterator();
getMap().clear();
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_CLEAR)
@CollectionSize.Require(absent = ZERO)
public void testClear_unsupported() {
try {
getMap().clear();
fail("clear() should throw UnsupportedOperation if a map does "
+ "not support it and is not empty.");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_CLEAR)
@CollectionSize.Require(ZERO)
public void testClear_unsupportedByEmptyCollection() {
try {
getMap().clear();
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD_ALL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests addAll operations on a set. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.SetTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class SetAddAllTester<E> extends AbstractSetTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_supportedSomePresent() {
assertTrue("add(somePresent) should return true",
getSet().addAll(MinimalCollection.of(samples.e3, samples.e0)));
expectAdded(samples.e3);
}
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
public void testAddAll_withDuplicates() {
MinimalCollection<E> elementsToAdd
= MinimalCollection.of(samples.e3, samples.e4, samples.e3, samples.e4);
assertTrue("add(hasDuplicates) should return true",
getSet().addAll(elementsToAdd));
expectAdded(samples.e3, samples.e4);
}
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_supportedAllPresent() {
assertFalse("add(allPresent) should return false",
getSet().addAll(MinimalCollection.of(samples.e0)));
expectUnchanged();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import com.google.common.collect.testing.AbstractCollectionTester;
import java.util.Queue;
/**
* Base class for queue collection tests.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
public class AbstractQueueTester<E> extends AbstractCollectionTester<E> {
protected final Queue<E> getQueue() {
return (Queue<E>) collection;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_QUERIES;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* A generic JUnit test which tests {@code containsKey()} operations on a map.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class MapContainsKeyTester<K, V> extends AbstractMapTester<K, V> {
@CollectionSize.Require(absent = ZERO)
public void testContains_yes() {
assertTrue("containsKey(present) should return true",
getMap().containsKey(samples.e0.getKey()));
}
public void testContains_no() {
assertFalse("containsKey(notPresent) should return false",
getMap().containsKey(samples.e3.getKey()));
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testContains_nullNotContainedButAllowed() {
assertFalse("containsKey(null) should return false",
getMap().containsKey(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContains_nullNotContainedAndUnsupported() {
expectNullKeyMissingWhenNullKeysUnsupported(
"containsKey(null) should return false or throw");
}
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testContains_nonNullWhenNullContained() {
initMapWithNullKey();
assertFalse("containsKey(notPresent) should return false",
getMap().containsKey(samples.e3.getKey()));
}
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testContains_nullContained() {
initMapWithNullKey();
assertTrue("containsKey(null) should return true",
getMap().containsKey(null));
}
public void testContains_wrongType() {
try {
//noinspection SuspiciousMethodCalls
assertFalse("containsKey(wrongType) should return false or throw",
getMap().containsKey(WrongType.VALUE));
} catch (ClassCastException tolerated) {
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code remove} operations on a map. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class MapRemoveTester<K, V> extends AbstractMapTester<K, V> {
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemove_present() {
int initialSize = getMap().size();
assertEquals("remove(present) should return the associated value",
samples.e0.getValue(), getMap().remove(samples.e0.getKey()));
assertEquals("remove(present) should decrease a map's size by one.",
initialSize - 1, getMap().size());
expectMissing(samples.e0);
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_REMOVE})
@CollectionSize.Require(absent = ZERO)
public void testRemovePresentConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
getMap().remove(samples.e0.getKey());
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_REMOVE})
@CollectionSize.Require(absent = ZERO)
public void testRemovePresentConcurrentWithKeySetIteration() {
try {
Iterator<K> iterator = getMap().keySet().iterator();
getMap().remove(samples.e0.getKey());
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_REMOVE})
@CollectionSize.Require(absent = ZERO)
public void testRemovePresentConcurrentWithValuesIteration() {
try {
Iterator<V> iterator = getMap().values().iterator();
getMap().remove(samples.e0.getKey());
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemove_notPresent() {
assertNull("remove(notPresent) should return null",
getMap().remove(samples.e3.getKey()));
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_KEYS})
@CollectionSize.Require(absent = ZERO)
public void testRemove_nullPresent() {
initMapWithNullKey();
int initialSize = getMap().size();
assertEquals("remove(null) should return the associated value",
getValueForNullKey(), getMap().remove(null));
assertEquals("remove(present) should decrease a map's size by one.",
initialSize - 1, getMap().size());
expectMissing(entry(null, getValueForNullKey()));
}
@MapFeature.Require(absent = SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemove_unsupported() {
try {
getMap().remove(samples.e0.getKey());
fail("remove(present) should throw UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
assertEquals("remove(present) should not remove the element",
samples.e0.getValue(), get(samples.e0.getKey()));
}
@MapFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemove_unsupportedNotPresent() {
try {
assertNull("remove(notPresent) should return null or throw "
+ "UnsupportedOperationException",
getMap().remove(samples.e3.getKey()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@MapFeature.Require(
value = SUPPORTS_REMOVE,
absent = ALLOWS_NULL_QUERIES)
public void testRemove_nullQueriesNotSupported() {
try {
assertNull("remove(null) should return null or throw "
+ "NullPointerException",
getMap().remove(null));
} catch (NullPointerException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES})
public void testRemove_nullSupportedMissing() {
assertNull("remove(null) should return null", getMap().remove(null));
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_REMOVE)
public void testRemove_wrongType() {
try {
assertNull(getMap().remove(WrongType.VALUE));
} catch (ClassCastException tolerated) {
}
expectUnchanged();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD_ALL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code addAll(Collection)} operations on a
* list. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class ListAddAllTester<E> extends AbstractListTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_supportedAllPresent() {
assertTrue("addAll(allPresent) should return true",
getList().addAll(MinimalCollection.of(samples.e0)));
expectAdded(samples.e0);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD_ALL)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_unsupportedAllPresent() {
try {
getList().addAll(MinimalCollection.of(samples.e0));
fail("addAll(allPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
public void testAddAll_withDuplicates() {
MinimalCollection<E> elementsToAdd
= MinimalCollection.of(samples.e0, samples.e1, samples.e0, samples.e1);
assertTrue("addAll(hasDuplicates) should return true",
getList().addAll(elementsToAdd));
expectAdded(samples.e0, samples.e1, samples.e0, samples.e1);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect.testing.testers;
import java.lang.reflect.Method;
/**
* This class is emulated in GWT.
*
* @author Hayward Chan
*/
class Platform {
/**
* Delegate to {@link Class#getMethod(String, Class[])}. Not
* usable in GWT.
*/
static Method getMethod(Class<?> clazz, String methodName) {
try {
return clazz.getMethod(methodName);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
/**
* Format the template with args, only supports the placeholder
* {@code %s}.
*/
static String format(String template, Object... args) {
return String.format(template, args);
}
/** See {@link ListListIteratorTester} */
static int listListIteratorTesterNumIterations() {
return 4;
}
/** See {@link CollectionIteratorTester} */
static int collectionIteratorTesterNumIterations() {
return 5;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT_ALL;
import static java.util.Collections.singletonList;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code putAll} operations on a map. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class MapPutAllTester<K, V> extends AbstractMapTester<K, V> {
private List<Entry<K, V>> containsNullKey;
private List<Entry<K, V>> containsNullValue;
@Override public void setUp() throws Exception {
super.setUp();
containsNullKey = singletonList(entry(null, samples.e3.getValue()));
containsNullValue = singletonList(entry(samples.e3.getKey(), null));
}
@MapFeature.Require(SUPPORTS_PUT_ALL)
public void testPutAll_supportedNothing() {
getMap().putAll(emptyMap());
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT_ALL)
public void testPutAll_unsupportedNothing() {
try {
getMap().putAll(emptyMap());
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT_ALL)
public void testPutAll_supportedNonePresent() {
putAll(createDisjointCollection());
expectAdded(samples.e3, samples.e4);
}
@MapFeature.Require(absent = SUPPORTS_PUT_ALL)
public void testPutAll_unsupportedNonePresent() {
try {
putAll(createDisjointCollection());
fail("putAll(nonePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3, samples.e4);
}
@MapFeature.Require(SUPPORTS_PUT_ALL)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_supportedSomePresent() {
putAll(MinimalCollection.of(samples.e3, samples.e0));
expectAdded(samples.e3);
}
@MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_PUT_ALL })
@CollectionSize.Require(absent = ZERO)
public void testPutAllSomePresentConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
putAll(MinimalCollection.of(samples.e3, samples.e0));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_PUT_ALL)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_unsupportedSomePresent() {
try {
putAll(MinimalCollection.of(samples.e3, samples.e0));
fail("putAll(somePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT_ALL)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_unsupportedAllPresent() {
try {
putAll(MinimalCollection.of(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_PUT_ALL,
ALLOWS_NULL_KEYS})
public void testPutAll_nullKeySupported() {
putAll(containsNullKey);
expectAdded(containsNullKey.get(0));
}
@MapFeature.Require(value = SUPPORTS_PUT_ALL,
absent = ALLOWS_NULL_KEYS)
public void testAdd_nullKeyUnsupported() {
try {
putAll(containsNullKey);
fail("putAll(containsNullKey) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullKeyMissingWhenNullKeysUnsupported(
"Should not contain null key after unsupported " +
"putAll(containsNullKey)");
}
@MapFeature.Require({SUPPORTS_PUT_ALL,
ALLOWS_NULL_VALUES})
public void testPutAll_nullValueSupported() {
putAll(containsNullValue);
expectAdded(containsNullValue.get(0));
}
@MapFeature.Require(value = SUPPORTS_PUT_ALL,
absent = ALLOWS_NULL_VALUES)
public void testAdd_nullValueUnsupported() {
try {
putAll(containsNullValue);
fail("putAll(containsNullValue) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null value after unsupported " +
"putAll(containsNullValue)");
}
@MapFeature.Require(SUPPORTS_PUT_ALL)
public void testPutAll_nullCollectionReference() {
try {
getMap().putAll(null);
fail("putAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
private Map<K, V> emptyMap() {
return Collections.emptyMap();
}
private void putAll(Iterable<Entry<K, V>> entries) {
Map<K, V> map = new LinkedHashMap<K, V>();
for (Entry<K, V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
getMap().putAll(map);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.testing.SerializableTester;
/**
* Basic reserialization test for collections.
*
* @author Louis Wasserman
*/
public class CollectionSerializationTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SERIALIZABLE)
public void testReserialize() {
// For a bare Collection, the most we can guarantee is that the elements are preserved.
Helpers.assertEqualIgnoringOrder(
actualContents(),
SerializableTester.reserialize(actualContents()));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code put} operations on a map. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class MapPutTester<K, V> extends AbstractMapTester<K, V> {
private Entry<K, V> nullKeyEntry;
private Entry<K, V> nullValueEntry;
private Entry<K, V> nullKeyValueEntry;
private Entry<K, V> presentKeyNullValueEntry;
@Override public void setUp() throws Exception {
super.setUp();
nullKeyEntry = entry(null, samples.e3.getValue());
nullValueEntry = entry(samples.e3.getKey(), null);
nullKeyValueEntry = entry(null, null);
presentKeyNullValueEntry = entry(samples.e0.getKey(), null);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPut_supportedNotPresent() {
assertNull("put(notPresent, value) should return null", put(samples.e3));
expectAdded(samples.e3);
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
public void testPutAbsentConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
public void testPutAbsentConcurrentWithKeySetIteration() {
try {
Iterator<K> iterator = getMap().keySet().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
public void testPutAbsentConcurrentWithValueIteration() {
try {
Iterator<V> iterator = getMap().values().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPut_unsupportedNotPresent() {
try {
put(samples.e3);
fail("put(notPresent, value) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPut_unsupportedPresentExistingValue() {
try {
assertEquals("put(present, existingValue) should return present or throw",
samples.e0.getValue(), put(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPut_unsupportedPresentDifferentValue() {
try {
getMap().put(samples.e0.getKey(), samples.e3.getValue());
fail("put(present, differentValue) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPut_nullKeySupportedNotPresent() {
assertNull("put(null, value) should return null", put(nullKeyEntry));
expectAdded(nullKeyEntry);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
@CollectionSize.Require(absent = ZERO)
public void testPut_nullKeySupportedPresent() {
Entry<K, V> newEntry = entry(null, samples.e3.getValue());
initMapWithNullKey();
assertEquals("put(present, value) should return the associated value",
getValueForNullKey(), put(newEntry));
Entry<K, V>[] expected = createArrayWithNullKey();
expected[getNullLocation()] = newEntry;
expectContents(expected);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS)
public void testPut_nullKeyUnsupported() {
try {
put(nullKeyEntry);
fail("put(null, value) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullKeyMissingWhenNullKeysUnsupported(
"Should not contain null key after unsupported put(null, value)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPut_nullValueSupported() {
assertNull("put(key, null) should return null", put(nullValueEntry));
expectAdded(nullValueEntry);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPut_nullValueUnsupported() {
try {
put(nullValueEntry);
fail("put(key, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null value after unsupported put(key, null)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceWithNullValueSupported() {
assertEquals("put(present, null) should return the associated value",
samples.e0.getValue(), put(presentKeyNullValueEntry));
expectReplacement(presentKeyNullValueEntry);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceWithNullValueUnsupported() {
try {
put(presentKeyNullValueEntry);
fail("put(present, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null after unsupported put(present, null)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceNullValueWithNullSupported() {
initMapWithNullValue();
assertNull("put(present, null) should return the associated value (null)",
getMap().put(getKeyForNullValue(), null));
expectContents(createArrayWithNullValue());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceNullValueWithNonNullSupported() {
Entry<K, V> newEntry = entry(getKeyForNullValue(), samples.e3.getValue());
initMapWithNullValue();
assertNull("put(present, value) should return the associated value (null)",
put(newEntry));
Entry<K, V>[] expected = createArrayWithNullValue();
expected[getNullLocation()] = newEntry;
expectContents(expected);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
public void testPut_nullKeyAndValueSupported() {
assertNull("put(null, null) should return null", put(nullKeyValueEntry));
expectAdded(nullKeyValueEntry);
}
private V put(Map.Entry<K, V> entry) {
return getMap().put(entry.getKey(), entry.getValue());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import com.google.common.collect.testing.features.CollectionFeature;
/**
* A generic JUnit test which tests offer operations on a queue. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class QueueOfferTester<E> extends AbstractQueueTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testOffer_supportedNotPresent() {
assertTrue("offer(notPresent) should return true",
getQueue().offer(samples.e3));
expectAdded(samples.e3);
}
@CollectionFeature.Require({SUPPORTS_ADD, ALLOWS_NULL_VALUES})
public void testOffer_nullSupported() {
assertTrue("offer(null) should return true", getQueue().offer(null));
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES)
public void testOffer_nullUnsupported() {
try {
getQueue().offer(null);
fail("offer(null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported offer(null)");
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import com.google.common.collect.testing.MinimalSet;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Tests {@link List#equals}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class ListEqualsTester<E> extends AbstractListTester<E> {
public void testEquals_otherListWithSameElements() {
assertTrue(
"A List should equal any other List containing the same elements.",
getList().equals(new ArrayList<E>(getSampleElements())));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
public void testEquals_otherListWithDifferentElements() {
ArrayList<E> other = new ArrayList<E>(getSampleElements());
other.set(other.size() / 2, getSubjectGenerator().samples().e3);
assertFalse(
"A List should not equal another List containing different elements.",
getList().equals(other));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
public void testEquals_otherListContainingNull() {
List<E> other = new ArrayList<E>(getSampleElements());
other.set(other.size() / 2, null);
assertFalse("Two Lists should not be equal if exactly one of them has "
+ "null at a given index.",
getList().equals(other));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testEquals_containingNull() {
ArrayList<E> elements = new ArrayList<E>(getSampleElements());
elements.set(elements.size() / 2, null);
collection = getSubjectGenerator().create(elements.toArray());
List<E> other = new ArrayList<E>(getSampleElements());
assertFalse("Two Lists should not be equal if exactly one of them has "
+ "null at a given index.",
getList().equals(other));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
public void testEquals_shorterList() {
Collection<E> fewerElements = getSampleElements(getNumElements() - 1);
assertFalse("Lists of different sizes should not be equal.",
getList().equals(new ArrayList<E>(fewerElements)));
}
public void testEquals_longerList() {
Collection<E> moreElements = getSampleElements(getNumElements() + 1);
assertFalse("Lists of different sizes should not be equal.",
getList().equals(new ArrayList<E>(moreElements)));
}
public void testEquals_set() {
assertFalse("A List should never equal a Set.",
getList().equals(MinimalSet.from(getList())));
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.NoSuchElementException;
/**
* A generic JUnit test which tests {@code element()} operations on a queue.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
public class QueueElementTester<E> extends AbstractQueueTester<E> {
@CollectionSize.Require(ZERO)
public void testElement_empty() {
try {
getQueue().element();
fail("emptyQueue.element() should throw");
} catch (NoSuchElementException expected) {}
expectUnchanged();
}
@CollectionSize.Require(ONE)
public void testElement_size1() {
assertEquals("size1Queue.element() should return first element",
samples.e0, getQueue().element());
expectUnchanged();
}
@CollectionFeature.Require(KNOWN_ORDER)
@CollectionSize.Require(SEVERAL)
public void testElement_sizeMany() {
assertEquals("sizeManyQueue.element() should return first element",
samples.e0, getQueue().element());
expectUnchanged();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code isEmpty()} operations on a
* map. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public class MapIsEmptyTester<K, V> extends AbstractMapTester<K, V> {
@CollectionSize.Require(ZERO)
public void testIsEmpty_yes() {
assertTrue("isEmpty() should return true", getMap().isEmpty());
}
@CollectionSize.Require(absent = ZERO)
public void testIsEmpty_no() {
assertFalse("isEmpty() should return false", getMap().isEmpty());
}
} | Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
/**
* A generic JUnit test which tests operations on a NavigableMap. Can't be
* invoked directly; please see {@code MapTestSuiteBuilder}.
*
* @author Jesse Wilson
* @author Louis Wasserman
*/
public class MapNavigationTester<K, V> extends AbstractMapTester<K, V> {
private NavigableMap<K, V> navigableMap;
private List<Entry<K, V>> entries;
private Entry<K, V> a;
private Entry<K, V> b;
private Entry<K, V> c;
@Override public void setUp() throws Exception {
super.setUp();
navigableMap = (NavigableMap<K, V>) getMap();
entries = Helpers.copyToList(getSubjectGenerator().getSampleElements(
getSubjectGenerator().getCollectionSize().getNumElements()));
Collections.sort(entries, Helpers.<K, V>entryComparator(navigableMap.comparator()));
// some tests assume SEVERAL == 3
if (entries.size() >= 1) {
a = entries.get(0);
if (entries.size() >= 3) {
b = entries.get(1);
c = entries.get(2);
}
}
}
/**
* Resets the contents of navigableMap to have entries a, c, for the
* navigation tests.
*/
@SuppressWarnings("unchecked") // Needed to stop Eclipse whining
private void resetWithHole() {
Entry<K, V>[] entries = new Entry[] {a, c};
super.resetMap(entries);
navigableMap = (NavigableMap<K, V>) getMap();
}
@CollectionSize.Require(ZERO)
public void testEmptyMapFirst() {
assertNull(navigableMap.firstEntry());
try {
navigableMap.firstKey();
fail();
} catch (NoSuchElementException e) {
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptyMapPollFirst() {
assertNull(navigableMap.pollFirstEntry());
}
@CollectionSize.Require(ZERO)
public void testEmptyMapNearby() {
assertNull(navigableMap.lowerEntry(samples.e0.getKey()));
assertNull(navigableMap.lowerKey(samples.e0.getKey()));
assertNull(navigableMap.floorEntry(samples.e0.getKey()));
assertNull(navigableMap.floorKey(samples.e0.getKey()));
assertNull(navigableMap.ceilingEntry(samples.e0.getKey()));
assertNull(navigableMap.ceilingKey(samples.e0.getKey()));
assertNull(navigableMap.higherEntry(samples.e0.getKey()));
assertNull(navigableMap.higherKey(samples.e0.getKey()));
}
@CollectionSize.Require(ZERO)
public void testEmptyMapLast() {
assertNull(navigableMap.lastEntry());
try {
assertNull(navigableMap.lastKey());
fail();
} catch (NoSuchElementException e) {
}
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testEmptyMapPollLast() {
assertNull(navigableMap.pollLastEntry());
}
@CollectionSize.Require(ONE)
public void testSingletonMapFirst() {
assertEquals(a, navigableMap.firstEntry());
assertEquals(a.getKey(), navigableMap.firstKey());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonMapPollFirst() {
assertEquals(a, navigableMap.pollFirstEntry());
assertTrue(navigableMap.isEmpty());
}
@CollectionSize.Require(ONE)
public void testSingletonMapNearby() {
assertNull(navigableMap.lowerEntry(samples.e0.getKey()));
assertNull(navigableMap.lowerKey(samples.e0.getKey()));
assertEquals(a, navigableMap.floorEntry(samples.e0.getKey()));
assertEquals(a.getKey(), navigableMap.floorKey(samples.e0.getKey()));
assertEquals(a, navigableMap.ceilingEntry(samples.e0.getKey()));
assertEquals(a.getKey(), navigableMap.ceilingKey(samples.e0.getKey()));
assertNull(navigableMap.higherEntry(samples.e0.getKey()));
assertNull(navigableMap.higherKey(samples.e0.getKey()));
}
@CollectionSize.Require(ONE)
public void testSingletonMapLast() {
assertEquals(a, navigableMap.lastEntry());
assertEquals(a.getKey(), navigableMap.lastKey());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testSingletonMapPollLast() {
assertEquals(a, navigableMap.pollLastEntry());
assertTrue(navigableMap.isEmpty());
}
@CollectionSize.Require(SEVERAL)
public void testFirst() {
assertEquals(a, navigableMap.firstEntry());
assertEquals(a.getKey(), navigableMap.firstKey());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollFirst() {
assertEquals(a, navigableMap.pollFirstEntry());
assertEquals(entries.subList(1, entries.size()),
Helpers.copyToList(navigableMap.entrySet()));
}
@MapFeature.Require(absent = SUPPORTS_REMOVE)
public void testPollFirstUnsupported() {
try {
navigableMap.pollFirstEntry();
fail();
} catch (UnsupportedOperationException e) {
}
}
@CollectionSize.Require(SEVERAL)
public void testLower() {
resetWithHole();
assertEquals(null, navigableMap.lowerEntry(a.getKey()));
assertEquals(null, navigableMap.lowerKey(a.getKey()));
assertEquals(a, navigableMap.lowerEntry(b.getKey()));
assertEquals(a.getKey(), navigableMap.lowerKey(b.getKey()));
assertEquals(a, navigableMap.lowerEntry(c.getKey()));
assertEquals(a.getKey(), navigableMap.lowerKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testFloor() {
resetWithHole();
assertEquals(a, navigableMap.floorEntry(a.getKey()));
assertEquals(a.getKey(), navigableMap.floorKey(a.getKey()));
assertEquals(a, navigableMap.floorEntry(b.getKey()));
assertEquals(a.getKey(), navigableMap.floorKey(b.getKey()));
assertEquals(c, navigableMap.floorEntry(c.getKey()));
assertEquals(c.getKey(), navigableMap.floorKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testCeiling() {
resetWithHole();
assertEquals(a, navigableMap.ceilingEntry(a.getKey()));
assertEquals(a.getKey(), navigableMap.ceilingKey(a.getKey()));
assertEquals(c, navigableMap.ceilingEntry(b.getKey()));
assertEquals(c.getKey(), navigableMap.ceilingKey(b.getKey()));
assertEquals(c, navigableMap.ceilingEntry(c.getKey()));
assertEquals(c.getKey(), navigableMap.ceilingKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testHigher() {
resetWithHole();
assertEquals(c, navigableMap.higherEntry(a.getKey()));
assertEquals(c.getKey(), navigableMap.higherKey(a.getKey()));
assertEquals(c, navigableMap.higherEntry(b.getKey()));
assertEquals(c.getKey(), navigableMap.higherKey(b.getKey()));
assertEquals(null, navigableMap.higherEntry(c.getKey()));
assertEquals(null, navigableMap.higherKey(c.getKey()));
}
@CollectionSize.Require(SEVERAL)
public void testLast() {
assertEquals(c, navigableMap.lastEntry());
assertEquals(c.getKey(), navigableMap.lastKey());
}
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollLast() {
assertEquals(c, navigableMap.pollLastEntry());
assertEquals(entries.subList(0, entries.size() - 1),
Helpers.copyToList(navigableMap.entrySet()));
}
@MapFeature.Require(absent = SUPPORTS_REMOVE)
@CollectionSize.Require(SEVERAL)
public void testPollLastUnsupported() {
try {
navigableMap.pollLastEntry();
fail();
} catch (UnsupportedOperationException e) {
}
}
@CollectionSize.Require(SEVERAL)
public void testDescendingNavigation() {
List<Entry<K, V>> descending = new ArrayList<Entry<K, V>>();
for (Entry<K, V> entry : navigableMap.descendingMap().entrySet()) {
descending.add(entry);
}
Collections.reverse(descending);
assertEquals(entries, descending);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import java.lang.reflect.Method;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code add(int, Object)} operations on a
* list. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class ListAddAtIndexTester<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAtIndex_supportedPresent() {
getList().add(0, samples.e0);
expectAdded(0, samples.e0);
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
/*
* absent = ZERO isn't required, since unmodList.add() must
* throw regardless, but it keeps the method name accurate.
*/
public void testAddAtIndex_unsupportedPresent() {
try {
getList().add(0, samples.e0);
fail("add(n, present) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_supportedNotPresent() {
getList().add(0, samples.e3);
expectAdded(0, samples.e3);
}
@CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION)
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndexConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
getList().add(0, samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_unsupportedNotPresent() {
try {
getList().add(0, samples.e3);
fail("add(n, notPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testAddAtIndex_middle() {
getList().add(getNumElements() / 2, samples.e3);
expectAdded(getNumElements() / 2, samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAtIndex_end() {
getList().add(getNumElements(), samples.e3);
expectAdded(getNumElements(), samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testAddAtIndex_nullSupported() {
getList().add(0, null);
expectAdded(0, (E) null);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testAddAtIndex_nullUnsupported() {
try {
getList().add(0, null);
fail("add(n, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported add(n, null)");
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_negative() {
try {
getList().add(-1, samples.e3);
fail("add(-1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_tooLarge() {
try {
getList().add(getNumElements() + 1, samples.e3);
fail("add(size + 1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
/**
* Returns the {@link Method} instance for
* {@link #testAddAtIndex_nullSupported()} so that tests can suppress it. See
* {@link CollectionAddTester#getAddNullSupportedMethod()} for details.
*/
public static Method getAddNullSupportedMethod() {
return Platform.getMethod(
ListAddAtIndexTester.class, "testAddAtIndex_nullSupported");
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Tests {@link java.util.Map#equals}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
* @author Chris Povirk
*/
public class MapEqualsTester<K, V> extends AbstractMapTester<K, V> {
public void testEquals_otherMapWithSameEntries() {
assertTrue(
"A Map should equal any other Map containing the same entries.",
getMap().equals(newHashMap(getSampleEntries())));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
public void testEquals_otherMapWithDifferentEntries() {
Map<K, V> other = newHashMap(getSampleEntries(getNumEntries() - 1));
Entry<K, V> e3 = getSubjectGenerator().samples().e3;
other.put(e3.getKey(), e3.getValue());
assertFalse(
"A Map should not equal another Map containing different entries.",
getMap().equals(other)
);
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
@MapFeature.Require(ALLOWS_NULL_KEYS)
public void testEquals_containingNullKey() {
Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1);
entries.add(entry(null, samples.e3.getValue()));
resetContainer(getSubjectGenerator().create(entries.toArray()));
assertTrue("A Map should equal any other Map containing the same entries,"
+ " even if some keys are null.",
getMap().equals(newHashMap(entries)));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
public void testEquals_otherContainsNullKey() {
Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1);
entries.add(entry(null, samples.e3.getValue()));
Map<K, V> other = newHashMap(entries);
assertFalse(
"Two Maps should not be equal if exactly one of them contains a null "
+ "key.",
getMap().equals(other));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
@MapFeature.Require(ALLOWS_NULL_VALUES)
public void testEquals_containingNullValue() {
Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1);
entries.add(entry(samples.e3.getKey(), null));
resetContainer(getSubjectGenerator().create(entries.toArray()));
assertTrue("A Map should equal any other Map containing the same entries,"
+ " even if some values are null.",
getMap().equals(newHashMap(entries)));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
public void testEquals_otherContainsNullValue() {
Collection<Map.Entry<K, V>> entries = getSampleEntries(getNumEntries() - 1);
entries.add(entry(samples.e3.getKey(), null));
Map<K, V> other = newHashMap(entries);
assertFalse(
"Two Maps should not be equal if exactly one of them contains a null "
+ "value.",
getMap().equals(other));
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
public void testEquals_smallerMap() {
Collection<Map.Entry<K, V>> fewerEntries
= getSampleEntries(getNumEntries() - 1);
assertFalse("Maps of different sizes should not be equal.",
getMap().equals(newHashMap(fewerEntries)));
}
public void testEquals_largerMap() {
Collection<Map.Entry<K, V>> moreEntries
= getSampleEntries(getNumEntries() + 1);
assertFalse("Maps of different sizes should not be equal.",
getMap().equals(newHashMap(moreEntries)));
}
public void testEquals_list() {
assertFalse("A List should never equal a Map.",
getMap().equals(Helpers.copyToList(getMap().entrySet())));
}
private static <K, V> HashMap<K, V> newHashMap(
Collection<? extends Map.Entry<? extends K, ? extends V>> entries) {
HashMap<K, V> map = new HashMap<K, V>();
for (Map.Entry<? extends K, ? extends V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Arrays;
/**
* A generic JUnit test which tests {@code toArray()} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
public class ListToArrayTester<E> extends AbstractListTester<E> {
// CollectionToArrayTester tests everything except ordering.
public void testToArray_noArg() {
Object[] actual = getList().toArray();
assertArrayEquals("toArray() order should match list",
createSamplesArray(), actual);
}
@CollectionSize.Require(absent = ZERO)
public void testToArray_tooSmall() {
Object[] actual = getList().toArray(new Object[0]);
assertArrayEquals("toArray(tooSmall) order should match list",
createSamplesArray(), actual);
}
public void testToArray_largeEnough() {
Object[] actual = getList().toArray(new Object[getNumElements()]);
assertArrayEquals("toArray(largeEnough) order should match list",
createSamplesArray(), actual);
}
private static void assertArrayEquals(String message, Object[] expected,
Object[] actual) {
assertEquals(message, Arrays.asList(expected), Arrays.asList(actual));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collection;
/**
* A generic JUnit test which tests {@code containsAll()} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class CollectionContainsAllTester<E>
extends AbstractCollectionTester<E> {
public void testContainsAll_empty() {
assertTrue("containsAll(empty) should return true",
collection.containsAll(MinimalCollection.of()));
}
@CollectionSize.Require(absent = ZERO)
public void testContainsAll_subset() {
assertTrue("containsAll(subset) should return true",
collection.containsAll(MinimalCollection.of(samples.e0)));
}
public void testContainsAll_sameElements() {
assertTrue("containsAll(sameElements) should return true",
collection.containsAll(MinimalCollection.of(createSamplesArray())));
}
public void testContainsAll_self() {
assertTrue("containsAll(this) should return true",
collection.containsAll(collection));
}
public void testContainsAll_partialOverlap() {
assertFalse("containsAll(partialOverlap) should return false",
collection.containsAll(MinimalCollection.of(samples.e0, samples.e3)));
}
public void testContainsAll_disjoint() {
assertFalse("containsAll(disjoint) should return false",
collection.containsAll(MinimalCollection.of(samples.e3)));
}
@CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContainsAll_nullNotAllowed() {
try {
assertFalse(collection.containsAll(MinimalCollection.of((E) null)));
} catch (NullPointerException tolerated) {}
}
@CollectionFeature.Require(ALLOWS_NULL_QUERIES)
public void testContainsAll_nullAllowed() {
assertFalse(collection.containsAll(MinimalCollection.of((E) null)));
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testContainsAll_nullPresent() {
initCollectionWithNullElement();
assertTrue(collection.containsAll(MinimalCollection.of((E) null)));
}
public void testContainsAll_wrongType() {
Collection<WrongType> wrong = MinimalCollection.of(WrongType.VALUE);
try {
assertFalse("containsAll(wrongType) should return false or throw",
collection.containsAll(wrong));
} catch (ClassCastException tolerated) {
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code isEmpty()} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public class CollectionIsEmptyTester<E> extends AbstractCollectionTester<E> {
@CollectionSize.Require(ZERO)
public void testIsEmpty_yes() {
assertTrue("isEmpty() should return true", collection.isEmpty());
}
@CollectionSize.Require(absent = ZERO)
public void testIsEmpty_no() {
assertFalse("isEmpty() should return false", collection.isEmpty());
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code contains()} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
public class CollectionContainsTester<E> extends AbstractCollectionTester<E> {
@CollectionSize.Require(absent = ZERO)
public void testContains_yes() {
assertTrue("contains(present) should return true",
collection.contains(samples.e0));
}
public void testContains_no() {
assertFalse("contains(notPresent) should return false",
collection.contains(samples.e3));
}
@CollectionFeature.Require(ALLOWS_NULL_QUERIES)
public void testContains_nullNotContainedButQueriesSupported() {
assertFalse("contains(null) should return false",
collection.contains(null));
}
@CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContains_nullNotContainedAndUnsupported() {
expectNullMissingWhenNullUnsupported(
"contains(null) should return false or throw");
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContains_nonNullWhenNullContained() {
initCollectionWithNullElement();
assertFalse("contains(notPresent) should return false",
collection.contains(samples.e3));
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContains_nullContained() {
initCollectionWithNullElement();
assertTrue("contains(null) should return true", collection.contains(null));
}
public void testContains_wrongType() {
try {
assertFalse("contains(wrongType) should return false or throw",
collection.contains(WrongType.VALUE));
} catch (ClassCastException tolerated) {
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.List;
/**
* A generic JUnit test which tests {@code add(Object)} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class ListAddTester<E> extends AbstractListTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedPresent() {
assertTrue("add(present) should return true", getList().add(samples.e0));
expectAdded(samples.e0);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
/*
* absent = ZERO isn't required, since unmodList.add() must
* throw regardless, but it keeps the method name accurate.
*/
public void testAdd_unsupportedPresent() {
try {
getList().add(samples.e0);
fail("add(present) should throw");
} catch (UnsupportedOperationException expected) {
}
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedNullPresent() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
assertTrue("add(nullPresent) should return true", getList().add(null));
List<E> expected = Helpers.copyToList(array);
expected.add(null);
expectContents(expected);
}
/**
* Returns the {@link Method} instance for
* {@link #testAdd_supportedNullPresent()} so that tests can suppress it. See
* {@link CollectionAddTester#getAddNullSupportedMethod()} for details.
*/
public static Method getAddSupportedNullPresentMethod() {
return Platform.getMethod(ListAddTester.class, "testAdd_supportedNullPresent");
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD_ALL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static java.util.Collections.singletonList;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
/**
* A generic JUnit test which tests addAll operations on a collection. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class CollectionAddAllTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
public void testAddAll_supportedNothing() {
assertFalse("addAll(nothing) should return false",
collection.addAll(emptyCollection()));
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_ADD_ALL)
public void testAddAll_unsupportedNothing() {
try {
assertFalse("addAll(nothing) should return false or throw",
collection.addAll(emptyCollection()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
public void testAddAll_supportedNonePresent() {
assertTrue("addAll(nonePresent) should return true",
collection.addAll(createDisjointCollection()));
expectAdded(samples.e3, samples.e4);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD_ALL)
public void testAddAll_unsupportedNonePresent() {
try {
collection.addAll(createDisjointCollection());
fail("addAll(nonePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3, samples.e4);
}
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_supportedSomePresent() {
assertTrue("addAll(somePresent) should return true",
collection.addAll(MinimalCollection.of(samples.e3, samples.e0)));
assertTrue("should contain " + samples.e3, collection.contains(samples.e3));
assertTrue("should contain " + samples.e0, collection.contains(samples.e0));
}
@CollectionFeature.Require(absent = SUPPORTS_ADD_ALL)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_unsupportedSomePresent() {
try {
collection.addAll(MinimalCollection.of(samples.e3, samples.e0));
fail("addAll(somePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testAddAllConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.addAll(MinimalCollection.of(samples.e3, samples.e0)));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(absent = SUPPORTS_ADD_ALL)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_unsupportedAllPresent() {
try {
assertFalse("addAll(allPresent) should return false or throw",
collection.addAll(MinimalCollection.of(samples.e0)));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(value = {SUPPORTS_ADD_ALL,
ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS)
public void testAddAll_nullSupported() {
List<E> containsNull = singletonList(null);
assertTrue("addAll(containsNull) should return true", collection
.addAll(containsNull));
/*
* We need (E) to force interpretation of null as the single element of a
* varargs array, not the array itself
*/
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD_ALL,
absent = ALLOWS_NULL_VALUES)
public void testAddAll_nullUnsupported() {
List<E> containsNull = singletonList(null);
try {
collection.addAll(containsNull);
fail("addAll(containsNull) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported addAll(containsNull)");
}
@CollectionFeature.Require(SUPPORTS_ADD_ALL)
public void testAddAll_nullCollectionReference() {
try {
collection.addAll(null);
fail("addAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
/**
* Returns the {@link Method} instance for {@link
* #testAddAll_nullUnsupported()} so that tests can suppress it with {@code
* FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun
* bug 5045147</a> is fixed.
*/
public static Method getAddAllNullUnsupportedMethod() {
return Platform.getMethod(CollectionAddAllTester.class, "testAddAll_nullUnsupported");
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_RETAIN_ALL;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code retainAll} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
public class ListRetainAllTester<E> extends AbstractListTester<E> {
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testRetainAll_duplicatesKept() {
E[] array = createSamplesArray();
array[1] = samples.e0;
collection = getSubjectGenerator().create(array);
assertFalse("containsDuplicates.retainAll(superset) should return false",
collection.retainAll(MinimalCollection.of(createSamplesArray())));
expectContents(array);
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(SUPPORTS_RETAIN_ALL)
@CollectionSize.Require(SEVERAL)
public void testRetainAll_duplicatesRemoved() {
E[] array = createSamplesArray();
array[1] = samples.e0;
collection = getSubjectGenerator().create(array);
assertTrue("containsDuplicates.retainAll(subset) should return true",
collection.retainAll(MinimalCollection.of(samples.e2)));
expectContents(samples.e2);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.*;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
/**
* A generic JUnit test which tests {@code containsValue()} operations on a map.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
* @author Chris Povirk
*/
public class MapContainsValueTester<K, V> extends AbstractMapTester<K, V> {
@CollectionSize.Require(absent = ZERO)
public void testContains_yes() {
assertTrue("containsValue(present) should return true",
getMap().containsValue(samples.e0.getValue()));
}
public void testContains_no() {
assertFalse("containsValue(notPresent) should return false",
getMap().containsValue(samples.e3.getValue()));
}
@MapFeature.Require(ALLOWS_NULL_QUERIES)
public void testContains_nullNotContainedButAllowed() {
assertFalse("containsValue(null) should return false",
getMap().containsValue(null));
}
@MapFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testContains_nullNotContainedAndUnsupported() {
expectNullValueMissingWhenNullValuesUnsupported(
"containsValue(null) should return false or throw");
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContains_nonNullWhenNullContained() {
initMapWithNullValue();
assertFalse("containsValue(notPresent) should return false",
getMap().containsValue(samples.e3.getValue()));
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testContains_nullContained() {
initMapWithNullValue();
assertTrue("containsValue(null) should return true",
getMap().containsValue(null));
}
public void testContains_wrongType() {
try {
//noinspection SuspiciousMethodCalls
assertFalse("containsValue(wrongType) should return false or throw",
getMap().containsValue(WrongType.VALUE));
} catch (ClassCastException tolerated) {
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code remove} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class CollectionRemoveTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemove_present() {
int initialSize = collection.size();
assertTrue("remove(present) should return true",
collection.remove(samples.e0));
assertEquals("remove(present) should decrease a collection's size by one.",
initialSize - 1, collection.size());
expectMissing(samples.e0);
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testRemovePresentConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.remove(samples.e0));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_notPresent() {
assertFalse("remove(notPresent) should return false",
collection.remove(samples.e3));
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testRemove_nullPresent() {
collection = getSubjectGenerator().create(createArrayWithNullElement());
int initialSize = collection.size();
assertTrue("remove(null) should return true", collection.remove(null));
assertEquals("remove(present) should decrease a collection's size by one.",
initialSize - 1, collection.size());
expectMissing((E) null);
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testRemove_unsupported() {
try {
collection.remove(samples.e0);
fail("remove(present) should throw UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
assertTrue("remove(present) should not remove the element",
collection.contains(samples.e0));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemove_unsupportedNotPresent() {
try {
assertFalse("remove(notPresent) should return false or throw "
+ "UnsupportedOperationException",
collection.remove(samples.e3));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@CollectionFeature.Require(
value = SUPPORTS_REMOVE,
absent = ALLOWS_NULL_QUERIES)
public void testRemove_nullNotSupported() {
try {
assertFalse("remove(null) should return false or throw "
+ "NullPointerException",
collection.remove(null));
} catch (NullPointerException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES})
public void testRemove_nullAllowed() {
assertFalse("remove(null) should return false", collection.remove(null));
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
@CollectionSize.Require(absent = ZERO)
public void testIteratorRemove_unsupported() {
Iterator<E> iterator = collection.iterator();
iterator.next();
try {
iterator.remove();
fail("iterator.remove() should throw UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
assertTrue(collection.contains(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_wrongType() {
try {
assertFalse(collection.remove(WrongType.VALUE));
} catch (ClassCastException tolerated) {
}
expectUnchanged();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_CLEAR;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code clear()} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class CollectionClearTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_CLEAR)
public void testClear() {
collection.clear();
assertTrue("After clear(), a collection should be empty.",
collection.isEmpty());
}
@CollectionFeature.Require(absent = SUPPORTS_CLEAR)
@CollectionSize.Require(absent = ZERO)
public void testClear_unsupported() {
try {
collection.clear();
fail("clear() should throw UnsupportedOperation if a collection does "
+ "not support it and is not empty.");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_CLEAR)
@CollectionSize.Require(ZERO)
public void testClear_unsupportedByEmptyCollection() {
try {
collection.clear();
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_CLEAR,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testClearConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
collection.clear();
iterator.next();
/*
* We prefer for iterators to fail immediately on hasNext, but ArrayList
* and LinkedList will notably return true on hasNext here!
*/
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
import java.util.Collection;
/**
* Tests {@link java.util.Set#hashCode}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class SetHashCodeTester<E> extends AbstractSetTester<E> {
public void testHashCode() {
int expectedHashCode = 0;
for (E element : getSampleElements()) {
expectedHashCode += ((element == null) ? 0 : element.hashCode());
}
assertEquals(
"A Set's hashCode() should be the sum of those of its elements.",
expectedHashCode, getSet().hashCode());
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testHashCode_containingNull() {
Collection<E> elements = getSampleElements(getNumElements() - 1);
int expectedHashCode = 0;
for (E element : elements) {
expectedHashCode += ((element == null) ? 0 : element.hashCode());
}
elements.add(null);
collection = getSubjectGenerator().create(elements.toArray());
assertEquals(
"A Set's hashCode() should be the sum of those of its elements (with "
+ "a null element counting as having a hash of zero).",
expectedHashCode, getSet().hashCode());
}
/**
* Returns the {@link Method} instances for the test methods in this class
* which call {@code hashCode()} on the set values so that set tests on
* unhashable objects can suppress it with
* {@code FeatureSpecificTestSuiteBuilder.suppressing()}.
*/
public static Method[] getHashCodeMethods() {
return new Method[]{
Platform.getMethod(SetHashCodeTester.class, "testHashCode"),
Platform.getMethod(SetHashCodeTester.class, "testHashCode_containingNull") };
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import com.google.common.collect.testing.AbstractCollectionTester;
import java.util.Set;
/**
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class AbstractSetTester<E> extends AbstractCollectionTester<E> {
/*
* Previously we had a field named set that was initialized to the value of
* collection in setUp(), but that caused problems when a tester changed the
* value of set or collection but not both.
*/
protected final Set<E> getSet() {
return (Set<E>) collection;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests creation (typically through a constructor or
* static factory method) of a map. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
public class MapCreationTester<K, V> extends AbstractMapTester<K, V> {
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeySupported() {
initMapWithNullKey();
expectContents(createArrayWithNullKey());
}
@MapFeature.Require(absent = ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyUnsupported() {
try {
initMapWithNullKey();
fail("Creating a map containing a null key should fail");
} catch (NullPointerException expected) {
}
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueSupported() {
initMapWithNullValue();
expectContents(createArrayWithNullValue());
}
@MapFeature.Require(absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueUnsupported() {
try {
initMapWithNullValue();
fail("Creating a map containing a null value should fail");
} catch (NullPointerException expected) {
}
}
@MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyAndValueSupported() {
Entry<K, V>[] entries = createSamplesArray();
entries[getNullLocation()] = entry(null, null);
resetMap(entries);
expectContents(entries);
}
@MapFeature.Require(value = ALLOWS_NULL_KEYS,
absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNullKeys());
}
@MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNonNullKeys());
}
@MapFeature.Require({ALLOWS_NULL_KEYS, REJECTS_DUPLICATES_AT_CREATION})
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNullKeys();
try {
resetMap(entries);
fail("Should reject duplicate null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
@MapFeature.Require(REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNonNullKeys();
try {
resetMap(entries);
fail("Should reject duplicate non-null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
private Entry<K, V>[] getEntriesMultipleNullKeys() {
Entry<K, V>[] entries = createArrayWithNullKey();
entries[0] = entries[getNullLocation()];
return entries;
}
private Entry<K, V>[] getEntriesMultipleNonNullKeys() {
Entry<K, V>[] entries = createSamplesArray();
entries[0] = samples.e1;
return entries;
}
private void expectFirstRemoved(Entry<K, V>[] entries) {
resetMap(entries);
List<Entry<K, V>> expectedWithDuplicateRemoved =
Arrays.asList(entries).subList(1, getNumElements());
expectContents(expectedWithDuplicateRemoved);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.lang.reflect.Method;
/**
* A generic JUnit test which tests creation (typically through a constructor or
* static factory method) of a collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
public class CollectionCreationTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNull_supported() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
expectContents(array);
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNull_unsupported() {
E[] array = createArrayWithNullElement();
try {
getSubjectGenerator().create(array);
fail("Creating a collection containing null should fail");
} catch (NullPointerException expected) {
}
}
/**
* Returns the {@link Method} instance for {@link
* #testCreateWithNull_unsupported()} so that tests can suppress it
* with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun
* bug 5045147</a> is fixed.
*/
public static Method getCreateWithNullUnsupportedMethod() {
return Platform.getMethod(CollectionCreationTester.class, "testCreateWithNull_unsupported");
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests {@code poll()} operations on a queue.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Jared Levy
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class QueuePollTester<E> extends AbstractQueueTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testPoll_empty() {
assertNull("emptyQueue.poll() should return null", getQueue().poll());
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ONE)
public void testPoll_size1() {
assertEquals("size1Queue.poll() should return first element",
samples.e0, getQueue().poll());
expectMissing(samples.e0);
}
@CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE})
@CollectionSize.Require(SEVERAL)
public void testPoll_sizeMany() {
assertEquals("sizeManyQueue.poll() should return first element",
samples.e0, getQueue().poll());
expectMissing(samples.e0);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import com.google.common.collect.testing.AbstractCollectionTester;
/**
* A generic JUnit test which tests {@code size()} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public class CollectionSizeTester<E> extends AbstractCollectionTester<E> {
public void testSize() {
assertEquals("size():", getNumElements(), collection.size());
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE_ALL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code removeAll} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
public class CollectionRemoveAllTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
public void testRemoveAll_emptyCollection() {
assertFalse("removeAll(emptyCollection) should return false",
collection.removeAll(MinimalCollection.of()));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
public void testRemoveAll_nonePresent() {
assertFalse("removeAll(disjointCollection) should return false",
collection.removeAll(MinimalCollection.of(samples.e3)));
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_allPresent() {
assertTrue("removeAll(intersectingCollection) should return true",
collection.removeAll(MinimalCollection.of(samples.e0)));
expectMissing(samples.e0);
}
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_somePresent() {
assertTrue("removeAll(intersectingCollection) should return true",
collection.removeAll(MinimalCollection.of(samples.e0, samples.e3)));
expectMissing(samples.e0);
}
@CollectionFeature.Require({SUPPORTS_REMOVE_ALL,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testRemoveAllSomePresentConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.removeAll(MinimalCollection.of(samples.e0, samples.e3)));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
/**
* Trigger the other.size() >= this.size() case in AbstractSet.removeAll().
*/
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_somePresentLargeCollectionToRemove() {
assertTrue("removeAll(largeIntersectingCollection) should return true",
collection.removeAll(MinimalCollection.of(
samples.e0, samples.e0, samples.e0,
samples.e3, samples.e3, samples.e3)));
expectMissing(samples.e0);
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE_ALL)
public void testRemoveAll_unsupportedEmptyCollection() {
try {
assertFalse("removeAll(emptyCollection) should return false or throw "
+ "UnsupportedOperationException",
collection.removeAll(MinimalCollection.of()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE_ALL)
public void testRemoveAll_unsupportedNonePresent() {
try {
assertFalse("removeAll(disjointCollection) should return false or throw "
+ "UnsupportedOperationException",
collection.removeAll(MinimalCollection.of(samples.e3)));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_unsupportedPresent() {
try {
collection.removeAll(MinimalCollection.of(samples.e0));
fail("removeAll(intersectingCollection) should throw "
+ "UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
assertTrue(collection.contains(samples.e0));
}
/*
* AbstractCollection fails the removeAll(null) test when the subject
* collection is empty, but we'd still like to test removeAll(null) when we
* can. We split the test into empty and non-empty cases. This allows us to
* suppress only the former.
*/
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
@CollectionSize.Require(ZERO)
public void testRemoveAll_nullCollectionReferenceEmptySubject() {
try {
collection.removeAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException expected) {
}
}
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_nullCollectionReferenceNonEmptySubject() {
try {
collection.removeAll(null);
fail("removeAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
@CollectionFeature.Require(value = SUPPORTS_REMOVE_ALL,
absent = ALLOWS_NULL_QUERIES)
public void testRemoveAll_containsNullNo() {
MinimalCollection<?> containsNull = MinimalCollection.of((Object) null);
try {
assertFalse("removeAll(containsNull) should return false or throw",
collection.removeAll(containsNull));
} catch (NullPointerException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_REMOVE_ALL, ALLOWS_NULL_QUERIES})
public void testRemoveAll_containsNullNoButAllowed() {
MinimalCollection<?> containsNull = MinimalCollection.of((Object) null);
assertFalse("removeAll(containsNull) should return false",
collection.removeAll(containsNull));
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_REMOVE_ALL, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testRemoveAll_containsNullYes() {
initCollectionWithNullElement();
assertTrue("removeAll(containsNull) should return true",
collection.removeAll(Collections.singleton(null)));
// TODO: make this work with MinimalCollection
}
@CollectionFeature.Require(SUPPORTS_REMOVE_ALL)
public void testRemoveAll_containsWrongType() {
try {
assertFalse("removeAll(containsWrongType) should return false or throw",
collection.removeAll(MinimalCollection.of(WrongType.VALUE)));
} catch (ClassCastException tolerated) {
}
expectUnchanged();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import java.util.Collection;
import java.util.List;
/**
* Base class for list testers.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class AbstractListTester<E> extends AbstractCollectionTester<E> {
/*
* Previously we had a field named list that was initialized to the value of
* collection in setUp(), but that caused problems when a tester changed the
* value of list or collection but not both.
*/
protected final List<E> getList() {
return (List<E>) collection;
}
/**
* {@inheritDoc}
* <p>
* The {@code AbstractListTester} implementation overrides
* {@link AbstractCollectionTester#expectContents(Collection)} to verify that
* the order of the elements in the list under test matches what is expected.
*/
@Override protected void expectContents(Collection<E> expectedCollection) {
List<E> expectedList = Helpers.copyToList(expectedCollection);
// Avoid expectEquals() here to delay reason manufacture until necessary.
if (getList().size() != expectedList.size()) {
fail("size mismatch: " + reportContext(expectedList));
}
for (int i = 0; i < expectedList.size(); i++) {
E expected = expectedList.get(i);
E actual = getList().get(i);
if (expected != actual &&
(expected == null || !expected.equals(actual))) {
fail("mismatch at index " + i + ": " + reportContext(expectedList));
}
}
}
/**
* Used to delay string formatting until actually required, as it
* otherwise shows up in the test execution profile when running an
* extremely large numbers of tests.
*/
private String reportContext(List<E> expected) {
return Platform.format("expected collection %s; actual collection %s",
expected, this.collection);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* Common parent class for {@link ListIndexOfTester} and
* {@link ListLastIndexOfTester}.
*
* <p>This class is GWT compatible.
*
* @author Chris Povirk
*/
public abstract class AbstractListIndexOfTester<E>
extends AbstractListTester<E> {
/** Override to call {@code indexOf()} or {@code lastIndexOf()}. */
protected abstract int find(Object o);
/**
* Override to return "indexOf" or "lastIndexOf()" for use in failure
* messages.
*/
protected abstract String getMethodName();
@CollectionSize.Require(absent = ZERO)
public void testFind_yes() {
assertEquals(getMethodName() + "(firstElement) should return 0",
0, find(samples.e0));
}
public void testFind_no() {
assertEquals(getMethodName() + "(notPresent) should return -1",
-1, find(samples.e3));
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testFind_nullNotContainedButSupported() {
assertEquals(getMethodName() + "(nullNotPresent) should return -1",
-1, find(null));
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testFind_nullNotContainedAndUnsupported() {
try {
assertEquals(
getMethodName() + "(nullNotPresent) should return -1 or throw",
-1, find(null));
} catch (NullPointerException tolerated) {
}
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testFind_nonNullWhenNullContained() {
initCollectionWithNullElement();
assertEquals(getMethodName() + "(notPresent) should return -1",
-1, find(samples.e3));
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testFind_nullContained() {
initCollectionWithNullElement();
assertEquals(getMethodName() + "(null) should return " + getNullLocation(),
getNullLocation(), find(null));
}
public void testFind_wrongType() {
try {
assertEquals(getMethodName() + "(wrongType) should return -1 or throw",
-1, find(WrongType.VALUE));
} catch (ClassCastException tolerated) {
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import java.lang.reflect.Method;
/**
* A generic JUnit test which tests {@code set()} operations on a list. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* <p>This class is GWT compatible.
*
* @author George van den Driessche
*/
public class ListSetTester<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSet() {
doTestSet(samples.e3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@ListFeature.Require(SUPPORTS_SET)
public void testSet_null() {
doTestSet(null);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@ListFeature.Require(SUPPORTS_SET)
public void testSet_replacingNull() {
E[] elements = createSamplesArray();
int i = aValidIndex();
elements[i] = null;
collection = getSubjectGenerator().create(elements);
doTestSet(samples.e3);
}
private void doTestSet(E newValue) {
int index = aValidIndex();
E initialValue = getList().get(index);
assertEquals("set(i, x) should return the old element at position i.",
initialValue, getList().set(index, newValue));
assertEquals("After set(i, x), get(i) should return x",
newValue, getList().get(index));
assertEquals("set() should not change the size of a list.",
getNumElements(), getList().size());
}
@ListFeature.Require(SUPPORTS_SET)
public void testSet_indexTooLow() {
try {
getList().set(-1, samples.e3);
fail("set(-1) should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_SET)
public void testSet_indexTooHigh() {
int index = getNumElements();
try {
getList().set(index, samples.e3);
fail("set(size) should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@ListFeature.Require(absent = SUPPORTS_SET)
public void testSet_unsupported() {
try {
getList().set(aValidIndex(), samples.e3);
fail("set() should throw UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionSize.Require(ZERO)
@ListFeature.Require(absent = SUPPORTS_SET)
public void testSet_unsupportedByEmptyList() {
try {
getList().set(0, samples.e3);
fail("set() should throw UnsupportedOperationException "
+ "or IndexOutOfBoundsException");
} catch (UnsupportedOperationException tolerated) {
} catch (IndexOutOfBoundsException tolerated) {
}
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@ListFeature.Require(SUPPORTS_SET)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testSet_nullUnsupported() {
try {
getList().set(aValidIndex(), null);
fail("set(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
expectUnchanged();
}
private int aValidIndex() {
return getList().size() / 2;
}
/**
* Returns the {@link java.lang.reflect.Method} instance for
* {@link #testSet_null()} so that tests of {@link
* java.util.Collections#checkedCollection(java.util.Collection, Class)} can
* suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()}
* until <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6409434">Sun bug
* 6409434</a> is fixed. It's unclear whether nulls were to be permitted or
* forbidden, but presumably the eventual fix will be to permit them, as it
* seems more likely that code would depend on that behavior than on the
* other. Thus, we say the bug is in set(), which fails to support null.
*/
public static Method getSetNullSupportedMethod() {
return Platform.getMethod(ListSetTester.class, "testSet_null");
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.testing.SerializableTester;
/**
* Basic serialization test for maps.
*
* @author Louis Wasserman
*/
public class MapSerializationTester<K, V> extends AbstractMapTester<K, V> {
@CollectionFeature.Require(SERIALIZABLE)
public void testReserializeMap() {
SerializableTester.reserializeAndAssert(getMap());
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.