diff options
author | Paul Duffin <paulduffin@google.com> | 2015-05-29 15:33:20 +0100 |
---|---|---|
committer | Paul Duffin <paulduffin@google.com> | 2015-06-11 12:37:00 +0100 |
commit | 3ecfa412eddc4b084663f38d562537b86b9734d5 (patch) | |
tree | fcdd6fcea5843db15e5afa87883979c2f32139ba /guava-tests | |
parent | 6a5ff04444ec0ece7d92e418867d8c222c825535 (diff) | |
download | guava-3ecfa412eddc4b084663f38d562537b86b9734d5.tar.gz |
Upgraded Guava to unmodified v18.0
This simply copies the Guava source for v18.0 straight from the
github repository into this one.
See https://github.com/google/guava.git
Additional commits will be made which will allow this to compile
on Android.
BUG=19672715
Change-Id: Ief2c7a00b4456aa03ce3ca73db34cb86abdbad14
Diffstat (limited to 'guava-tests')
163 files changed, 8612 insertions, 1501 deletions
diff --git a/guava-tests/benchmark/com/google/common/collect/MapBenchmark.java b/guava-tests/benchmark/com/google/common/collect/MapBenchmark.java index 2e309fcd5..9f9353556 100644 --- a/guava-tests/benchmark/com/google/common/collect/MapBenchmark.java +++ b/guava-tests/benchmark/com/google/common/collect/MapBenchmark.java @@ -28,6 +28,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentSkipListMap; /** * A microbenchmark that tests the performance of get() and iteration on various map @@ -77,6 +78,15 @@ public class MapBenchmark { return map; } }, + SkipList { + @Override Map<Element, Element> create(Collection<Element> keys) { + Map<Element, Element> map = new ConcurrentSkipListMap<Element, Element>(); + for (Element element: keys) { + map.put(element, element); + } + return map; + } + }, ConcurrentHM1 { @Override Map<Element, Element> create(Collection<Element> keys) { Map<Element, Element> map = diff --git a/guava-tests/benchmark/com/google/common/math/IntMathBenchmark.java b/guava-tests/benchmark/com/google/common/math/IntMathBenchmark.java index 717d46088..fd7dd6922 100644 --- a/guava-tests/benchmark/com/google/common/math/IntMathBenchmark.java +++ b/guava-tests/benchmark/com/google/common/math/IntMathBenchmark.java @@ -46,8 +46,8 @@ public class IntMathBenchmark { exponent[i] = randomExponent(); factorial[i] = RANDOM_SOURCE.nextInt(50); binomial[i] = RANDOM_SOURCE.nextInt(factorial[i] + 1); - positive[i] = randomPositiveBigInteger(Integer.SIZE - 2).intValue(); - nonnegative[i] = randomNonNegativeBigInteger(Integer.SIZE - 2).intValue(); + positive[i] = randomPositiveBigInteger(Integer.SIZE - 1).intValue(); + nonnegative[i] = randomNonNegativeBigInteger(Integer.SIZE - 1).intValue(); ints[i] = RANDOM_SOURCE.nextInt(); } } diff --git a/guava-tests/benchmark/com/google/common/math/LongMathBenchmark.java b/guava-tests/benchmark/com/google/common/math/LongMathBenchmark.java index e8e09f32d..912eb251f 100644 --- a/guava-tests/benchmark/com/google/common/math/LongMathBenchmark.java +++ b/guava-tests/benchmark/com/google/common/math/LongMathBenchmark.java @@ -44,8 +44,8 @@ public class LongMathBenchmark { void setUp() { for (int i = 0; i < ARRAY_SIZE; i++) { exponents[i] = randomExponent(); - positive[i] = randomPositiveBigInteger(Long.SIZE - 2).longValue(); - nonnegative[i] = randomNonNegativeBigInteger(Long.SIZE - 2).longValue(); + positive[i] = randomPositiveBigInteger(Long.SIZE - 1).longValue(); + nonnegative[i] = randomNonNegativeBigInteger(Long.SIZE - 1).longValue(); longs[i] = RANDOM_SOURCE.nextLong(); factorialArguments[i] = RANDOM_SOURCE.nextInt(30); binomialArguments[i][1] = RANDOM_SOURCE.nextInt(MathBenchmarking.biggestBinomials.length); diff --git a/guava-tests/benchmark/com/google/common/primitives/UnsignedBytesBenchmark.java b/guava-tests/benchmark/com/google/common/primitives/UnsignedBytesBenchmark.java index 9b1cac270..19b6802b8 100644 --- a/guava-tests/benchmark/com/google/common/primitives/UnsignedBytesBenchmark.java +++ b/guava-tests/benchmark/com/google/common/primitives/UnsignedBytesBenchmark.java @@ -19,8 +19,8 @@ package com.google.common.primitives; import com.google.caliper.BeforeExperiment; import com.google.caliper.Benchmark; import com.google.caliper.Param; -import com.google.common.jdk5backport.Arrays; +import java.util.Arrays; import java.util.Comparator; import java.util.Random; @@ -36,6 +36,7 @@ public class UnsignedBytesBenchmark { private byte[] ba3; private byte[] ba4; private Comparator<byte[]> javaImpl; + private Comparator<byte[]> unsafeImpl; // 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned) //@Param({"4", "8", "64", "1024", "1048576", "1048577", "6710884", "6710883"}) @@ -55,6 +56,8 @@ public class UnsignedBytesBenchmark { ba4[ba1.length - 1] = (byte) 42; javaImpl = UnsignedBytes.lexicographicalComparatorJavaImpl(); + unsafeImpl = + UnsignedBytes.LexicographicalComparatorHolder.UnsafeComparator.INSTANCE; } @Benchmark void longEqualJava(int reps) { @@ -65,6 +68,14 @@ public class UnsignedBytesBenchmark { } } + @Benchmark void longEqualUnsafe(int reps) { + for (int i = 0; i < reps; ++i) { + if (unsafeImpl.compare(ba1, ba2) != 0) { + throw new Error(); // deoptimization + } + } + } + @Benchmark void diffLastJava(int reps) { for (int i = 0; i < reps; ++i) { if (javaImpl.compare(ba3, ba4) == 0) { @@ -73,6 +84,14 @@ public class UnsignedBytesBenchmark { } } + @Benchmark void diffLastUnsafe(int reps) { + for (int i = 0; i < reps; ++i) { + if (unsafeImpl.compare(ba3, ba4) == 0) { + throw new Error(); // deoptimization + } + } + } + /* try { UnsignedBytesBenchmark bench = new UnsignedBytesBenchmark(); diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/CycleDetectingLockFactoryBenchmark.java b/guava-tests/benchmark/com/google/common/util/concurrent/CycleDetectingLockFactoryBenchmark.java new file mode 100644 index 000000000..a8c780709 --- /dev/null +++ b/guava-tests/benchmark/com/google/common/util/concurrent/CycleDetectingLockFactoryBenchmark.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.util.concurrent; + +import com.google.caliper.BeforeExperiment; +import com.google.caliper.Benchmark; +import com.google.caliper.Param; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * Benchmarks for {@link CycleDetectingLockFactory}. + * + * @author Darick Tong + */ +public class CycleDetectingLockFactoryBenchmark { + + @Param({"2","3","4","5","10"}) int lockNestingDepth; + + CycleDetectingLockFactory factory; + private Lock[] plainLocks; + private Lock[] detectingLocks; + + @BeforeExperiment + void setUp() throws Exception { + this.factory = CycleDetectingLockFactory.newInstance( + CycleDetectingLockFactory.Policies.WARN); + this.plainLocks = new Lock[lockNestingDepth]; + for (int i = 0; i < lockNestingDepth; i++) { + plainLocks[i] = new ReentrantLock(); + } + this.detectingLocks = new Lock[lockNestingDepth]; + for (int i = 0; i < lockNestingDepth; i++) { + detectingLocks[i] = factory.newReentrantLock("Lock" + i); + } + } + + @Benchmark void unorderedPlainLocks(int reps) { + lockAndUnlock(new ReentrantLock(), reps); + } + + @Benchmark void unorderedCycleDetectingLocks(int reps) { + lockAndUnlock(factory.newReentrantLock("foo"), reps); + } + + private void lockAndUnlock(Lock lock, int reps) { + for (int i = 0; i < reps; i++) { + lock.lock(); + lock.unlock(); + } + } + + @Benchmark void orderedPlainLocks(int reps) { + lockAndUnlockNested(plainLocks, reps); + } + + @Benchmark void orderedCycleDetectingLocks(int reps) { + lockAndUnlockNested(detectingLocks, reps); + } + + private void lockAndUnlockNested(Lock[] locks, int reps) { + for (int i = 0; i < reps; i++) { + for (int j = 0; j < locks.length; j++) { + locks[j].lock(); + } + for (int j = locks.length - 1; j >= 0; j--) { + locks[j].unlock(); + } + } + } +} diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java b/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java index 3db52dbff..4e8604340 100644 --- a/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java +++ b/guava-tests/benchmark/com/google/common/util/concurrent/ExecutionListBenchmark.java @@ -16,6 +16,8 @@ package com.google.common.util.concurrent; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; + import com.google.caliper.AfterExperiment; import com.google.caliper.BeforeExperiment; import com.google.caliper.Benchmark; @@ -46,10 +48,6 @@ import javax.annotation.concurrent.GuardedBy; public class ExecutionListBenchmark { private static final int NUM_THREADS = 10; // make a param? - // We execute the listeners on the sameThreadExecutor because we don't really care about what the - // listeners are doing, and they aren't doing much. - private static final Executor SAME_THREAD_EXECUTOR = MoreExecutors.sameThreadExecutor(); - // simple interface to wrap our two implementations. interface ExecutionListWrapper { void add(Runnable runnable, Executor executor); @@ -189,7 +187,7 @@ public class ExecutionListBenchmark { public Object measureSize() { list = impl.newExecutionList(); for (int i = 0; i < numListeners; i++) { - list.add(listener, SAME_THREAD_EXECUTOR); + list.add(listener, directExecutor()); } return list.getImpl(); } @@ -200,7 +198,7 @@ public class ExecutionListBenchmark { list = impl.newExecutionList(); listenerLatch = new CountDownLatch(numListeners); for (int j = 0; j < numListeners; j++) { - list.add(listener, SAME_THREAD_EXECUTOR); + list.add(listener, directExecutor()); returnValue += listenerLatch.getCount(); } list.execute(); @@ -216,7 +214,7 @@ public class ExecutionListBenchmark { list.execute(); listenerLatch = new CountDownLatch(numListeners); for (int j = 0; j < numListeners; j++) { - list.add(listener, SAME_THREAD_EXECUTOR); + list.add(listener, directExecutor()); returnValue += listenerLatch.getCount(); } returnValue += listenerLatch.getCount(); @@ -234,7 +232,7 @@ public class ExecutionListBenchmark { Runnable addTask = new Runnable() { @Override public void run() { for (int i = 0; i < numListeners; i++) { - list.add(listener, SAME_THREAD_EXECUTOR); + list.add(listener, directExecutor()); } } }; @@ -256,7 +254,7 @@ public class ExecutionListBenchmark { Runnable addTask = new Runnable() { @Override public void run() { for (int i = 0; i < numListeners; i++) { - list.add(listener, SAME_THREAD_EXECUTOR); + list.add(listener, directExecutor()); } } }; diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/FuturesCombineBenchmark.java b/guava-tests/benchmark/com/google/common/util/concurrent/FuturesCombineBenchmark.java new file mode 100644 index 000000000..60b5e5ce5 --- /dev/null +++ b/guava-tests/benchmark/com/google/common/util/concurrent/FuturesCombineBenchmark.java @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2014 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.util.concurrent; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.caliper.Benchmark; +import com.google.caliper.Param; +import com.google.caliper.api.VmOptions; +import com.google.common.collect.ImmutableList; + +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; + +/** + * A benchmark for {@link Futures#combine} + */ +@VmOptions({"-Xms12g", "-Xmx12g", "-d64"}) +public class FuturesCombineBenchmark { + + enum Impl { + OLD { + @Override <V> ListenableFuture<V> combine(final Callable<V> combiner, Executor executor, + Iterable<? extends ListenableFuture<?>> futures) { + ListenableFuture<?> trigger = Futures.successfulAsList(futures); + checkNotNull(combiner); + checkNotNull(trigger); + return Futures.transform(trigger, new AsyncFunction<Object, V>() { + @Override public ListenableFuture<V> apply(Object arg) throws Exception { + try { + return Futures.immediateFuture(combiner.call()); + } catch (CancellationException e) { + return Futures.immediateCancelledFuture(); + } catch (ExecutionException e) { + return Futures.immediateFailedFuture(e.getCause()); // OK to rethrow on Error + } + } + }, executor); + } + }, + NEW { + @Override + <V> ListenableFuture<V> combine(Callable<V> combiner, final Executor executor, + Iterable<? extends ListenableFuture<?>> futures) { + return Futures.combine(combiner, executor, futures); + } + }; + + abstract <V> ListenableFuture<V> combine( + Callable<V> combiner, Executor executor, + Iterable<? extends ListenableFuture<?>> futures); + } + + private static final Executor INLINE_EXECUTOR = new Executor() { + @Override public void execute(Runnable command) { + command.run(); + } + }; + + @Param Impl impl; + @Param({"1", "5", "10"}) int numInputs; + + @Benchmark int timeDoneSuccesfulFutures(int reps) throws Exception { + ImmutableList.Builder<ListenableFuture<?>> futuresBuilder = ImmutableList.builder(); + for (int i = 0; i < numInputs; i++) { + futuresBuilder.add(Futures.immediateFuture(i)); + } + ImmutableList<ListenableFuture<?>> futures = futuresBuilder.build(); + Impl impl = this.impl; + Callable<Integer> callable = Callables.returning(12); + int sum = 0; + for (int i = 0; i < reps; i++) { + sum += impl.combine(callable, INLINE_EXECUTOR, futures).get(); + } + return sum; + } + + @Benchmark int timeDoneFailedFutures(int reps) throws Exception { + ImmutableList.Builder<ListenableFuture<?>> futuresBuilder = ImmutableList.builder(); + for (int i = 0; i < numInputs; i++) { + futuresBuilder.add(Futures.immediateFailedFuture(new Exception("boom"))); + } + ImmutableList<ListenableFuture<?>> futures = futuresBuilder.build(); + Impl impl = this.impl; + Callable<Integer> callable = Callables.returning(12); + int sum = 0; + for (int i = 0; i < reps; i++) { + sum += impl.combine(callable, INLINE_EXECUTOR, futures).get(); + } + return sum; + } + + @Benchmark int timeSuccesfulFutures(int reps) throws Exception { + Impl impl = this.impl; + Callable<Integer> callable = Callables.returning(12); + int sum = 0; + for (int i = 0; i < reps; i++) { + ImmutableList<SettableFuture<Integer>> futures = getSettableFutureList(); + ListenableFuture<Integer> combined = impl.combine(callable, INLINE_EXECUTOR, futures); + for (SettableFuture<Integer> future : futures) { + future.set(i); + } + sum += combined.get(); + } + return sum; + } + + @Benchmark int timeFailedFutures(int reps) throws Exception { + Impl impl = this.impl; + Callable<Integer> callable = Callables.returning(12); + int sum = 0; + Exception throwable = new Exception("boom"); + for (int i = 0; i < reps; i++) { + ImmutableList<SettableFuture<Integer>> futures = getSettableFutureList(); + ListenableFuture<Integer> combined = impl.combine(callable, INLINE_EXECUTOR, futures); + for (SettableFuture<Integer> future : futures) { + future.setException(throwable); + } + sum += combined.get(); + } + return sum; + } + + private ImmutableList<SettableFuture<Integer>> getSettableFutureList() { + ImmutableList.Builder<SettableFuture<Integer>> futuresBuilder = ImmutableList.builder(); + for (int i = 0; i < numInputs; i++) { + futuresBuilder.add(SettableFuture.<Integer>create()); + } + return futuresBuilder.build(); + } +} diff --git a/guava-tests/benchmark/com/google/common/util/concurrent/MoreExecutorsDirectExecutorBenchmark.java b/guava-tests/benchmark/com/google/common/util/concurrent/MoreExecutorsDirectExecutorBenchmark.java new file mode 100644 index 000000000..aaecd50cd --- /dev/null +++ b/guava-tests/benchmark/com/google/common/util/concurrent/MoreExecutorsDirectExecutorBenchmark.java @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2014 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.util.concurrent; + +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; +import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService; + +import com.google.caliper.AfterExperiment; +import com.google.caliper.BeforeExperiment; +import com.google.caliper.Benchmark; +import com.google.caliper.Param; +import com.google.caliper.api.Footprint; +import com.google.caliper.api.VmOptions; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * A benchmark comparing the {@link MoreExecutors#newDirectExecutorService()} to + * {@link MoreExecutors#directExecutor}. + */ +@VmOptions({"-Xms12g", "-Xmx12g", "-d64"}) +public class MoreExecutorsDirectExecutorBenchmark { + enum Impl { + EXECUTOR_SERVICE { + @Override Executor executor() { + return newDirectExecutorService(); + } + }, + EXECUTOR { + @Override Executor executor() { + return directExecutor(); + } + }; + abstract Executor executor(); + } + + @Param Impl impl; + Executor executor; + + static final class CountingRunnable implements Runnable { + AtomicInteger integer = new AtomicInteger(); + @Override public void run() { + integer.incrementAndGet(); + } + } + + CountingRunnable countingRunnable = new CountingRunnable(); + + Set<Thread> threads = new HashSet<Thread>(); + + @BeforeExperiment void before() { + executor = impl.executor(); + for (int i = 0; i < 4; i++) { + Thread thread = new Thread() { + @Override public void run() { + CountingRunnable localRunnable = new CountingRunnable(); + while (!isInterrupted()) { + executor.execute(localRunnable); + } + countingRunnable.integer.addAndGet(localRunnable.integer.get()); + } + }; + threads.add(thread); + } + } + + @AfterExperiment void after() { + for (Thread thread : threads) { + thread.interrupt(); // try to get them to exit + } + threads.clear(); + } + + @Footprint Object measureSize() { + return executor; + } + + @Benchmark int timeUncontendedExecute(int reps) { + final Executor executor = this.executor; + final CountingRunnable countingRunnable = this.countingRunnable; + for (int i = 0; i < reps; i++) { + executor.execute(countingRunnable); + } + return countingRunnable.integer.get(); + } + + @Benchmark int timeContendedExecute(int reps) { + final Executor executor = this.executor; + for (Thread thread : threads) { + if (!thread.isAlive()) { + thread.start(); + } + } + final CountingRunnable countingRunnable = this.countingRunnable; + for (int i = 0; i < reps; i++) { + executor.execute(countingRunnable); + } + return countingRunnable.integer.get(); + } +} diff --git a/guava-tests/pom.xml b/guava-tests/pom.xml index 55cd277eb..ea1e3031f 100644 --- a/guava-tests/pom.xml +++ b/guava-tests/pom.xml @@ -4,11 +4,11 @@ <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.google.guava</groupId> - <artifactId>guava-parent-jdk5</artifactId> - <version>17.0</version> + <artifactId>guava-parent</artifactId> + <version>18.0</version> </parent> - <artifactId>guava-tests-jdk5</artifactId> - <name>Guava Unit Tests (JDK5 Backport)</name> + <artifactId>guava-tests</artifactId> + <name>Guava Unit Tests</name> <description> The unit tests for the Guava libraries - separated into a separate artifact to allow for the testlibs to depend on guava @@ -17,17 +17,11 @@ <dependencies> <dependency> <groupId>${project.groupId}</groupId> - <artifactId>guava-testlib-jdk5</artifactId> + <artifactId>guava-testlib</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>guava-bootstrap-jdk5</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> </dependency> @@ -44,7 +38,7 @@ <artifactId>mockito-core</artifactId> </dependency> <dependency> - <groupId>org.truth0</groupId> + <groupId>com.google.truth</groupId> <artifactId>truth</artifactId> </dependency> <dependency> @@ -56,23 +50,6 @@ <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <!-- Prepend guava-bootstrap to avoid an API incompatibility between JDK5 and JDK6 --> - <compilerArgument>-Xbootclasspath/p:${project.build.directory}/dependency/guava-bootstrap-jdk5-${project.version}.jar</compilerArgument> - </configuration> - </plugin> - <plugin> - <artifactId>maven-dependency-plugin</artifactId> - <executions> - <execution> - <id>prep-guava-bootstrap</id> - <phase>process-sources</phase> - <goals><goal>copy-dependencies</goal></goals> - <configuration> - <includeArtifactIds>guava-bootstrap-jdk5</includeArtifactIds> - </configuration> - </execution> - </executions> </plugin> <plugin> <artifactId>maven-source-plugin</artifactId> diff --git a/guava-tests/test/com/google/common/base/AsciiTest.java b/guava-tests/test/com/google/common/base/AsciiTest.java index 8aaff5ede..03a6a3e37 100644 --- a/guava-tests/test/com/google/common/base/AsciiTest.java +++ b/guava-tests/test/com/google/common/base/AsciiTest.java @@ -17,6 +17,7 @@ package com.google.common.base; import com.google.common.annotations.GwtCompatible; +import com.google.common.annotations.GwtIncompatible; import junit.framework.TestCase; @@ -135,6 +136,7 @@ public class AsciiTest extends TestCase { assertFalse(Ascii.equalsIgnoreCase("[", "{")); } + @GwtIncompatible("String.toUpperCase() has browser semantics") public void testEqualsIgnoreCaseUnicodeEquivalence() { // Note that it's possible in future that the JDK's idea to toUpperCase() or equalsIgnoreCase() // may change and break assumptions in this test [*]. This is not a bug in the implementation of diff --git a/guava-tests/test/com/google/common/base/CharsetsTest.java b/guava-tests/test/com/google/common/base/CharsetsTest.java index bf0b177bb..f604dd029 100644 --- a/guava-tests/test/com/google/common/base/CharsetsTest.java +++ b/guava-tests/test/com/google/common/base/CharsetsTest.java @@ -21,7 +21,6 @@ import com.google.common.annotations.GwtIncompatible; import junit.framework.TestCase; -import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Arrays; @@ -63,12 +62,12 @@ public class CharsetsTest extends TestCase { } @GwtIncompatible("Non-UTF-8 Charset") - public void testWhyUsAsciiIsDangerous() throws UnsupportedEncodingException { - byte[] b1 = "朝日新聞".getBytes(Charsets.US_ASCII.name()); - byte[] b2 = "聞朝日新".getBytes(Charsets.US_ASCII.name()); - byte[] b3 = "????".getBytes(Charsets.US_ASCII.name()); - byte[] b4 = "ニュース".getBytes(Charsets.US_ASCII.name()); - byte[] b5 = "スューー".getBytes(Charsets.US_ASCII.name()); + public void testWhyUsAsciiIsDangerous() { + byte[] b1 = "朝日新聞".getBytes(Charsets.US_ASCII); + byte[] b2 = "聞朝日新".getBytes(Charsets.US_ASCII); + byte[] b3 = "????".getBytes(Charsets.US_ASCII); + byte[] b4 = "ニュース".getBytes(Charsets.US_ASCII); + byte[] b5 = "スューー".getBytes(Charsets.US_ASCII); // Assert they are all equal (using the transitive property) assertTrue(Arrays.equals(b1, b2)); assertTrue(Arrays.equals(b2, b3)); diff --git a/guava-tests/test/com/google/common/base/EnumsTest.java b/guava-tests/test/com/google/common/base/EnumsTest.java index c85455c02..a5faed2c0 100644 --- a/guava-tests/test/com/google/common/base/EnumsTest.java +++ b/guava-tests/test/com/google/common/base/EnumsTest.java @@ -19,7 +19,6 @@ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.ImmutableSet; -import com.google.common.testing.EqualsTester; import com.google.common.testing.GcFinalization; import com.google.common.testing.NullPointerTester; import com.google.common.testing.SerializableTester; @@ -50,39 +49,6 @@ public class EnumsTest extends TestCase { private enum OtherEnum {} - public void testValueOfFunction() { - Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class); - assertEquals(TestEnum.CHEETO, function.apply("CHEETO")); - assertEquals(TestEnum.HONDA, function.apply("HONDA")); - assertEquals(TestEnum.POODLE, function.apply("POODLE")); - } - - public void testValueOfFunction_caseSensitive() { - Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class); - assertNull(function.apply("cHEETO")); - assertNull(function.apply("Honda")); - assertNull(function.apply("poodlE")); - } - - public void testValueOfFunction_nullWhenNoMatchingConstant() { - Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class); - assertNull(function.apply("WOMBAT")); - } - - public void testValueOfFunction_equals() { - new EqualsTester() - .addEqualityGroup( - Enums.valueOfFunction(TestEnum.class), Enums.valueOfFunction(TestEnum.class)) - .addEqualityGroup(Enums.valueOfFunction(OtherEnum.class)) - .testEquals(); - } - - @GwtIncompatible("SerializableTester") - public void testValueOfFunction_serialization() { - Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class); - SerializableTester.reserializeAndAssert(function); - } - public void testGetIfPresent() { assertEquals(Optional.of(TestEnum.CHEETO), Enums.getIfPresent(TestEnum.class, "CHEETO")); assertEquals(Optional.of(TestEnum.HONDA), Enums.getIfPresent(TestEnum.class, "HONDA")); diff --git a/guava-tests/test/com/google/common/base/FinalizableReferenceQueueClassLoaderUnloadingTest.java b/guava-tests/test/com/google/common/base/FinalizableReferenceQueueClassLoaderUnloadingTest.java index 7f498b675..080c66778 100644 --- a/guava-tests/test/com/google/common/base/FinalizableReferenceQueueClassLoaderUnloadingTest.java +++ b/guava-tests/test/com/google/common/base/FinalizableReferenceQueueClassLoaderUnloadingTest.java @@ -26,9 +26,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; -import java.security.CodeSource; import java.security.Permission; -import java.security.PermissionCollection; import java.security.Policy; import java.security.ProtectionDomain; import java.util.concurrent.Callable; @@ -77,16 +75,6 @@ public class FinalizableReferenceQueueClassLoaderUnloadingTest extends TestCase public boolean implies(ProtectionDomain pd, Permission perm) { return true; } - - @Override - public PermissionCollection getPermissions(CodeSource codesource) { - throw new AssertionError(); - } - - @Override - public void refresh() { - throw new AssertionError(); - } } private WeakReference<ClassLoader> useFrqInSeparateLoader() throws Exception { diff --git a/guava-tests/test/com/google/common/base/JoinerTest.java b/guava-tests/test/com/google/common/base/JoinerTest.java index 169313e61..32f22e264 100644 --- a/guava-tests/test/com/google/common/base/JoinerTest.java +++ b/guava-tests/test/com/google/common/base/JoinerTest.java @@ -22,7 +22,6 @@ import com.google.common.base.Joiner.MapJoiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.testing.NullPointerTester; @@ -357,10 +356,7 @@ public class JoinerTest extends TestCase { @GwtIncompatible("NullPointerTester") public void testNullPointers() { - NullPointerTester tester = new NullPointerTester() - // This is necessary because of the generics hackery we have to temporarily support - // parameters which implement both Iterator and Iterable.; - .setDefault(Object.class, Iterators.emptyIterator()); + NullPointerTester tester = new NullPointerTester(); tester.testAllPublicStaticMethods(Joiner.class); tester.testInstanceMethods(Joiner.on(","), NullPointerTester.Visibility.PACKAGE); tester.testInstanceMethods(Joiner.on(",").skipNulls(), NullPointerTester.Visibility.PACKAGE); diff --git a/guava-tests/test/com/google/common/base/OptionalTest.java b/guava-tests/test/com/google/common/base/OptionalTest.java index 113e331cf..daa892027 100644 --- a/guava-tests/test/com/google/common/base/OptionalTest.java +++ b/guava-tests/test/com/google/common/base/OptionalTest.java @@ -16,7 +16,7 @@ package com.google.common.base; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -221,34 +221,34 @@ public final class OptionalTest extends TestCase { public void testPresentInstances_allPresent() { List<Optional<String>> optionals = ImmutableList.of(Optional.of("a"), Optional.of("b"), Optional.of("c")); - ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "b", "c"); + assertThat(Optional.presentInstances(optionals)).iteratesAs("a", "b", "c"); } public void testPresentInstances_allAbsent() { List<Optional<Object>> optionals = ImmutableList.of(Optional.absent(), Optional.absent()); - ASSERT.that(Optional.presentInstances(optionals)).isEmpty(); + assertThat(Optional.presentInstances(optionals)).isEmpty(); } public void testPresentInstances_somePresent() { List<Optional<String>> optionals = ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c")); - ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "c"); + assertThat(Optional.presentInstances(optionals)).iteratesAs("a", "c"); } public void testPresentInstances_callingIteratorTwice() { List<Optional<String>> optionals = ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c")); Iterable<String> onlyPresent = Optional.presentInstances(optionals); - ASSERT.that(onlyPresent).iteratesOverSequence("a", "c"); - ASSERT.that(onlyPresent).iteratesOverSequence("a", "c"); + assertThat(onlyPresent).iteratesAs("a", "c"); + assertThat(onlyPresent).iteratesAs("a", "c"); } public void testPresentInstances_wildcards() { List<Optional<? extends Number>> optionals = ImmutableList.<Optional<? extends Number>>of(Optional.<Double>absent(), Optional.of(2)); Iterable<Number> onlyPresent = Optional.presentInstances(optionals); - ASSERT.that(onlyPresent).iteratesOverSequence(2); + assertThat(onlyPresent).iteratesAs(2); } private static Optional<Integer> getSomeOptionalInt() { diff --git a/guava-tests/test/com/google/common/base/SplitterTest.java b/guava-tests/test/com/google/common/base/SplitterTest.java index 0ac09cfe0..88b4c80e0 100644 --- a/guava-tests/test/com/google/common/base/SplitterTest.java +++ b/guava-tests/test/com/google/common/base/SplitterTest.java @@ -16,7 +16,7 @@ package com.google.common.base; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -51,7 +51,7 @@ public class SplitterTest extends TestCase { public void testCharacterSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(simple); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } /** @@ -65,7 +65,7 @@ public class SplitterTest extends TestCase { public void testCharacterSimpleSplitToList() { String simple = "a,b,c"; List<String> letters = COMMA_SPLITTER.splitToList(simple); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } public void testToString() { @@ -77,37 +77,37 @@ public class SplitterTest extends TestCase { public void testCharacterSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on('.').split(simple); - ASSERT.that(letters).iteratesOverSequence("a,b,c"); + assertThat(letters).iteratesAs("a,b,c"); } public void testCharacterSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "", "b", "c"); + assertThat(letters).iteratesAs("a", "", "b", "c"); } public void testCharacterSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = COMMA_SPLITTER.split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "", " b", "c"); + assertThat(letters).iteratesAs("a", "", " b", "c"); } public void testCharacterSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = COMMA_SPLITTER.split(trailing); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); + assertThat(letters).iteratesAs("a", "b", "c", ""); } public void testCharacterSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(leading); - ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); + assertThat(letters).iteratesAs("", "a", "b", "c"); } public void testCharacterSplitWithMulitpleLetters() { Iterable<String> testCharacteringMotto = Splitter.on('-').split( "Testing-rocks-Debugging-sucks"); - ASSERT.that(testCharacteringMotto).iteratesOverSequence( + assertThat(testCharacteringMotto).iteratesAs( "Testing", "rocks", "Debugging", "sucks"); } @@ -115,7 +115,7 @@ public class SplitterTest extends TestCase { Iterable<String> testCharacteringMotto = Splitter .on(CharMatcher.WHITESPACE) .split("Testing\nrocks\tDebugging sucks"); - ASSERT.that(testCharacteringMotto).iteratesOverSequence( + assertThat(testCharacteringMotto).iteratesAs( "Testing", "rocks", "Debugging", "sucks"); } @@ -123,40 +123,40 @@ public class SplitterTest extends TestCase { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } public void testCharacterSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.').trimResults() .split(emptyToken); - ASSERT.that(letters).iteratesOverSequence("a", "", "c"); + assertThat(letters).iteratesAs("a", "", "c"); } public void testCharacterSplitEmptyTokenOmitEmptyStrings() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().trimResults().split(emptyToken); - ASSERT.that(letters).iteratesOverSequence("a", "c"); + assertThat(letters).iteratesAs("a", "c"); } public void testCharacterSplitOnEmptyString() { Iterable<String> nothing = Splitter.on('.').split(""); - ASSERT.that(nothing).iteratesOverSequence(""); + assertThat(nothing).iteratesAs(""); } public void testCharacterSplitOnEmptyStringOmitEmptyStrings() { - ASSERT.that(Splitter.on('.').omitEmptyStrings().split("")).isEmpty(); + assertThat(Splitter.on('.').omitEmptyStrings().split("")).isEmpty(); } public void testCharacterSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on('.').split("."); - ASSERT.that(blankblank).iteratesOverSequence("", ""); + assertThat(blankblank).iteratesAs("", ""); } public void testCharacterSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on('.').omitEmptyStrings().split("..."); - ASSERT.that(empty).isEmpty(); + assertThat(empty).isEmpty(); } public void testCharacterSplitWithTrim() { @@ -165,50 +165,50 @@ public class SplitterTest extends TestCase { Iterable<String> family = COMMA_SPLITTER .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.WHITESPACE)) .split(jacksons); - ASSERT.that(family).iteratesOverSequence( + assertThat(family).iteratesAs( "(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)"); } public void testStringSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on(',').split(simple); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } public void testStringSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on('.').split(simple); - ASSERT.that(letters).iteratesOverSequence("a,b,c"); + assertThat(letters).iteratesAs("a,b,c"); } public void testStringSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = Splitter.on(',').split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "", "b", "c"); + assertThat(letters).iteratesAs("a", "", "b", "c"); } public void testStringSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = Splitter.on(',').split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "", " b", "c"); + assertThat(letters).iteratesAs("a", "", " b", "c"); } public void testStringSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = Splitter.on(',').split(trailing); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); + assertThat(letters).iteratesAs("a", "b", "c", ""); } public void testStringSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = Splitter.on(',').split(leading); - ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); + assertThat(letters).iteratesAs("", "a", "b", "c"); } public void testStringSplitWithMultipleLetters() { Iterable<String> testStringingMotto = Splitter.on('-').split( "Testing-rocks-Debugging-sucks"); - ASSERT.that(testStringingMotto).iteratesOverSequence( + assertThat(testStringingMotto).iteratesAs( "Testing", "rocks", "Debugging", "sucks"); } @@ -216,46 +216,46 @@ public class SplitterTest extends TestCase { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } public void testStringSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.').trimResults() .split(emptyToken); - ASSERT.that(letters).iteratesOverSequence("a", "", "c"); + assertThat(letters).iteratesAs("a", "", "c"); } public void testStringSplitEmptyTokenOmitEmptyStrings() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().trimResults().split(emptyToken); - ASSERT.that(letters).iteratesOverSequence("a", "c"); + assertThat(letters).iteratesAs("a", "c"); } public void testStringSplitWithLongDelimiter() { String longDelimiter = "a, b, c"; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } public void testStringSplitWithLongLeadingDelimiter() { String longDelimiter = ", a, b, c"; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); - ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); + assertThat(letters).iteratesAs("", "a", "b", "c"); } public void testStringSplitWithLongTrailingDelimiter() { String longDelimiter = "a, b, c, "; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); + assertThat(letters).iteratesAs("a", "b", "c", ""); } public void testStringSplitWithDelimiterSubstringInValue() { String fourCommasAndFourSpaces = ",,,, "; Iterable<String> threeCommasThenThreeSpaces = Splitter.on(", ").split( fourCommasAndFourSpaces); - ASSERT.that(threeCommasThenThreeSpaces).iteratesOverSequence(",,,", " "); + assertThat(threeCommasThenThreeSpaces).iteratesAs(",,,", " "); } public void testStringSplitWithEmptyString() { @@ -268,21 +268,21 @@ public class SplitterTest extends TestCase { public void testStringSplitOnEmptyString() { Iterable<String> notMuch = Splitter.on('.').split(""); - ASSERT.that(notMuch).iteratesOverSequence(""); + assertThat(notMuch).iteratesAs(""); } public void testStringSplitOnEmptyStringOmitEmptyString() { - ASSERT.that(Splitter.on('.').omitEmptyStrings().split("")).isEmpty(); + assertThat(Splitter.on('.').omitEmptyStrings().split("")).isEmpty(); } public void testStringSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on('.').split("."); - ASSERT.that(blankblank).iteratesOverSequence("", ""); + assertThat(blankblank).iteratesAs("", ""); } public void testStringSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on('.').omitEmptyStrings().split("..."); - ASSERT.that(empty).isEmpty(); + assertThat(empty).isEmpty(); } public void testStringSplitWithTrim() { @@ -291,7 +291,7 @@ public class SplitterTest extends TestCase { Iterable<String> family = Splitter.on(',') .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.WHITESPACE)) .split(jacksons); - ASSERT.that(family).iteratesOverSequence( + assertThat(family).iteratesAs( "(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)"); } @@ -299,42 +299,42 @@ public class SplitterTest extends TestCase { public void testPatternSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = Splitter.onPattern(",").split(simple); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } @GwtIncompatible("Splitter.onPattern") public void testPatternSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.onPattern("foo").split(simple); - ASSERT.that(letters).iteratesOverSequence("a,b,c"); + assertThat(letters).iteratesAs("a,b,c"); } @GwtIncompatible("Splitter.onPattern") public void testPatternSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = Splitter.onPattern(",").split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "", "b", "c"); + assertThat(letters).iteratesAs("a", "", "b", "c"); } @GwtIncompatible("Splitter.onPattern") public void testPatternSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = Splitter.onPattern(",").split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "", " b", "c"); + assertThat(letters).iteratesAs("a", "", " b", "c"); } @GwtIncompatible("Splitter.onPattern") public void testPatternSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = Splitter.onPattern(",").split(trailing); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); + assertThat(letters).iteratesAs("a", "b", "c", ""); } @GwtIncompatible("Splitter.onPattern") public void testPatternSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = Splitter.onPattern(",").split(leading); - ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); + assertThat(letters).iteratesAs("", "a", "b", "c"); } // TODO(kevinb): the name of this method suggests it might not actually be testing what it @@ -343,7 +343,7 @@ public class SplitterTest extends TestCase { public void testPatternSplitWithMultipleLetters() { Iterable<String> testPatterningMotto = Splitter.onPattern("-").split( "Testing-rocks-Debugging-sucks"); - ASSERT.that(testPatterningMotto).iteratesOverSequence("Testing", "rocks", "Debugging", "sucks"); + assertThat(testPatterningMotto).iteratesAs("Testing", "rocks", "Debugging", "sucks"); } @GwtIncompatible("java.util.regex.Pattern") @@ -356,7 +356,7 @@ public class SplitterTest extends TestCase { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on(literalDotPattern()) .omitEmptyStrings().split(doubled); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } @GwtIncompatible("java.util.regex.Pattern") @@ -364,7 +364,7 @@ public class SplitterTest extends TestCase { String toSplit = ":foo::barbaz:"; String regexPattern = "(?<=:)"; Iterable<String> split = Splitter.onPattern(regexPattern).split(toSplit); - ASSERT.that(split).iteratesOverSequence(":", "foo:", ":", "barbaz:"); + assertThat(split).iteratesAs(":", "foo:", ":", "barbaz:"); // splits into chunks ending in : } @@ -372,14 +372,14 @@ public class SplitterTest extends TestCase { public void testPatternSplitWordBoundary() { String string = "foo<bar>bletch"; Iterable<String> words = Splitter.on(Pattern.compile("\\b")).split(string); - ASSERT.that(words).iteratesOverSequence("foo", "<", "bar", ">", "bletch"); + assertThat(words).iteratesAs("foo", "<", "bar", ">", "bletch"); } @GwtIncompatible("java.util.regex.Pattern") public void testPatternSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on(literalDotPattern()).trimResults().split(emptyToken); - ASSERT.that(letters).iteratesOverSequence("a", "", "c"); + assertThat(letters).iteratesAs("a", "", "c"); } @GwtIncompatible("java.util.regex.Pattern") @@ -387,21 +387,21 @@ public class SplitterTest extends TestCase { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on(literalDotPattern()) .omitEmptyStrings().trimResults().split(emptyToken); - ASSERT.that(letters).iteratesOverSequence("a", "c"); + assertThat(letters).iteratesAs("a", "c"); } @GwtIncompatible("java.util.regex.Pattern") public void testPatternSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on(literalDotPattern()).split("."); - ASSERT.that(blankblank).iteratesOverSequence("", ""); + assertThat(blankblank).iteratesAs("", ""); } @GwtIncompatible("java.util.regex.Pattern") public void testPatternSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on(literalDotPattern()).omitEmptyStrings() .split("..."); - ASSERT.that(empty).isEmpty(); + assertThat(empty).isEmpty(); } @GwtIncompatible("java.util.regex.Pattern") @@ -409,7 +409,7 @@ public class SplitterTest extends TestCase { String longDelimiter = "a, b, c"; Iterable<String> letters = Splitter.on(Pattern.compile(",\\s*")) .split(longDelimiter); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); + assertThat(letters).iteratesAs("a", "b", "c"); } @GwtIncompatible("java.util.regex.Pattern") @@ -417,7 +417,7 @@ public class SplitterTest extends TestCase { String longDelimiter = ", a, b, c"; Iterable<String> letters = Splitter.on(Pattern.compile(", ")) .split(longDelimiter); - ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); + assertThat(letters).iteratesAs("", "a", "b", "c"); } @GwtIncompatible("java.util.regex.Pattern") @@ -425,7 +425,7 @@ public class SplitterTest extends TestCase { String longDelimiter = "a, b, c/ "; Iterable<String> letters = Splitter.on(Pattern.compile("[,/]\\s")) .split(longDelimiter); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); + assertThat(letters).iteratesAs("a", "b", "c", ""); } @GwtIncompatible("java.util.regex.Pattern") @@ -444,7 +444,7 @@ public class SplitterTest extends TestCase { Iterable<String> family = Splitter.on(Pattern.compile(",")) .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.WHITESPACE)) .split(jacksons); - ASSERT.that(family).iteratesOverSequence( + assertThat(family).iteratesAs( "(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)"); } @@ -505,41 +505,41 @@ public class SplitterTest extends TestCase { public void testFixedLengthSimpleSplit() { String simple = "abcde"; Iterable<String> letters = Splitter.fixedLength(2).split(simple); - ASSERT.that(letters).iteratesOverSequence("ab", "cd", "e"); + assertThat(letters).iteratesAs("ab", "cd", "e"); } public void testFixedLengthSplitEqualChunkLength() { String simple = "abcdef"; Iterable<String> letters = Splitter.fixedLength(2).split(simple); - ASSERT.that(letters).iteratesOverSequence("ab", "cd", "ef"); + assertThat(letters).iteratesAs("ab", "cd", "ef"); } public void testFixedLengthSplitOnlyOneChunk() { String simple = "abc"; Iterable<String> letters = Splitter.fixedLength(3).split(simple); - ASSERT.that(letters).iteratesOverSequence("abc"); + assertThat(letters).iteratesAs("abc"); } public void testFixedLengthSplitSmallerString() { String simple = "ab"; Iterable<String> letters = Splitter.fixedLength(3).split(simple); - ASSERT.that(letters).iteratesOverSequence("ab"); + assertThat(letters).iteratesAs("ab"); } public void testFixedLengthSplitEmptyString() { String simple = ""; Iterable<String> letters = Splitter.fixedLength(3).split(simple); - ASSERT.that(letters).iteratesOverSequence(""); + assertThat(letters).iteratesAs(""); } public void testFixedLengthSplitEmptyStringWithOmitEmptyStrings() { - ASSERT.that(Splitter.fixedLength(3).omitEmptyStrings().split("")).isEmpty(); + assertThat(Splitter.fixedLength(3).omitEmptyStrings().split("")).isEmpty(); } public void testFixedLengthSplitIntoChars() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).split(simple); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "d"); + assertThat(letters).iteratesAs("a", "b", "c", "d"); } public void testFixedLengthSplitZeroChunkLen() { @@ -561,79 +561,79 @@ public class SplitterTest extends TestCase { public void testLimitLarge() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(100).split(simple); - ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "d"); + assertThat(letters).iteratesAs("a", "b", "c", "d"); } public void testLimitOne() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(1).split(simple); - ASSERT.that(letters).iteratesOverSequence("abcd"); + assertThat(letters).iteratesAs("abcd"); } public void testLimitFixedLength() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(2).split(simple); - ASSERT.that(letters).iteratesOverSequence("a", "bcd"); + assertThat(letters).iteratesAs("a", "bcd"); } public void testLimitSeparator() { String simple = "a,b,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).split(simple); - ASSERT.that(items).iteratesOverSequence("a", "b,c,d"); + assertThat(items).iteratesAs("a", "b,c,d"); } public void testLimitExtraSeparators() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).split(text); - ASSERT.that(items).iteratesOverSequence("a", ",,b,,c,d"); + assertThat(items).iteratesAs("a", ",,b,,c,d"); } public void testLimitExtraSeparatorsOmitEmpty() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().split(text); - ASSERT.that(items).iteratesOverSequence("a", "b,,c,d"); + assertThat(items).iteratesAs("a", "b,,c,d"); } public void testLimitExtraSeparatorsOmitEmpty3() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().split(text); - ASSERT.that(items).iteratesOverSequence("a", "b", "c,d"); + assertThat(items).iteratesAs("a", "b", "c,d"); } public void testLimitExtraSeparatorsTrim() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().trimResults().split(text); - ASSERT.that(items).iteratesOverSequence("a", "b ,, c,d"); + assertThat(items).iteratesAs("a", "b ,, c,d"); } public void testLimitExtraSeparatorsTrim3() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().trimResults().split(text); - ASSERT.that(items).iteratesOverSequence("a", "b", "c,d"); + assertThat(items).iteratesAs("a", "b", "c,d"); } public void testLimitExtraSeparatorsTrim1() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(1).omitEmptyStrings().trimResults().split(text); - ASSERT.that(items).iteratesOverSequence("a,, , b ,, c,d"); + assertThat(items).iteratesAs("a,, , b ,, c,d"); } public void testLimitExtraSeparatorsTrim1NoOmit() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(1).trimResults().split(text); - ASSERT.that(items).iteratesOverSequence(",,a,, , b ,, c,d"); + assertThat(items).iteratesAs(",,a,, , b ,, c,d"); } public void testLimitExtraSeparatorsTrim1Empty() { String text = ""; Iterable<String> items = COMMA_SPLITTER.limit(1).split(text); - ASSERT.that(items).iteratesOverSequence(""); + assertThat(items).iteratesAs(""); } public void testLimitExtraSeparatorsTrim1EmptyOmit() { String text = ""; Iterable<String> items = COMMA_SPLITTER.omitEmptyStrings().limit(1).split(text); - ASSERT.that(items).isEmpty(); + assertThat(items).isEmpty(); } @SuppressWarnings("ReturnValueIgnored") // testing for exception @@ -664,8 +664,8 @@ public class SplitterTest extends TestCase { .split("boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); - ASSERT.that(m).isEqualTo(expected); - ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); + assertThat(m).isEqualTo(expected); + assertThat(asList(m.entrySet())).isEqualTo(asList(expected.entrySet())); } public void testMapSplitter_trimmedEntries() { @@ -676,8 +676,8 @@ public class SplitterTest extends TestCase { ImmutableMap<String, String> expected = ImmutableMap.of("boy ", " tom", "girl", " tina", "cat ", " kitty", "dog", " tommy"); - ASSERT.that(m).isEqualTo(expected); - ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); + assertThat(m).isEqualTo(expected); + assertThat(asList(m.entrySet())).isEqualTo(asList(expected.entrySet())); } public void testMapSplitter_trimmedKeyValue() { @@ -686,8 +686,8 @@ public class SplitterTest extends TestCase { "boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); - ASSERT.that(m).isEqualTo(expected); - ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); + assertThat(m).isEqualTo(expected); + assertThat(asList(m.entrySet())).isEqualTo(asList(expected.entrySet())); } public void testMapSplitter_notTrimmed() { @@ -695,8 +695,8 @@ public class SplitterTest extends TestCase { " boy:tom , girl: tina , cat :kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of(" boy", "tom ", " girl", " tina ", " cat ", "kitty ", " dog", " tommy "); - ASSERT.that(m).isEqualTo(expected); - ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); + assertThat(m).isEqualTo(expected); + assertThat(asList(m.entrySet())).isEqualTo(asList(expected.entrySet())); } public void testMapSplitter_CharacterSeparator() { @@ -708,8 +708,8 @@ public class SplitterTest extends TestCase { ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); - ASSERT.that(m).isEqualTo(expected); - ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); + assertThat(m).isEqualTo(expected); + assertThat(asList(m.entrySet())).isEqualTo(asList(expected.entrySet())); } public void testMapSplitter_multiCharacterSeparator() { @@ -721,8 +721,8 @@ public class SplitterTest extends TestCase { ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); - ASSERT.that(m).isEqualTo(expected); - ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); + assertThat(m).isEqualTo(expected); + assertThat(asList(m.entrySet())).isEqualTo(asList(expected.entrySet())); } @SuppressWarnings("ReturnValueIgnored") // testing for exception @@ -747,8 +747,8 @@ public class SplitterTest extends TestCase { .withKeyValueSeparator(":") .split("boy:tom,girl:tina,cat:kitty,dog:tommy"); - ASSERT.that(m.keySet()).iteratesOverSequence("boy", "girl", "cat", "dog"); - ASSERT.that(m).isEqualTo( + assertThat(m.keySet()).iteratesAs("boy", "girl", "cat", "dog"); + assertThat(m).isEqualTo( ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy")); // try in a different order @@ -756,8 +756,8 @@ public class SplitterTest extends TestCase { .withKeyValueSeparator(":") .split("girl:tina,boy:tom,dog:tommy,cat:kitty"); - ASSERT.that(m.keySet()).iteratesOverSequence("girl", "boy", "dog", "cat"); - ASSERT.that(m).isEqualTo( + assertThat(m.keySet()).iteratesAs("girl", "boy", "dog", "cat"); + assertThat(m).isEqualTo( ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy")); } diff --git a/guava-tests/test/com/google/common/base/StopwatchTest.java b/guava-tests/test/com/google/common/base/StopwatchTest.java index 4787343dc..bd6b2d241 100644 --- a/guava-tests/test/com/google/common/base/StopwatchTest.java +++ b/guava-tests/test/com/google/common/base/StopwatchTest.java @@ -233,6 +233,18 @@ public class StopwatchTest extends TestCase { stopwatch.start(); ticker.advance(5000000000L); assertEquals("5.000 s", stopwatch.toString()); + stopwatch.reset(); + stopwatch.start(); + ticker.advance((long) (1.5 * 60 * 1000000000L)); + assertEquals("1.500 min", stopwatch.toString()); + stopwatch.reset(); + stopwatch.start(); + ticker.advance((long) (2.5 * 60 * 60 * 1000000000L)); + assertEquals("2.500 h", stopwatch.toString()); + stopwatch.reset(); + stopwatch.start(); + ticker.advance((long) (7.25 * 24 * 60 * 60 * 1000000000L)); + assertEquals("7.250 d", stopwatch.toString()); } } diff --git a/guava-tests/test/com/google/common/base/Utf8Test.java b/guava-tests/test/com/google/common/base/Utf8Test.java index e56a53a25..f098123a3 100644 --- a/guava-tests/test/com/google/common/base/Utf8Test.java +++ b/guava-tests/test/com/google/common/base/Utf8Test.java @@ -21,7 +21,6 @@ import com.google.common.annotations.GwtIncompatible; import junit.framework.TestCase; -import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import java.util.Random; @@ -310,14 +309,9 @@ public class Utf8Test extends TestCase { } boolean isRoundTrippable = Utf8.isWellFormed(bytes); assertEquals(isRoundTrippable, Utf8.isWellFormed(bytes, 0, numBytes)); - boolean bytesEqual; - try { - String s = new String(bytes, Charsets.UTF_8.name()); - byte[] bytesReencoded = s.getBytes(Charsets.UTF_8.name()); - bytesEqual = Arrays.equals(bytes, bytesReencoded); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + String s = new String(bytes, Charsets.UTF_8); + byte[] bytesReencoded = s.getBytes(Charsets.UTF_8); + boolean bytesEqual = Arrays.equals(bytes, bytesReencoded); if (bytesEqual != isRoundTrippable) { fail(); diff --git a/guava-tests/test/com/google/common/cache/AbstractCacheTest.java b/guava-tests/test/com/google/common/cache/AbstractCacheTest.java index 693513379..b3bee1aba 100644 --- a/guava-tests/test/com/google/common/cache/AbstractCacheTest.java +++ b/guava-tests/test/com/google/common/cache/AbstractCacheTest.java @@ -19,6 +19,7 @@ package com.google.common.cache; import com.google.common.cache.AbstractCache.SimpleStatsCounter; import com.google.common.cache.AbstractCache.StatsCounter; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import junit.framework.TestCase; @@ -33,7 +34,7 @@ import java.util.concurrent.atomic.AtomicReference; */ public class AbstractCacheTest extends TestCase { - public void testGetAllPresent() { + public void testGetIfPresent() { final AtomicReference<Object> valueRef = new AtomicReference<Object>(); Cache<Object, Object> cache = new AbstractCache<Object, Object>() { @Override @@ -49,6 +50,34 @@ public class AbstractCacheTest extends TestCase { assertSame(newValue, cache.getIfPresent(new Object())); } + public void testGetAllPresent_empty() { + Cache<Object, Object> cache = new AbstractCache<Object, Object>() { + @Override + public Object getIfPresent(Object key) { + return null; + } + }; + + assertEquals( + ImmutableMap.of(), + cache.getAllPresent(ImmutableList.of(new Object()))); + } + + public void testGetAllPresent_cached() { + final Object cachedKey = new Object(); + final Object cachedValue = new Object(); + Cache<Object, Object> cache = new AbstractCache<Object, Object>() { + @Override + public Object getIfPresent(Object key) { + return cachedKey.equals(key) ? cachedValue : null; + } + }; + + assertEquals( + ImmutableMap.of(cachedKey, cachedValue), + cache.getAllPresent(ImmutableList.of(cachedKey, new Object()))); + } + public void testInvalidateAll() { final List<Object> invalidated = Lists.newArrayList(); Cache<Integer, Integer> cache = new AbstractCache<Integer, Integer>() { diff --git a/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java b/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java index 865faf852..83ecf48d9 100644 --- a/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java +++ b/guava-tests/test/com/google/common/cache/CacheBuilderFactory.java @@ -15,6 +15,7 @@ package com.google.common.cache; import com.google.common.base.Function; +import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; @@ -208,7 +209,7 @@ class CacheBuilderFactory { @Override public String toString() { - return Objects.toStringHelper(this) + return MoreObjects.toStringHelper(this) .add("duration", duration) .add("unit", unit) .toString(); diff --git a/guava-tests/test/com/google/common/cache/CacheBuilderSpecTest.java b/guava-tests/test/com/google/common/cache/CacheBuilderSpecTest.java index aae9a460b..7dd5261d1 100644 --- a/guava-tests/test/com/google/common/cache/CacheBuilderSpecTest.java +++ b/guava-tests/test/com/google/common/cache/CacheBuilderSpecTest.java @@ -262,27 +262,27 @@ public class CacheBuilderSpecTest extends TestCase { assertNull(spec.concurrencyLevel); assertNull(spec.keyStrength); assertNull(spec.valueStrength); - assertEquals(TimeUnit.SECONDS, spec.writeExpirationTimeUnit); - assertEquals(24 * 60 * 60 * 10L, spec.writeExpirationDuration); + assertEquals(TimeUnit.DAYS, spec.writeExpirationTimeUnit); + assertEquals(10L, spec.writeExpirationDuration); assertNull(spec.accessExpirationTimeUnit); assertCacheBuilderEquivalence( - CacheBuilder.newBuilder().expireAfterWrite(24 * 60 * 60 * 10L, TimeUnit.SECONDS), CacheBuilder.from(spec)); + CacheBuilder.newBuilder().expireAfterWrite(10L, TimeUnit.DAYS), CacheBuilder.from(spec)); } public void testParse_writeExpirationHours() { CacheBuilderSpec spec = parse("expireAfterWrite=150h"); - assertEquals(TimeUnit.SECONDS, spec.writeExpirationTimeUnit); - assertEquals(60 * 60 * 150L, spec.writeExpirationDuration); + assertEquals(TimeUnit.HOURS, spec.writeExpirationTimeUnit); + assertEquals(150L, spec.writeExpirationDuration); assertCacheBuilderEquivalence( - CacheBuilder.newBuilder().expireAfterWrite(60 * 60 * 150L, TimeUnit.SECONDS), CacheBuilder.from(spec)); + CacheBuilder.newBuilder().expireAfterWrite(150L, TimeUnit.HOURS), CacheBuilder.from(spec)); } public void testParse_writeExpirationMinutes() { CacheBuilderSpec spec = parse("expireAfterWrite=10m"); - assertEquals(TimeUnit.SECONDS, spec.writeExpirationTimeUnit); - assertEquals(60 * 10L, spec.writeExpirationDuration); + assertEquals(TimeUnit.MINUTES, spec.writeExpirationTimeUnit); + assertEquals(10L, spec.writeExpirationDuration); assertCacheBuilderEquivalence( - CacheBuilder.newBuilder().expireAfterWrite(60 * 10L, TimeUnit.SECONDS), CacheBuilder.from(spec)); + CacheBuilder.newBuilder().expireAfterWrite(10L, TimeUnit.MINUTES), CacheBuilder.from(spec)); } public void testParse_writeExpirationSeconds() { @@ -312,26 +312,26 @@ public class CacheBuilderSpecTest extends TestCase { assertNull(spec.keyStrength); assertNull(spec.valueStrength); assertNull(spec.writeExpirationTimeUnit); - assertEquals(TimeUnit.SECONDS, spec.accessExpirationTimeUnit); - assertEquals(24 * 60 * 60 * 10L, spec.accessExpirationDuration); + assertEquals(TimeUnit.DAYS, spec.accessExpirationTimeUnit); + assertEquals(10L, spec.accessExpirationDuration); assertCacheBuilderEquivalence( - CacheBuilder.newBuilder().expireAfterAccess(24 * 60 * 60 * 10L, TimeUnit.SECONDS), CacheBuilder.from(spec)); + CacheBuilder.newBuilder().expireAfterAccess(10L, TimeUnit.DAYS), CacheBuilder.from(spec)); } public void testParse_accessExpirationHours() { CacheBuilderSpec spec = parse("expireAfterAccess=150h"); - assertEquals(TimeUnit.SECONDS, spec.accessExpirationTimeUnit); - assertEquals(60 * 60 * 150L, spec.accessExpirationDuration); + assertEquals(TimeUnit.HOURS, spec.accessExpirationTimeUnit); + assertEquals(150L, spec.accessExpirationDuration); assertCacheBuilderEquivalence( - CacheBuilder.newBuilder().expireAfterAccess(60 * 60 * 150L, TimeUnit.SECONDS), CacheBuilder.from(spec)); + CacheBuilder.newBuilder().expireAfterAccess(150L, TimeUnit.HOURS), CacheBuilder.from(spec)); } public void testParse_accessExpirationMinutes() { CacheBuilderSpec spec = parse("expireAfterAccess=10m"); - assertEquals(TimeUnit.SECONDS, spec.accessExpirationTimeUnit); - assertEquals(60 * 10L, spec.accessExpirationDuration); + assertEquals(TimeUnit.MINUTES, spec.accessExpirationTimeUnit); + assertEquals(10L, spec.accessExpirationDuration); assertCacheBuilderEquivalence( - CacheBuilder.newBuilder().expireAfterAccess(60 * 10L, TimeUnit.SECONDS), + CacheBuilder.newBuilder().expireAfterAccess(10L, TimeUnit.MINUTES), CacheBuilder.from(spec)); } @@ -380,14 +380,14 @@ public class CacheBuilderSpecTest extends TestCase { public void testParse_accessExpirationAndWriteExpiration() { CacheBuilderSpec spec = parse("expireAfterAccess=10s,expireAfterWrite=9m"); - assertEquals(TimeUnit.SECONDS, spec.writeExpirationTimeUnit); - assertEquals(60 * 9L, spec.writeExpirationDuration); + assertEquals(TimeUnit.MINUTES, spec.writeExpirationTimeUnit); + assertEquals(9L, spec.writeExpirationDuration); assertEquals(TimeUnit.SECONDS, spec.accessExpirationTimeUnit); assertEquals(10L, spec.accessExpirationDuration); assertCacheBuilderEquivalence( CacheBuilder.newBuilder() .expireAfterAccess(10L, TimeUnit.SECONDS) - .expireAfterWrite(60 * 9L, TimeUnit.SECONDS), + .expireAfterWrite(9L, TimeUnit.MINUTES), CacheBuilder.from(spec)); } @@ -400,18 +400,18 @@ public class CacheBuilderSpecTest extends TestCase { assertEquals(30, spec.concurrencyLevel.intValue()); assertEquals(Strength.WEAK, spec.keyStrength); assertEquals(Strength.WEAK, spec.valueStrength); - assertEquals(TimeUnit.SECONDS, spec.writeExpirationTimeUnit); - assertEquals(TimeUnit.SECONDS, spec.accessExpirationTimeUnit); - assertEquals(60 * 60 * 1L, spec.writeExpirationDuration); - assertEquals(60 * 10L, spec.accessExpirationDuration); + assertEquals(TimeUnit.HOURS, spec.writeExpirationTimeUnit); + assertEquals(TimeUnit.MINUTES, spec.accessExpirationTimeUnit); + assertEquals(1L, spec.writeExpirationDuration); + assertEquals(10L, spec.accessExpirationDuration); CacheBuilder<?, ?> expected = CacheBuilder.newBuilder() .initialCapacity(10) .maximumSize(20) .concurrencyLevel(30) .weakKeys() .weakValues() - .expireAfterAccess(60 * 10L, TimeUnit.SECONDS) - .expireAfterWrite(60 * 60 * 1L, TimeUnit.SECONDS); + .expireAfterAccess(10L, TimeUnit.MINUTES) + .expireAfterWrite(1L, TimeUnit.HOURS); assertCacheBuilderEquivalence(expected, CacheBuilder.from(spec)); } @@ -540,7 +540,7 @@ public class CacheBuilderSpecTest extends TestCase { .concurrencyLevel(30) .weakKeys() .weakValues() - .expireAfterAccess(60 * 10L, TimeUnit.SECONDS); + .expireAfterAccess(10L, TimeUnit.MINUTES); assertCacheBuilderEquivalence(expected, fromString); } diff --git a/guava-tests/test/com/google/common/cache/CacheEvictionTest.java b/guava-tests/test/com/google/common/cache/CacheEvictionTest.java index 6746b7e5f..351af8b30 100644 --- a/guava-tests/test/com/google/common/cache/CacheEvictionTest.java +++ b/guava-tests/test/com/google/common/cache/CacheEvictionTest.java @@ -18,8 +18,8 @@ import static com.google.common.cache.TestingCacheLoaders.identityLoader; import static com.google.common.cache.TestingRemovalListeners.countingRemovalListener; import static com.google.common.cache.TestingWeighers.constantWeigher; import static com.google.common.cache.TestingWeighers.intKeyWeigher; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.cache.CacheTesting.Receiver; import com.google.common.cache.LocalCache.ReferenceEntry; @@ -131,6 +131,21 @@ public class CacheEvictionTest extends TestCase { CacheTesting.checkValidState(cache); } + public void testEviction_overflow() { + CountingRemovalListener<Object, Object> removalListener = countingRemovalListener(); + IdentityLoader<Object> loader = identityLoader(); + LoadingCache<Object, Object> cache = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .maximumWeight(1L << 31) + .weigher(constantWeigher(Integer.MAX_VALUE)) + .removalListener(removalListener) + .build(loader); + cache.getUnchecked(objectWithHash(0)); + cache.getUnchecked(objectWithHash(0)); + CacheTesting.processPendingNotifications(cache); + assertEquals(1, removalListener.getCount()); + } + public void testUpdateRecency_onGet() { IdentityLoader<Integer> loader = identityLoader(); final LoadingCache<Integer, Integer> cache = @@ -169,27 +184,27 @@ public class CacheEvictionTest extends TestCase { .build(loader); CacheTesting.warmUp(cache, 0, 10); Set<Integer> keySet = cache.asMap().keySet(); - ASSERT.that(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // re-order getAll(cache, asList(0, 1, 2)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0, 1, 2); + assertThat(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0, 1, 2); // evict 3, 4, 5 getAll(cache, asList(10, 11, 12)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(6, 7, 8, 9, 0, 1, 2, 10, 11, 12); + assertThat(keySet).has().exactly(6, 7, 8, 9, 0, 1, 2, 10, 11, 12); // re-order getAll(cache, asList(6, 7, 8)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(9, 0, 1, 2, 10, 11, 12, 6, 7, 8); + assertThat(keySet).has().exactly(9, 0, 1, 2, 10, 11, 12, 6, 7, 8); // evict 9, 0, 1 getAll(cache, asList(13, 14, 15)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(2, 10, 11, 12, 6, 7, 8, 13, 14, 15); + assertThat(keySet).has().exactly(2, 10, 11, 12, 6, 7, 8, 13, 14, 15); } public void testEviction_weightedLru() { @@ -202,37 +217,37 @@ public class CacheEvictionTest extends TestCase { .build(loader); CacheTesting.warmUp(cache, 0, 10); Set<Integer> keySet = cache.asMap().keySet(); - ASSERT.that(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // re-order getAll(cache, asList(0, 1, 2)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0, 1, 2); + assertThat(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0, 1, 2); // evict 3, 4, 5 getAll(cache, asList(10)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(6, 7, 8, 9, 0, 1, 2, 10); + assertThat(keySet).has().exactly(6, 7, 8, 9, 0, 1, 2, 10); // re-order getAll(cache, asList(6, 7, 8)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(9, 0, 1, 2, 10, 6, 7, 8); + assertThat(keySet).has().exactly(9, 0, 1, 2, 10, 6, 7, 8); // evict 9, 1, 2, 10 getAll(cache, asList(15)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(0, 6, 7, 8, 15); + assertThat(keySet).has().exactly(0, 6, 7, 8, 15); // fill empty space getAll(cache, asList(9)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(0, 6, 7, 8, 15, 9); + assertThat(keySet).has().exactly(0, 6, 7, 8, 15, 9); // evict 6 getAll(cache, asList(1)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(0, 7, 8, 15, 9, 1); + assertThat(keySet).has().exactly(0, 7, 8, 15, 9, 1); } public void testEviction_overweight() { @@ -245,17 +260,17 @@ public class CacheEvictionTest extends TestCase { .build(loader); CacheTesting.warmUp(cache, 0, 10); Set<Integer> keySet = cache.asMap().keySet(); - ASSERT.that(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // add an at-the-maximum-weight entry getAll(cache, asList(45)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(0, 45); + assertThat(keySet).has().exactly(0, 45); // add an over-the-maximum-weight entry getAll(cache, asList(46)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().item(0); + assertThat(keySet).has().item(0); } public void testEviction_invalidateAll() { @@ -267,22 +282,22 @@ public class CacheEvictionTest extends TestCase { .build(loader); Set<Integer> keySet = cache.asMap().keySet(); - ASSERT.that(keySet).isEmpty(); + assertThat(keySet).isEmpty(); // add 0, 1, 2, 3, 4 getAll(cache, asList(0, 1, 2, 3, 4)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(0, 1, 2, 3, 4); + assertThat(keySet).has().exactly(0, 1, 2, 3, 4); // invalidate all cache.invalidateAll(); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).isEmpty(); + assertThat(keySet).isEmpty(); // add 5, 6, 7, 8, 9, 10, 11, 12 getAll(cache, asList(5, 6, 7, 8, 9, 10, 11, 12)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(5, 6, 7, 8, 9, 10, 11, 12); + assertThat(keySet).has().exactly(5, 6, 7, 8, 9, 10, 11, 12); } private void getAll(LoadingCache<Integer, Integer> cache, List<Integer> keys) { @@ -290,4 +305,12 @@ public class CacheEvictionTest extends TestCase { cache.getUnchecked(i); } } + + private Object objectWithHash(final int hash) { + return new Object() { + @Override public int hashCode() { + return hash; + } + }; + } } diff --git a/guava-tests/test/com/google/common/cache/CacheExpirationTest.java b/guava-tests/test/com/google/common/cache/CacheExpirationTest.java index d39374d82..b5c826604 100644 --- a/guava-tests/test/com/google/common/cache/CacheExpirationTest.java +++ b/guava-tests/test/com/google/common/cache/CacheExpirationTest.java @@ -16,9 +16,9 @@ package com.google.common.cache; import static com.google.common.cache.TestingCacheLoaders.identityLoader; import static com.google.common.cache.TestingRemovalListeners.countingRemovalListener; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.truth0.Truth.ASSERT; import com.google.common.cache.TestingCacheLoaders.IdentityLoader; import com.google.common.cache.TestingRemovalListeners.CountingRemovalListener; @@ -260,42 +260,42 @@ public class CacheExpirationTest extends TestCase { ticker.advance(1, MILLISECONDS); } Set<Integer> keySet = cache.asMap().keySet(); - ASSERT.that(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // 0 expires ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(1, 2, 3, 4, 5, 6, 7, 8, 9); // reorder getAll(cache, asList(0, 1, 2)); CacheTesting.drainRecencyQueues(cache); ticker.advance(2, MILLISECONDS); - ASSERT.that(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0, 1, 2); + assertThat(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0, 1, 2); // 3 expires ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(4, 5, 6, 7, 8, 9, 0, 1, 2); + assertThat(keySet).has().exactly(4, 5, 6, 7, 8, 9, 0, 1, 2); // reorder getAll(cache, asList(5, 7, 9)); CacheTesting.drainRecencyQueues(cache); - ASSERT.that(keySet).has().exactly(4, 6, 8, 0, 1, 2, 5, 7, 9); + assertThat(keySet).has().exactly(4, 6, 8, 0, 1, 2, 5, 7, 9); // 4 expires ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(6, 8, 0, 1, 2, 5, 7, 9); + assertThat(keySet).has().exactly(6, 8, 0, 1, 2, 5, 7, 9); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(6, 8, 0, 1, 2, 5, 7, 9); + assertThat(keySet).has().exactly(6, 8, 0, 1, 2, 5, 7, 9); // 6 expires ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(8, 0, 1, 2, 5, 7, 9); + assertThat(keySet).has().exactly(8, 0, 1, 2, 5, 7, 9); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(8, 0, 1, 2, 5, 7, 9); + assertThat(keySet).has().exactly(8, 0, 1, 2, 5, 7, 9); // 8 expires ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(0, 1, 2, 5, 7, 9); + assertThat(keySet).has().exactly(0, 1, 2, 5, 7, 9); } public void testExpirationOrder_write() throws ExecutionException { @@ -312,37 +312,37 @@ public class CacheExpirationTest extends TestCase { ticker.advance(1, MILLISECONDS); } Set<Integer> keySet = cache.asMap().keySet(); - ASSERT.that(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // 0 expires ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(1, 2, 3, 4, 5, 6, 7, 8, 9); // get doesn't stop 1 from expiring getAll(cache, asList(0, 1, 2)); CacheTesting.drainRecencyQueues(cache); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(2, 3, 4, 5, 6, 7, 8, 9, 0); + assertThat(keySet).has().exactly(2, 3, 4, 5, 6, 7, 8, 9, 0); // get(K, Callable) doesn't stop 2 from expiring cache.get(2, Callables.returning(-2)); CacheTesting.drainRecencyQueues(cache); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0); + assertThat(keySet).has().exactly(3, 4, 5, 6, 7, 8, 9, 0); // asMap.put saves 3 cache.asMap().put(3, -3); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(4, 5, 6, 7, 8, 9, 0, 3); + assertThat(keySet).has().exactly(4, 5, 6, 7, 8, 9, 0, 3); // asMap.replace saves 4 cache.asMap().replace(4, -4); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(5, 6, 7, 8, 9, 0, 3, 4); + assertThat(keySet).has().exactly(5, 6, 7, 8, 9, 0, 3, 4); // 5 expires ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(6, 7, 8, 9, 0, 3, 4); + assertThat(keySet).has().exactly(6, 7, 8, 9, 0, 3, 4); } public void testExpirationOrder_writeAccess() throws ExecutionException { @@ -365,33 +365,33 @@ public class CacheExpirationTest extends TestCase { ticker.advance(1, MILLISECONDS); Set<Integer> keySet = cache.asMap().keySet(); - ASSERT.that(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(keySet).has().exactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // get saves 1, 3; 0, 2, 4 expire getAll(cache, asList(1, 3)); CacheTesting.drainRecencyQueues(cache); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(5, 6, 7, 8, 9, 1, 3); + assertThat(keySet).has().exactly(5, 6, 7, 8, 9, 1, 3); // get saves 6, 8; 5, 7, 9 expire getAll(cache, asList(6, 8)); CacheTesting.drainRecencyQueues(cache); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(1, 3, 6, 8); + assertThat(keySet).has().exactly(1, 3, 6, 8); // get fails to save 1, put saves 3 cache.asMap().put(3, -3); getAll(cache, asList(1)); CacheTesting.drainRecencyQueues(cache); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(6, 8, 3); + assertThat(keySet).has().exactly(6, 8, 3); // get(K, Callable) fails to save 8, replace saves 6 cache.asMap().replace(6, -6); cache.get(8, Callables.returning(-8)); CacheTesting.drainRecencyQueues(cache); ticker.advance(1, MILLISECONDS); - ASSERT.that(keySet).has().exactly(3, 6); + assertThat(keySet).has().exactly(3, 6); } private void runRemovalScheduler(LoadingCache<String, Integer> cache, diff --git a/guava-tests/test/com/google/common/cache/CacheLoadingTest.java b/guava-tests/test/com/google/common/cache/CacheLoadingTest.java index 7d984d787..a08114d89 100644 --- a/guava-tests/test/com/google/common/cache/CacheLoadingTest.java +++ b/guava-tests/test/com/google/common/cache/CacheLoadingTest.java @@ -20,10 +20,10 @@ import static com.google.common.cache.TestingCacheLoaders.errorLoader; import static com.google.common.cache.TestingCacheLoaders.exceptionLoader; import static com.google.common.cache.TestingCacheLoaders.identityLoader; import static com.google.common.cache.TestingRemovalListeners.countingRemovalListener; +import static com.google.common.truth.Truth.assertThat; import static java.lang.Thread.currentThread; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.truth0.Truth.ASSERT; import com.google.common.cache.CacheLoader.InvalidCacheLoadException; import com.google.common.cache.TestingCacheLoaders.CountingLoader; @@ -440,7 +440,7 @@ public class CacheLoadingTest extends TestCase { Object[] lookupKeys = new Object[] { new Object(), new Object(), new Object() }; Map<Object, Object> result = cache.getAll(asList(lookupKeys)); - ASSERT.that(result.keySet()).has().exactlyAs(asList(lookupKeys)); + assertThat(result.keySet()).has().exactlyAs(asList(lookupKeys)); for (Map.Entry<Object, Object> entry : result.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); @@ -477,7 +477,7 @@ public class CacheLoadingTest extends TestCase { Object[] lookupKeys = new Object[] { new Object(), new Object(), new Object() }; Map<Object, Object> result = cache.getAll(asList(lookupKeys)); - ASSERT.that(result.keySet()).has().exactlyAs(asList(lookupKeys)); + assertThat(result.keySet()).has().exactlyAs(asList(lookupKeys)); for (Map.Entry<Object, Object> entry : result.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); diff --git a/guava-tests/test/com/google/common/cache/CacheReferencesTest.java b/guava-tests/test/com/google/common/cache/CacheReferencesTest.java index 8c7850cd8..88d6b2312 100644 --- a/guava-tests/test/com/google/common/cache/CacheReferencesTest.java +++ b/guava-tests/test/com/google/common/cache/CacheReferencesTest.java @@ -16,7 +16,7 @@ package com.google.common.cache; import static com.google.common.cache.LocalCache.Strength.STRONG; import static com.google.common.collect.Maps.immutableEntry; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Function; import com.google.common.cache.LocalCache.Strength; @@ -94,7 +94,7 @@ public class CacheReferencesTest extends TestCase { assertSame(value1, cache.getUnchecked(key1)); assertSame(value2, cache.getUnchecked(key2)); assertEquals(ImmutableSet.of(key1, key2), cache.asMap().keySet()); - ASSERT.that(cache.asMap().values()).has().exactly(value1, value2); + assertThat(cache.asMap().values()).has().exactly(value1, value2); assertEquals(ImmutableSet.of(immutableEntry(key1, value1), immutableEntry(key2, value2)), cache.asMap().entrySet()); } @@ -113,7 +113,7 @@ public class CacheReferencesTest extends TestCase { assertTrue(cache.asMap().containsKey(key2)); assertEquals(1, cache.size()); assertEquals(ImmutableSet.of(key2), cache.asMap().keySet()); - ASSERT.that(cache.asMap().values()).has().item(value2); + assertThat(cache.asMap().values()).has().item(value2); assertEquals(ImmutableSet.of(immutableEntry(key2, value2)), cache.asMap().entrySet()); } } diff --git a/guava-tests/test/com/google/common/cache/EmptyCachesTest.java b/guava-tests/test/com/google/common/cache/EmptyCachesTest.java index 905186172..994f236dc 100644 --- a/guava-tests/test/com/google/common/cache/EmptyCachesTest.java +++ b/guava-tests/test/com/google/common/cache/EmptyCachesTest.java @@ -17,6 +17,7 @@ package com.google.common.cache; import static com.google.common.cache.CacheTesting.checkEmpty; import static com.google.common.cache.TestingCacheLoaders.identityLoader; import static java.util.Arrays.asList; +import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.base.Function; @@ -368,14 +369,14 @@ public class EmptyCachesTest extends TestCase { .withExpireAfterWrites(ImmutableSet.of( DurationSpec.of(0, SECONDS), DurationSpec.of(1, SECONDS), - DurationSpec.of(24 * 60 * 60 * 1, SECONDS))) + DurationSpec.of(1, DAYS))) .withExpireAfterAccesses(ImmutableSet.of( DurationSpec.of(0, SECONDS), DurationSpec.of(1, SECONDS), - DurationSpec.of(24 * 60 * 60 * 1, SECONDS))) + DurationSpec.of(1, DAYS))) .withRefreshes(ImmutableSet.of( DurationSpec.of(1, SECONDS), - DurationSpec.of(24 * 60 * 60 * 1, SECONDS))); + DurationSpec.of(1, DAYS))); } private void warmUp(LoadingCache<Object, Object> cache, int minimum, int maximum) { diff --git a/guava-tests/test/com/google/common/cache/LocalCacheTest.java b/guava-tests/test/com/google/common/cache/LocalCacheTest.java index 9801f12ff..7e1d614d5 100644 --- a/guava-tests/test/com/google/common/cache/LocalCacheTest.java +++ b/guava-tests/test/com/google/common/cache/LocalCacheTest.java @@ -27,6 +27,7 @@ import static com.google.common.cache.TestingRemovalListeners.queuingRemovalList import static com.google.common.cache.TestingWeighers.constantWeigher; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.immutableEntry; +import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; @@ -2395,7 +2396,7 @@ public class LocalCacheTest extends TestCase { .weakKeys() .softValues() .expireAfterAccess(123, SECONDS) - .expireAfterWrite(60 * 456, SECONDS) // 456 minutes + .expireAfterWrite(456, MINUTES) .maximumWeight(789) .weigher(weigher) .concurrencyLevel(12) diff --git a/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java b/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java index f4684fc42..5ae1b45de 100644 --- a/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java +++ b/guava-tests/test/com/google/common/cache/LocalLoadingCacheTest.java @@ -19,7 +19,7 @@ package com.google.common.cache; import static com.google.common.cache.CacheBuilder.EMPTY_STATS; import static com.google.common.cache.LocalCacheTest.SMALL_MAX_SIZE; import static com.google.common.cache.TestingCacheLoaders.identityLoader; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.cache.LocalCache.LocalLoadingCache; import com.google.common.cache.LocalCache.Segment; @@ -160,17 +160,17 @@ public class LocalLoadingCacheTest extends TestCase { assertNull(map.put(three, one)); assertNull(map.put(one, two)); - ASSERT.that(map).hasKey(three).withValue(one); - ASSERT.that(map).hasKey(one).withValue(two); + assertThat(map).hasKey(three).withValue(one); + assertThat(map).hasKey(one).withValue(two); //TODO(user): Confirm with fry@ that this is a reasonable substitute. //Set<Map.Entry<Object, Object>> entries = map.entrySet(); - //ASSERT.that(entries).has().exactly( + //assertThat(entries).has().exactly( // Maps.immutableEntry(three, one), Maps.immutableEntry(one, two)); //Set<Object> keys = map.keySet(); - //ASSERT.that(keys).has().exactly(one, three); + //assertThat(keys).has().exactly(one, three); //Collection<Object> values = map.values(); - //ASSERT.that(values).has().exactly(one, two); + //assertThat(values).has().exactly(one, two); map.clear(); diff --git a/guava-tests/test/com/google/common/cache/LongAdderTest.java b/guava-tests/test/com/google/common/cache/LongAdderTest.java new file mode 100644 index 000000000..78f6edc63 --- /dev/null +++ b/guava-tests/test/com/google/common/cache/LongAdderTest.java @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2014 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.common.cache; + +/** + * No-op null-pointer test for {@link LongAdder} to override the {@link PackageSanityTests} version, + * which checks package-private methods that we don't want to have to annotate as {@code Nullable} + * because we don't want diffs from jsr166e. + */ +public class LongAdderTest { + public void testNulls() {} +} diff --git a/guava-tests/test/com/google/common/cache/PopulatedCachesTest.java b/guava-tests/test/com/google/common/cache/PopulatedCachesTest.java index 6d5003016..d7fee8276 100644 --- a/guava-tests/test/com/google/common/cache/PopulatedCachesTest.java +++ b/guava-tests/test/com/google/common/cache/PopulatedCachesTest.java @@ -17,8 +17,9 @@ package com.google.common.cache; import static com.google.common.cache.CacheTesting.checkEmpty; import static com.google.common.cache.CacheTesting.checkValidState; import static com.google.common.cache.TestingCacheLoaders.identityLoader; +import static com.google.common.truth.Truth.assertThat; +import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.truth0.Truth.ASSERT; import com.google.common.base.Function; import com.google.common.cache.CacheBuilderFactory.DurationSpec; @@ -33,8 +34,6 @@ import com.google.common.testing.EqualsTester; import junit.framework.TestCase; -import junit.framework.TestCase; - import java.util.Collection; import java.util.List; import java.util.Map; @@ -196,9 +195,9 @@ public class PopulatedCachesTest extends TestCase { List<Entry<Object, Object>> warmed = warmUp(cache); Set<Object> expected = Maps.newHashMap(cache.asMap()).keySet(); - ASSERT.that(keys).has().exactlyAs(expected); - ASSERT.that(keys.toArray()).has().exactlyAs(expected); - ASSERT.that(keys.toArray(new Object[0])).has().exactlyAs(expected); + assertThat(keys).has().exactlyAs(expected); + assertThat(keys.toArray()).asList().has().exactlyAs(expected); + assertThat(keys.toArray(new Object[0])).asList().has().exactlyAs(expected); new EqualsTester() .addEqualityGroup(cache.asMap().keySet(), keys) @@ -223,9 +222,9 @@ public class PopulatedCachesTest extends TestCase { List<Entry<Object, Object>> warmed = warmUp(cache); Collection<Object> expected = Maps.newHashMap(cache.asMap()).values(); - ASSERT.that(values).has().exactlyAs(expected); - ASSERT.that(values.toArray()).has().exactlyAs(expected); - ASSERT.that(values.toArray(new Object[0])).has().exactlyAs(expected); + assertThat(values).has().exactlyAs(expected); + assertThat(values.toArray()).asList().has().exactlyAs(expected); + assertThat(values.toArray(new Object[0])).asList().has().exactlyAs(expected); assertEquals(WARMUP_SIZE, values.size()); for (int i = WARMUP_MIN; i < WARMUP_MAX; i++) { @@ -248,9 +247,10 @@ public class PopulatedCachesTest extends TestCase { List<Entry<Object, Object>> warmed = warmUp(cache, WARMUP_MIN, WARMUP_MAX); Set<?> expected = Maps.newHashMap(cache.asMap()).entrySet(); - ASSERT.that(entries).has().exactlyAs((Collection<Entry<Object, Object>>) expected); - ASSERT.that(entries.toArray()).has().exactlyAs((Collection<Object>) expected); - ASSERT.that(entries.toArray(new Entry[0])).has().exactlyAs((Collection<Entry>) expected); + assertThat(entries).has().exactlyAs((Collection<Entry<Object, Object>>) expected); + assertThat(entries.toArray()).asList().has().exactlyAs((Collection<Object>) expected); + assertThat(entries.toArray(new Entry[0])).asList() + .has().exactlyAs((Collection<Entry>) expected); new EqualsTester() .addEqualityGroup(cache.asMap().entrySet(), entries) @@ -320,15 +320,15 @@ public class PopulatedCachesTest extends TestCase { .withExpireAfterWrites(ImmutableSet.of( // DurationSpec.of(500, MILLISECONDS), DurationSpec.of(1, SECONDS), - DurationSpec.of(24 * 60 * 60 * 1, SECONDS))) + DurationSpec.of(1, DAYS))) .withExpireAfterAccesses(ImmutableSet.of( // DurationSpec.of(500, MILLISECONDS), DurationSpec.of(1, SECONDS), - DurationSpec.of(24 * 60 * 60 * 1, SECONDS))) + DurationSpec.of(1, DAYS))) .withRefreshes(ImmutableSet.of( // DurationSpec.of(500, MILLISECONDS), DurationSpec.of(1, SECONDS), - DurationSpec.of(24 * 60 * 60 * 1, SECONDS))); + DurationSpec.of(1, DAYS))); } private List<Map.Entry<Object, Object>> warmUp(LoadingCache<Object, Object> cache) { diff --git a/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java b/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java index 16d5fd81d..ea309f452 100644 --- a/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java @@ -17,8 +17,8 @@ package com.google.common.collect; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -295,7 +295,7 @@ public abstract class AbstractImmutableSetTest extends TestCase { .add("d", "e", "f") .add("g", "h", "i", "j") .build(); - ASSERT.that(set).has().exactly( + assertThat(set).has().exactly( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j").inOrder(); } @@ -303,9 +303,9 @@ public abstract class AbstractImmutableSetTest extends TestCase { ImmutableSet.Builder<String> builder = this.<String>builder() .add("a") .add("b"); - ASSERT.that(builder.build()).has().exactly("a", "b").inOrder(); + assertThat(builder.build()).has().exactly("a", "b").inOrder(); builder.add("c", "d"); - ASSERT.that(builder.build()).has().exactly("a", "b", "c", "d").inOrder(); + assertThat(builder.build()).has().exactly("a", "b", "c", "d").inOrder(); } public void testBuilderWithDuplicateElements() { @@ -325,9 +325,9 @@ public abstract class AbstractImmutableSetTest extends TestCase { .add("a") .add("a", "a") .add("b"); - ASSERT.that(builder.build()).has().exactly("a", "b").inOrder(); + assertThat(builder.build()).has().exactly("a", "b").inOrder(); builder.add("a", "b", "c", "c"); - ASSERT.that(builder.build()).has().exactly("a", "b", "c").inOrder(); + assertThat(builder.build()).has().exactly("a", "b", "c").inOrder(); } public void testBuilderAddAll() { @@ -337,7 +337,7 @@ public abstract class AbstractImmutableSetTest extends TestCase { .addAll(a) .addAll(b) .build(); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e").inOrder(); } static final int LAST_COLOR_ADDED = 0x00BFFF; diff --git a/guava-tests/test/com/google/common/collect/AbstractRangeSetTest.java b/guava-tests/test/com/google/common/collect/AbstractRangeSetTest.java new file mode 100644 index 000000000..1a44e87b3 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/AbstractRangeSetTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.collect; + +import com.google.common.annotations.GwtIncompatible; + +import junit.framework.TestCase; + +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +/** + * Base class for {@link RangeSet} tests. + * + * @author Louis Wasserman + */ +@GwtIncompatible("TreeRangeSet") +public abstract class AbstractRangeSetTest extends TestCase { + public static void testInvariants(RangeSet<?> rangeSet) { + testInvariantsInternal(rangeSet); + testInvariantsInternal(rangeSet.complement()); + } + + private static <C extends Comparable> void testInvariantsInternal(RangeSet<C> rangeSet) { + assertEquals(rangeSet.asRanges().isEmpty(), rangeSet.isEmpty()); + assertEquals(!rangeSet.asRanges().iterator().hasNext(), rangeSet.isEmpty()); + + List<Range<C>> asRanges = ImmutableList.copyOf(rangeSet.asRanges()); + + // test that connected ranges are coalesced + for (int i = 0; i + 1 < asRanges.size(); i++) { + Range<C> range1 = asRanges.get(i); + Range<C> range2 = asRanges.get(i + 1); + assertFalse(range1.isConnected(range2)); + } + + // test that there are no empty ranges + for (Range<C> range : asRanges) { + assertFalse(range.isEmpty()); + } + + Iterator<Range<C>> itr = rangeSet.asRanges().iterator(); + Range<C> expectedSpan = null; + if (itr.hasNext()) { + expectedSpan = itr.next(); + while (itr.hasNext()) { + expectedSpan = expectedSpan.span(itr.next()); + } + } + + try { + Range<C> span = rangeSet.span(); + assertEquals(expectedSpan, span); + } catch (NoSuchElementException e) { + assertNull(expectedSpan); + } + } +} diff --git a/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java b/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java index 803ea5ab1..83b3900be 100644 --- a/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java @@ -17,7 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -50,7 +50,7 @@ public class AbstractSequentialIteratorTest extends TestCase { return newDoubler(2, 32); } }; - ASSERT.that(doubled).iteratesOverSequence(2, 4, 8, 16, 32); + assertThat(doubled).iteratesAs(2, 4, 8, 16, 32); } public void testSampleCode() { @@ -65,7 +65,7 @@ public class AbstractSequentialIteratorTest extends TestCase { return powersOfTwo; } }; - ASSERT.that(actual).iteratesOverSequence(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, + assertThat(actual).iteratesAs(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824); } diff --git a/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java b/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java index 1265e31d7..45a08c52f 100644 --- a/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -183,7 +183,7 @@ public abstract class AbstractTableReadTest extends TestCase { public void testColumnSetPartialOverlap() { table = create( "foo", 1, 'a', "bar", 1, 'b', "foo", 2, 'c', "bar", 3, 'd'); - ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3); + assertThat(table.columnKeySet()).has().exactly(1, 2, 3); } @GwtIncompatible("NullPointerTester") diff --git a/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java b/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java index 676e17507..6a567d84d 100644 --- a/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java @@ -16,8 +16,8 @@ package com.google.common.collect; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -119,9 +119,9 @@ public class ArrayListMultimapTest extends TestCase { ListMultimap<String, Integer> multimap = create(); multimap.putAll("foo", asList(1, 2, 3, 4, 5)); List<Integer> list = multimap.get("foo"); - ASSERT.that(multimap.get("foo")).has().exactly(1, 2, 3, 4, 5).inOrder(); + assertThat(multimap.get("foo")).has().exactly(1, 2, 3, 4, 5).inOrder(); List<Integer> sublist = list.subList(0, 5); - ASSERT.that(sublist).has().exactly(1, 2, 3, 4, 5).inOrder(); + assertThat(sublist).has().exactly(1, 2, 3, 4, 5).inOrder(); sublist.clear(); assertTrue(sublist.isEmpty()); @@ -190,7 +190,7 @@ public class ArrayListMultimapTest extends TestCase { multimap.put("bar", 3); multimap.trimToSize(); assertEquals(3, multimap.size()); - ASSERT.that(multimap.get("foo")).has().exactly(1, 2).inOrder(); - ASSERT.that(multimap.get("bar")).has().item(3); + assertThat(multimap.get("foo")).has().exactly(1, 2).inOrder(); + assertThat(multimap.get("bar")).has().item(3); } } diff --git a/guava-tests/test/com/google/common/collect/ArrayTableTest.java b/guava-tests/test/com/google/common/collect/ArrayTableTest.java index 29100ceaf..c5356196b 100644 --- a/guava-tests/test/com/google/common/collect/ArrayTableTest.java +++ b/guava-tests/test/com/google/common/collect/ArrayTableTest.java @@ -16,8 +16,8 @@ package com.google.common.collect; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -286,13 +286,13 @@ public class ArrayTableTest extends AbstractTableTest { public void testRowKeyList() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - ASSERT.that(table.rowKeyList()).has().exactly("foo", "bar", "cat").inOrder(); + assertThat(table.rowKeyList()).has().exactly("foo", "bar", "cat").inOrder(); } public void testColumnKeyList() { ArrayTable<String, Integer, Character> table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - ASSERT.that(table.columnKeyList()).has().exactly(1, 2, 3).inOrder(); + assertThat(table.columnKeyList()).has().exactly(1, 2, 3).inOrder(); } public void testGetMissingKeys() { @@ -400,9 +400,9 @@ public class ArrayTableTest extends AbstractTableTest { = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Character[][] array = table.toArray(Character.class); assertEquals(3, array.length); - ASSERT.that(array[0]).has().exactly('a', null, 'c').inOrder(); - ASSERT.that(array[1]).has().exactly('b', null, null).inOrder(); - ASSERT.that(array[2]).has().exactly(null, null, null).inOrder(); + assertThat(array[0]).asList().has().exactly('a', null, 'c').inOrder(); + assertThat(array[1]).asList().has().exactly('b', null, null).inOrder(); + assertThat(array[2]).asList().has().exactly(null, null, null).inOrder(); table.set(0, 2, 'd'); assertEquals((Character) 'c', array[0][2]); array[0][2] = 'e'; diff --git a/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java b/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java index f7fc52000..4997e69ad 100644 --- a/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java +++ b/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java @@ -26,6 +26,7 @@ import java.util.Set; import java.util.SortedMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentSkipListMap; /** * Helper classes for various benchmarks. @@ -172,6 +173,12 @@ final class BenchmarkHelpers { return result; } }, + ConcurrentSkipList { + @Override + <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { + return new ConcurrentSkipListMap<K, V>(map); + } + }, ImmutableSorted { @Override <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { diff --git a/guava-tests/test/com/google/common/collect/Collections2Test.java b/guava-tests/test/com/google/common/collect/Collections2Test.java index ed21ec60b..83d901455 100644 --- a/guava-tests/test/com/google/common/collect/Collections2Test.java +++ b/guava-tests/test/com/google/common/collect/Collections2Test.java @@ -19,9 +19,9 @@ package com.google.common.collect; import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newLinkedList; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static java.util.Collections.nCopies; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -237,7 +237,7 @@ public class Collections2Test extends TestCase { Collections2.orderedPermutations(list); assertEquals(1, permutationSet.size()); - ASSERT.that(permutationSet).has().item(list); + assertThat(permutationSet).has().item(list); Iterator<List<Integer>> permutations = permutationSet.iterator(); diff --git a/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetBasherTest.java b/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetBasherTest.java index 87e73ca9a..6c022a7dd 100644 --- a/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetBasherTest.java +++ b/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetBasherTest.java @@ -26,6 +26,7 @@ import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -47,6 +48,10 @@ public class ConcurrentHashMultisetBasherTest extends TestCase { testAddAndRemove(new ConcurrentHashMap<String, AtomicInteger>()); } + public void testAddAndRemove_ConcurrentSkipListMap() throws Exception { + testAddAndRemove(new ConcurrentSkipListMap<String, AtomicInteger>()); + } + public void testAddAndRemove_MapMakerMap() throws Exception { MapMaker mapMaker = new MapMaker(); // force MapMaker to use its own MapMakerInternalMap diff --git a/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetTest.java b/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetTest.java index 467d79311..c935f2797 100644 --- a/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/ConcurrentHashMultisetTest.java @@ -42,6 +42,7 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -62,6 +63,14 @@ public class ConcurrentHashMultisetTest extends TestCase { CollectionFeature.ALLOWS_NULL_QUERIES) .named("ConcurrentHashMultiset") .createTestSuite()); + suite.addTest(MultisetTestSuiteBuilder.using(concurrentSkipListMultisetGenerator()) + .withFeatures(CollectionSize.ANY, + CollectionFeature.KNOWN_ORDER, + CollectionFeature.GENERAL_PURPOSE, + CollectionFeature.SERIALIZABLE, + CollectionFeature.ALLOWS_NULL_QUERIES) + .named("ConcurrentSkipListMultiset") + .createTestSuite()); suite.addTestSuite(ConcurrentHashMultisetTest.class); return suite; } @@ -74,6 +83,22 @@ public class ConcurrentHashMultisetTest extends TestCase { }; } + private static TestStringMultisetGenerator concurrentSkipListMultisetGenerator() { + return new TestStringMultisetGenerator() { + @Override protected Multiset<String> create(String[] elements) { + Multiset<String> multiset = new ConcurrentHashMultiset<String>( + new ConcurrentSkipListMap<String, AtomicInteger>()); + Collections.addAll(multiset, elements); + return multiset; + } + + @Override + public List<String> order(List<String> insertionOrder) { + return Ordering.natural().sortedCopy(insertionOrder); + } + }; + } + private static final String KEY = "puppies"; ConcurrentMap<String, AtomicInteger> backingMap; diff --git a/guava-tests/test/com/google/common/collect/ConstraintsTest.java b/guava-tests/test/com/google/common/collect/ConstraintsTest.java index cd24240df..d93c642ad 100644 --- a/guava-tests/test/com/google/common/collect/ConstraintsTest.java +++ b/guava-tests/test/com/google/common/collect/ConstraintsTest.java @@ -16,8 +16,8 @@ package com.google.common.collect; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; @@ -68,9 +68,9 @@ public class ConstraintsTest extends TestCase { constrained.add("qux"); constrained.addAll(asList("cat", "dog")); /* equals and hashCode aren't defined for Collection */ - ASSERT.that(collection).has() + assertThat(collection).has() .exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); - ASSERT.that(constrained).has() + assertThat(constrained).has() .exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); } @@ -86,8 +86,8 @@ public class ConstraintsTest extends TestCase { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} - ASSERT.that(constrained).has().exactly("foo", "bar").inOrder(); - ASSERT.that(collection).has().exactly("foo", "bar").inOrder(); + assertThat(constrained).has().exactly("foo", "bar").inOrder(); + assertThat(collection).has().exactly("foo", "bar").inOrder(); } public void testConstrainedSetLegal() { @@ -100,8 +100,8 @@ public class ConstraintsTest extends TestCase { assertTrue(constrained.equals(set)); assertEquals(set.toString(), constrained.toString()); assertEquals(set.hashCode(), constrained.hashCode()); - ASSERT.that(set).has().exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); - ASSERT.that(constrained).has() + assertThat(set).has().exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); + assertThat(constrained).has() .exactly("foo", "bar", TEST_ELEMENT, "qux", "cat", "dog").inOrder(); } @@ -116,8 +116,8 @@ public class ConstraintsTest extends TestCase { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} - ASSERT.that(constrained).has().exactly("foo", "bar").inOrder(); - ASSERT.that(set).has().exactly("foo", "bar").inOrder(); + assertThat(constrained).has().exactly("foo", "bar").inOrder(); + assertThat(set).has().exactly("foo", "bar").inOrder(); } public void testConstrainedSortedSetLegal() { @@ -131,8 +131,8 @@ public class ConstraintsTest extends TestCase { assertTrue(constrained.equals(sortedSet)); assertEquals(sortedSet.toString(), constrained.toString()); assertEquals(sortedSet.hashCode(), constrained.hashCode()); - ASSERT.that(sortedSet).has().exactly("bar", "cat", "dog", "foo", "qux", TEST_ELEMENT).inOrder(); - ASSERT.that(constrained).has() + assertThat(sortedSet).has().exactly("bar", "cat", "dog", "foo", "qux", TEST_ELEMENT).inOrder(); + assertThat(constrained).has() .exactly("bar", "cat", "dog", "foo", "qux", TEST_ELEMENT).inOrder(); assertNull(constrained.comparator()); assertEquals("bar", constrained.first()); @@ -163,8 +163,8 @@ public class ConstraintsTest extends TestCase { constrained.addAll(asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} - ASSERT.that(constrained).has().exactly("bar", "foo").inOrder(); - ASSERT.that(sortedSet).has().exactly("bar", "foo").inOrder(); + assertThat(constrained).has().exactly("bar", "foo").inOrder(); + assertThat(sortedSet).has().exactly("bar", "foo").inOrder(); } public void testConstrainedListLegal() { @@ -181,17 +181,17 @@ public class ConstraintsTest extends TestCase { assertTrue(constrained.equals(list)); assertEquals(list.toString(), constrained.toString()); assertEquals(list.hashCode(), constrained.hashCode()); - ASSERT.that(list).has().exactly( + assertThat(list).has().exactly( "foo", "cow", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); - ASSERT.that(constrained).has().exactly( + assertThat(constrained).has().exactly( "foo", "cow", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); ListIterator<String> iterator = constrained.listIterator(); iterator.next(); iterator.set("sun"); constrained.listIterator(2).add("sky"); - ASSERT.that(list).has().exactly( + assertThat(list).has().exactly( "sun", "cow", "sky", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); - ASSERT.that(constrained).has().exactly( + assertThat(constrained).has().exactly( "sun", "cow", "sky", "baz", TEST_ELEMENT, "box", "fan", "qux", "cat", "dog").inOrder(); assertTrue(constrained instanceof RandomAccess); } @@ -249,8 +249,8 @@ public class ConstraintsTest extends TestCase { constrained.addAll(1, asList("baz", TEST_ELEMENT)); fail("TestElementException expected"); } catch (TestElementException expected) {} - ASSERT.that(constrained).has().exactly("foo", "bar").inOrder(); - ASSERT.that(list).has().exactly("foo", "bar").inOrder(); + assertThat(constrained).has().exactly("foo", "bar").inOrder(); + assertThat(list).has().exactly("foo", "bar").inOrder(); } public void testNefariousAddAll() { @@ -259,8 +259,8 @@ public class ConstraintsTest extends TestCase { list, TEST_CONSTRAINT); Collection<String> onceIterable = onceIterableCollection("baz"); constrained.addAll(onceIterable); - ASSERT.that(constrained).has().exactly("foo", "bar", "baz").inOrder(); - ASSERT.that(list).has().exactly("foo", "bar", "baz").inOrder(); + assertThat(constrained).has().exactly("foo", "bar", "baz").inOrder(); + assertThat(list).has().exactly("foo", "bar", "baz").inOrder(); } /** diff --git a/guava-tests/test/com/google/common/collect/ContiguousSetTest.java b/guava-tests/test/com/google/common/collect/ContiguousSetTest.java index 1d269416c..5e01e02cf 100644 --- a/guava-tests/test/com/google/common/collect/ContiguousSetTest.java +++ b/guava-tests/test/com/google/common/collect/ContiguousSetTest.java @@ -19,16 +19,29 @@ package com.google.common.collect; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.DiscreteDomain.integers; +import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; +import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; +import static com.google.common.collect.testing.features.CollectionFeature.NON_STANDARD_TOSTRING; +import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS; +import static com.google.common.collect.testing.testers.NavigableSetNavigationTester.getHoleMethods; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.testing.SerializableTester.reserializeAndAssert; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; +import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.google.SetGenerators.ContiguousSetDescendingGenerator; +import com.google.common.collect.testing.google.SetGenerators.ContiguousSetGenerator; +import com.google.common.collect.testing.google.SetGenerators.ContiguousSetHeadsetGenerator; +import com.google.common.collect.testing.google.SetGenerators.ContiguousSetSubsetGenerator; +import com.google.common.collect.testing.google.SetGenerators.ContiguousSetTailsetGenerator; import com.google.common.testing.EqualsTester; import junit.framework.Test; import junit.framework.TestCase; +import junit.framework.TestSuite; import java.util.Set; @@ -132,53 +145,53 @@ public class ContiguousSetTest extends TestCase { public void testHeadSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); - ASSERT.that(set.headSet(1)).isEmpty(); - ASSERT.that(set.headSet(2)).has().item(1); - ASSERT.that(set.headSet(3)).has().exactly(1, 2).inOrder(); - ASSERT.that(set.headSet(4)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.headSet(Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.headSet(1, true)).has().item(1); - ASSERT.that(set.headSet(2, true)).has().exactly(1, 2).inOrder(); - ASSERT.that(set.headSet(3, true)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.headSet(4, true)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.headSet(Integer.MAX_VALUE, true)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.headSet(1)).isEmpty(); + assertThat(set.headSet(2)).has().item(1); + assertThat(set.headSet(3)).has().exactly(1, 2).inOrder(); + assertThat(set.headSet(4)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.headSet(Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.headSet(1, true)).has().item(1); + assertThat(set.headSet(2, true)).has().exactly(1, 2).inOrder(); + assertThat(set.headSet(3, true)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.headSet(4, true)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.headSet(Integer.MAX_VALUE, true)).has().exactly(1, 2, 3).inOrder(); } public void testHeadSet_tooSmall() { - ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).headSet(0)).isEmpty(); + assertThat(ContiguousSet.create(Range.closed(1, 3), integers()).headSet(0)).isEmpty(); } public void testTailSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); - ASSERT.that(set.tailSet(Integer.MIN_VALUE)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.tailSet(1)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.tailSet(2)).has().exactly(2, 3).inOrder(); - ASSERT.that(set.tailSet(3)).has().item(3); - ASSERT.that(set.tailSet(Integer.MIN_VALUE, false)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.tailSet(1, false)).has().exactly(2, 3).inOrder(); - ASSERT.that(set.tailSet(2, false)).has().item(3); - ASSERT.that(set.tailSet(3, false)).isEmpty(); + assertThat(set.tailSet(Integer.MIN_VALUE)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.tailSet(1)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.tailSet(2)).has().exactly(2, 3).inOrder(); + assertThat(set.tailSet(3)).has().item(3); + assertThat(set.tailSet(Integer.MIN_VALUE, false)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.tailSet(1, false)).has().exactly(2, 3).inOrder(); + assertThat(set.tailSet(2, false)).has().item(3); + assertThat(set.tailSet(3, false)).isEmpty(); } public void testTailSet_tooLarge() { - ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).tailSet(4)).isEmpty(); + assertThat(ContiguousSet.create(Range.closed(1, 3), integers()).tailSet(4)).isEmpty(); } public void testSubSet() { ImmutableSortedSet<Integer> set = ContiguousSet.create(Range.closed(1, 3), integers()); - ASSERT.that(set.subSet(1, 4)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.subSet(2, 4)).has().exactly(2, 3).inOrder(); - ASSERT.that(set.subSet(3, 4)).has().item(3); - ASSERT.that(set.subSet(3, 3)).isEmpty(); - ASSERT.that(set.subSet(2, 3)).has().item(2); - ASSERT.that(set.subSet(1, 3)).has().exactly(1, 2).inOrder(); - ASSERT.that(set.subSet(1, 2)).has().item(1); - ASSERT.that(set.subSet(2, 2)).isEmpty(); - ASSERT.that(set.subSet(Integer.MIN_VALUE, Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.subSet(1, true, 3, true)).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(set.subSet(1, false, 3, true)).has().exactly(2, 3).inOrder(); - ASSERT.that(set.subSet(1, true, 3, false)).has().exactly(1, 2).inOrder(); - ASSERT.that(set.subSet(1, false, 3, false)).has().item(2); + assertThat(set.subSet(1, 4)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.subSet(2, 4)).has().exactly(2, 3).inOrder(); + assertThat(set.subSet(3, 4)).has().item(3); + assertThat(set.subSet(3, 3)).isEmpty(); + assertThat(set.subSet(2, 3)).has().item(2); + assertThat(set.subSet(1, 3)).has().exactly(1, 2).inOrder(); + assertThat(set.subSet(1, 2)).has().item(1); + assertThat(set.subSet(2, 2)).isEmpty(); + assertThat(set.subSet(Integer.MIN_VALUE, Integer.MAX_VALUE)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.subSet(1, true, 3, true)).has().exactly(1, 2, 3).inOrder(); + assertThat(set.subSet(1, false, 3, true)).has().exactly(2, 3).inOrder(); + assertThat(set.subSet(1, true, 3, false)).has().exactly(1, 2).inOrder(); + assertThat(set.subSet(1, false, 3, false)).has().item(2); } public void testSubSet_outOfOrder() { @@ -190,11 +203,11 @@ public class ContiguousSetTest extends TestCase { } public void testSubSet_tooLarge() { - ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(4, 6)).isEmpty(); + assertThat(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(4, 6)).isEmpty(); } public void testSubSet_tooSmall() { - ASSERT.that(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(-1, 0)).isEmpty(); + assertThat(ContiguousSet.create(Range.closed(1, 3), integers()).subSet(-1, 0)).isEmpty(); } public void testFirst() { @@ -303,4 +316,53 @@ public class ContiguousSetTest extends TestCase { assertEquals(ImmutableSet.of(1, 2, 3), set.intersection(ContiguousSet.create(Range.open(-1, 4), integers()))); } + + @GwtIncompatible("suite") + public static class BuiltTests extends TestCase { + public static Test suite() { + TestSuite suite = new TestSuite(); + + suite.addTest(NavigableSetTestSuiteBuilder.using( + new ContiguousSetGenerator()) + .named("Range.asSet") + .withFeatures(CollectionSize.ANY, KNOWN_ORDER, ALLOWS_NULL_QUERIES, + NON_STANDARD_TOSTRING, RESTRICTS_ELEMENTS) + .suppressing(getHoleMethods()) + .createTestSuite()); + + suite.addTest(NavigableSetTestSuiteBuilder.using( + new ContiguousSetHeadsetGenerator()) + .named("Range.asSet, headset") + .withFeatures(CollectionSize.ANY, KNOWN_ORDER, ALLOWS_NULL_QUERIES, + NON_STANDARD_TOSTRING, RESTRICTS_ELEMENTS) + .suppressing(getHoleMethods()) + .createTestSuite()); + + suite.addTest(NavigableSetTestSuiteBuilder.using( + new ContiguousSetTailsetGenerator()) + .named("Range.asSet, tailset") + .withFeatures(CollectionSize.ANY, KNOWN_ORDER, ALLOWS_NULL_QUERIES, + NON_STANDARD_TOSTRING, RESTRICTS_ELEMENTS) + .suppressing(getHoleMethods()) + .createTestSuite()); + + suite.addTest(NavigableSetTestSuiteBuilder.using( + new ContiguousSetSubsetGenerator()) + .named("Range.asSet, subset") + .withFeatures(CollectionSize.ANY, KNOWN_ORDER, ALLOWS_NULL_QUERIES, + NON_STANDARD_TOSTRING, RESTRICTS_ELEMENTS) + .suppressing(getHoleMethods()) + .createTestSuite()); + + suite.addTest(NavigableSetTestSuiteBuilder.using( + new ContiguousSetDescendingGenerator()) + .named("Range.asSet.descendingSet") + .withFeatures(CollectionSize.ANY, KNOWN_ORDER, ALLOWS_NULL_QUERIES, + NON_STANDARD_TOSTRING, RESTRICTS_ELEMENTS) + .suppressing(getHoleMethods()) + .createTestSuite()); + + return suite; + } + } } diff --git a/guava-tests/test/com/google/common/collect/EnumBiMapTest.java b/guava-tests/test/com/google/common/collect/EnumBiMapTest.java index 4d2a89dcd..6d75bf31b 100644 --- a/guava-tests/test/com/google/common/collect/EnumBiMapTest.java +++ b/guava-tests/test/com/google/common/collect/EnumBiMapTest.java @@ -17,7 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.testing.Helpers.orderEntriesByKey; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -196,16 +196,16 @@ public class EnumBiMapTest extends TestCase { EnumBiMap<Currency, Country> bimap = EnumBiMap.create(map); // forward map ordered by currency - ASSERT.that(bimap.keySet()) + assertThat(bimap.keySet()) .has().exactly(Currency.DOLLAR, Currency.FRANC, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) - ASSERT.that(bimap.values()) + assertThat(bimap.values()) .has().exactly(Country.CANADA, Country.SWITZERLAND, Country.CHILE).inOrder(); // backward map ordered by country - ASSERT.that(bimap.inverse().keySet()) + assertThat(bimap.inverse().keySet()) .has().exactly(Country.CANADA, Country.CHILE, Country.SWITZERLAND).inOrder(); // backward map ordered by country (even for currency values) - ASSERT.that(bimap.inverse().values()) + assertThat(bimap.inverse().values()) .has().exactly(Currency.DOLLAR, Currency.PESO, Currency.FRANC).inOrder(); } @@ -223,16 +223,16 @@ public class EnumBiMapTest extends TestCase { iter.remove(); // forward map ordered by currency - ASSERT.that(bimap.keySet()) + assertThat(bimap.keySet()) .has().exactly(Currency.FRANC, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) - ASSERT.that(bimap.values()) + assertThat(bimap.values()) .has().exactly(Country.SWITZERLAND, Country.CHILE).inOrder(); // backward map ordered by country - ASSERT.that(bimap.inverse().keySet()) + assertThat(bimap.inverse().keySet()) .has().exactly(Country.CHILE, Country.SWITZERLAND).inOrder(); // backward map ordered by country (even for currency values) - ASSERT.that(bimap.inverse().values()) + assertThat(bimap.inverse().values()) .has().exactly(Currency.PESO, Currency.FRANC).inOrder(); } @@ -251,16 +251,16 @@ public class EnumBiMapTest extends TestCase { iter.remove(); // forward map ordered by currency - ASSERT.that(bimap.keySet()) + assertThat(bimap.keySet()) .has().exactly(Currency.DOLLAR, Currency.PESO).inOrder(); // forward map ordered by currency (even for country values) - ASSERT.that(bimap.values()) + assertThat(bimap.values()) .has().exactly(Country.CANADA, Country.CHILE).inOrder(); // backward map ordered by country - ASSERT.that(bimap.inverse().keySet()) + assertThat(bimap.inverse().keySet()) .has().exactly(Country.CANADA, Country.CHILE).inOrder(); // backward map ordered by country (even for currency values) - ASSERT.that(bimap.inverse().values()) + assertThat(bimap.inverse().values()) .has().exactly(Currency.DOLLAR, Currency.PESO).inOrder(); } diff --git a/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java b/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java index 20fb592b6..579d3785d 100644 --- a/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java +++ b/guava-tests/test/com/google/common/collect/FilteredCollectionsTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Predicate; import com.google.common.base.Predicates; @@ -27,6 +27,7 @@ import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator; import java.util.List; +import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; @@ -100,7 +101,7 @@ public class FilteredCollectionsTest extends TestCase { target.add(4); C addThenFilter = filter(createUnfiltered(target), EVEN); - ASSERT.that(filterThenAdd).has().exactlyAs(addThenFilter); + assertThat(filterThenAdd).has().exactlyAs(addThenFilter); } } @@ -156,7 +157,7 @@ public class FilteredCollectionsTest extends TestCase { } catch (IllegalArgumentException expected) { } - ASSERT.that(filteredToModify).has().exactlyAs(filtered); + assertThat(filteredToModify).has().exactlyAs(filtered); } } @@ -190,7 +191,7 @@ public class FilteredCollectionsTest extends TestCase { Predicates.not(Predicates.and(EVEN, PRIME_DIGIT))); filtered2.clear(); - ASSERT.that(unfiltered).has().exactlyAs(inverseFiltered); + assertThat(unfiltered).has().exactlyAs(inverseFiltered); } } } @@ -277,6 +278,94 @@ public class FilteredCollectionsTest extends TestCase { } } + public static abstract class AbstractFilteredNavigableSetTest + extends AbstractFilteredSortedSetTest<NavigableSet<Integer>> { + + public void testNavigableHeadSet() { + for (List<Integer> contents : SAMPLE_INPUTS) { + for (int i = 0; i < 10; i++) { + for (boolean inclusive : ImmutableList.of(true, false)) { + assertEquals( + filter(createUnfiltered(contents).headSet(i, inclusive), EVEN), + filter(createUnfiltered(contents), EVEN).headSet(i, inclusive)); + } + } + } + } + + public void testNavigableTailSet() { + for (List<Integer> contents : SAMPLE_INPUTS) { + for (int i = 0; i < 10; i++) { + for (boolean inclusive : ImmutableList.of(true, false)) { + assertEquals( + filter(createUnfiltered(contents).tailSet(i, inclusive), EVEN), + filter(createUnfiltered(contents), EVEN).tailSet(i, inclusive)); + } + } + } + } + + public void testNavigableSubSet() { + for (List<Integer> contents : SAMPLE_INPUTS) { + for (int i = 0; i < 10; i++) { + for (int j = i + 1; j < 10; j++) { + for (boolean fromInclusive : ImmutableList.of(true, false)) { + for (boolean toInclusive : ImmutableList.of(true, false)) { + NavigableSet<Integer> filterSubset = filter( + createUnfiltered(contents).subSet(i, fromInclusive, j, toInclusive), EVEN); + NavigableSet<Integer> subsetFilter = filter(createUnfiltered(contents), EVEN) + .subSet(i, fromInclusive, j, toInclusive); + assertEquals(filterSubset, subsetFilter); + } + } + } + } + } + } + + public void testDescendingSet() { + for (List<Integer> contents : SAMPLE_INPUTS) { + NavigableSet<Integer> filtered = filter(createUnfiltered(contents), EVEN); + NavigableSet<Integer> unfiltered = createUnfiltered(filtered); + + assertThat(filtered.descendingSet()).has().exactlyAs(unfiltered.descendingSet()).inOrder(); + } + } + + public void testPollFirst() { + for (List<Integer> contents : SAMPLE_INPUTS) { + NavigableSet<Integer> filtered = filter(createUnfiltered(contents), EVEN); + NavigableSet<Integer> unfiltered = createUnfiltered(filtered); + + assertEquals(unfiltered.pollFirst(), filtered.pollFirst()); + assertEquals(unfiltered, filtered); + } + } + + public void testPollLast() { + for (List<Integer> contents : SAMPLE_INPUTS) { + NavigableSet<Integer> filtered = filter(createUnfiltered(contents), EVEN); + NavigableSet<Integer> unfiltered = createUnfiltered(filtered); + + assertEquals(unfiltered.pollLast(), filtered.pollLast()); + assertEquals(unfiltered, filtered); + } + } + + public void testNavigation() { + for (List<Integer> contents : SAMPLE_INPUTS) { + NavigableSet<Integer> filtered = filter(createUnfiltered(contents), EVEN); + NavigableSet<Integer> unfiltered = createUnfiltered(filtered); + for (int i = 0; i < 10; i++) { + assertEquals(unfiltered.lower(i), filtered.lower(i)); + assertEquals(unfiltered.floor(i), filtered.floor(i)); + assertEquals(unfiltered.ceiling(i), filtered.ceiling(i)); + assertEquals(unfiltered.higher(i), filtered.higher(i)); + } + } + } + } + // implementation tests public static final class IterablesFilterArrayListTest @@ -338,6 +427,19 @@ public class FilteredCollectionsTest extends TestCase { } } + public static final class SetsFilterNavigableSetTest extends AbstractFilteredNavigableSetTest { + @Override + NavigableSet<Integer> createUnfiltered(Iterable<Integer> contents) { + return Sets.newTreeSet(contents); + } + + @Override + NavigableSet<Integer> filter( + NavigableSet<Integer> elements, Predicate<? super Integer> predicate) { + return Sets.filter(elements, predicate); + } + } + /** No-op test so that the class has at least one method, making Maven's test runner happy. */ public void testNoop() { } diff --git a/guava-tests/test/com/google/common/collect/FluentIterableTest.java b/guava-tests/test/com/google/common/collect/FluentIterableTest.java index 492586189..674c642a9 100644 --- a/guava-tests/test/com/google/common/collect/FluentIterableTest.java +++ b/guava-tests/test/com/google/common/collect/FluentIterableTest.java @@ -16,13 +16,14 @@ package com.google.common.collect; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Functions; +import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; @@ -68,6 +69,11 @@ public class FluentIterableTest extends TestCase { assertSame(iterable, FluentIterable.from(iterable)); } + public void testOfArray() { + assertEquals(ImmutableList.of("1", "2", "3", "4"), + Lists.newArrayList(FluentIterable.of(new Object[] {"1", "2", "3", "4"}))); + } + public void testSize1Collection() { assertEquals(1, FluentIterable.from(asList("a")).size()); } @@ -160,6 +166,32 @@ public class FluentIterableTest extends TestCase { assertFalse(cycle.iterator().hasNext()); } + public void testAppend() { + FluentIterable<Integer> result = + FluentIterable.<Integer>from(asList(1, 2, 3)).append(Lists.newArrayList(4, 5, 6)); + assertEquals(asList(1, 2, 3, 4, 5, 6), Lists.newArrayList(result)); + assertEquals("[1, 2, 3, 4, 5, 6]", result.toString()); + + result = FluentIterable.<Integer>from(asList(1, 2, 3)).append(4, 5, 6); + assertEquals(asList(1, 2, 3, 4, 5, 6), Lists.newArrayList(result)); + assertEquals("[1, 2, 3, 4, 5, 6]", result.toString()); + } + + public void testAppend_emptyList() { + FluentIterable<Integer> result = + FluentIterable.<Integer>from(asList(1, 2, 3)).append(Lists.<Integer>newArrayList()); + assertEquals(asList(1, 2, 3), Lists.newArrayList(result)); + } + + @SuppressWarnings("ReturnValueIgnored") + public void testAppend_nullPointerException() { + try { + FluentIterable.<Integer>from(asList(1, 2)).append((List<Integer>) null); + fail("Appending null iterable should throw NPE."); + } catch (NullPointerException expected) { + } + } + /* * Tests for partition(int size) method. */ @@ -189,7 +221,7 @@ public class FluentIterableTest extends TestCase { FluentIterable<TypeA> alist = FluentIterable.from(asList(new TypeA(), new TypeA(), hasBoth, new TypeA())); Iterable<TypeB> blist = alist.filter(TypeB.class); - ASSERT.that(blist).iteratesOverSequence(hasBoth); + assertThat(blist).iteratesAs(hasBoth); } public void testAnyMatch() { @@ -450,7 +482,7 @@ public class FluentIterableTest extends TestCase { FluentIterable<String> tail = FluentIterable.from(set).skip(1); set.remove("b"); set.addAll(Lists.newArrayList("X", "Y", "Z")); - ASSERT.that(tail).iteratesOverSequence("c", "X", "Y", "Z"); + assertThat(tail).iteratesAs("c", "X", "Y", "Z"); } public void testSkip_structurallyModifiedSkipSomeList() throws Exception { @@ -458,7 +490,7 @@ public class FluentIterableTest extends TestCase { FluentIterable<String> tail = FluentIterable.from(list).skip(1); list.subList(1, 3).clear(); list.addAll(0, Lists.newArrayList("X", "Y", "Z")); - ASSERT.that(tail).iteratesOverSequence("Y", "Z", "a"); + assertThat(tail).iteratesAs("Y", "Z", "a"); } public void testSkip_structurallyModifiedSkipAll() throws Exception { @@ -474,7 +506,7 @@ public class FluentIterableTest extends TestCase { List<String> list = Lists.newArrayList("a", "b", "c"); FluentIterable<String> tail = FluentIterable.from(list).skip(2); list.subList(0, 2).clear(); - ASSERT.that(tail).isEmpty(); + assertThat(tail).isEmpty(); } @SuppressWarnings("ReturnValueIgnored") @@ -528,11 +560,11 @@ public class FluentIterableTest extends TestCase { } public void testToSet() { - ASSERT.that(fluent(1, 2, 3, 4).toSet()).has().exactly(1, 2, 3, 4).inOrder(); + assertThat(fluent(1, 2, 3, 4).toSet()).has().exactly(1, 2, 3, 4).inOrder(); } public void testToSet_removeDuplicates() { - ASSERT.that(fluent(1, 2, 1, 2).toSet()).has().exactly(1, 2).inOrder(); + assertThat(fluent(1, 2, 1, 2).toSet()).has().exactly(1, 2).inOrder(); } public void testToSet_empty() { @@ -540,17 +572,17 @@ public class FluentIterableTest extends TestCase { } public void testToSortedSet() { - ASSERT.that(fluent(1, 4, 2, 3).toSortedSet(Ordering.<Integer>natural().reverse())) + assertThat(fluent(1, 4, 2, 3).toSortedSet(Ordering.<Integer>natural().reverse())) .has().exactly(4, 3, 2, 1).inOrder(); } public void testToSortedSet_removeDuplicates() { - ASSERT.that(fluent(1, 4, 1, 3).toSortedSet(Ordering.<Integer>natural().reverse())) + assertThat(fluent(1, 4, 1, 3).toSortedSet(Ordering.<Integer>natural().reverse())) .has().exactly(4, 3, 1).inOrder(); } public void testToMap() { - ASSERT.that(fluent(1, 2, 3).toMap(Functions.toStringFunction()).entrySet()) + assertThat(fluent(1, 2, 3).toMap(Functions.toStringFunction()).entrySet()) .has().exactly( Maps.immutableEntry(1, "1"), Maps.immutableEntry(2, "2"), @@ -657,17 +689,17 @@ public class FluentIterableTest extends TestCase { } public void testCopyInto_List() { - ASSERT.that(fluent(1, 3, 5).copyInto(Lists.newArrayList(1, 2))) + assertThat(fluent(1, 3, 5).copyInto(Lists.newArrayList(1, 2))) .has().exactly(1, 2, 1, 3, 5).inOrder(); } public void testCopyInto_Set() { - ASSERT.that(fluent(1, 3, 5).copyInto(Sets.newHashSet(1, 2))) + assertThat(fluent(1, 3, 5).copyInto(Sets.newHashSet(1, 2))) .has().exactly(1, 2, 3, 5); } public void testCopyInto_SetAllDuplicates() { - ASSERT.that(fluent(1, 3, 5).copyInto(Sets.newHashSet(1, 2, 3, 5))) + assertThat(fluent(1, 3, 5).copyInto(Sets.newHashSet(1, 2, 3, 5))) .has().exactly(1, 2, 3, 5); } @@ -682,10 +714,18 @@ public class FluentIterableTest extends TestCase { } }; - ASSERT.that(FluentIterable.from(iterable).copyInto(list)) + assertThat(FluentIterable.from(iterable).copyInto(list)) .has().exactly(1, 2, 3, 9, 8, 7).inOrder(); } + public void testJoin() { + assertEquals("2,1,3,4", fluent(2, 1, 3, 4).join(Joiner.on(","))); + } + + public void testJoin_empty() { + assertEquals("", fluent().join(Joiner.on(","))); + } + public void testGet() { assertEquals("a", FluentIterable .from(Lists.newArrayList("a", "b", "c")).get(0)); diff --git a/guava-tests/test/com/google/common/collect/ForwardingBlockingDequeTest.java b/guava-tests/test/com/google/common/collect/ForwardingBlockingDequeTest.java new file mode 100644 index 000000000..ecb67bb12 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/ForwardingBlockingDequeTest.java @@ -0,0 +1,120 @@ +/* + * 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; + +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.TimeUnit; + +/** + * Test for {@link ForwardingBlockingDeque} + * + * @author Emily Soldal + */ +public class ForwardingBlockingDequeTest extends ForwardingTestCase { + private BlockingDeque<String> forward; + + /* + * Class parameters must be raw, so we can't create a proxy with generic + * type arguments. The created proxy only records calls and returns null, so + * the type is irrelevant at runtime. + */ + @SuppressWarnings("unchecked") + @Override protected void setUp() throws Exception { + super.setUp(); + final BlockingDeque<String> deque = createProxyInstance(BlockingDeque.class); + forward = new ForwardingBlockingDeque<String>() { + @Override protected BlockingDeque<String> delegate() { + return deque; + } + }; + } + + public void testRemainingCapacity() { + forward.remainingCapacity(); + assertEquals("[remainingCapacity]", getCalls()); + } + + public void testPutFirst_T() throws InterruptedException { + forward.putFirst("asf"); + assertEquals("[putFirst(Object)]", getCalls()); + } + + public void testPutLast_T() throws InterruptedException { + forward.putFirst("asf"); + assertEquals("[putFirst(Object)]", getCalls()); + } + + public void testOfferFirst_T() throws InterruptedException { + forward.offerFirst("asf", 2L, TimeUnit.SECONDS); + assertEquals("[offerFirst(Object,long,TimeUnit)]", getCalls()); + } + + public void testOfferLast_T() throws InterruptedException { + forward.offerLast("asf", 2L, TimeUnit.SECONDS); + assertEquals("[offerLast(Object,long,TimeUnit)]", getCalls()); + } + + public void testTakeFirst() throws InterruptedException { + forward.takeFirst(); + assertEquals("[takeFirst]", getCalls()); + } + + public void testTakeLast() throws InterruptedException { + forward.takeLast(); + assertEquals("[takeLast]", getCalls()); + } + + public void testPollFirst() throws InterruptedException { + forward.pollFirst(2L, TimeUnit.SECONDS); + assertEquals("[pollFirst(long,TimeUnit)]", getCalls()); + } + + public void testPollLast() throws InterruptedException { + forward.pollLast(2L, TimeUnit.SECONDS); + assertEquals("[pollLast(long,TimeUnit)]", getCalls()); + } + + public void testPut_T() throws InterruptedException { + forward.put("asf"); + assertEquals("[put(Object)]", getCalls()); + } + + public void testOffer_T() throws InterruptedException { + forward.offer("asf", 2L, TimeUnit.SECONDS); + assertEquals("[offer(Object,long,TimeUnit)]", getCalls()); + } + + public void testTake() throws InterruptedException { + forward.take(); + assertEquals("[take]", getCalls()); + } + + public void testPoll() throws InterruptedException { + forward.poll(2L, TimeUnit.SECONDS); + assertEquals("[poll(long,TimeUnit)]", getCalls()); + } + + public void testDrainTo_T() { + forward.drainTo(Lists.newArrayList()); + assertEquals("[drainTo(Collection)]", getCalls()); + } + + public void testDrainTo_T_maxElements() { + forward.drainTo(Lists.newArrayList(), 3); + assertEquals("[drainTo(Collection,int)]", getCalls()); + } +} diff --git a/guava-tests/test/com/google/common/collect/ForwardingDequeTest.java b/guava-tests/test/com/google/common/collect/ForwardingDequeTest.java new file mode 100644 index 000000000..0ff18fb22 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/ForwardingDequeTest.java @@ -0,0 +1,225 @@ +/* + * 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; + +import java.util.Collections; +import java.util.Deque; + +/** + * Tests for {@code ForwardingDeque}. + * + * @author Kurt Alfred Kluever + */ +public class ForwardingDequeTest extends ForwardingTestCase { + private Deque<String> forward; + + /* + * Class parameters must be raw, so we can't create a proxy with generic + * type arguments. The created proxy only records calls and returns null, so + * the type is irrelevant at runtime. + */ + @SuppressWarnings("unchecked") + @Override protected void setUp() throws Exception { + super.setUp(); + final Deque<String> deque = createProxyInstance(Deque.class); + forward = new ForwardingDeque<String>() { + @Override protected Deque<String> delegate() { + return deque; + } + }; + } + + public void testAdd_T() { + forward.add("asdf"); + assertEquals("[add(Object)]", getCalls()); + } + + public void testAddFirst_T() { + forward.addFirst("asdf"); + assertEquals("[addFirst(Object)]", getCalls()); + } + + public void testAddLast_T() { + forward.addLast("asdf"); + assertEquals("[addLast(Object)]", getCalls()); + } + + public void testAddAll_Collection() { + forward.addAll(Collections.singleton("asdf")); + assertEquals("[addAll(Collection)]", getCalls()); + } + + public void testClear() { + forward.clear(); + assertEquals("[clear]", getCalls()); + } + + public void testContains_T() { + forward.contains("asdf"); + assertEquals("[contains(Object)]", getCalls()); + } + + public void testContainsAll_Collection() { + forward.containsAll(Collections.singleton("asdf")); + assertEquals("[containsAll(Collection)]", getCalls()); + } + + public void testDescendingIterator() { + forward.descendingIterator(); + assertEquals("[descendingIterator]", getCalls()); + } + + public void testElement() { + forward.element(); + assertEquals("[element]", getCalls()); + } + + public void testGetFirst() { + forward.getFirst(); + assertEquals("[getFirst]", getCalls()); + } + + public void testGetLast() { + forward.getLast(); + assertEquals("[getLast]", getCalls()); + } + + public void testIterator() { + forward.iterator(); + assertEquals("[iterator]", getCalls()); + } + + public void testIsEmpty() { + forward.isEmpty(); + assertEquals("[isEmpty]", getCalls()); + } + + public void testOffer_T() { + forward.offer("asdf"); + assertEquals("[offer(Object)]", getCalls()); + } + + public void testOfferFirst_T() { + forward.offerFirst("asdf"); + assertEquals("[offerFirst(Object)]", getCalls()); + } + + public void testOfferLast_T() { + forward.offerLast("asdf"); + assertEquals("[offerLast(Object)]", getCalls()); + } + + public void testPeek() { + forward.peek(); + assertEquals("[peek]", getCalls()); + } + + public void testPeekFirst() { + forward.peekFirst(); + assertEquals("[peekFirst]", getCalls()); + } + + public void testPeekLast() { + forward.peekLast(); + assertEquals("[peekLast]", getCalls()); + } + + public void testPoll() { + forward.poll(); + assertEquals("[poll]", getCalls()); + } + + public void testPollFirst() { + forward.pollFirst(); + assertEquals("[pollFirst]", getCalls()); + } + + public void testPollLast() { + forward.pollLast(); + assertEquals("[pollLast]", getCalls()); + } + + public void testPop() { + forward.pop(); + assertEquals("[pop]", getCalls()); + } + + public void testPush_Object() { + forward.push("asdf"); + assertEquals("[push(Object)]", getCalls()); + } + + public void testRemove() { + forward.remove(); + assertEquals("[remove]", getCalls()); + } + + public void testRemoveFirst() { + forward.removeFirst(); + assertEquals("[removeFirst]", getCalls()); + } + + public void testRemoveLast() { + forward.removeLast(); + assertEquals("[removeLast]", getCalls()); + } + + public void testRemove_Object() { + forward.remove(Object.class); + assertEquals("[remove(Object)]", getCalls()); + } + + public void testRemoveFirstOccurrence_Object() { + forward.removeFirstOccurrence(Object.class); + assertEquals("[removeFirstOccurrence(Object)]", getCalls()); + } + + public void testRemoveLastOccurrence_Object() { + forward.removeLastOccurrence(Object.class); + assertEquals("[removeLastOccurrence(Object)]", getCalls()); + } + + public void testRemoveAll_Collection() { + forward.removeAll(Collections.singleton("asdf")); + assertEquals("[removeAll(Collection)]", getCalls()); + } + + public void testRetainAll_Collection() { + forward.retainAll(Collections.singleton("asdf")); + assertEquals("[retainAll(Collection)]", getCalls()); + } + + public void testSize() { + forward.size(); + assertEquals("[size]", getCalls()); + } + + public void testToArray() { + forward.toArray(); + assertEquals("[toArray]", getCalls()); + } + + public void testToArray_TArray() { + forward.toArray(new String[0]); + assertEquals("[toArray(Object[])]", getCalls()); + } + + public void testToString() { + forward.toString(); + assertEquals("[toString]", getCalls()); + } +} diff --git a/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java b/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java new file mode 100644 index 000000000..d10ff0973 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/ForwardingNavigableMapTest.java @@ -0,0 +1,381 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.collect; + +import static com.google.common.collect.Maps.immutableEntry; + +import com.google.common.collect.testing.NavigableMapTestSuiteBuilder; +import com.google.common.collect.testing.SafeTreeMap; +import com.google.common.collect.testing.TestStringSortedMapGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.NavigableSet; +import java.util.Set; +import java.util.SortedMap; + +/** + * Tests for {@code ForwardingNavigableMap}. + * + * @author Robert Konigsberg + * @author Louis Wasserman + */ +public class ForwardingNavigableMapTest extends ForwardingSortedMapTest { + static class StandardImplForwardingNavigableMap<K, V> + extends ForwardingNavigableMap<K, V> { + private final NavigableMap<K, V> backingMap; + + StandardImplForwardingNavigableMap(NavigableMap<K, V> backingMap) { + this.backingMap = backingMap; + } + + @Override protected NavigableMap<K, V> delegate() { + return backingMap; + } + + @Override public boolean containsKey(Object key) { + return standardContainsKey(key); + } + + @Override public boolean containsValue(Object value) { + return standardContainsValue(value); + } + + @Override public void putAll(Map<? extends K, ? extends V> map) { + standardPutAll(map); + } + + @Override public V remove(Object object) { + return standardRemove(object); + } + + @Override public boolean equals(Object object) { + return standardEquals(object); + } + + @Override public int hashCode() { + return standardHashCode(); + } + + @Override public Set<K> keySet() { + /* + * We can't use StandardKeySet, as NavigableMapTestSuiteBuilder assumes that our keySet is a + * NavigableSet. We test StandardKeySet in the superclass, so it's still covered. + */ + return navigableKeySet(); + } + + @Override public Collection<V> values() { + return new StandardValues(); + } + + @Override public String toString() { + return standardToString(); + } + + @Override public Set<Entry<K, V>> entrySet() { + return new StandardEntrySet() { + @Override + public Iterator<Entry<K, V>> iterator() { + return backingMap.entrySet().iterator(); + } + }; + } + + @Override public void clear() { + standardClear(); + } + + @Override public boolean isEmpty() { + return standardIsEmpty(); + } + + @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { + return standardSubMap(fromKey, toKey); + } + + @Override + public Entry<K, V> lowerEntry(K key) { + return standardLowerEntry(key); + } + + @Override + public K lowerKey(K key) { + return standardLowerKey(key); + } + + @Override + public Entry<K, V> floorEntry(K key) { + return standardFloorEntry(key); + } + + @Override + public K floorKey(K key) { + return standardFloorKey(key); + } + + @Override + public Entry<K, V> ceilingEntry(K key) { + return standardCeilingEntry(key); + } + + @Override + public K ceilingKey(K key) { + return standardCeilingKey(key); + } + + @Override + public Entry<K, V> higherEntry(K key) { + return standardHigherEntry(key); + } + + @Override + public K higherKey(K key) { + return standardHigherKey(key); + } + + @Override + public Entry<K, V> firstEntry() { + return standardFirstEntry(); + } + + /* + * We can't override lastEntry to delegate to standardLastEntry, as it would create an infinite + * loop. Instead, we test standardLastEntry manually below. + */ + + @Override + public Entry<K, V> pollFirstEntry() { + return standardPollFirstEntry(); + } + + @Override + public Entry<K, V> pollLastEntry() { + return standardPollLastEntry(); + } + + @Override + public NavigableMap<K, V> descendingMap() { + return new StandardDescendingMap(); + } + + @Override + public NavigableSet<K> navigableKeySet() { + return new StandardNavigableKeySet(); + } + + @Override + public NavigableSet<K> descendingKeySet() { + return standardDescendingKeySet(); + } + + @Override + public K firstKey() { + return standardFirstKey(); + } + + @Override + public SortedMap<K, V> headMap(K toKey) { + return standardHeadMap(toKey); + } + + @Override + public K lastKey() { + return standardLastKey(); + } + + @Override + public SortedMap<K, V> tailMap(K fromKey) { + return standardTailMap(fromKey); + } + } + + static class StandardLastEntryForwardingNavigableMap<K, V> + extends ForwardingNavigableMap<K, V> { + private final NavigableMap<K, V> backingMap; + + StandardLastEntryForwardingNavigableMap(NavigableMap<K, V> backingMap) { + this.backingMap = backingMap; + } + + @Override protected NavigableMap<K, V> delegate() { + return backingMap; + } + + @Override + public Entry<K, V> lastEntry() { + return standardLastEntry(); + } + } + + public static Test suite() { + TestSuite suite = new TestSuite(); + + suite.addTestSuite(ForwardingNavigableMapTest.class); + suite.addTest(NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + @Override protected SortedMap<String, String> create( + Entry<String, String>[] entries) { + NavigableMap<String, String> map = new SafeTreeMap<String, String>(); + for (Entry<String, String> entry : entries) { + map.put(entry.getKey(), entry.getValue()); + } + return new StandardImplForwardingNavigableMap<String, String>(map); + } + }).named("ForwardingNavigableMap[SafeTreeMap] with no comparator and standard " + + "implementations").withFeatures(CollectionSize.ANY, + CollectionFeature.KNOWN_ORDER, MapFeature.ALLOWS_NULL_VALUES, + CollectionFeature.SUPPORTS_ITERATOR_REMOVE, MapFeature.GENERAL_PURPOSE) + .createTestSuite()); + // TODO(user): add forwarding-to-ImmutableSortedMap test + return suite; + } + + @Override public void setUp() throws Exception { + super.setUp(); + /* + * Class parameters must be raw, so we can't create a proxy with generic + * type arguments. The created proxy only records calls and returns null, so + * the type is irrelevant at runtime. + */ + @SuppressWarnings("unchecked") + final NavigableMap<String, Boolean> sortedMap = + createProxyInstance(NavigableMap.class); + forward = new ForwardingNavigableMap<String, Boolean>() { + @Override protected NavigableMap<String, Boolean> delegate() { + return sortedMap; + } + }; + } + + public void testStandardLastEntry() { + NavigableMap<String, Integer> forwarding = + new StandardLastEntryForwardingNavigableMap<String, Integer>( + new SafeTreeMap<String, Integer>()); + assertNull(forwarding.lastEntry()); + forwarding.put("b", 2); + assertEquals(immutableEntry("b", 2), forwarding.lastEntry()); + forwarding.put("c", 3); + assertEquals(immutableEntry("c", 3), forwarding.lastEntry()); + forwarding.put("a", 1); + assertEquals(immutableEntry("c", 3), forwarding.lastEntry()); + forwarding.remove("c"); + assertEquals(immutableEntry("b", 2), forwarding.lastEntry()); + } + + public void testLowerEntry() { + forward().lowerEntry("key"); + assertEquals("[lowerEntry(Object)]", getCalls()); + } + + public void testLowerKey() { + forward().lowerKey("key"); + assertEquals("[lowerKey(Object)]", getCalls()); + } + + public void testFloorEntry() { + forward().floorEntry("key"); + assertEquals("[floorEntry(Object)]", getCalls()); + } + + public void testFloorKey() { + forward().floorKey("key"); + assertEquals("[floorKey(Object)]", getCalls()); + } + + public void testCeilingEntry() { + forward().ceilingEntry("key"); + assertEquals("[ceilingEntry(Object)]", getCalls()); + } + + public void testCeilingKey() { + forward().ceilingKey("key"); + assertEquals("[ceilingKey(Object)]", getCalls()); + } + + public void testHigherEntry() { + forward().higherEntry("key"); + assertEquals("[higherEntry(Object)]", getCalls()); + } + + public void testHigherKey() { + forward().higherKey("key"); + assertEquals("[higherKey(Object)]", getCalls()); + } + + public void testPollFirstEntry() { + forward().pollFirstEntry(); + assertEquals("[pollFirstEntry]", getCalls()); + } + + public void testPollLastEntry() { + forward().pollLastEntry(); + assertEquals("[pollLastEntry]", getCalls()); + } + + public void testFirstEntry() { + forward().firstEntry(); + assertEquals("[firstEntry]", getCalls()); + } + + public void testLastEntry() { + forward().lastEntry(); + assertEquals("[lastEntry]", getCalls()); + } + + public void testDescendingMap() { + forward().descendingMap(); + assertEquals("[descendingMap]", getCalls()); + } + + public void testNavigableKeySet() { + forward().navigableKeySet(); + assertEquals("[navigableKeySet]", getCalls()); + } + + public void testDescendingKeySet() { + forward().descendingKeySet(); + assertEquals("[descendingKeySet]", getCalls()); + } + + public void testSubMap_K_Bool_K_Bool() { + forward().subMap("a", false, "b", true); + assertEquals("[subMap(Object,boolean,Object,boolean)]", getCalls()); + } + + public void testHeadMap_K_Bool() { + forward().headMap("a", false); + assertEquals("[headMap(Object,boolean)]", getCalls()); + } + + public void testTailMap_K_Bool() { + forward().tailMap("a", false); + assertEquals("[tailMap(Object,boolean)]", getCalls()); + } + + @Override NavigableMap<String, Boolean> forward() { + return (NavigableMap<String, Boolean>) super.forward(); + } +} diff --git a/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java b/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java new file mode 100644 index 000000000..70178b1ea --- /dev/null +++ b/guava-tests/test/com/google/common/collect/ForwardingNavigableSetTest.java @@ -0,0 +1,256 @@ +/* + * 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; + +import com.google.common.collect.testing.SafeTreeSet; +import com.google.common.collect.testing.SetTestSuiteBuilder; +import com.google.common.collect.testing.TestStringSetGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.NavigableSet; +import java.util.Set; +import java.util.SortedSet; + +/** + * Tests for {@code ForwardingNavigableSet}. + * + * @author Louis Wasserman + */ +public class ForwardingNavigableSetTest extends ForwardingSortedSetTest { + static class StandardImplForwardingNavigableSet<T> + extends ForwardingNavigableSet<T> { + private final NavigableSet<T> backingSet; + + StandardImplForwardingNavigableSet(NavigableSet<T> backingSet) { + this.backingSet = backingSet; + } + + @Override protected NavigableSet<T> delegate() { + return backingSet; + } + + @Override public boolean equals(Object object) { + return standardEquals(object); + } + + @Override public int hashCode() { + return standardHashCode(); + } + + @Override public boolean addAll(Collection<? extends T> collection) { + return standardAddAll(collection); + } + + @Override public void clear() { + standardClear(); + } + + @Override public boolean contains(Object object) { + return standardContains(object); + } + + @Override public boolean containsAll(Collection<?> collection) { + return standardContainsAll(collection); + } + + @Override public boolean remove(Object object) { + return standardRemove(object); + } + + @Override public boolean removeAll(Collection<?> collection) { + return standardRemoveAll(collection); + } + + @Override public boolean retainAll(Collection<?> collection) { + return standardRetainAll(collection); + } + + @Override public Object[] toArray() { + return standardToArray(); + } + + @Override public <T> T[] toArray(T[] array) { + return standardToArray(array); + } + + @Override public String toString() { + return standardToString(); + } + + @Override public SortedSet<T> subSet(T fromElement, T toElement) { + return standardSubSet(fromElement, toElement); + } + + @Override + public T lower(T e) { + return standardLower(e); + } + + @Override + public T floor(T e) { + return standardFloor(e); + } + + @Override + public T ceiling(T e) { + return standardCeiling(e); + } + + @Override + public T higher(T e) { + return standardHigher(e); + } + + @Override + public T pollFirst() { + return standardPollFirst(); + } + + @Override + public T pollLast() { + return standardPollLast(); + } + + @Override + public SortedSet<T> headSet(T toElement) { + return standardHeadSet(toElement); + } + + @Override + public SortedSet<T> tailSet(T fromElement) { + return standardTailSet(fromElement); + } + } + + public static Test suite() { + TestSuite suite = new TestSuite(); + + suite.addTestSuite(ForwardingNavigableSetTest.class); + suite.addTest( + SetTestSuiteBuilder.using(new TestStringSetGenerator() { + @Override protected Set<String> create(String[] elements) { + return new StandardImplForwardingNavigableSet<String>( + new SafeTreeSet<String>(Arrays.asList(elements))); + } + + @Override public List<String> order(List<String> insertionOrder) { + return Lists.newArrayList(Sets.newTreeSet(insertionOrder)); + } + }).named( + "ForwardingNavigableSet[SafeTreeSet] with standard implementations") + .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, + CollectionFeature.GENERAL_PURPOSE).createTestSuite()); + suite.addTest( + SetTestSuiteBuilder.using(new TestStringSetGenerator() { + @Override protected Set<String> create(String[] elements) { + SafeTreeSet<String> set = new SafeTreeSet<String>(Ordering.natural().nullsFirst()); + Collections.addAll(set, elements); + return new StandardImplForwardingNavigableSet<String>(set); + } + + @Override public List<String> order(List<String> insertionOrder) { + return Lists.newArrayList(Sets.newTreeSet(insertionOrder)); + } + }).named( + "ForwardingNavigableSet[SafeTreeSet[Ordering.natural.nullsFirst]]" + + " with standard implementations") + .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, + CollectionFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES) + .createTestSuite()); + + return suite; + } + + @Override public void setUp() throws Exception { + super.setUp(); + /* + * Class parameters must be raw, so we can't create a proxy with generic + * type arguments. The created proxy only records calls and returns null, so + * the type is irrelevant at runtime. + */ + @SuppressWarnings("unchecked") + final NavigableSet<String> navigableSet + = createProxyInstance(NavigableSet.class); + forward = new ForwardingNavigableSet<String>() { + @Override protected NavigableSet<String> delegate() { + return navigableSet; + } + }; + } + + public void testLower() { + forward().lower("a"); + assertEquals("[lower(Object)]", getCalls()); + } + + public void testFloor() { + forward().floor("a"); + assertEquals("[floor(Object)]", getCalls()); + } + + public void testCeiling() { + forward().ceiling("a"); + assertEquals("[ceiling(Object)]", getCalls()); + } + + public void testHigher() { + forward().higher("a"); + assertEquals("[higher(Object)]", getCalls()); + } + + public void testPollFirst() { + forward().pollFirst(); + assertEquals("[pollFirst]", getCalls()); + } + + public void testPollLast() { + forward().pollLast(); + assertEquals("[pollLast]", getCalls()); + } + + public void testDescendingIterator() { + forward().descendingIterator(); + assertEquals("[descendingIterator]", getCalls()); + } + + public void testHeadSet_K_Boolean() { + forward().headSet("key", false); + assertEquals("[headSet(Object,boolean)]", getCalls()); + } + + public void testSubSet_K_Boolean_K_Boolean() { + forward().subSet("a", true, "b", false); + assertEquals("[subSet(Object,boolean,Object,boolean)]", getCalls()); + } + + public void testTailSet_K_Boolean() { + forward().tailSet("key", false); + assertEquals("[tailSet(Object,boolean)]", getCalls()); + } + + @Override NavigableSet<String> forward() { + return (NavigableSet<String>) super.forward(); + } +} diff --git a/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java b/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java index e2cf067ea..36d55b76d 100644 --- a/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java +++ b/guava-tests/test/com/google/common/collect/ForwardingSortedMapTest.java @@ -17,7 +17,6 @@ package com.google.common.collect; import com.google.common.collect.testing.Helpers.NullsBeforeTwo; -import com.google.common.collect.testing.MapTestSuiteBuilder; import com.google.common.collect.testing.SafeTreeMap; import com.google.common.collect.testing.SortedMapTestSuiteBuilder; import com.google.common.collect.testing.TestStringSortedMapGenerator; @@ -66,11 +65,9 @@ public class ForwardingSortedMapTest extends ForwardingMapTest { standardPutAll(map); } - /* This test would fail due to a bug fixed in JDK7 @Override public V remove(Object object) { return standardRemove(object); } - */ @Override public boolean equals(Object object) { return standardEquals(object); @@ -132,7 +129,7 @@ public class ForwardingSortedMapTest extends ForwardingMapTest { CollectionFeature.KNOWN_ORDER, MapFeature.ALLOWS_NULL_VALUES, MapFeature.GENERAL_PURPOSE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE) .createTestSuite()); - suite.addTest(MapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + suite.addTest(SortedMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { private final Comparator<String> comparator = NullsBeforeTwo.INSTANCE; @Override protected SortedMap<String, String> create( diff --git a/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java b/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java index 092fe0dc4..33aed37c3 100644 --- a/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/ForwardingSortedMultisetTest.java @@ -29,7 +29,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; -import java.util.SortedSet; +import java.util.NavigableSet; import javax.annotation.Nullable; @@ -66,7 +66,7 @@ public class ForwardingSortedMultisetTest extends ForwardingMultisetTest { } @Override - public SortedSet<E> elementSet() { + public NavigableSet<E> elementSet() { return new StandardElementSet(); } diff --git a/guava-tests/test/com/google/common/collect/ForwardingTestCase.java b/guava-tests/test/com/google/common/collect/ForwardingTestCase.java index 15f89e588..31e54a3c2 100644 --- a/guava-tests/test/com/google/common/collect/ForwardingTestCase.java +++ b/guava-tests/test/com/google/common/collect/ForwardingTestCase.java @@ -115,6 +115,28 @@ public abstract class ForwardingTestCase extends TestCase { return Iterators.emptyModifiableIterator(); } else if (returnType.isArray()) { return Array.newInstance(returnType.getComponentType(), 0); + } else if ("java.util.function.Predicate".equals(returnType.getCanonicalName()) + || ("java.util.function.Consumer".equals(returnType.getCanonicalName()))) { + // Generally, methods that accept java.util.function.* instances + // don't like to get null values. We generate them dynamically + // using Proxy so that we can have Java 7 compliant code. + InvocationHandler handler = new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, + Object[] args) { + // Crude, but acceptable until we can use Java 8. Other + // methods have default implementations, and it is hard to + // distinguish. + if ("test".equals(method.getName()) + || "accept".equals(method.getName())) { + return getDefaultValue(method.getReturnType()); + } + throw new IllegalStateException( + "Unexpected " + method + " invoked on " + proxy); + } + }; + return Proxy.newProxyInstance(returnType.getClassLoader(), + new Class[] { returnType }, + handler); } else { return null; } diff --git a/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java index 3c7111a95..8609e050d 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -445,7 +445,7 @@ public class ImmutableBiMapTest extends TestCase { ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4)); Set<String> keys = bimap.keySet(); assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys); - ASSERT.that(keys).has().exactly("one", "two", "three", "four").inOrder(); + assertThat(keys).has().exactly("one", "two", "three", "four").inOrder(); } public void testValues() { @@ -453,7 +453,7 @@ public class ImmutableBiMapTest extends TestCase { ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4)); Set<Integer> values = bimap.values(); assertEquals(Sets.newHashSet(1, 2, 3, 4), values); - ASSERT.that(values).has().exactly(1, 2, 3, 4).inOrder(); + assertThat(values).has().exactly(1, 2, 3, 4).inOrder(); } public void testDoubleInverse() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java index 3bcb17a97..e8244a9b9 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -74,7 +74,7 @@ public class ImmutableEnumMapTest extends TestCase { ImmutableMap<AnEnum, String> map = Maps.immutableEnumMap( ImmutableMap.of(AnEnum.C, "c", AnEnum.A, "a", AnEnum.E, "e")); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( Helpers.mapEntry(AnEnum.A, "a"), Helpers.mapEntry(AnEnum.C, "c"), Helpers.mapEntry(AnEnum.E, "e")).inOrder(); diff --git a/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java b/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java index 3e680f118..b632735d8 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -263,10 +263,10 @@ public class ImmutableListMultimapTest extends TestCase { builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); - ASSERT.that(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("b")).has().exactly(3, 6).inOrder(); + assertThat(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); + assertThat(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("b")).has().exactly(3, 6).inOrder(); } public void testBuilderOrderKeysByDuplicates() { @@ -285,10 +285,10 @@ public class ImmutableListMultimapTest extends TestCase { builder.put("a", 2); builder.put("bb", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); - ASSERT.that(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("bb")).has().exactly(3, 6).inOrder(); + assertThat(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); + assertThat(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("bb")).has().exactly(3, 6).inOrder(); } public void testBuilderOrderValuesBy() { @@ -302,10 +302,10 @@ public class ImmutableListMultimapTest extends TestCase { builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); - ASSERT.that(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); + assertThat(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); + assertThat(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("b")).has().exactly(6, 3).inOrder(); } public void testBuilderOrderKeysAndValuesBy() { @@ -320,10 +320,10 @@ public class ImmutableListMultimapTest extends TestCase { builder.put("a", 2); builder.put("b", 6); ImmutableListMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); - ASSERT.that(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); + assertThat(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); + assertThat(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("b")).has().exactly(6, 3).inOrder(); } public void testCopyOf() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java b/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java index 5e94ac31f..a0ad48103 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java @@ -17,8 +17,8 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -452,7 +452,7 @@ public class ImmutableMultisetTest extends TestCase { public void testSerialization_multiple() { Collection<String> c = ImmutableMultiset.of("a", "b", "a"); Collection<String> copy = SerializableTester.reserializeAndAssert(c); - ASSERT.that(copy).has().exactly("a", "a", "b").inOrder(); + assertThat(copy).has().exactly("a", "a", "b").inOrder(); } @GwtIncompatible("SerializableTester") @@ -460,7 +460,7 @@ public class ImmutableMultisetTest extends TestCase { Multiset<String> c = ImmutableMultiset.of("a", "b", "a"); Collection<String> copy = LenientSerializableTester.reserializeAndAssertLenient(c.elementSet()); - ASSERT.that(copy).has().exactly("a", "b").inOrder(); + assertThat(copy).has().exactly("a", "b").inOrder(); } @GwtIncompatible("SerializableTester") @@ -473,13 +473,13 @@ public class ImmutableMultisetTest extends TestCase { Collection<String> c = ImmutableMultiset.of("a", "b", "a"); assertEquals(c, ImmutableMultiset.of("a", "b", "a")); assertEquals(c, ImmutableMultiset.of("a", "a", "b")); - ASSERT.that(c).isNotEqualTo(ImmutableMultiset.of("a", "b")); - ASSERT.that(c).isNotEqualTo(ImmutableMultiset.of("a", "b", "c", "d")); + assertThat(c).isNotEqualTo(ImmutableMultiset.of("a", "b")); + assertThat(c).isNotEqualTo(ImmutableMultiset.of("a", "b", "c", "d")); } public void testIterationOrder() { Collection<String> c = ImmutableMultiset.of("a", "b", "a"); - ASSERT.that(c).has().exactly("a", "a", "b").inOrder(); + assertThat(c).has().exactly("a", "a", "b").inOrder(); } public void testMultisetWrites() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableRangeMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableRangeMapTest.java new file mode 100644 index 000000000..3d1d7b41d --- /dev/null +++ b/guava-tests/test/com/google/common/collect/ImmutableRangeMapTest.java @@ -0,0 +1,228 @@ +/* + * 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; + +import static com.google.common.collect.BoundType.OPEN; + +import com.google.common.annotations.GwtIncompatible; + +import junit.framework.TestCase; + +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; + +/** + * Tests for {@code ImmutableRangeMap}. + * + * @author Louis Wasserman + */ +@GwtIncompatible("NavigableMap") +public class ImmutableRangeMapTest extends TestCase { + private static final ImmutableList<Range<Integer>> RANGES; + private static final int MIN_BOUND = 0; + private static final int MAX_BOUND = 10; + static { + ImmutableList.Builder<Range<Integer>> builder = ImmutableList.builder(); + + builder.add(Range.<Integer>all()); + + // Add one-ended ranges + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + for (BoundType type : BoundType.values()) { + builder.add(Range.upTo(i, type)); + builder.add(Range.downTo(i, type)); + } + } + + // Add two-ended ranges + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + for (int j = i + 1; j <= MAX_BOUND; j++) { + for (BoundType lowerType : BoundType.values()) { + for (BoundType upperType : BoundType.values()) { + if (i == j & lowerType == OPEN & upperType == OPEN) { + continue; + } + builder.add(Range.range(i, lowerType, j, upperType)); + } + } + } + } + RANGES = builder.build(); + } + + public void testBuilderRejectsEmptyRanges() { + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + ImmutableRangeMap.Builder<Integer, Integer> builder = ImmutableRangeMap.builder(); + try { + builder.put(Range.closedOpen(i, i), 1); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + // success + } + try { + builder.put(Range.openClosed(i, i), 1); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + } + } + } + + public void testOverlapRejection() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + boolean expectRejection = + range1.isConnected(range2) && !range1.intersection(range2).isEmpty(); + ImmutableRangeMap.Builder<Integer, Integer> builder = ImmutableRangeMap.builder(); + builder.put(range1, 1); + try { + builder.put(range2, 2); + assertFalse(expectRejection); + } catch (IllegalArgumentException e) { + assertTrue(expectRejection); + } + } + } + } + + public void testGet() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + if (!range1.isConnected(range2) || range1.intersection(range2).isEmpty()) { + ImmutableRangeMap<Integer, Integer> rangeMap = + ImmutableRangeMap.<Integer, Integer>builder().put(range1, 1).put(range2, 2).build(); + + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + Integer expectedValue = null; + if (range1.contains(i)) { + expectedValue = 1; + } else if (range2.contains(i)) { + expectedValue = 2; + } + + assertEquals(expectedValue, rangeMap.get(i)); + } + } + } + } + } + + public void testSpanEmpty() { + try { + ImmutableRangeMap.of().span(); + fail("Expected NoSuchElementException"); + } catch (NoSuchElementException expected) { + } + } + + public void testSpanSingleRange() { + for (Range<Integer> range : RANGES) { + RangeMap<Integer, Integer> rangemap = + ImmutableRangeMap.<Integer, Integer>builder().put(range, 1).build(); + assertEquals(range, rangemap.span()); + } + } + + public void testSpanTwoRanges() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + if (!range1.isConnected(range2) || range1.intersection(range2).isEmpty()) { + RangeMap<Integer, Integer> rangemap = + ImmutableRangeMap.<Integer, Integer>builder().put(range1, 1).put(range2, 2).build(); + assertEquals(range1.span(range2), rangemap.span()); + } + } + } + } + + public void testGetEntry() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + if (!range1.isConnected(range2) || range1.intersection(range2).isEmpty()) { + ImmutableRangeMap<Integer, Integer> rangeMap = + ImmutableRangeMap.<Integer, Integer>builder().put(range1, 1).put(range2, 2).build(); + + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + Entry<Range<Integer>, Integer> expectedEntry = null; + if (range1.contains(i)) { + expectedEntry = Maps.immutableEntry(range1, 1); + } else if (range2.contains(i)) { + expectedEntry = Maps.immutableEntry(range2, 2); + } + + assertEquals(expectedEntry, rangeMap.getEntry(i)); + } + } + } + } + } + + public void testGetLargeRangeMap() { + ImmutableRangeMap.Builder<Integer, Integer> builder = ImmutableRangeMap.builder(); + for (int i = 0; i < 100; i++) { + builder.put(Range.closedOpen(i, i + 1), i); + } + ImmutableRangeMap<Integer, Integer> map = builder.build(); + for (int i = 0; i < 100; i++) { + assertEquals(Integer.valueOf(i), map.get(i)); + } + } + + public void testAsMapOfRanges() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + if (!range1.isConnected(range2) || range1.intersection(range2).isEmpty()) { + ImmutableRangeMap<Integer, Integer> rangeMap = + ImmutableRangeMap.<Integer, Integer>builder().put(range1, 1).put(range2, 2).build(); + + ImmutableMap<Range<Integer>, Integer> expectedAsMap = + ImmutableMap.of(range1, 1, range2, 2); + ImmutableMap<Range<Integer>, Integer> asMap = rangeMap.asMapOfRanges(); + assertEquals(expectedAsMap, asMap); + + for (Range<Integer> query : RANGES) { + assertEquals(expectedAsMap.get(query), asMap.get(query)); + } + } + } + } + } + + public void testSubRangeMap() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + if (!range1.isConnected(range2) || range1.intersection(range2).isEmpty()) { + for (Range<Integer> subRange : RANGES) { + ImmutableRangeMap<Integer, Integer> rangeMap = + ImmutableRangeMap.<Integer, Integer>builder() + .put(range1, 1).put(range2, 2).build(); + + ImmutableRangeMap.Builder<Integer, Integer> expectedBuilder = + ImmutableRangeMap.builder(); + for (Map.Entry<Range<Integer>, Integer> entry : rangeMap.asMapOfRanges().entrySet()) { + if (entry.getKey().isConnected(subRange) + && !entry.getKey().intersection(subRange).isEmpty()) { + expectedBuilder.put(entry.getKey().intersection(subRange), entry.getValue()); + } + } + + ImmutableRangeMap<Integer, Integer> expected = expectedBuilder.build(); + assertEquals(expected, rangeMap.subRangeMap(subRange)); + } + } + } + } + } +} diff --git a/guava-tests/test/com/google/common/collect/ImmutableRangeSetTest.java b/guava-tests/test/com/google/common/collect/ImmutableRangeSetTest.java new file mode 100644 index 000000000..cf7843bc3 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/ImmutableRangeSetTest.java @@ -0,0 +1,508 @@ +/* + * 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; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.common.annotations.GwtIncompatible; +import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.TestSetGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.testing.SerializableTester; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import java.math.BigInteger; +import java.util.List; +import java.util.Set; + +/** + * Tests for {@link ImmutableRangeSet}. + * + * @author Louis Wasserman + */ +@GwtIncompatible("ImmutableRangeSet") +public class ImmutableRangeSetTest extends AbstractRangeSetTest { + @SuppressWarnings("unchecked") // varargs + private static final ImmutableSet<Range<Integer>> RANGES = ImmutableSet.of( + Range.<Integer>all(), + Range.closedOpen(3, 5), + Range.singleton(1), + Range.lessThan(2), + Range.greaterThan(10), + Range.atMost(4), + Range.atLeast(3), + Range.closed(4, 6), + Range.closedOpen(1, 3), + Range.openClosed(5, 7), + Range.open(3, 4)); + + static final class ImmutableRangeSetIntegerAsSetGenerator implements TestSetGenerator<Integer> { + @Override + public SampleElements<Integer> samples() { + return new SampleElements<Integer>(1, 4, 3, 2, 5); + } + + @Override + public Integer[] createArray(int length) { + return new Integer[length]; + } + + @Override + public Iterable<Integer> order(List<Integer> insertionOrder) { + return Ordering.natural().sortedCopy(insertionOrder); + } + + @Override + public Set<Integer> create(Object... elements) { + ImmutableRangeSet.Builder<Integer> builder = ImmutableRangeSet.builder(); + for (Object o : elements) { + Integer i = (Integer) o; + builder.add(Range.singleton(i)); + } + return builder.build().asSet(DiscreteDomain.integers()); + } + } + + static final class ImmutableRangeSetBigIntegerAsSetGenerator + implements TestSetGenerator<BigInteger> { + @Override + public SampleElements<BigInteger> samples() { + return new SampleElements<BigInteger>( + BigInteger.valueOf(1), + BigInteger.valueOf(4), + BigInteger.valueOf(3), + BigInteger.valueOf(2), + BigInteger.valueOf(5)); + } + + @Override + public BigInteger[] createArray(int length) { + return new BigInteger[length]; + } + + @Override + public Iterable<BigInteger> order(List<BigInteger> insertionOrder) { + return Ordering.natural().sortedCopy(insertionOrder); + } + + @Override + public Set<BigInteger> create(Object... elements) { + ImmutableRangeSet.Builder<BigInteger> builder = ImmutableRangeSet.builder(); + for (Object o : elements) { + BigInteger i = (BigInteger) o; + builder.add(Range.closedOpen(i, i.add(BigInteger.ONE))); + } + return builder.build().asSet(DiscreteDomain.bigIntegers()); + } + } + + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(ImmutableRangeSetTest.class); + suite.addTest(NavigableSetTestSuiteBuilder.using(new ImmutableRangeSetIntegerAsSetGenerator()) + .named("ImmutableRangeSet.asSet[DiscreteDomain.integers[]]") + .withFeatures( + CollectionSize.ANY, + CollectionFeature.REJECTS_DUPLICATES_AT_CREATION, + CollectionFeature.ALLOWS_NULL_QUERIES, + CollectionFeature.KNOWN_ORDER, + CollectionFeature.NON_STANDARD_TOSTRING, + CollectionFeature.SERIALIZABLE) + .createTestSuite()); + + suite.addTest(NavigableSetTestSuiteBuilder.using( + new ImmutableRangeSetBigIntegerAsSetGenerator()) + .named("ImmutableRangeSet.asSet[DiscreteDomain.bigIntegers[]]") + .withFeatures( + CollectionSize.ANY, + CollectionFeature.REJECTS_DUPLICATES_AT_CREATION, + CollectionFeature.ALLOWS_NULL_QUERIES, + CollectionFeature.KNOWN_ORDER, + CollectionFeature.NON_STANDARD_TOSTRING, + CollectionFeature.SERIALIZABLE) + .createTestSuite()); + return suite; + } + + public void testEmpty() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.of(); + + assertThat(rangeSet.asRanges()).isEmpty(); + assertEquals(ImmutableRangeSet.<Integer>all(), rangeSet.complement()); + assertFalse(rangeSet.contains(0)); + assertFalse(rangeSet.encloses(Range.singleton(0))); + assertTrue(rangeSet.enclosesAll(rangeSet)); + assertTrue(rangeSet.isEmpty()); + } + + public void testAll() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.all(); + + assertThat(rangeSet.asRanges()).has().item(Range.<Integer>all()); + assertTrue(rangeSet.contains(0)); + assertTrue(rangeSet.encloses(Range.<Integer>all())); + assertTrue(rangeSet.enclosesAll(rangeSet)); + assertEquals(ImmutableRangeSet.<Integer>of(), rangeSet.complement()); + } + + public void testSingleBoundedRange() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.of(Range.closedOpen(1, 5)); + + assertThat(rangeSet.asRanges()).has().item(Range.closedOpen(1, 5)); + + assertTrue(rangeSet.encloses(Range.closed(3, 4))); + assertTrue(rangeSet.encloses(Range.closedOpen(1, 4))); + assertTrue(rangeSet.encloses(Range.closedOpen(1, 5))); + assertFalse(rangeSet.encloses(Range.greaterThan(2))); + + assertTrue(rangeSet.contains(3)); + assertFalse(rangeSet.contains(5)); + assertFalse(rangeSet.contains(0)); + + RangeSet<Integer> expectedComplement = TreeRangeSet.create(); + expectedComplement.add(Range.lessThan(1)); + expectedComplement.add(Range.atLeast(5)); + + assertEquals(expectedComplement, rangeSet.complement()); + } + + public void testSingleBoundedBelowRange() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.of(Range.greaterThan(2)); + + assertThat(rangeSet.asRanges()).has().item(Range.greaterThan(2)); + + assertTrue(rangeSet.encloses(Range.closed(3, 4))); + assertTrue(rangeSet.encloses(Range.greaterThan(3))); + assertFalse(rangeSet.encloses(Range.closedOpen(1, 5))); + + assertTrue(rangeSet.contains(3)); + assertTrue(rangeSet.contains(5)); + assertFalse(rangeSet.contains(0)); + assertFalse(rangeSet.contains(2)); + + assertEquals(ImmutableRangeSet.of(Range.atMost(2)), rangeSet.complement()); + } + + public void testSingleBoundedAboveRange() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.of(Range.atMost(3)); + + assertThat(rangeSet.asRanges()).has().item(Range.atMost(3)); + + assertTrue(rangeSet.encloses(Range.closed(2, 3))); + assertTrue(rangeSet.encloses(Range.lessThan(1))); + assertFalse(rangeSet.encloses(Range.closedOpen(1, 5))); + + assertTrue(rangeSet.contains(3)); + assertTrue(rangeSet.contains(0)); + assertFalse(rangeSet.contains(4)); + assertFalse(rangeSet.contains(5)); + + assertEquals(ImmutableRangeSet.of(Range.greaterThan(3)), rangeSet.complement()); + } + + public void testMultipleBoundedRanges() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(5, 8)).add(Range.closedOpen(1, 3)).build(); + + assertThat(rangeSet.asRanges()) + .has().exactly(Range.closedOpen(1, 3), Range.closed(5, 8)).inOrder(); + + assertTrue(rangeSet.encloses(Range.closed(1, 2))); + assertTrue(rangeSet.encloses(Range.open(5, 8))); + assertFalse(rangeSet.encloses(Range.closed(1, 8))); + assertFalse(rangeSet.encloses(Range.greaterThan(5))); + + RangeSet<Integer> expectedComplement = ImmutableRangeSet.<Integer>builder() + .add(Range.lessThan(1)) + .add(Range.closedOpen(3, 5)) + .add(Range.greaterThan(8)) + .build(); + + assertEquals(expectedComplement, rangeSet.complement()); + } + + public void testMultipleBoundedBelowRanges() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.greaterThan(6)).add(Range.closedOpen(1, 3)).build(); + + assertThat(rangeSet.asRanges()) + .has().exactly(Range.closedOpen(1, 3), Range.greaterThan(6)).inOrder(); + + assertTrue(rangeSet.encloses(Range.closed(1, 2))); + assertTrue(rangeSet.encloses(Range.open(6, 8))); + assertFalse(rangeSet.encloses(Range.closed(1, 8))); + assertFalse(rangeSet.encloses(Range.greaterThan(5))); + + RangeSet<Integer> expectedComplement = ImmutableRangeSet.<Integer>builder() + .add(Range.lessThan(1)) + .add(Range.closed(3, 6)) + .build(); + + assertEquals(expectedComplement, rangeSet.complement()); + } + + public void testMultipleBoundedAboveRanges() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.atMost(0)).add(Range.closedOpen(2, 5)).build(); + + assertThat(rangeSet.asRanges()) + .has().exactly(Range.atMost(0), Range.closedOpen(2, 5)).inOrder(); + + assertTrue(rangeSet.encloses(Range.closed(2, 4))); + assertTrue(rangeSet.encloses(Range.open(-5, -2))); + assertFalse(rangeSet.encloses(Range.closed(1, 8))); + assertFalse(rangeSet.encloses(Range.greaterThan(5))); + + RangeSet<Integer> expectedComplement = ImmutableRangeSet.<Integer>builder() + .add(Range.open(0, 2)) + .add(Range.atLeast(5)) + .build(); + + assertEquals(expectedComplement, rangeSet.complement()); + } + + public void testAddUnsupported() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(5, 8)).add(Range.closedOpen(1, 3)).build(); + + try { + rangeSet.add(Range.open(3, 4)); + fail(); + } catch (UnsupportedOperationException expected) { + // success + } + } + + public void testAddAllUnsupported() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(5, 8)).add(Range.closedOpen(1, 3)).build(); + + try { + rangeSet.addAll(ImmutableRangeSet.<Integer>of()); + fail(); + } catch (UnsupportedOperationException expected) { + // success + } + } + + public void testRemoveUnsupported() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(5, 8)).add(Range.closedOpen(1, 3)).build(); + + try { + rangeSet.remove(Range.closed(6, 7)); + fail(); + } catch (UnsupportedOperationException expected) { + // success + } + } + + public void testRemoveAllUnsupported() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(5, 8)).add(Range.closedOpen(1, 3)).build(); + + try { + rangeSet.removeAll(ImmutableRangeSet.<Integer>of()); + fail(); + } catch (UnsupportedOperationException expected) { + // success + } + + try { + rangeSet.removeAll(ImmutableRangeSet.of(Range.closed(6, 8))); + fail(); + } catch (UnsupportedOperationException expected) { + // success + } + } + + public void testExhaustive() { + @SuppressWarnings("unchecked") + ImmutableSet<Range<Integer>> ranges = ImmutableSet.of( + Range.<Integer>all(), + Range.<Integer>closedOpen(3, 5), + Range.singleton(1), + Range.lessThan(2), + Range.greaterThan(10), + Range.atMost(4), + Range.atLeast(3), + Range.closed(4, 6), + Range.closedOpen(1, 3), + Range.openClosed(5, 7), + Range.open(3, 4)); + for (Set<Range<Integer>> subset : Sets.powerSet(ranges)) { + RangeSet<Integer> mutable = TreeRangeSet.create(); + ImmutableRangeSet.Builder<Integer> builder = ImmutableRangeSet.builder(); + + int expectedRanges = 0; + for (Range<Integer> range : subset) { + boolean overlaps = false; + for (Range<Integer> other : mutable.asRanges()) { + if (other.isConnected(range) && !other.intersection(range).isEmpty()) { + overlaps = true; + } + } + + try { + builder.add(range); + assertFalse(overlaps); + mutable.add(range); + } catch (IllegalArgumentException e) { + assertTrue(overlaps); + } + } + + ImmutableRangeSet<Integer> built = builder.build(); + assertEquals(mutable, built); + assertEquals(ImmutableRangeSet.copyOf(mutable), built); + assertEquals(mutable.complement(), built.complement()); + + for (int i = 0; i <= 11; i++) { + assertEquals(mutable.contains(i), built.contains(i)); + } + + SerializableTester.reserializeAndAssert(built); + } + } + + public void testAsSet() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(2, 4)) + .add(Range.open(6, 7)) + .add(Range.closedOpen(8, 10)) + .add(Range.openClosed(15, 17)) + .build(); + ImmutableSortedSet<Integer> expectedSet = ImmutableSortedSet.of(2, 3, 4, 8, 9, 16, 17); + ImmutableSortedSet<Integer> asSet = rangeSet.asSet(DiscreteDomain.integers()); + assertEquals(expectedSet, asSet); + assertThat(asSet).has().exactlyAs(expectedSet).inOrder(); + assertTrue(asSet.containsAll(expectedSet)); + SerializableTester.reserializeAndAssert(asSet); + } + + public void testAsSetHeadSet() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(2, 4)) + .add(Range.open(6, 7)) + .add(Range.closedOpen(8, 10)) + .add(Range.openClosed(15, 17)) + .build(); + + ImmutableSortedSet<Integer> expectedSet = ImmutableSortedSet.of(2, 3, 4, 8, 9, 16, 17); + ImmutableSortedSet<Integer> asSet = rangeSet.asSet(DiscreteDomain.integers()); + + for (int i = 0; i <= 20; i++) { + assertEquals(asSet.headSet(i, false), expectedSet.headSet(i, false)); + assertEquals(asSet.headSet(i, true), expectedSet.headSet(i, true)); + } + } + + public void testAsSetTailSet() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(2, 4)) + .add(Range.open(6, 7)) + .add(Range.closedOpen(8, 10)) + .add(Range.openClosed(15, 17)) + .build(); + + ImmutableSortedSet<Integer> expectedSet = ImmutableSortedSet.of(2, 3, 4, 8, 9, 16, 17); + ImmutableSortedSet<Integer> asSet = rangeSet.asSet(DiscreteDomain.integers()); + + for (int i = 0; i <= 20; i++) { + assertEquals(asSet.tailSet(i, false), expectedSet.tailSet(i, false)); + assertEquals(asSet.tailSet(i, true), expectedSet.tailSet(i, true)); + } + } + + public void testAsSetSubSet() { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(Range.closed(2, 4)) + .add(Range.open(6, 7)) + .add(Range.closedOpen(8, 10)) + .add(Range.openClosed(15, 17)) + .build(); + + ImmutableSortedSet<Integer> expectedSet = ImmutableSortedSet.of(2, 3, 4, 8, 9, 16, 17); + ImmutableSortedSet<Integer> asSet = rangeSet.asSet(DiscreteDomain.integers()); + + for (int i = 0; i <= 20; i++) { + for (int j = i + 1; j <= 20; j++) { + assertEquals(expectedSet.subSet(i, false, j, false), + asSet.subSet(i, false, j, false)); + assertEquals(expectedSet.subSet(i, true, j, false), + asSet.subSet(i, true, j, false)); + assertEquals(expectedSet.subSet(i, false, j, true), + asSet.subSet(i, false, j, true)); + assertEquals(expectedSet.subSet(i, true, j, true), + asSet.subSet(i, true, j, true)); + } + } + } + + public void testSubRangeSet() { + ImmutableList.Builder<Range<Integer>> rangesBuilder = ImmutableList.builder(); + rangesBuilder.add(Range.<Integer>all()); + for (int i = -2; i <= 2; i++) { + for (BoundType boundType : BoundType.values()) { + rangesBuilder.add(Range.upTo(i, boundType)); + rangesBuilder.add(Range.downTo(i, boundType)); + } + for (int j = i + 1; j <= 2; j++) { + for (BoundType lbType : BoundType.values()) { + for (BoundType ubType : BoundType.values()) { + rangesBuilder.add(Range.range(i, lbType, j, ubType)); + } + } + } + } + ImmutableList<Range<Integer>> ranges = rangesBuilder.build(); + for (int i = -2; i <= 2; i++) { + rangesBuilder.add(Range.closedOpen(i, i)); + rangesBuilder.add(Range.openClosed(i, i)); + } + ImmutableList<Range<Integer>> subRanges = rangesBuilder.build(); + for (Range<Integer> range1 : ranges) { + for (Range<Integer> range2 : ranges) { + if (!range1.isConnected(range2) || range1.intersection(range2).isEmpty()) { + ImmutableRangeSet<Integer> rangeSet = ImmutableRangeSet.<Integer>builder() + .add(range1) + .add(range2) + .build(); + for (Range<Integer> subRange : subRanges) { + RangeSet<Integer> expected = TreeRangeSet.create(); + for (Range<Integer> range : rangeSet.asRanges()) { + if (range.isConnected(subRange)) { + expected.add(range.intersection(subRange)); + } + } + ImmutableRangeSet<Integer> subRangeSet = rangeSet.subRangeSet(subRange); + assertEquals(expected, subRangeSet); + assertEquals(expected.asRanges(), subRangeSet.asRanges()); + if (!expected.isEmpty()) { + assertEquals(expected.span(), subRangeSet.span()); + } + for (int i = -3; i <= 3; i++) { + assertEquals(expected.contains(i), subRangeSet.contains(i)); + } + } + } + } + } + } +} diff --git a/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java b/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java index 66214833a..cf50625e6 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -249,10 +249,10 @@ public class ImmutableSetMultimapTest extends TestCase { builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); - ASSERT.that(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("b")).has().exactly(3, 6).inOrder(); + assertThat(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); + assertThat(multimap.values()).has().exactly(2, 4, 3, 6, 5, 2).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("b")).has().exactly(3, 6).inOrder(); assertFalse(multimap.get("a") instanceof ImmutableSortedSet); assertFalse(multimap.get("x") instanceof ImmutableSortedSet); assertFalse(multimap.asMap().get("a") instanceof ImmutableSortedSet); @@ -274,10 +274,10 @@ public class ImmutableSetMultimapTest extends TestCase { builder.put("a", 2); builder.put("bb", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); - ASSERT.that(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("bb")).has().exactly(3, 6).inOrder(); + assertThat(multimap.keySet()).has().exactly("d", "a", "bb", "cc").inOrder(); + assertThat(multimap.values()).has().exactly(2, 5, 2, 3, 6, 4).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("bb")).has().exactly(3, 6).inOrder(); assertFalse(multimap.get("a") instanceof ImmutableSortedSet); assertFalse(multimap.get("x") instanceof ImmutableSortedSet); assertFalse(multimap.asMap().get("a") instanceof ImmutableSortedSet); @@ -294,10 +294,10 @@ public class ImmutableSetMultimapTest extends TestCase { builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); - ASSERT.that(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); + assertThat(multimap.keySet()).has().exactly("b", "d", "a", "c").inOrder(); + assertThat(multimap.values()).has().exactly(6, 3, 2, 5, 2, 4).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("b")).has().exactly(6, 3).inOrder(); assertTrue(multimap.get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("a")).comparator()); @@ -321,10 +321,10 @@ public class ImmutableSetMultimapTest extends TestCase { builder.put("a", 2); builder.put("b", 6); ImmutableSetMultimap<String, Integer> multimap = builder.build(); - ASSERT.that(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); - ASSERT.that(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(5, 2).inOrder(); - ASSERT.that(multimap.get("b")).has().exactly(6, 3).inOrder(); + assertThat(multimap.keySet()).has().exactly("d", "c", "b", "a").inOrder(); + assertThat(multimap.values()).has().exactly(2, 4, 6, 3, 5, 2).inOrder(); + assertThat(multimap.get("a")).has().exactly(5, 2).inOrder(); + assertThat(multimap.get("b")).has().exactly(6, 3).inOrder(); assertTrue(multimap.get("a") instanceof ImmutableSortedSet); assertEquals(Collections.reverseOrder(), ((ImmutableSortedSet<Integer>) multimap.get("a")).comparator()); @@ -536,8 +536,8 @@ public class ImmutableSetMultimapTest extends TestCase { .put("b", 1) .build(); multimap = SerializableTester.reserialize(multimap); - ASSERT.that(multimap.keySet()).has().exactly("b", "a").inOrder(); - ASSERT.that(multimap.get("a")).has().exactly(10, 2).inOrder(); + assertThat(multimap.keySet()).has().exactly("b", "a").inOrder(); + assertThat(multimap.get("a")).has().exactly(10, 2).inOrder(); assertEquals(Ordering.usingToString(), ((ImmutableSortedSet<Integer>) multimap.get("a")).comparator()); assertEquals(Ordering.usingToString(), diff --git a/guava-tests/test/com/google/common/collect/ImmutableSetTest.java b/guava-tests/test/com/google/common/collect/ImmutableSetTest.java index fb561d66f..43a935221 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSetTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSetTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -153,7 +153,7 @@ public class ImmutableSetTest extends AbstractImmutableSetTest { // now we'll get the varargs overload ImmutableSet<String> set = ImmutableSet.of( "a", "b", "c", "c", "c", "c", "b", "b", "a", "a", "c", "c", "c", "a"); - ASSERT.that(set).has().exactly("a", "b", "c").inOrder(); + assertThat(set).has().exactly("a", "b", "c").inOrder(); } public void testCreation_arrayOfArray() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java index 335072230..8ea66602b 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java @@ -16,17 +16,20 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSortedMap.Builder; import com.google.common.collect.testing.ListTestSuiteBuilder; +import com.google.common.collect.testing.NavigableMapTestSuiteBuilder; import com.google.common.collect.testing.SortedMapInterfaceTest; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; import com.google.common.collect.testing.google.SortedMapGenerators.ImmutableSortedMapEntryListGenerator; +import com.google.common.collect.testing.google.SortedMapGenerators.ImmutableSortedMapGenerator; import com.google.common.collect.testing.google.SortedMapGenerators.ImmutableSortedMapKeyListGenerator; import com.google.common.collect.testing.google.SortedMapGenerators.ImmutableSortedMapValueListGenerator; import com.google.common.testing.NullPointerTester; @@ -60,6 +63,17 @@ public class ImmutableSortedMapTest extends TestCase { TestSuite suite = new TestSuite(); suite.addTestSuite(ImmutableSortedMapTest.class); + suite.addTest(NavigableMapTestSuiteBuilder.using( + new ImmutableSortedMapGenerator()) + .withFeatures( + CollectionSize.ANY, + CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS, + CollectionFeature.KNOWN_ORDER, + MapFeature.REJECTS_DUPLICATES_AT_CREATION, + MapFeature.ALLOWS_ANY_NULL_QUERIES) + .named("ImmutableSortedMap") + .createTestSuite()); + suite.addTest(ListTestSuiteBuilder.using( new ImmutableSortedMapEntryListGenerator()) .named("ImmutableSortedMap.entrySet.asList") @@ -696,7 +710,7 @@ public class ImmutableSortedMapTest extends TestCase { public void testHeadMapInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).headMap("three", true); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3)).inOrder(); } @@ -705,14 +719,14 @@ public class ImmutableSortedMapTest extends TestCase { public void testHeadMapExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).headMap("three", false); - ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1)).inOrder(); + assertThat(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testTailMapInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).tailMap("three", true); - ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), + assertThat(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } @@ -720,21 +734,21 @@ public class ImmutableSortedMapTest extends TestCase { public void testTailMapExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).tailMap("three", false); - ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("two", 2)).inOrder(); + assertThat(map.entrySet()).has().exactly(Maps.immutableEntry("two", 2)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapExclusiveExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", false, "two", false); - ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3)).inOrder(); + assertThat(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs public void testSubMapInclusiveExclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", true, "two", false); - ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), + assertThat(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3)).inOrder(); } @@ -742,7 +756,7 @@ public class ImmutableSortedMapTest extends TestCase { public void testSubMapExclusiveInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", false, "two", true); - ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), + assertThat(map.entrySet()).has().exactly(Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } @@ -750,7 +764,7 @@ public class ImmutableSortedMapTest extends TestCase { public void testSubMapInclusiveInclusive() { Map<String, Integer> map = ImmutableSortedMap.of("one", 1, "two", 2, "three", 3).subMap("one", true, "two", true); - ASSERT.that(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), + assertThat(map.entrySet()).has().exactly(Maps.immutableEntry("one", 1), Maps.immutableEntry("three", 3), Maps.immutableEntry("two", 2)).inOrder(); } diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMultisetTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMultisetTest.java index e82a7199f..ed069fb79 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSortedMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMultisetTest.java @@ -15,8 +15,8 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.base.Function; import com.google.common.collect.Multiset.Entry; @@ -422,13 +422,13 @@ public class ImmutableSortedMultisetTest extends TestCase { public void testSerialization_multiple() { Collection<String> c = ImmutableSortedMultiset.of("a", "b", "a"); Collection<String> copy = SerializableTester.reserializeAndAssert(c); - ASSERT.that(copy).has().exactly("a", "a", "b").inOrder(); + assertThat(copy).has().exactly("a", "a", "b").inOrder(); } public void testSerialization_elementSet() { Multiset<String> c = ImmutableSortedMultiset.of("a", "b", "a"); Collection<String> copy = SerializableTester.reserializeAndAssert(c.elementSet()); - ASSERT.that(copy).has().exactly("a", "b").inOrder(); + assertThat(copy).has().exactly("a", "b").inOrder(); } public void testSerialization_entrySet() { @@ -440,13 +440,13 @@ public class ImmutableSortedMultisetTest extends TestCase { Collection<String> c = ImmutableSortedMultiset.of("a", "b", "a"); assertEquals(c, ImmutableSortedMultiset.of("a", "b", "a")); assertEquals(c, ImmutableSortedMultiset.of("a", "a", "b")); - ASSERT.that(c).isNotEqualTo(ImmutableSortedMultiset.of("a", "b")); - ASSERT.that(c).isNotEqualTo(ImmutableSortedMultiset.of("a", "b", "c", "d")); + assertThat(c).isNotEqualTo(ImmutableSortedMultiset.of("a", "b")); + assertThat(c).isNotEqualTo(ImmutableSortedMultiset.of("a", "b", "c", "d")); } public void testIterationOrder() { Collection<String> c = ImmutableSortedMultiset.of("a", "b", "a"); - ASSERT.that(c).has().exactly("a", "a", "b").inOrder(); + assertThat(c).has().exactly("a", "a", "b").inOrder(); } public void testMultisetWrites() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java index e8d4a313d..ea0c8254f 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java @@ -16,13 +16,13 @@ package com.google.common.collect; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.ListTestSuiteBuilder; -import com.google.common.collect.testing.SortedSetTestSuiteBuilder; +import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.google.SetGenerators.ImmutableSortedSetAsListGenerator; @@ -63,7 +63,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTest(SortedSetTestSuiteBuilder.using( + suite.addTest(NavigableSetTestSuiteBuilder.using( new ImmutableSortedSetCopyOfGenerator()) .named(ImmutableSortedSetTest.class.getName()) .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, @@ -71,7 +71,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); - suite.addTest(SortedSetTestSuiteBuilder.using( + suite.addTest(NavigableSetTestSuiteBuilder.using( new ImmutableSortedSetExplicitComparator()) .named(ImmutableSortedSetTest.class.getName() + ", explicit comparator, vararg") @@ -80,7 +80,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); - suite.addTest(SortedSetTestSuiteBuilder.using( + suite.addTest(NavigableSetTestSuiteBuilder.using( new ImmutableSortedSetExplicitSuperclassComparatorGenerator()) .named(ImmutableSortedSetTest.class.getName() + ", explicit superclass comparator, iterable") @@ -89,7 +89,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); - suite.addTest(SortedSetTestSuiteBuilder.using( + suite.addTest(NavigableSetTestSuiteBuilder.using( new ImmutableSortedSetReversedOrderGenerator()) .named(ImmutableSortedSetTest.class.getName() + ", reverseOrder, iterator") @@ -98,7 +98,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); - suite.addTest(SortedSetTestSuiteBuilder.using( + suite.addTest(NavigableSetTestSuiteBuilder.using( new ImmutableSortedSetUnhashableGenerator()) .suppressing(SetHashCodeTester.getHashCodeMethods()) .named(ImmutableSortedSetTest.class.getName() + ", unhashable") @@ -106,7 +106,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); - suite.addTest(SortedSetTestSuiteBuilder.using( + suite.addTest(NavigableSetTestSuiteBuilder.using( new ImmutableSortedSetDescendingGenerator()) .named(ImmutableSortedSetTest.class.getName() + ", descending") .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, @@ -264,7 +264,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testSingle_headSet() { SortedSet<String> set = of("e"); assertTrue(set.headSet("g") instanceof ImmutableSortedSet); - ASSERT.that(set.headSet("g")).has().item("e"); + assertThat(set.headSet("g")).has().item("e"); assertSame(of(), set.headSet("c")); assertSame(of(), set.headSet("e")); } @@ -272,16 +272,16 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testSingle_tailSet() { SortedSet<String> set = of("e"); assertTrue(set.tailSet("c") instanceof ImmutableSortedSet); - ASSERT.that(set.tailSet("c")).has().item("e"); - ASSERT.that(set.tailSet("e")).has().item("e"); + assertThat(set.tailSet("c")).has().item("e"); + assertThat(set.tailSet("e")).has().item("e"); assertSame(of(), set.tailSet("g")); } public void testSingle_subSet() { SortedSet<String> set = of("e"); assertTrue(set.subSet("c", "g") instanceof ImmutableSortedSet); - ASSERT.that(set.subSet("c", "g")).has().item("e"); - ASSERT.that(set.subSet("e", "g")).has().item("e"); + assertThat(set.subSet("c", "g")).has().item("e"); + assertThat(set.subSet("e", "g")).has().item("e"); assertSame(of(), set.subSet("f", "g")); assertSame(of(), set.subSet("c", "e")); assertSame(of(), set.subSet("c", "d")); @@ -306,7 +306,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testOf_ordering() { SortedSet<String> set = of("e", "a", "f", "b", "d", "c"); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } /* @@ -355,7 +355,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testOf_ordering_dupes() { SortedSet<String> set = of("e", "a", "e", "f", "b", "b", "d", "a", "c"); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testOf_comparator() { @@ -366,8 +366,8 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testOf_headSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.headSet("e") instanceof ImmutableSortedSet); - ASSERT.that(set.headSet("e")).has().exactly("b", "c", "d").inOrder(); - ASSERT.that(set.headSet("g")).has().exactly("b", "c", "d", "e", "f").inOrder(); + assertThat(set.headSet("e")).has().exactly("b", "c", "d").inOrder(); + assertThat(set.headSet("g")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.headSet("a")); assertSame(of(), set.headSet("b")); } @@ -375,16 +375,16 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testOf_tailSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.tailSet("e") instanceof ImmutableSortedSet); - ASSERT.that(set.tailSet("e")).has().exactly("e", "f").inOrder(); - ASSERT.that(set.tailSet("a")).has().exactly("b", "c", "d", "e", "f").inOrder(); + assertThat(set.tailSet("e")).has().exactly("e", "f").inOrder(); + assertThat(set.tailSet("a")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.tailSet("g")); } public void testOf_subSet() { SortedSet<String> set = of("e", "f", "b", "d", "c"); assertTrue(set.subSet("c", "e") instanceof ImmutableSortedSet); - ASSERT.that(set.subSet("c", "e")).has().exactly("c", "d").inOrder(); - ASSERT.that(set.subSet("a", "g")).has().exactly("b", "c", "d", "e", "f").inOrder(); + assertThat(set.subSet("c", "e")).has().exactly("c", "d").inOrder(); + assertThat(set.subSet("a", "g")).has().exactly("b", "c", "d", "e", "f").inOrder(); assertSame(of(), set.subSet("a", "b")); assertSame(of(), set.subSet("g", "h")); assertSame(of(), set.subSet("c", "c")); @@ -424,14 +424,14 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testExplicit_ordering() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "jumped", "over", "a").build(); - ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); + assertThat(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testExplicit_ordering_dupes() { SortedSet<String> set = ImmutableSortedSet.orderedBy(STRING_LENGTH).add( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog").build(); - ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); + assertThat(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testExplicit_contains() { @@ -461,8 +461,8 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.headSet("a") instanceof ImmutableSortedSet); assertTrue(set.headSet("fish") instanceof ImmutableSortedSet); - ASSERT.that(set.headSet("fish")).has().exactly("a", "in", "the").inOrder(); - ASSERT.that(set.headSet("california")).has() + assertThat(set.headSet("fish")).has().exactly("a", "in", "the").inOrder(); + assertThat(set.headSet("california")).has() .exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.headSet("a").isEmpty()); assertTrue(set.headSet("").isEmpty()); @@ -473,8 +473,8 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.tailSet("california") instanceof ImmutableSortedSet); assertTrue(set.tailSet("fish") instanceof ImmutableSortedSet); - ASSERT.that(set.tailSet("fish")).has().exactly("over", "quick", "jumped").inOrder(); - ASSERT.that( + assertThat(set.tailSet("fish")).has().exactly("over", "quick", "jumped").inOrder(); + assertThat( set.tailSet("a")).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.tailSet("california").isEmpty()); } @@ -484,8 +484,8 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { "in", "the", "quick", "jumped", "over", "a").build(); assertTrue(set.subSet("the", "quick") instanceof ImmutableSortedSet); assertTrue(set.subSet("", "b") instanceof ImmutableSortedSet); - ASSERT.that(set.subSet("the", "quick")).has().exactly("the", "over").inOrder(); - ASSERT.that(set.subSet("a", "california")) + assertThat(set.subSet("the", "quick")).has().exactly("the", "over").inOrder(); + assertThat(set.subSet("a", "california")) .has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertTrue(set.subSet("", "b").isEmpty()); assertTrue(set.subSet("vermont", "california").isEmpty()); @@ -530,13 +530,13 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testCopyOf_ordering() { SortedSet<String> set = copyOf(asList("e", "a", "f", "b", "d", "c")); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_ordering_dupes() { SortedSet<String> set = copyOf(asList("e", "a", "e", "f", "b", "b", "d", "a", "c")); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_subSet() { @@ -567,13 +567,13 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testCopyOf_iterator_ordering() { SortedSet<String> set = copyOf(asIterator("e", "a", "f", "b", "d", "c")); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_iterator_ordering_dupes() { SortedSet<String> set = copyOf(asIterator("e", "a", "e", "f", "b", "b", "d", "a", "c")); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_iterator_comparator() { @@ -584,7 +584,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testCopyOf_sortedSet_ordering() { SortedSet<String> set = copyOf(Sets.newTreeSet(asList("e", "a", "f", "b", "d", "c"))); - ASSERT.that(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(set).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); } public void testCopyOf_sortedSet_comparator() { @@ -596,7 +596,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "jumped", "over", "a")); - ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); + assertThat(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_ordering_dupes() { @@ -604,7 +604,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { ImmutableSortedSet.copyOf(STRING_LENGTH, asList( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog")); - ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); + assertThat(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_comparator() { @@ -618,7 +618,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { SortedSet<String> set = ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "jumped", "over", "a")); - ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); + assertThat(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_iterator_ordering_dupes() { @@ -626,7 +626,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { ImmutableSortedSet.copyOf(STRING_LENGTH, asIterator( "in", "the", "quick", "brown", "fox", "jumped", "over", "a", "lazy", "dog")); - ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); + assertThat(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); } public void testCopyOfExplicit_iterator_comparator() { @@ -640,14 +640,14 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { SortedSet<String> input = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(input, "in", "the", "quick", "jumped", "over", "a"); SortedSet<String> set = copyOf(input); - ASSERT.that(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); + assertThat(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); } public void testCopyOfSorted_natural_ordering() { SortedSet<String> input = Sets.newTreeSet( asList("in", "the", "quick", "jumped", "over", "a")); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); - ASSERT.that(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); + assertThat(set).has().exactly("a", "in", "jumped", "over", "quick", "the").inOrder(); } public void testCopyOfSorted_natural_comparator() { @@ -661,7 +661,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { SortedSet<String> input = Sets.newTreeSet(STRING_LENGTH); Collections.addAll(input, "in", "the", "quick", "jumped", "over", "a"); SortedSet<String> set = ImmutableSortedSet.copyOfSorted(input); - ASSERT.that(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); + assertThat(set).has().exactly("a", "in", "the", "over", "quick", "jumped").inOrder(); assertSame(STRING_LENGTH, set.comparator()); } @@ -760,7 +760,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testReverseOrder() { SortedSet<String> set = ImmutableSortedSet.<String>reverseOrder() .add("a", "b", "c").build(); - ASSERT.that(set).has().exactly("c", "b", "a").inOrder(); + assertThat(set).has().exactly("c", "b", "a").inOrder(); assertEquals(Ordering.natural().reverse(), set.comparator()); } @@ -775,13 +775,13 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { public void testSupertypeComparator() { SortedSet<Integer> set = new ImmutableSortedSet.Builder<Integer>(TO_STRING) .add(3, 12, 101, 44).build(); - ASSERT.that(set).has().exactly(101, 12, 3, 44).inOrder(); + assertThat(set).has().exactly(101, 12, 3, 44).inOrder(); } public void testSupertypeComparatorSubtypeElements() { SortedSet<Number> set = new ImmutableSortedSet.Builder<Number>(TO_STRING) .add(3, 12, 101, 44).build(); - ASSERT.that(set).has().exactly(101, 12, 3, 44).inOrder(); + assertThat(set).has().exactly(101, 12, 3, 44).inOrder(); } @Override <E extends Comparable<E>> ImmutableSortedSet.Builder<E> builder() { @@ -912,7 +912,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { private static void assertNotEqualLenient( TreeSet<?> unexpected, SortedSet<?> actual) { try { - ASSERT.that(actual).isNotEqualTo(unexpected); + assertThat(actual).isNotEqualTo(unexpected); } catch (ClassCastException accepted) { } } @@ -922,7 +922,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { - ASSERT.that(set.headSet(strings[i], true)) + assertThat(set.headSet(strings[i], true)) .has().exactlyAs(sortedNumberNames(0, i + 1)).inOrder(); } } @@ -932,7 +932,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { - ASSERT.that(set.headSet(strings[i], false)).has().exactlyAs( + assertThat(set.headSet(strings[i], false)).has().exactlyAs( sortedNumberNames(0, i)).inOrder(); } } @@ -942,7 +942,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { - ASSERT.that(set.tailSet(strings[i], true)).has().exactlyAs( + assertThat(set.tailSet(strings[i], true)).has().exactlyAs( sortedNumberNames(i, strings.length)).inOrder(); } } @@ -952,7 +952,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { ImmutableSortedSet<String> set = ImmutableSortedSet.copyOf(strings); Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { - ASSERT.that(set.tailSet(strings[i], false)).has().exactlyAs( + assertThat(set.tailSet(strings[i], false)).has().exactlyAs( sortedNumberNames(i + 1, strings.length)).inOrder(); } } @@ -963,7 +963,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { - ASSERT.that(set.subSet(strings[i], false, strings[j], false)) + assertThat(set.subSet(strings[i], false, strings[j], false)) .has().exactlyAs(sortedNumberNames(Math.min(i + 1, j), j)).inOrder(); } } @@ -975,7 +975,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { - ASSERT.that(set.subSet(strings[i], true, strings[j], false)) + assertThat(set.subSet(strings[i], true, strings[j], false)) .has().exactlyAs(sortedNumberNames(i, j)).inOrder(); } } @@ -987,7 +987,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { - ASSERT.that(set.subSet(strings[i], false, strings[j], true)) + assertThat(set.subSet(strings[i], false, strings[j], true)) .has().exactlyAs(sortedNumberNames(i + 1, j + 1)).inOrder(); } } @@ -999,7 +999,7 @@ public class ImmutableSortedSetTest extends AbstractImmutableSetTest { Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { for (int j = i; j < strings.length; j++) { - ASSERT.that(set.subSet(strings[i], true, strings[j], true)) + assertThat(set.subSet(strings[i], true, strings[j], true)) .has().exactlyAs(sortedNumberNames(i, j + 1)).inOrder(); } } diff --git a/guava-tests/test/com/google/common/collect/ImmutableTableTest.java b/guava-tests/test/com/google/common/collect/ImmutableTableTest.java index 36931fe2b..7d8861957 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableTableTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableTableTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -185,8 +185,8 @@ public class ImmutableTableTest extends AbstractTableReadTest { validateTableCopies(table); // Even though rowKeySet, columnKeySet, and cellSet have the same // iteration ordering, row has an inconsistent ordering. - ASSERT.that(table.row('b').keySet()).has().exactly(1, 2).inOrder(); - ASSERT.that(ImmutableTable.copyOf(table).row('b').keySet()) + assertThat(table.row('b').keySet()).has().exactly(1, 2).inOrder(); + assertThat(ImmutableTable.copyOf(table).row('b').keySet()) .has().exactly(2, 1).inOrder(); } @@ -228,10 +228,10 @@ public class ImmutableTableTest extends AbstractTableReadTest { = builder.orderRowsBy(Ordering.natural()) .orderColumnsBy(Ordering.natural()) .putAll(table).build(); - ASSERT.that(copy.rowKeySet()).has().exactly('a', 'b').inOrder(); - ASSERT.that(copy.columnKeySet()).has().exactly(1, 2).inOrder(); - ASSERT.that(copy.values()).has().exactly("baz", "bar", "foo").inOrder(); - ASSERT.that(copy.row('b').keySet()).has().exactly(1, 2).inOrder(); + assertThat(copy.rowKeySet()).has().exactly('a', 'b').inOrder(); + assertThat(copy.columnKeySet()).has().exactly(1, 2).inOrder(); + assertThat(copy.values()).has().exactly("baz", "bar", "foo").inOrder(); + assertThat(copy.row('b').keySet()).has().exactly(1, 2).inOrder(); } public void testBuilder_orderRowsAndColumnsBy_sparse() { @@ -249,12 +249,12 @@ public class ImmutableTableTest extends AbstractTableReadTest { builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); - ASSERT.that(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); - ASSERT.that(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); - ASSERT.that(table.values()).has().exactly("cat", "axe", "baz", "tub", + assertThat(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); + assertThat(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); + assertThat(table.values()).has().exactly("cat", "axe", "baz", "tub", "dog", "bar", "foo", "foo", "bar").inOrder(); - ASSERT.that(table.row('c').keySet()).has().exactly(0, 3).inOrder(); - ASSERT.that(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); + assertThat(table.row('c').keySet()).has().exactly(0, 3).inOrder(); + assertThat(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); } public void testBuilder_orderRowsAndColumnsBy_dense() { @@ -271,12 +271,12 @@ public class ImmutableTableTest extends AbstractTableReadTest { builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); - ASSERT.that(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); - ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(table.values()).has().exactly("baz", "bar", "foo", "dog", + assertThat(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); + assertThat(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); + assertThat(table.values()).has().exactly("baz", "bar", "foo", "dog", "cat", "baz", "bar", "foo").inOrder(); - ASSERT.that(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); + assertThat(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); + assertThat(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); } public void testBuilder_orderRowsBy_sparse() { @@ -293,8 +293,8 @@ public class ImmutableTableTest extends AbstractTableReadTest { builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); - ASSERT.that(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); - ASSERT.that(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); + assertThat(table.rowKeySet()).has().exactly('b', 'c', 'e', 'r', 'x').inOrder(); + assertThat(table.column(5).keySet()).has().exactly('e', 'x').inOrder(); } public void testBuilder_orderRowsBy_dense() { @@ -310,8 +310,8 @@ public class ImmutableTableTest extends AbstractTableReadTest { builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); - ASSERT.that(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); - ASSERT.that(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); + assertThat(table.rowKeySet()).has().exactly('a', 'b', 'c').inOrder(); + assertThat(table.column(1).keySet()).has().exactly('a', 'b', 'c').inOrder(); } public void testBuilder_orderColumnsBy_sparse() { @@ -328,8 +328,8 @@ public class ImmutableTableTest extends AbstractTableReadTest { builder.put('r', 4, "foo"); builder.put('x', 5, "bar"); Table<Character, Integer, String> table = builder.build(); - ASSERT.that(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); - ASSERT.that(table.row('c').keySet()).has().exactly(0, 3).inOrder(); + assertThat(table.columnKeySet()).has().exactly(0, 1, 2, 3, 4, 5, 7).inOrder(); + assertThat(table.row('c').keySet()).has().exactly(0, 3).inOrder(); } public void testBuilder_orderColumnsBy_dense() { @@ -345,8 +345,8 @@ public class ImmutableTableTest extends AbstractTableReadTest { builder.put('a', 2, "bar"); builder.put('a', 1, "baz"); Table<Character, Integer, String> table = builder.build(); - ASSERT.that(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); - ASSERT.that(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); + assertThat(table.columnKeySet()).has().exactly(1, 2, 3).inOrder(); + assertThat(table.row('c').keySet()).has().exactly(1, 2, 3).inOrder(); } @GwtIncompatible("Mind-bogglingly slow in GWT") diff --git a/guava-tests/test/com/google/common/collect/IterablesTest.java b/guava-tests/test/com/google/common/collect/IterablesTest.java index a16beacba..1dbbb9719 100644 --- a/guava-tests/test/com/google/common/collect/IterablesTest.java +++ b/guava-tests/test/com/google/common/collect/IterablesTest.java @@ -21,9 +21,9 @@ import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -283,7 +283,7 @@ public class IterablesTest extends TestCase { Iterable<TypeA> alist = Lists .newArrayList(new TypeA(), new TypeA(), hasBoth, new TypeA()); Iterable<TypeB> blist = Iterables.filter(alist, TypeB.class); - ASSERT.that(blist).iteratesOverSequence(hasBoth); + assertThat(blist).iteratesAs(hasBoth); } public void testTransform() { @@ -411,7 +411,7 @@ public class IterablesTest extends TestCase { int n = 4; Iterable<Integer> repeated = Iterables.concat(Collections.nCopies(n, iterable)); - ASSERT.that(repeated).iteratesOverSequence( + assertThat(repeated).iteratesAs( 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3); } @@ -510,7 +510,7 @@ public class IterablesTest extends TestCase { List<String> freshlyAdded = newArrayList("freshly", "added"); boolean changed = Iterables.addAll(alreadyThere, freshlyAdded); - ASSERT.that(alreadyThere).has().exactly( + assertThat(alreadyThere).has().exactly( "already", "there", "freshly", "added").inOrder(); assertTrue(changed); } @@ -688,7 +688,7 @@ public class IterablesTest extends TestCase { Iterable<String> tail = skip(set, 1); set.remove("b"); set.addAll(newArrayList("A", "B", "C")); - ASSERT.that(tail).iteratesOverSequence("c", "A", "B", "C"); + assertThat(tail).iteratesAs("c", "A", "B", "C"); } public void testSkip_structurallyModifiedSkipSomeList() throws Exception { @@ -696,7 +696,7 @@ public class IterablesTest extends TestCase { Iterable<String> tail = skip(list, 1); list.subList(1, 3).clear(); list.addAll(0, newArrayList("A", "B", "C")); - ASSERT.that(tail).iteratesOverSequence("B", "C", "a"); + assertThat(tail).iteratesAs("B", "C", "a"); } public void testSkip_structurallyModifiedSkipAll() throws Exception { @@ -1127,16 +1127,16 @@ public class IterablesTest extends TestCase { assertEquals("Iterables.consumingIterable(...)", consumingIterable.toString()); Iterator<String> consumingIterator = consumingIterable.iterator(); - ASSERT.that(list).has().exactly("a", "b").inOrder(); + assertThat(list).has().exactly("a", "b").inOrder(); assertTrue(consumingIterator.hasNext()); - ASSERT.that(list).has().exactly("a", "b").inOrder(); + assertThat(list).has().exactly("a", "b").inOrder(); assertEquals("a", consumingIterator.next()); - ASSERT.that(list).has().item("b"); + assertThat(list).has().item("b"); assertTrue(consumingIterator.hasNext()); assertEquals("b", consumingIterator.next()); - ASSERT.that(list).isEmpty(); + assertThat(list).isEmpty(); assertFalse(consumingIterator.hasNext()); } diff --git a/guava-tests/test/com/google/common/collect/IteratorsTest.java b/guava-tests/test/com/google/common/collect/IteratorsTest.java index 2f9d83a47..c3f92631d 100644 --- a/guava-tests/test/com/google/common/collect/IteratorsTest.java +++ b/guava-tests/test/com/google/common/collect/IteratorsTest.java @@ -22,9 +22,9 @@ import static com.google.common.collect.Iterators.getLast; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static java.util.Collections.singleton; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -765,7 +765,7 @@ public class IteratorsTest extends TestCase { boolean changed = Iterators.addAll(alreadyThere, Iterators.<String>emptyIterator()); - ASSERT.that(alreadyThere).has().exactly("already", "there").inOrder(); + assertThat(alreadyThere).has().exactly("already", "there").inOrder(); assertFalse(changed); } @@ -775,7 +775,7 @@ public class IteratorsTest extends TestCase { boolean changed = Iterators.addAll(alreadyThere, freshlyAdded.iterator()); - ASSERT.that(alreadyThere).has().exactly("already", "there", "freshly", "added"); + assertThat(alreadyThere).has().exactly("already", "there", "freshly", "added"); assertTrue(changed); } @@ -785,7 +785,7 @@ public class IteratorsTest extends TestCase { List<String> oneMore = Lists.newArrayList("there"); boolean changed = Iterators.addAll(alreadyThere, oneMore.iterator()); - ASSERT.that(alreadyThere).has().exactly("already", "there").inOrder(); + assertThat(alreadyThere).has().exactly("already", "there").inOrder(); assertFalse(changed); } @@ -1523,16 +1523,16 @@ public class IteratorsTest extends TestCase { assertEquals("Iterators.consumingIterator(...)", consumingIterator.toString()); - ASSERT.that(list).has().exactly("a", "b").inOrder(); + assertThat(list).has().exactly("a", "b").inOrder(); assertTrue(consumingIterator.hasNext()); - ASSERT.that(list).has().exactly("a", "b").inOrder(); + assertThat(list).has().exactly("a", "b").inOrder(); assertEquals("a", consumingIterator.next()); - ASSERT.that(list).has().item("b"); + assertThat(list).has().item("b"); assertTrue(consumingIterator.hasNext()); assertEquals("b", consumingIterator.next()); - ASSERT.that(list).isEmpty(); + assertThat(list).isEmpty(); assertFalse(consumingIterator.hasNext()); } diff --git a/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java b/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java index c9053706e..80bbcc178 100644 --- a/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java @@ -21,8 +21,8 @@ import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -151,8 +151,8 @@ public class LinkedHashMultimapTest extends TestCase { multimap.put("c", 4); multimap.remove("a", 1); multimap = SerializableTester.reserializeAndAssert(multimap); - ASSERT.that(multimap.keySet()).has().exactly("a", "b", "c").inOrder(); - ASSERT.that(multimap.entries()).has().exactly( + assertThat(multimap.keySet()).has().exactly("a", "b", "c").inOrder(); + assertThat(multimap.entries()).has().exactly( mapEntry("b", 2), mapEntry("a", 3), mapEntry("c", 4)).inOrder(); @@ -160,12 +160,12 @@ public class LinkedHashMultimapTest extends TestCase { } private void assertOrderingReadOnly(Multimap<String, Integer> multimap) { - ASSERT.that(multimap.get("foo")).has().exactly(5, 3).inOrder(); - ASSERT.that(multimap.get("bar")).has().exactly(4, 1).inOrder(); - ASSERT.that(multimap.get("cow")).has().item(2); + assertThat(multimap.get("foo")).has().exactly(5, 3).inOrder(); + assertThat(multimap.get("bar")).has().exactly(4, 1).inOrder(); + assertThat(multimap.get("cow")).has().item(2); - ASSERT.that(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); - ASSERT.that(multimap.values()).has().exactly(5, 4, 3, 2, 1).inOrder(); + assertThat(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); + assertThat(multimap.values()).has().exactly(5, 4, 3, 2, 1).inOrder(); Iterator<Map.Entry<String, Integer>> entryIterator = multimap.entries().iterator(); @@ -179,28 +179,28 @@ public class LinkedHashMultimapTest extends TestCase { multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = collectionIterator.next(); assertEquals("foo", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(5, 3).inOrder(); + assertThat(entry.getValue()).has().exactly(5, 3).inOrder(); entry = collectionIterator.next(); assertEquals("bar", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(4, 1).inOrder(); + assertThat(entry.getValue()).has().exactly(4, 1).inOrder(); entry = collectionIterator.next(); assertEquals("cow", entry.getKey()); - ASSERT.that(entry.getValue()).has().item(2); + assertThat(entry.getValue()).has().item(2); } public void testOrderingUpdates() { Multimap<String, Integer> multimap = initializeMultimap5(); - ASSERT.that(multimap.replaceValues("foo", asList(6, 7))).has().exactly(5, 3).inOrder(); - ASSERT.that(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); - ASSERT.that(multimap.removeAll("foo")).has().exactly(6, 7).inOrder(); - ASSERT.that(multimap.keySet()).has().exactly("bar", "cow").inOrder(); + assertThat(multimap.replaceValues("foo", asList(6, 7))).has().exactly(5, 3).inOrder(); + assertThat(multimap.keySet()).has().exactly("foo", "bar", "cow").inOrder(); + assertThat(multimap.removeAll("foo")).has().exactly(6, 7).inOrder(); + assertThat(multimap.keySet()).has().exactly("bar", "cow").inOrder(); assertTrue(multimap.remove("bar", 4)); - ASSERT.that(multimap.keySet()).has().exactly("bar", "cow").inOrder(); + assertThat(multimap.keySet()).has().exactly("bar", "cow").inOrder(); assertTrue(multimap.remove("bar", 1)); - ASSERT.that(multimap.keySet()).has().item("cow"); + assertThat(multimap.keySet()).has().item("cow"); multimap.put("bar", 9); - ASSERT.that(multimap.keySet()).has().exactly("cow", "bar").inOrder(); + assertThat(multimap.keySet()).has().exactly("cow", "bar").inOrder(); } public void testToStringNullExact() { diff --git a/guava-tests/test/com/google/common/collect/LinkedHashMultisetTest.java b/guava-tests/test/com/google/common/collect/LinkedHashMultisetTest.java index db8859aa0..ca359cb65 100644 --- a/guava-tests/test/com/google/common/collect/LinkedHashMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/LinkedHashMultisetTest.java @@ -16,8 +16,8 @@ package com.google.common.collect; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -121,13 +121,13 @@ public class LinkedHashMultisetTest extends TestCase { ms.add("a"); ms.add("b", 2); ms.add("c"); - ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); + assertThat(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.remove("b"); - ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); + assertThat(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.add("b"); - ASSERT.that(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); + assertThat(ms.elementSet()).has().exactly("a", "b", "c").inOrder(); ms.remove("b", 2); ms.add("b"); - ASSERT.that(ms.elementSet()).has().exactly("a", "c", "b").inOrder(); + assertThat(ms.elementSet()).has().exactly("a", "c", "b").inOrder(); } } diff --git a/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java b/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java index fc4ff6051..bc4a2df7e 100644 --- a/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java @@ -22,8 +22,8 @@ import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.SUPPORTS_REMOVE; import static com.google.common.collect.testing.IteratorFeature.SUPPORTS_SET; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -136,7 +136,7 @@ public class LinkedListMultimapTest extends TestCase { LinkedListMultimap<String, Integer> copy = LinkedListMultimap.create(multimap); assertEquals(multimap, copy); - ASSERT.that(copy.entries()).has().exactlyAs(multimap.entries()).inOrder(); + assertThat(copy.entries()).has().exactlyAs(multimap.entries()).inOrder(); } public void testCreateFromSize() { @@ -230,10 +230,10 @@ public class LinkedListMultimapTest extends TestCase { List<Integer> foos = map.get("foo"); Collection<Integer> values = map.values(); assertEquals(asList(1, 2), foos); - ASSERT.that(values).has().exactly(1, 2, 3).inOrder(); + assertThat(values).has().exactly(1, 2, 3).inOrder(); map.clear(); assertEquals(Collections.emptyList(), foos); - ASSERT.that(values).isEmpty(); + assertThat(values).isEmpty(); assertEquals("[]", map.entries().toString()); assertEquals("{}", map.toString()); } @@ -257,7 +257,7 @@ public class LinkedListMultimapTest extends TestCase { map.put("bar", 4); assertEquals("[bar=1, foo=2, bar=3, bar=4]", map.entries().toString()); - ASSERT.that(map.keys()).has().exactly("bar", "foo", "bar", "bar").inOrder(); + assertThat(map.keys()).has().exactly("bar", "foo", "bar", "bar").inOrder(); map.keys().remove("bar"); // bar is no longer the first key! assertEquals("{foo=[2], bar=[3, 4]}", map.toString()); } @@ -303,7 +303,7 @@ public class LinkedListMultimapTest extends TestCase { = map.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = entries.next(); assertEquals("bar", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(1, 3).inOrder(); + assertThat(entry.getValue()).has().exactly(1, 3).inOrder(); try { entry.setValue(Arrays.<Integer>asList()); fail("UnsupportedOperationException expected"); @@ -311,7 +311,7 @@ public class LinkedListMultimapTest extends TestCase { entries.remove(); // clear entry = entries.next(); assertEquals("foo", entry.getKey()); - ASSERT.that(entry.getValue()).has().item(2); + assertThat(entry.getValue()).has().item(2); assertFalse(entries.hasNext()); assertEquals("{foo=[2]}", map.toString()); } diff --git a/guava-tests/test/com/google/common/collect/ListsTest.java b/guava-tests/test/com/google/common/collect/ListsTest.java index 31731f23d..7c422f408 100644 --- a/guava-tests/test/com/google/common/collect/ListsTest.java +++ b/guava-tests/test/com/google/common/collect/ListsTest.java @@ -18,9 +18,9 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -418,7 +418,7 @@ public class ListsTest extends TestCase { } private void checkFooBarBazList(List<String> list) { - ASSERT.that(list).has().exactly("foo", "bar", "baz").inOrder(); + assertThat(list).has().exactly("foo", "bar", "baz").inOrder(); assertEquals(3, list.size()); assertIndexIsOutOfBounds(list, -1); assertEquals("foo", list.get(0)); @@ -429,7 +429,7 @@ public class ListsTest extends TestCase { public void testAsList1Small() { List<String> list = Lists.asList("foo", new String[0]); - ASSERT.that(list).has().item("foo"); + assertThat(list).has().item("foo"); assertEquals(1, list.size()); assertIndexIsOutOfBounds(list, -1); assertEquals("foo", list.get(0)); @@ -460,7 +460,7 @@ public class ListsTest extends TestCase { @GwtIncompatible("SerializableTester") public void testAsList2Small() { List<String> list = Lists.asList("foo", "bar", new String[0]); - ASSERT.that(list).has().exactly("foo", "bar").inOrder(); + assertThat(list).has().exactly("foo", "bar").inOrder(); assertEquals(2, list.size()); assertIndexIsOutOfBounds(list, -1); assertEquals("foo", list.get(0)); @@ -532,24 +532,24 @@ public class ListsTest extends TestCase { @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x1() { - ASSERT.that(Lists.cartesianProduct(list(1), list(2))).has().item(list(1, 2)); + assertThat(Lists.cartesianProduct(list(1), list(2))).has().item(list(1, 2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x2() { - ASSERT.that(Lists.cartesianProduct(list(1), list(2, 3))) + assertThat(Lists.cartesianProduct(list(1), list(2, 3))) .has().exactly(list(1, 2), list(1, 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary2x2() { - ASSERT.that(Lists.cartesianProduct(list(1, 2), list(3, 4))) + assertThat(Lists.cartesianProduct(list(1, 2), list(3, 4))) .has().exactly(list(1, 3), list(1, 4), list(2, 3), list(2, 4)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_2x2x2() { - ASSERT.that(Lists.cartesianProduct(list(0, 1), list(0, 1), list(0, 1))).has().exactly( + assertThat(Lists.cartesianProduct(list(0, 1), list(0, 1), list(0, 1))).has().exactly( list(0, 0, 0), list(0, 0, 1), list(0, 1, 0), list(0, 1, 1), list(1, 0, 0), list(1, 0, 1), list(1, 1, 0), list(1, 1, 1)).inOrder(); } @@ -574,7 +574,7 @@ public class ListsTest extends TestCase { List<Object> exp3 = list((Object) 2, "3"); List<Object> exp4 = list((Object) 2, "4"); - ASSERT.that(Lists.<Object>cartesianProduct(x, y)) + assertThat(Lists.<Object>cartesianProduct(x, y)) .has().exactly(exp1, exp2, exp3, exp4).inOrder(); } diff --git a/guava-tests/test/com/google/common/collect/MapConstraintsTest.java b/guava-tests/test/com/google/common/collect/MapConstraintsTest.java index 3f9fa66c7..70ac072ac 100644 --- a/guava-tests/test/com/google/common/collect/MapConstraintsTest.java +++ b/guava-tests/test/com/google/common/collect/MapConstraintsTest.java @@ -17,7 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -115,7 +115,7 @@ public class MapConstraintsTest extends TestCase { assertFalse(map.values() instanceof Serializable); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), @@ -163,7 +163,7 @@ public class MapConstraintsTest extends TestCase { assertEquals(map.values(), constrained.values()); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), @@ -230,9 +230,9 @@ public class MapConstraintsTest extends TestCase { .put("dag", 11).build()); assertTrue(multimap.equals(constrained)); assertTrue(constrained.equals(multimap)); - ASSERT.that(ImmutableList.copyOf(multimap.entries())) - .is(ImmutableList.copyOf(constrained.entries())); - ASSERT.that(constrained.asMap().get("foo")).has().item(1); + assertThat(ImmutableList.copyOf(multimap.entries())).isEqualTo( + ImmutableList.copyOf(constrained.entries())); + assertThat(constrained.asMap().get("foo")).has().item(1); assertNull(constrained.asMap().get("missing")); assertEquals(multimap.asMap(), constrained.asMap()); assertEquals(multimap.values(), constrained.values()); @@ -240,7 +240,7 @@ public class MapConstraintsTest extends TestCase { assertEquals(multimap.keySet(), constrained.keySet()); assertEquals(multimap.toString(), constrained.toString()); assertEquals(multimap.hashCode(), constrained.hashCode()); - ASSERT.that(multimap.entries()).has().exactly( + assertThat(multimap.entries()).has().exactly( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), @@ -407,8 +407,8 @@ public class MapConstraintsTest extends TestCase { .add(TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) {} - ASSERT.that(ImmutableList.copyOf(multimap.entries())) - .is(ImmutableList.copyOf(constrained.entries())); + assertThat(ImmutableList.copyOf(multimap.entries())).isEqualTo( + ImmutableList.copyOf(constrained.entries())); assertEquals(multimap.asMap(), constrained.asMap()); assertEquals(multimap.values(), constrained.values()); assertEquals(multimap.keys(), constrained.keys()); diff --git a/guava-tests/test/com/google/common/collect/MapMakerTest.java b/guava-tests/test/com/google/common/collect/MapMakerTest.java index 27e34b937..3d12ec3f0 100644 --- a/guava-tests/test/com/google/common/collect/MapMakerTest.java +++ b/guava-tests/test/com/google/common/collect/MapMakerTest.java @@ -17,7 +17,7 @@ package com.google.common.collect; import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; -import static java.util.concurrent.TimeUnit.SECONDS; +import static java.util.concurrent.TimeUnit.HOURS; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -222,10 +222,10 @@ public class MapMakerTest extends TestCase { @SuppressWarnings("deprecation") // test of deprecated method public void testExpiration_setTwice() { - MapMaker maker = new MapMaker().expireAfterWrite(1 * 60 * 60, SECONDS); + MapMaker maker = new MapMaker().expireAfterWrite(1, HOURS); try { // even to the same value is not allowed - maker.expireAfterWrite(1 * 60 * 60, SECONDS); + maker.expireAfterWrite(1, HOURS); fail(); } catch (IllegalStateException expected) { } diff --git a/guava-tests/test/com/google/common/collect/MapsCollectionTest.java b/guava-tests/test/com/google/common/collect/MapsCollectionTest.java index a6f4b040d..2024399ae 100644 --- a/guava-tests/test/com/google/common/collect/MapsCollectionTest.java +++ b/guava-tests/test/com/google/common/collect/MapsCollectionTest.java @@ -25,6 +25,7 @@ import com.google.common.base.Predicate; import com.google.common.collect.Maps.EntryTransformer; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.MapTestSuiteBuilder; +import com.google.common.collect.testing.NavigableMapTestSuiteBuilder; import com.google.common.collect.testing.SafeTreeMap; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SortedMapTestSuiteBuilder; @@ -42,12 +43,13 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -import java.io.UnsupportedEncodingException; 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.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; @@ -63,6 +65,20 @@ public class MapsCollectionTest extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(); + suite.addTest(NavigableMapTestSuiteBuilder + .using(new TestStringSortedMapGenerator() { + @Override + protected SortedMap<String, String> create(Entry<String, String>[] entries) { + SafeTreeMap<String, String> map = new SafeTreeMap<String, String>(); + putEntries(map, entries); + return Maps.unmodifiableNavigableMap(map); + } + }) + .named("unmodifiableNavigableMap[SafeTreeMap]") + .withFeatures(CollectionSize.ANY, + MapFeature.ALLOWS_NULL_VALUES, + CollectionFeature.SERIALIZABLE) + .createTestSuite()); suite.addTest(BiMapTestSuiteBuilder .using(new TestStringBiMapGenerator() { @Override @@ -196,6 +212,67 @@ public class MapsCollectionTest extends TestCase { } }) .named("Maps.asMap[SortedSet, Function]") + .withFeatures(CollectionSize.ANY, + CollectionFeature.SUPPORTS_ITERATOR_REMOVE, + MapFeature.SUPPORTS_REMOVE) + .createTestSuite()); + suite.addTest(NavigableMapTestSuiteBuilder + .using(new TestMapGenerator<String, Integer>() { + @Override + public String[] createKeyArray(int length) { + return new String[length]; + } + + @Override + public Integer[] createValueArray(int length) { + return new Integer[length]; + } + + @Override + public SampleElements<Entry<String, Integer>> samples() { + return new SampleElements<Entry<String, Integer>>( + mapEntry("a", 1), + mapEntry("aa", 2), + mapEntry("aba", 3), + mapEntry("bbbb", 4), + mapEntry("ccccc", 5)); + } + + @Override + public NavigableMap<String, Integer> create(Object... elements) { + NavigableSet<String> set = Sets.newTreeSet(Ordering.natural()); + for (Object e : elements) { + Map.Entry<?, ?> entry = (Entry<?, ?>) e; + checkNotNull(entry.getValue()); + set.add((String) checkNotNull(entry.getKey())); + } + return Maps.asMap(set, new Function<String, Integer>() { + @Override + public Integer apply(String input) { + return input.length(); + } + }); + } + + @SuppressWarnings("unchecked") + @Override + public Entry<String, Integer>[] createArray(int length) { + return new Entry[length]; + } + + @Override + public Iterable<Entry<String, Integer>> order( + List<Entry<String, Integer>> insertionOrder) { + Collections.sort(insertionOrder, new Comparator<Entry<String, Integer>>() { + @Override + public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { + return o1.getKey().compareTo(o2.getKey()); + } + }); + return insertionOrder; + } + }) + .named("Maps.asMap[NavigableSet, Function]") .withFeatures(CollectionSize.ANY, MapFeature.SUPPORTS_REMOVE, CollectionFeature.SUPPORTS_ITERATOR_REMOVE) @@ -210,6 +287,7 @@ public class MapsCollectionTest extends TestCase { suite.addTest(filterMapSuite()); suite.addTest(filterBiMapSuite()); suite.addTest(filterSortedMapSuite()); + suite.addTest(filterNavigableMapSuite()); return suite; } @@ -392,6 +470,59 @@ public class MapsCollectionTest extends TestCase { return suite; } + static TestSuite filterNavigableMapSuite() { + TestSuite suite = new TestSuite("FilterNavigableMap"); + suite.addTest(NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + @Override + protected NavigableMap<String, String> create(Entry<String, String>[] entries) { + NavigableMap<String, String> map = new SafeTreeMap<String, String>(); + putEntries(map, entries); + map.put("banana", "toast"); + map.put("eggplant", "spam"); + return Maps.filterKeys(map, FILTER_KEYS); + } + }) + .named("Maps.filterKeys[NavigableMap, Predicate]") + .withFeatures( + MapFeature.ALLOWS_NULL_VALUES, + MapFeature.GENERAL_PURPOSE, + CollectionSize.ANY) + .createTestSuite()); + suite.addTest(NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + @Override + protected NavigableMap<String, String> create(Entry<String, String>[] entries) { + NavigableMap<String, String> map = new SafeTreeMap<String, String>(); + putEntries(map, entries); + map.put("banana", "toast"); + map.put("eggplant", "spam"); + return Maps.filterValues(map, FILTER_VALUES); + } + }) + .named("Maps.filterValues[NavigableMap, Predicate]") + .withFeatures( + MapFeature.ALLOWS_NULL_VALUES, + MapFeature.GENERAL_PURPOSE, + CollectionSize.ANY) + .createTestSuite()); + suite.addTest(NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + @Override + protected NavigableMap<String, String> create(Entry<String, String>[] entries) { + NavigableMap<String, String> map = new SafeTreeMap<String, String>(); + putEntries(map, entries); + map.put("banana", "toast"); + map.put("eggplant", "spam"); + return Maps.filterEntries(map, FILTER_ENTRIES); + } + }) + .named("Maps.filterEntries[NavigableMap, Predicate]") + .withFeatures( + MapFeature.ALLOWS_NULL_VALUES, + MapFeature.GENERAL_PURPOSE, + CollectionSize.ANY) + .createTestSuite()); + return suite; + } + static void putEntries(Map<String, String> map, Entry<String, String>[] entries) { for (Entry<String, String> entry : entries) { map.put(entry.getKey(), entry.getValue()); @@ -472,21 +603,13 @@ public class MapsCollectionTest extends TestCase { } private static String encode(String str) { - try { - return BaseEncoding.base64().encode(str.getBytes(Charsets.UTF_8.name())); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return BaseEncoding.base64().encode(str.getBytes(Charsets.UTF_8)); } private static final Function<String, String> DECODE_FUNCTION = new Function<String, String>() { @Override public String apply(String input) { - try { - return new String(BaseEncoding.base64().decode(input), Charsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return new String(BaseEncoding.base64().decode(input), Charsets.UTF_8); } }; @@ -502,6 +625,7 @@ public class MapsCollectionTest extends TestCase { TestSuite suite = new TestSuite("Maps.transform"); suite.addTest(transformMapSuite()); suite.addTest(transformSortedMapSuite()); + suite.addTest(transformNavigableMapSuite()); return suite; } @@ -586,4 +710,43 @@ public class MapsCollectionTest extends TestCase { .createTestSuite()); return suite; } + + static TestSuite transformNavigableMapSuite() { + TestSuite suite = new TestSuite("TransformNavigableMap"); + suite.addTest(NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + @Override + protected NavigableMap<String, String> create(Entry<String, String>[] entries) { + NavigableMap<String, String> map = new SafeTreeMap<String, String>(); + for (Entry<String, String> entry : entries) { + map.put(entry.getKey(), encode(entry.getValue())); + } + return Maps.transformValues(map, DECODE_FUNCTION); + } + }) + .named("Maps.transformValues[NavigableMap, Function]") + .withFeatures( + CollectionSize.ANY, + CollectionFeature.KNOWN_ORDER, + MapFeature.SUPPORTS_REMOVE, + CollectionFeature.SUPPORTS_ITERATOR_REMOVE) + .createTestSuite()); + suite.addTest(NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + @Override + protected NavigableMap<String, String> create(Entry<String, String>[] entries) { + NavigableMap<String, String> map = new SafeTreeMap<String, String>(); + for (Entry<String, String> entry : entries) { + map.put(entry.getKey(), encode(entry.getValue())); + } + return Maps.transformEntries(map, DECODE_ENTRY_TRANSFORMER); + } + }) + .named("Maps.transformEntries[NavigableMap, EntryTransformer]") + .withFeatures( + CollectionSize.ANY, + CollectionFeature.KNOWN_ORDER, + MapFeature.SUPPORTS_REMOVE, + CollectionFeature.SUPPORTS_ITERATOR_REMOVE) + .createTestSuite()); + return suite; + } } diff --git a/guava-tests/test/com/google/common/collect/MapsTest.java b/guava-tests/test/com/google/common/collect/MapsTest.java index 2eddd097a..226d83180 100644 --- a/guava-tests/test/com/google/common/collect/MapsTest.java +++ b/guava-tests/test/com/google/common/collect/MapsTest.java @@ -18,9 +18,10 @@ package com.google.common.collect; import static com.google.common.collect.Maps.transformEntries; import static com.google.common.collect.Maps.transformValues; +import static com.google.common.collect.Maps.unmodifiableNavigableMap; import static com.google.common.collect.testing.Helpers.mapEntry; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -40,7 +41,7 @@ import com.google.common.testing.SerializableTester; import junit.framework.TestCase; import java.io.IOException; -import java.io.StringBufferInputStream; +import java.io.StringReader; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collection; @@ -55,6 +56,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.NavigableSet; import java.util.Properties; import java.util.Set; import java.util.SortedMap; @@ -241,9 +244,9 @@ public class MapsTest extends TestCase { assertEquals(Collections.emptyMap(), map); map.put(new Derived("foo"), 1); map.put(new Derived("bar"), 2); - ASSERT.that(map.keySet()).has().exactly( + assertThat(map.keySet()).has().exactly( new Derived("bar"), new Derived("foo")).inOrder(); - ASSERT.that(map.values()).has().exactly(2, 1).inOrder(); + assertThat(map.values()).has().exactly(2, 1).inOrder(); assertNull(map.comparator()); } @@ -252,9 +255,9 @@ public class MapsTest extends TestCase { assertEquals(Collections.emptyMap(), map); map.put(new LegacyComparable("foo"), 1); map.put(new LegacyComparable("bar"), 2); - ASSERT.that(map.keySet()).has().exactly( + assertThat(map.keySet()).has().exactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); - ASSERT.that(map.values()).has().exactly(2, 1).inOrder(); + assertThat(map.values()).has().exactly(2, 1).inOrder(); assertNull(map.comparator()); } @@ -523,13 +526,13 @@ public class MapsTest extends TestCase { SortedMapDifference<Integer, String> diff1 = Maps.difference(left, right); assertFalse(diff1.areEqual()); - ASSERT.that(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( + assertThat(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( Maps.immutableEntry(4, "d"), Maps.immutableEntry(2, "b")).inOrder(); - ASSERT.that(diff1.entriesOnlyOnRight().entrySet()).has().item( + assertThat(diff1.entriesOnlyOnRight().entrySet()).has().item( Maps.immutableEntry(6, "z")); - ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( + assertThat(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); - ASSERT.that(diff1.entriesDiffering().entrySet()).has().exactly( + assertThat(diff1.entriesDiffering().entrySet()).has().exactly( Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g")), Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f"))).inOrder(); assertEquals("not equal: only on left={4=d, 2=b}: only on right={6=z}: " @@ -538,11 +541,11 @@ public class MapsTest extends TestCase { SortedMapDifference<Integer, String> diff2 = Maps.difference(right, left); assertFalse(diff2.areEqual()); - ASSERT.that(diff2.entriesOnlyOnLeft().entrySet()).has().item( + assertThat(diff2.entriesOnlyOnLeft().entrySet()).has().item( Maps.immutableEntry(6, "z")); - ASSERT.that(diff2.entriesOnlyOnRight().entrySet()).has().exactly( + assertThat(diff2.entriesOnlyOnRight().entrySet()).has().exactly( Maps.immutableEntry(2, "b"), Maps.immutableEntry(4, "d")).inOrder(); - ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( + assertThat(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); assertEquals(ImmutableMap.of( 3, ValueDifferenceImpl.create("f", "c"), @@ -562,13 +565,13 @@ public class MapsTest extends TestCase { Maps.difference(left, right); left.put(6, "z"); assertFalse(diff1.areEqual()); - ASSERT.that(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( + assertThat(diff1.entriesOnlyOnLeft().entrySet()).has().exactly( Maps.immutableEntry(2, "b"), Maps.immutableEntry(4, "d")).inOrder(); - ASSERT.that(diff1.entriesOnlyOnRight().entrySet()).has().item( + assertThat(diff1.entriesOnlyOnRight().entrySet()).has().item( Maps.immutableEntry(6, "z")); - ASSERT.that(diff1.entriesInCommon().entrySet()).has().item( + assertThat(diff1.entriesInCommon().entrySet()).has().item( Maps.immutableEntry(1, "a")); - ASSERT.that(diff1.entriesDiffering().entrySet()).has().exactly( + assertThat(diff1.entriesDiffering().entrySet()).has().exactly( Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f")), Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g"))).inOrder(); try { @@ -625,7 +628,7 @@ public class MapsTest extends TestCase { assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(5), map.get("three")); assertNull(map.get("five")); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); @@ -648,13 +651,13 @@ public class MapsTest extends TestCase { Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(3), map.remove("two")); - ASSERT.that(strings).has().exactly("one", "three").inOrder(); + assertThat(strings).has().exactly("one", "three").inOrder(); } public void testAsMapEmpty() { Set<String> strings = ImmutableSet.of(); Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); - ASSERT.that(map.entrySet()).isEmpty(); + assertThat(map.entrySet()).isEmpty(); assertTrue(map.isEmpty()); assertNull(map.get("five")); } @@ -681,14 +684,14 @@ public class MapsTest extends TestCase { assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(5), map.get("three")); assertNull(map.get("five")); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("three", 5), mapEntry("two", 3)).inOrder(); - ASSERT.that(map.tailMap("onea").entrySet()).has().exactly( + assertThat(map.tailMap("onea").entrySet()).has().exactly( mapEntry("three", 5), mapEntry("two", 3)).inOrder(); - ASSERT.that(map.subMap("one", "two").entrySet()).has().exactly( + assertThat(map.subMap("one", "two").entrySet()).has().exactly( mapEntry("one", 3), mapEntry("three", 5)).inOrder(); } @@ -714,7 +717,7 @@ public class MapsTest extends TestCase { assertEquals( ImmutableSortedMap.of("five", 4, "four", 4, "three", 5), headMap); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( mapEntry("five", 4), mapEntry("four", 4), mapEntry("three", 5), @@ -727,7 +730,7 @@ public class MapsTest extends TestCase { SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); assertEquals(Integer.valueOf(3), map.remove("two")); - ASSERT.that(strings).has().exactly("one", "three").inOrder(); + assertThat(strings).has().exactly("one", "three").inOrder(); } public void testAsMapSortedSubViewKeySetsDoNotSupportAdd() { @@ -758,7 +761,165 @@ public class MapsTest extends TestCase { public void testAsMapSortedEmpty() { SortedSet<String> strings = new NonNavigableSortedSet(); SortedMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); - ASSERT.that(map.entrySet()).isEmpty(); + assertThat(map.entrySet()).isEmpty(); + assertTrue(map.isEmpty()); + assertNull(map.get("five")); + } + + @GwtIncompatible("NavigableMap") + public void testAsMapReturnsNavigableMapForNavigableSetInput() { + Set<String> set = Sets.newTreeSet(); + assertTrue(Maps.asMap(set, Functions.identity()) instanceof NavigableMap); + } + + @GwtIncompatible("NavigableMap") + public void testAsMapNavigable() { + NavigableSet<String> strings = + Sets.newTreeSet(asList("one", "two", "three")); + NavigableMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); + assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); + assertEquals(Integer.valueOf(5), map.get("three")); + assertNull(map.get("five")); + assertThat(map.entrySet()).has().exactly( + mapEntry("one", 3), + mapEntry("three", 5), + mapEntry("two", 3)).inOrder(); + assertThat(map.tailMap("onea").entrySet()).has().exactly( + mapEntry("three", 5), + mapEntry("two", 3)).inOrder(); + assertThat(map.subMap("one", "two").entrySet()).has().exactly( + mapEntry("one", 3), + mapEntry("three", 5)).inOrder(); + + assertEquals(ImmutableSortedMap.of("two", 3, "three", 5), + map.tailMap("three", true)); + assertEquals(ImmutableSortedMap.of("one", 3, "three", 5), + map.headMap("two", false)); + assertEquals(ImmutableSortedMap.of("three", 5), + map.subMap("one", false, "tr", true)); + + assertEquals("three", map.higherKey("one")); + assertEquals("three", map.higherKey("r")); + assertEquals("three", map.ceilingKey("r")); + assertEquals("one", map.ceilingKey("one")); + assertEquals(mapEntry("three", 5), map.higherEntry("one")); + assertEquals(mapEntry("one", 3), map.ceilingEntry("one")); + assertEquals("one", map.lowerKey("three")); + assertEquals("one", map.lowerKey("r")); + assertEquals("one", map.floorKey("r")); + assertEquals("three", map.floorKey("three")); + + assertThat(map.descendingMap().entrySet()).has().exactly( + mapEntry("two", 3), + mapEntry("three", 5), + mapEntry("one", 3)).inOrder(); + assertEquals(map.headMap("three", true), + map.descendingMap().tailMap("three", true)); + assertThat(map.tailMap("three", false).entrySet()).has().item( + mapEntry("two", 3)); + assertNull(map.tailMap("three", true).lowerEntry("three")); + assertThat(map.headMap("two", false).values()).has().exactly(3, 5).inOrder(); + assertThat(map.headMap("two", false).descendingMap().values()) + .has().exactly(5, 3).inOrder(); + assertThat(map.descendingKeySet()).has().exactly( + "two", "three", "one").inOrder(); + + assertEquals(mapEntry("one", 3), map.pollFirstEntry()); + assertEquals(mapEntry("two", 3), map.pollLastEntry()); + assertEquals(1, map.size()); + } + + @GwtIncompatible("NavigableMap") + public void testAsMapNavigableReadsThrough() { + NavigableSet<String> strings = Sets.newTreeSet(); + Collections.addAll(strings, "one", "two", "three"); + NavigableMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); + assertNull(map.comparator()); + assertEquals(ImmutableSortedMap.of("one", 3, "two", 3, "three", 5), map); + assertNull(map.get("four")); + strings.add("four"); + assertEquals( + ImmutableSortedMap.of("one", 3, "two", 3, "three", 5, "four", 4), + map); + assertEquals(Integer.valueOf(4), map.get("four")); + SortedMap<String, Integer> headMap = map.headMap("two"); + assertEquals( + ImmutableSortedMap.of("four", 4, "one", 3, "three", 5), + headMap); + strings.add("five"); + strings.remove("one"); + assertEquals( + ImmutableSortedMap.of("five", 4, "four", 4, "three", 5), + headMap); + assertThat(map.entrySet()).has().exactly( + mapEntry("five", 4), + mapEntry("four", 4), + mapEntry("three", 5), + mapEntry("two", 3)).inOrder(); + + NavigableMap<String, Integer> tailMap = map.tailMap("s", true); + NavigableMap<String, Integer> subMap = map.subMap("a", true, "t", false); + + strings.add("six"); + strings.remove("two"); + assertThat(tailMap.entrySet()).has().exactly( + mapEntry("six", 3), + mapEntry("three", 5)).inOrder(); + assertThat(subMap.entrySet()).has().exactly( + mapEntry("five", 4), + mapEntry("four", 4), + mapEntry("six", 3)).inOrder(); + } + + @GwtIncompatible("NavigableMap") + public void testAsMapNavigableWritesThrough() { + NavigableSet<String> strings = Sets.newTreeSet(); + Collections.addAll(strings, "one", "two", "three"); + NavigableMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); + assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); + assertEquals(Integer.valueOf(3), map.remove("two")); + assertThat(strings).has().exactly("one", "three").inOrder(); + assertEquals(mapEntry("three", 5), + map.subMap("one", false, "zzz", true).pollLastEntry()); + assertThat(strings).has().item("one"); + } + + @GwtIncompatible("NavigableMap") + public void testAsMapNavigableSubViewKeySetsDoNotSupportAdd() { + NavigableMap<String, Integer> map = Maps.asMap( + Sets.<String>newTreeSet(), LENGTH_FUNCTION); + try { + map.descendingKeySet().add("a"); + fail(); + } catch (UnsupportedOperationException expected) { + } + try { + map.subMap("a", true, "z", false).keySet().add("a"); + fail(); + } catch (UnsupportedOperationException expected) { + } + try { + map.tailMap("a", true).keySet().add("a"); + fail(); + } catch (UnsupportedOperationException expected) { + } + try { + map.headMap("r", true).keySet().add("a"); + fail(); + } catch (UnsupportedOperationException expected) { + } + try { + map.headMap("r", false).tailMap("m", true).keySet().add("a"); + fail(); + } catch (UnsupportedOperationException expected) { + } + } + + @GwtIncompatible("NavigableMap") + public void testAsMapNavigableEmpty() { + NavigableSet<String> strings = ImmutableSortedSet.of(); + NavigableMap<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION); + assertThat(map.entrySet()).isEmpty(); assertTrue(map.isEmpty()); assertNull(map.get("five")); } @@ -767,7 +928,7 @@ public class MapsTest extends TestCase { Iterable<String> strings = ImmutableList.of("one", "two", "three"); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); @@ -777,7 +938,7 @@ public class MapsTest extends TestCase { Iterator<String> strings = ImmutableList.of("one", "two", "three").iterator(); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); @@ -787,7 +948,7 @@ public class MapsTest extends TestCase { Iterable<String> strings = ImmutableList.of("one", "two", "three", "two", "one"); ImmutableMap<String, Integer> map = Maps.toMap(strings, LENGTH_FUNCTION); assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map); - ASSERT.that(map.entrySet()).has().exactly( + assertThat(map.entrySet()).has().exactly( mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5)).inOrder(); @@ -895,7 +1056,7 @@ public class MapsTest extends TestCase { // Now test values loaded from a stream. String props = "test\n second = 2\n Third item : a short phrase "; - testProp.load(new StringBufferInputStream(props)); + testProp.load(new StringReader(props)); result = Maps.fromProperties(testProp); assertEquals(4, result.size()); @@ -913,7 +1074,7 @@ public class MapsTest extends TestCase { testProp = new Properties(System.getProperties()); String override = "test\njava.version : hidden"; - testProp.load(new StringBufferInputStream(override)); + testProp.load(new StringReader(override)); result = Maps.fromProperties(testProp); assertTrue(result.size() > 2); @@ -957,37 +1118,6 @@ public class MapsTest extends TestCase { } catch (ClassCastException expected) {} } - /** - * Constructs 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> nefariousEntry( - final K key, final V value) { - return new AbstractMapEntry<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 super.equals(o); - } - }; - } - public void testAsConverter_nominal() throws Exception { ImmutableBiMap<String, Integer> biMap = ImmutableBiMap.of( "one", 1, @@ -1487,6 +1617,21 @@ public class MapsTest extends TestCase { assertTrue(transformed instanceof SortedMap); } + @GwtIncompatible("NavigableMap") + public void testTransformValuesSecretlyNavigable() { + Map<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9); + Map<String, Double> transformed; + + transformed = transformValues(map, SQRT_FUNCTION); + assertEquals(ImmutableMap.of("a", 2.0, "b", 3.0), transformed); + assertTrue(transformed instanceof NavigableMap); + + transformed = + transformValues((SortedMap<String, Integer>) map, SQRT_FUNCTION); + assertEquals(ImmutableMap.of("a", 2.0, "b", 3.0), transformed); + assertTrue(transformed instanceof NavigableMap); + } + public void testTransformEntries() { Map<String, String> map = ImmutableMap.of("a", "4", "b", "9"); EntryTransformer<String, String, String> concat = @@ -1516,6 +1661,27 @@ public class MapsTest extends TestCase { assertTrue(transformed instanceof SortedMap); } + @GwtIncompatible("NavigableMap") + public void testTransformEntriesSecretlyNavigable() { + Map<String, String> map = ImmutableSortedMap.of("a", "4", "b", "9"); + EntryTransformer<String, String, String> concat = + new EntryTransformer<String, String, String>() { + @Override + public String transformEntry(String key, String value) { + return key + value; + } + }; + Map<String, String> transformed; + + transformed = transformEntries(map, concat); + assertEquals(ImmutableMap.of("a", "a4", "b", "b9"), transformed); + assertTrue(transformed instanceof NavigableMap); + + transformed = transformEntries((SortedMap<String, String>) map, concat); + assertEquals(ImmutableMap.of("a", "a4", "b", "b9"), transformed); + assertTrue(transformed instanceof NavigableMap); + } + @SuppressWarnings("unused") public void testTransformEntriesGenerics() { Map<Object, Object> map1 = ImmutableMap.<Object, Object>of(1, 2); @@ -1610,6 +1776,15 @@ public class MapsTest extends TestCase { assertEquals(ImmutableSortedMap.of("a", 2.0, "b", 3.0), transformed); } + @GwtIncompatible("NavigableMap") + public void testNavigableMapTransformValues() { + NavigableMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9); + NavigableMap<String, Double> transformed = + transformValues(map, SQRT_FUNCTION); + + assertEquals(ImmutableSortedMap.of("a", 2.0, "b", 3.0), transformed); + } + public void testSortedMapTransformEntries() { SortedMap<String, String> map = sortedNotNavigable(ImmutableSortedMap.of("a", "4", "b", "9")); @@ -1628,4 +1803,160 @@ public class MapsTest extends TestCase { */ assertEquals(ImmutableSortedMap.of("a", "a4", "b", "b9"), transformed); } + + @GwtIncompatible("NavigableMap") + public void testNavigableMapTransformEntries() { + NavigableMap<String, String> map = + ImmutableSortedMap.of("a", "4", "b", "9"); + EntryTransformer<String, String, String> concat = + new EntryTransformer<String, String, String>() { + @Override + public String transformEntry(String key, String value) { + return key + value; + } + }; + NavigableMap<String, String> transformed = transformEntries(map, concat); + + assertEquals(ImmutableSortedMap.of("a", "a4", "b", "b9"), transformed); + } + + @GwtIncompatible("NavigableMap") + public void testUnmodifiableNavigableMap() { + TreeMap<Integer, String> mod = Maps.newTreeMap(); + mod.put(1, "one"); + mod.put(2, "two"); + mod.put(3, "three"); + + NavigableMap<Integer, String> unmod = unmodifiableNavigableMap(mod); + + /* unmod is a view. */ + mod.put(4, "four"); + assertEquals("four", unmod.get(4)); + assertEquals("four", unmod.descendingMap().get(4)); + + ensureNotDirectlyModifiable(unmod); + ensureNotDirectlyModifiable(unmod.descendingMap()); + ensureNotDirectlyModifiable(unmod.headMap(2, true)); + ensureNotDirectlyModifiable(unmod.subMap(1, true, 3, true)); + ensureNotDirectlyModifiable(unmod.tailMap(2, true)); + + Collection<String> values = unmod.values(); + try { + values.add("4"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + values.remove("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + values.removeAll(Collections.singleton("four")); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + values.retainAll(Collections.singleton("four")); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + Iterator<String> iterator = values.iterator(); + iterator.next(); + iterator.remove(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + + Set<Map.Entry<Integer, String>> entries = unmod.entrySet(); + try { + Iterator<Map.Entry<Integer, String>> iterator = entries.iterator(); + iterator.next(); + iterator.remove(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + Map.Entry<Integer, String> entry = entries.iterator().next(); + try { + entry.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + entry = unmod.lowerEntry(1); + assertNull(entry); + entry = unmod.floorEntry(2); + try { + entry.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + entry = unmod.ceilingEntry(2); + try { + entry.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + entry = unmod.lowerEntry(2); + try { + entry.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + entry = unmod.higherEntry(2); + try { + entry.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + entry = unmod.firstEntry(); + try { + entry.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + entry = unmod.lastEntry(); + try { + entry.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + @SuppressWarnings("unchecked") + Map.Entry<Integer, String> entry2 = + (Map.Entry<Integer, String>) entries.toArray()[0]; + try { + entry2.setValue("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + } + + @GwtIncompatible("NavigableMap") + void ensureNotDirectlyModifiable(NavigableMap<Integer, String> unmod) { + try { + unmod.put(4, "four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.putAll(Collections.singletonMap(4, "four")); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.remove("four"); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.pollFirstEntry(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.pollLastEntry(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + } } diff --git a/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java b/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java index c6461c872..803f63f62 100644 --- a/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java +++ b/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.testing.IteratorFeature; import com.google.common.collect.testing.IteratorTester; @@ -355,7 +355,7 @@ public class MinMaxPriorityQueueTest extends TestCase { } } assertTrue(q.isIntact()); - ASSERT.that(result).has().exactly(1, 15, 13, 8, 14); + assertThat(result).has().exactly(1, 15, 13, 8, 14); } /** @@ -718,23 +718,23 @@ public class MinMaxPriorityQueueTest extends TestCase { List<Integer> contents = Lists.newArrayList(expected); List<Integer> elements = Lists.newArrayListWithCapacity(size); while (!q.isEmpty()) { - ASSERT.that(q).has().exactlyAs(contents); + assertThat(q).has().exactlyAs(contents); Integer next = q.pollFirst(); contents.remove(next); - ASSERT.that(q).has().exactlyAs(contents); + assertThat(q).has().exactlyAs(contents); for (int i = 0; i <= size; i++) { q.add(i); contents.add(i); - ASSERT.that(q).has().exactlyAs(contents); + assertThat(q).has().exactlyAs(contents); q.add(next); contents.add(next); - ASSERT.that(q).has().exactlyAs(contents); + assertThat(q).has().exactlyAs(contents); q.remove(i); assertTrue(contents.remove(Integer.valueOf(i))); - ASSERT.that(q).has().exactlyAs(contents); + assertThat(q).has().exactlyAs(contents); assertEquals(next, q.poll()); contents.remove(next); - ASSERT.that(q).has().exactlyAs(contents); + assertThat(q).has().exactlyAs(contents); } elements.add(next); } diff --git a/guava-tests/test/com/google/common/collect/MultimapBuilderTest.java b/guava-tests/test/com/google/common/collect/MultimapBuilderTest.java index 1dd3fa9f2..5733994eb 100644 --- a/guava-tests/test/com/google/common/collect/MultimapBuilderTest.java +++ b/guava-tests/test/com/google/common/collect/MultimapBuilderTest.java @@ -19,10 +19,13 @@ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.MultimapBuilder.MultimapBuilderWithKeys; -import com.google.common.testing.SerializableTester; import junit.framework.TestCase; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.math.RoundingMode; import java.util.SortedMap; import java.util.SortedSet; @@ -66,7 +69,8 @@ public class MultimapBuilderTest extends TestCase { assertTrue(multimap.asMap() instanceof SortedMap); } - public void testSerialization() { + @GwtIncompatible("serialization") + public void testSerialization() throws Exception { for (MultimapBuilderWithKeys<?> builderWithKeys : ImmutableList.of( MultimapBuilder.hashKeys(), MultimapBuilder.linkedHashKeys(), MultimapBuilder.treeKeys(), MultimapBuilder.enumKeys(RoundingMode.class))) { @@ -77,8 +81,25 @@ public class MultimapBuilderTest extends TestCase { builderWithKeys.linkedHashSetValues(), builderWithKeys.treeSetValues(), builderWithKeys.enumSetValues(RoundingMode.class))) { - SerializableTester.reserializeAndAssert(builder.build()); + /* + * Temporarily inlining SerializableTester here for obscure internal reasons. + */ + reserializeAndAssert(builder.build()); } } } + + @GwtIncompatible("serialization") + private static void reserializeAndAssert(Object object) throws Exception { + Object copy = reserialize(object); + assertEquals(object, copy); + assertEquals(object.getClass(), copy.getClass()); + } + + @GwtIncompatible("serialization") + private static Object reserialize(Object object) throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + new ObjectOutputStream(bytes).writeObject(object); + return new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject(); + } } diff --git a/guava-tests/test/com/google/common/collect/MultimapsTest.java b/guava-tests/test/com/google/common/collect/MultimapsTest.java index c99681a8d..43123efb6 100644 --- a/guava-tests/test/com/google/common/collect/MultimapsTest.java +++ b/guava-tests/test/com/google/common/collect/MultimapsTest.java @@ -21,8 +21,8 @@ import static com.google.common.collect.Maps.immutableEntry; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -297,7 +297,7 @@ public class MultimapsTest extends TestCase { assertEquals(multimap.hashCode(), unmodifiable.hashCode()); assertEquals(multimap, unmodifiable); - ASSERT.that(unmodifiable.asMap().get("bar")).has().exactly(5, -1); + assertThat(unmodifiable.asMap().get("bar")).has().exactly(5, -1); assertNull(unmodifiable.asMap().get("missing")); assertFalse(unmodifiable.entries() instanceof Serializable); @@ -454,11 +454,11 @@ public class MultimapsTest extends TestCase { assertFalse(map.containsKey("bar")); assertEquals(map.keySet(), multimapView.keySet()); assertEquals(map.keySet(), multimapView.keys().elementSet()); - ASSERT.that(multimapView.keys()).has().item("foo"); - ASSERT.that(multimapView.values()).has().item(1); - ASSERT.that(multimapView.entries()).has().item( + assertThat(multimapView.keys()).has().item("foo"); + assertThat(multimapView.values()).has().item(1); + assertThat(multimapView.entries()).has().item( Maps.immutableEntry("foo", 1)); - ASSERT.that(multimapView.asMap().entrySet()).has().item( + assertThat(multimapView.asMap().entrySet()).has().item( Maps.immutableEntry( "foo", (Collection<Integer>) Collections.singleton(1))); multimapView.clear(); @@ -615,7 +615,7 @@ public class MultimapsTest extends TestCase { } catch (IllegalArgumentException expected) { // expected } - ASSERT.that(multimap.entries()).has().exactly( + assertThat(multimap.entries()).has().exactly( Maps.immutableEntry(Color.RED, 1), Maps.immutableEntry(Color.BLUE, 2)); } @@ -838,7 +838,7 @@ public class MultimapsTest extends TestCase { } }; Multimap<String, Integer> transformed = Multimaps.transformValues(multimap, square); - ASSERT.that(transformed.entries()).has().exactly(immutableEntry("a", 4), + assertThat(transformed.entries()).has().exactly(immutableEntry("a", 4), immutableEntry("a", 16), immutableEntry("b", 9), immutableEntry("b", 9), immutableEntry("c", 36)).inOrder(); } @@ -856,7 +856,7 @@ public class MultimapsTest extends TestCase { }); Entry<String, String> entry = multimap.entries().iterator().next(); entry.setValue("bbb"); - ASSERT.that(transformed.entries()).has().exactly(immutableEntry("a", 3)).inOrder(); + assertThat(transformed.entries()).has().exactly(immutableEntry("a", 3)).inOrder(); } @GwtIncompatible(value = "untested") @@ -871,7 +871,7 @@ public class MultimapsTest extends TestCase { }; ListMultimap<String, Integer> transformed = Multimaps.transformValues(multimap, square); - ASSERT.that(transformed.entries()).has().exactly(immutableEntry("a", 4), + assertThat(transformed.entries()).has().exactly(immutableEntry("a", 4), immutableEntry("a", 16), immutableEntry("b", 9), immutableEntry("b", 9), immutableEntry("c", 36)).inOrder(); } @@ -889,7 +889,7 @@ public class MultimapsTest extends TestCase { }; Multimap<String, String> transformed = Multimaps.transformEntries(multimap, transformer); - ASSERT.that(transformed.entries()).has().exactly(immutableEntry("a", "a"), + assertThat(transformed.entries()).has().exactly(immutableEntry("a", "a"), immutableEntry("a", "a"), immutableEntry("b", "nob")).inOrder(); } @@ -959,7 +959,7 @@ public class MultimapsTest extends TestCase { SetMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); Set<Integer> bazSet = filtered.get("baz"); - ASSERT.that(bazSet).isEmpty(); + assertThat(bazSet).isEmpty(); try { bazSet.add(5); fail("Expected IllegalArgumentException"); @@ -982,7 +982,7 @@ public class MultimapsTest extends TestCase { ListMultimap<String, Integer> filtered = Multimaps.filterKeys( multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); List<Integer> bazList = filtered.get("baz"); - ASSERT.that(bazList).isEmpty(); + assertThat(bazList).isEmpty(); try { bazList.add(5); fail("Expected IllegalArgumentException"); diff --git a/guava-tests/test/com/google/common/collect/MultisetsTest.java b/guava-tests/test/com/google/common/collect/MultisetsTest.java index 69cf56a7d..6623e151c 100644 --- a/guava-tests/test/com/google/common/collect/MultisetsTest.java +++ b/guava-tests/test/com/google/common/collect/MultisetsTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -27,6 +27,7 @@ import junit.framework.TestCase; import java.util.Arrays; import java.util.Collections; +import java.util.List; /** * Tests for {@link Multisets}. @@ -45,7 +46,7 @@ public class MultisetsTest extends TestCase { assertTrue(set.isEmpty()); set.add(new DerivedComparable("foo"), 2); set.add(new DerivedComparable("bar"), 3); - ASSERT.that(set).has().exactly( + assertThat(set).has().exactly( new DerivedComparable("bar"), new DerivedComparable("bar"), new DerivedComparable("bar"), new DerivedComparable("foo"), new DerivedComparable("foo")).inOrder(); } @@ -55,7 +56,7 @@ public class MultisetsTest extends TestCase { assertTrue(set.isEmpty()); set.add(new LegacyComparable("foo"), 2); set.add(new LegacyComparable("bar"), 3); - ASSERT.that(set).has().exactly(new LegacyComparable("bar"), + assertThat(set).has().exactly(new LegacyComparable("bar"), new LegacyComparable("bar"), new LegacyComparable("bar"), new LegacyComparable("foo"), new LegacyComparable("foo")).inOrder(); } @@ -65,7 +66,7 @@ public class MultisetsTest extends TestCase { = TreeMultiset.create(Collections.reverseOrder()); multiset.add("bar", 3); multiset.add("foo", 2); - ASSERT.that(multiset).has().exactly("foo", "foo", "bar", "bar", "bar").inOrder(); + assertThat(multiset).has().exactly("foo", "foo", "bar", "bar", "bar").inOrder(); } public void testRetainOccurrencesEmpty() { @@ -73,10 +74,17 @@ public class MultisetsTest extends TestCase { Multiset<String> toRetain = HashMultiset.create(Arrays.asList("a", "b", "a")); assertFalse(Multisets.retainOccurrences(multiset, toRetain)); - ASSERT.that(multiset).isEmpty(); + assertThat(multiset).isEmpty(); } - public void testRemoveOccurrencesEmpty() { + public void testRemoveOccurrencesIterableEmpty() { + Multiset<String> multiset = HashMultiset.create(); + Iterable<String> toRemove = Arrays.asList("a", "b", "a"); + assertFalse(Multisets.removeOccurrences(multiset, toRemove)); + assertTrue(multiset.isEmpty()); + } + + public void testRemoveOccurrencesMultisetEmpty() { Multiset<String> multiset = HashMultiset.create(); Multiset<String> toRemove = HashMultiset.create(Arrays.asList("a", "b", "a")); @@ -88,7 +96,7 @@ public class MultisetsTest extends TestCase { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create( Arrays.asList("a", "b", "b", "c")); - ASSERT.that(Multisets.union(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); + assertThat(Multisets.union(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); } public void testUnionEqualMultisets() { @@ -112,50 +120,50 @@ public class MultisetsTest extends TestCase { public void testIntersectEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); - ASSERT.that(Multisets.intersection(ms1, ms2)).isEmpty(); + assertThat(Multisets.intersection(ms1, ms2)).isEmpty(); } public void testIntersectNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); - ASSERT.that(Multisets.intersection(ms1, ms2)).isEmpty(); + assertThat(Multisets.intersection(ms1, ms2)).isEmpty(); } public void testSum() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("b", "c")); - ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); + assertThat(Multisets.sum(ms1, ms2)).has().exactly("a", "a", "b", "b", "c"); } public void testSumEmptyNonempty() { Multiset<String> ms1 = HashMultiset.create(); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "a")); - ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); + assertThat(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); } public void testSumNonemptyEmpty() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(); - ASSERT.that(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); + assertThat(Multisets.sum(ms1, ms2)).has().exactly("a", "b", "a"); } public void testDifferenceWithNoRemovedElements() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a")); - ASSERT.that(Multisets.difference(ms1, ms2)).has().exactly("a", "b"); + assertThat(Multisets.difference(ms1, ms2)).has().exactly("a", "b"); } public void testDifferenceWithRemovedElement() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("b")); - ASSERT.that(Multisets.difference(ms1, ms2)).has().exactly("a", "a"); + assertThat(Multisets.difference(ms1, ms2)).has().exactly("a", "a"); } public void testDifferenceWithMoreElementsInSecondMultiset() { Multiset<String> ms1 = HashMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> ms2 = HashMultiset.create(Arrays.asList("a", "b", "b", "b")); Multiset<String> diff = Multisets.difference(ms1, ms2); - ASSERT.that(diff).has().item("a"); + assertThat(diff).has().item("a"); assertEquals(0, diff.count("b")); assertEquals(1, diff.count("a")); assertFalse(diff.contains("b")); @@ -205,24 +213,40 @@ public class MultisetsTest extends TestCase { Multiset<String> toRetain = HashMultiset.create(Arrays.asList("a", "b", "b")); assertTrue(Multisets.retainOccurrences(multiset, toRetain)); - ASSERT.that(multiset).has().exactly("a", "b").inOrder(); + assertThat(multiset).has().exactly("a", "b").inOrder(); } - public void testRemoveEmptyOccurrences() { + public void testRemoveEmptyOccurrencesMultiset() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a")); Multiset<String> toRemove = HashMultiset.create(); assertFalse(Multisets.removeOccurrences(multiset, toRemove)); - ASSERT.that(multiset).has().exactly("a", "a", "b").inOrder(); + assertThat(multiset).has().exactly("a", "a", "b").inOrder(); } - public void testRemoveOccurrences() { + public void testRemoveOccurrencesMultiset() { Multiset<String> multiset = TreeMultiset.create(Arrays.asList("a", "b", "a", "c")); Multiset<String> toRemove = HashMultiset.create(Arrays.asList("a", "b", "b")); assertTrue(Multisets.removeOccurrences(multiset, toRemove)); - ASSERT.that(multiset).has().exactly("a", "c").inOrder(); + assertThat(multiset).has().exactly("a", "c").inOrder(); + } + + public void testRemoveEmptyOccurrencesIterable() { + Multiset<String> multiset = + TreeMultiset.create(Arrays.asList("a", "b", "a")); + Iterable<String> toRemove = ImmutableList.of(); + assertFalse(Multisets.removeOccurrences(multiset, toRemove)); + assertThat(multiset).has().exactly("a", "a", "b").inOrder(); + } + + public void testRemoveOccurrencesMultisetIterable() { + Multiset<String> multiset = + TreeMultiset.create(Arrays.asList("a", "b", "a", "c")); + List<String> toRemove = Arrays.asList("a", "b", "b"); + assertTrue(Multisets.removeOccurrences(multiset, toRemove)); + assertThat(multiset).has().exactly("a", "c").inOrder(); } @SuppressWarnings("deprecation") @@ -242,11 +266,11 @@ public class MultisetsTest extends TestCase { ImmutableMultiset<String> sortedMultiset = Multisets.copyHighestCountFirst(multiset); - ASSERT.that(sortedMultiset.entrySet()).has().exactly( + assertThat(sortedMultiset.entrySet()).has().exactly( Multisets.immutableEntry("a", 3), Multisets.immutableEntry("c", 2), Multisets.immutableEntry("b", 1)).inOrder(); - ASSERT.that(sortedMultiset).has().exactly( + assertThat(sortedMultiset).has().exactly( "a", "a", "a", @@ -254,7 +278,7 @@ public class MultisetsTest extends TestCase { "c", "b").inOrder(); - ASSERT.that(Multisets.copyHighestCountFirst(ImmutableMultiset.of())).isEmpty(); + assertThat(Multisets.copyHighestCountFirst(ImmutableMultiset.of())).isEmpty(); } @GwtIncompatible("NullPointerTester") diff --git a/guava-tests/test/com/google/common/collect/NewCustomTableTest.java b/guava-tests/test/com/google/common/collect/NewCustomTableTest.java index c17282683..9355aad60 100644 --- a/guava-tests/test/com/google/common/collect/NewCustomTableTest.java +++ b/guava-tests/test/com/google/common/collect/NewCustomTableTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; @@ -51,11 +51,11 @@ public class NewCustomTableTest extends AbstractTableTest { public void testRowKeySetOrdering() { table = create("foo", 3, 'a', "bar", 1, 'b', "foo", 2, 'c'); - ASSERT.that(table.rowKeySet()).has().exactly("foo", "bar").inOrder(); + assertThat(table.rowKeySet()).has().exactly("foo", "bar").inOrder(); } public void testRowOrdering() { table = create("foo", 3, 'a', "bar", 1, 'b', "foo", 2, 'c'); - ASSERT.that(table.row("foo").keySet()).has().exactly(2, 3).inOrder(); + assertThat(table.row("foo").keySet()).has().exactly(2, 3).inOrder(); } } diff --git a/guava-tests/test/com/google/common/collect/ObjectArraysTest.java b/guava-tests/test/com/google/common/collect/ObjectArraysTest.java index 4c2cd85f2..c37985703 100644 --- a/guava-tests/test/com/google/common/collect/ObjectArraysTest.java +++ b/guava-tests/test/com/google/common/collect/ObjectArraysTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -98,7 +98,7 @@ public class ObjectArraysTest extends TestCase { String[] result = ObjectArrays.concat( new String[0], new String[] { "a", "b" }, String.class); assertEquals(String[].class, result.getClass()); - ASSERT.that(result).has().exactly("a", "b").inOrder(); + assertThat(result).asList().has().exactly("a", "b").inOrder(); } @GwtIncompatible("ObjectArrays.concat(Object[], Object[], Class)") @@ -106,7 +106,7 @@ public class ObjectArraysTest extends TestCase { String[] result = ObjectArrays.concat( new String[] { "a", "b" }, new String[0], String.class); assertEquals(String[].class, result.getClass()); - ASSERT.that(result).has().exactly("a", "b").inOrder(); + assertThat(result).asList().has().exactly("a", "b").inOrder(); } @GwtIncompatible("ObjectArrays.concat(Object[], Object[], Class)") @@ -114,7 +114,7 @@ public class ObjectArraysTest extends TestCase { String[] result = ObjectArrays.concat( new String[] { "a", "b" }, new String[] { "c", "d" }, String.class); assertEquals(String[].class, result.getClass()); - ASSERT.that(result).has().exactly("a", "b", "c", "d").inOrder(); + assertThat(result).asList().has().exactly("a", "b", "c", "d").inOrder(); } @GwtIncompatible("ObjectArrays.concat(Object[], Object[], Class)") @@ -170,32 +170,32 @@ public class ObjectArraysTest extends TestCase { public void testPrependZeroElements() { String[] result = ObjectArrays.concat("foo", new String[] {}); - ASSERT.that(result).has().item("foo"); + assertThat(result).asList().has().item("foo"); } public void testPrependOneElement() { String[] result = ObjectArrays.concat("foo", new String[] { "bar" }); - ASSERT.that(result).has().exactly("foo", "bar").inOrder(); + assertThat(result).asList().has().exactly("foo", "bar").inOrder(); } public void testPrependTwoElements() { String[] result = ObjectArrays.concat("foo", new String[] { "bar", "baz" }); - ASSERT.that(result).has().exactly("foo", "bar", "baz").inOrder(); + assertThat(result).asList().has().exactly("foo", "bar", "baz").inOrder(); } public void testAppendZeroElements() { String[] result = ObjectArrays.concat(new String[] {}, "foo"); - ASSERT.that(result).has().item("foo"); + assertThat(result).asList().has().item("foo"); } public void testAppendOneElement() { String[] result = ObjectArrays.concat(new String[] { "foo" }, "bar"); - ASSERT.that(result).has().exactly("foo", "bar").inOrder(); + assertThat(result).asList().has().exactly("foo", "bar").inOrder(); } public void testAppendTwoElements() { String[] result = ObjectArrays.concat(new String[] { "foo", "bar" }, "baz"); - ASSERT.that(result).has().exactly("foo", "bar", "baz").inOrder(); + assertThat(result).asList().has().exactly("foo", "bar", "baz").inOrder(); } public void testEmptyArrayToEmpty() { diff --git a/guava-tests/test/com/google/common/collect/OrderingTest.java b/guava-tests/test/com/google/common/collect/OrderingTest.java index 4af99d53d..8054740ec 100644 --- a/guava-tests/test/com/google/common/collect/OrderingTest.java +++ b/guava-tests/test/com/google/common/collect/OrderingTest.java @@ -20,8 +20,8 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.testing.SerializableTester.reserializeAndAssert; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -157,7 +157,7 @@ public class OrderingTest extends TestCase { = Ordering.explicit(2, 8, 6, 1, 7, 5, 3, 4, 0, 9); List<Integer> list = Arrays.asList(0, 3, 5, 6, 7, 8, 9); Collections.sort(list, c); - ASSERT.that(list).has().exactly(8, 6, 7, 5, 3, 0, 9).inOrder(); + assertThat(list).has().exactly(8, 6, 7, 5, 3, 0, 9).inOrder(); reserializeAndAssert(c); } diff --git a/guava-tests/test/com/google/common/collect/QueuesTest.java b/guava-tests/test/com/google/common/collect/QueuesTest.java index bffcb3970..d64caaeee 100644 --- a/guava-tests/test/com/google/common/collect/QueuesTest.java +++ b/guava-tests/test/com/google/common/collect/QueuesTest.java @@ -208,6 +208,17 @@ public class QueuesTest extends TestCase { assertEquals(100, buf.size()); } + public void testNewLinkedBlockingDequeCapacity() { + try { + Queues.newLinkedBlockingDeque(0); + fail("Should have thrown IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + // any capacity less than 1 should throw IllegalArgumentException + } + assertEquals(1, Queues.newLinkedBlockingDeque(1).remainingCapacity()); + assertEquals(11, Queues.newLinkedBlockingDeque(11).remainingCapacity()); + } + public void testNewLinkedBlockingQueueCapacity() { try { Queues.newLinkedBlockingQueue(0); diff --git a/guava-tests/test/com/google/common/collect/RegularImmutableTableTest.java b/guava-tests/test/com/google/common/collect/RegularImmutableTableTest.java index b76942b4c..d1f97f569 100644 --- a/guava-tests/test/com/google/common/collect/RegularImmutableTableTest.java +++ b/guava-tests/test/com/google/common/collect/RegularImmutableTableTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Table.Cell; @@ -62,7 +62,7 @@ public class RegularImmutableTableTest extends AbstractImmutableTableTest { public void testValues() { for (ImmutableTable<Character, Integer, String> testInstance : getTestInstances()) { - ASSERT.that(testInstance.values()) + assertThat(testInstance.values()) .has().exactly("foo", "bar", "baz") .inOrder(); } diff --git a/guava-tests/test/com/google/common/collect/SetsTest.java b/guava-tests/test/com/google/common/collect/SetsTest.java index e726f63f7..68a76c68f 100644 --- a/guava-tests/test/com/google/common/collect/SetsTest.java +++ b/guava-tests/test/com/google/common/collect/SetsTest.java @@ -21,19 +21,21 @@ import static com.google.common.collect.Sets.newEnumSet; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.Sets.powerSet; +import static com.google.common.collect.Sets.unmodifiableNavigableSet; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; -import static com.google.common.collect.testing.testers.CollectionIteratorTester.getIteratorKnownOrderRemoveSupportedMethod; +import static com.google.common.truth.Truth.assertThat; import static java.io.ObjectStreamConstants.TC_REFERENCE; import static java.io.ObjectStreamConstants.baseWireHandle; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.MinimalIterable; +import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; +import com.google.common.collect.testing.SafeTreeSet; import com.google.common.collect.testing.SetTestSuiteBuilder; import com.google.common.collect.testing.TestEnumSetGenerator; import com.google.common.collect.testing.TestStringSetGenerator; @@ -68,6 +70,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; @@ -180,6 +183,22 @@ public class SetsTest extends TestCase { CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); + suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { + @Override protected Set<String> create(String[] elements) { + SafeTreeSet<String> set = new SafeTreeSet<String>(Arrays.asList(elements)); + return Sets.unmodifiableNavigableSet(set); + } + + @Override + public List<String> order(List<String> insertionOrder) { + return Ordering.natural().sortedCopy(insertionOrder); + } + }) + .named("Sets.unmodifiableNavigableSet[TreeSet]") + .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, + CollectionFeature.SERIALIZABLE) + .createTestSuite()); + suite.addTest(testsForFilter()); suite.addTest(testsForFilterNoNulls()); suite.addTest(testsForFilterFiltered()); @@ -205,7 +224,6 @@ public class SetsTest extends TestCase { CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) - .suppressing(getIteratorKnownOrderRemoveSupportedMethod()) .createTestSuite(); } @@ -222,11 +240,35 @@ public class SetsTest extends TestCase { } }) .named("Sets.filter, no nulls") - .withFeatures(SetFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, - CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES) - .suppressing(getIteratorKnownOrderRemoveSupportedMethod()) + .withFeatures( + CollectionFeature.SUPPORTS_ADD, + CollectionFeature.SUPPORTS_REMOVE, + CollectionFeature.KNOWN_ORDER, + CollectionSize.ANY, + CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); + suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { + @Override public NavigableSet<String> create(String[] elements) { + NavigableSet<String> unfiltered = Sets.newTreeSet(); + unfiltered.add("yyy"); + unfiltered.addAll(ImmutableList.copyOf(elements)); + unfiltered.add("zzz"); + return Sets.filter(unfiltered, Collections2Test.LENGTH_1); + } + @Override + public List<String> order(List<String> insertionOrder) { + return Ordering.natural().sortedCopy(insertionOrder); + } + }) + .named("Sets.filter[NavigableSet]") + .withFeatures( + CollectionFeature.SUPPORTS_ADD, + CollectionFeature.SUPPORTS_REMOVE, + CollectionFeature.KNOWN_ORDER, + CollectionSize.ANY, + CollectionFeature.ALLOWS_NULL_QUERIES) + .createTestSuite()); return suite; } @@ -251,7 +293,6 @@ public class SetsTest extends TestCase { CollectionFeature.KNOWN_ORDER, CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES) - .suppressing(getIteratorKnownOrderRemoveSupportedMethod()) .createTestSuite(); } @@ -260,7 +301,7 @@ public class SetsTest extends TestCase { public void testImmutableEnumSet() { Set<SomeEnum> units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); - ASSERT.that(units).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); + assertThat(units).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); try { units.remove(SomeEnum.B); fail("ImmutableEnumSet should throw an exception on remove()"); @@ -275,7 +316,7 @@ public class SetsTest extends TestCase { public void testImmutableEnumSet_serialized() { Set<SomeEnum> units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); - ASSERT.that(units).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); + assertThat(units).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); Set<SomeEnum> copy = SerializableTester.reserializeAndAssert(units); assertTrue(copy instanceof ImmutableEnumSet); @@ -284,15 +325,15 @@ public class SetsTest extends TestCase { public void testImmutableEnumSet_fromIterable() { ImmutableSet<SomeEnum> none = Sets.immutableEnumSet(MinimalIterable.<SomeEnum>of()); - ASSERT.that(none).isEmpty(); + assertThat(none).isEmpty(); ImmutableSet<SomeEnum> one = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.B)); - ASSERT.that(one).has().item(SomeEnum.B); + assertThat(one).has().item(SomeEnum.B); ImmutableSet<SomeEnum> two = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.D, SomeEnum.B)); - ASSERT.that(two).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); + assertThat(two).has().exactly(SomeEnum.B, SomeEnum.D).inOrder(); } @GwtIncompatible("java serialization not supported in GWT.") @@ -447,7 +488,7 @@ public class SetsTest extends TestCase { assertTrue(set.isEmpty()); set.add(new Derived("foo")); set.add(new Derived("bar")); - ASSERT.that(set).has().exactly(new Derived("bar"), new Derived("foo")).inOrder(); + assertThat(set).has().exactly(new Derived("bar"), new Derived("foo")).inOrder(); } public void testNewTreeSetEmptyNonGeneric() { @@ -455,7 +496,7 @@ public class SetsTest extends TestCase { assertTrue(set.isEmpty()); set.add(new LegacyComparable("foo")); set.add(new LegacyComparable("bar")); - ASSERT.that(set).has() + assertThat(set).has() .exactly(new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } @@ -473,7 +514,7 @@ public class SetsTest extends TestCase { Iterable<Derived> iterable = Arrays.asList(new Derived("foo"), new Derived("bar")); TreeSet<Derived> set = Sets.newTreeSet(iterable); - ASSERT.that(set).has().exactly( + assertThat(set).has().exactly( new Derived("bar"), new Derived("foo")).inOrder(); } @@ -481,7 +522,7 @@ public class SetsTest extends TestCase { Iterable<LegacyComparable> iterable = Arrays.asList(new LegacyComparable("foo"), new LegacyComparable("bar")); TreeSet<LegacyComparable> set = Sets.newTreeSet(iterable); - ASSERT.that(set).has().exactly( + assertThat(set).has().exactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } @@ -583,7 +624,7 @@ public class SetsTest extends TestCase { Sets.newSetFromMap(new LinkedHashMap<Integer, Boolean>()); set.addAll(SOME_COLLECTION); Set<Integer> copy = SerializableTester.reserializeAndAssert(set); - ASSERT.that(copy).has().exactly(0, 1).inOrder(); + assertThat(copy).has().exactly(0, 1).inOrder(); } public void testNewSetFromMapIllegal() { @@ -603,7 +644,7 @@ public class SetsTest extends TestCase { */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_zeroary() { - ASSERT.that(Sets.cartesianProduct()).has().exactly(list()); + assertThat(Sets.cartesianProduct()).has().exactly(list()); } /** @@ -612,7 +653,7 @@ public class SetsTest extends TestCase { */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unary() { - ASSERT.that(Sets.cartesianProduct(set(1, 2))).has().exactly(list(1), list(2)); + assertThat(Sets.cartesianProduct(set(1, 2))).has().exactly(list(1), list(2)); } @SuppressWarnings("unchecked") // varargs! @@ -641,24 +682,24 @@ public class SetsTest extends TestCase { @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x1() { - ASSERT.that(Sets.cartesianProduct(set(1), set(2))).has().item(list(1, 2)); + assertThat(Sets.cartesianProduct(set(1), set(2))).has().item(list(1, 2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x2() { - ASSERT.that(Sets.cartesianProduct(set(1), set(2, 3))) + assertThat(Sets.cartesianProduct(set(1), set(2, 3))) .has().exactly(list(1, 2), list(1, 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary2x2() { - ASSERT.that(Sets.cartesianProduct(set(1, 2), set(3, 4))) + assertThat(Sets.cartesianProduct(set(1, 2), set(3, 4))) .has().exactly(list(1, 3), list(1, 4), list(2, 3), list(2, 4)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_2x2x2() { - ASSERT.that(Sets.cartesianProduct(set(0, 1), set(0, 1), set(0, 1))).has().exactly( + assertThat(Sets.cartesianProduct(set(0, 1), set(0, 1), set(0, 1))).has().exactly( list(0, 0, 0), list(0, 0, 1), list(0, 1, 0), list(0, 1, 1), list(1, 0, 0), list(1, 0, 1), list(1, 1, 0), list(1, 1, 1)).inOrder(); } @@ -683,7 +724,7 @@ public class SetsTest extends TestCase { List<Object> exp3 = list((Object) 2, "3"); List<Object> exp4 = list((Object) 2, "4"); - ASSERT.that(Sets.<Object>cartesianProduct(x, y)) + assertThat(Sets.<Object>cartesianProduct(x, y)) .has().exactly(exp1, exp2, exp3, exp4).inOrder(); } @@ -1028,6 +1069,48 @@ public class SetsTest extends TestCase { private static final long serialVersionUID = 0; } + @GwtIncompatible("NavigableSet") + public void testUnmodifiableNavigableSet() { + TreeSet<Integer> mod = Sets.newTreeSet(); + mod.add(1); + mod.add(2); + mod.add(3); + + NavigableSet<Integer> unmod = unmodifiableNavigableSet(mod); + + /* Unmodifiable is a view. */ + mod.add(4); + assertTrue(unmod.contains(4)); + assertTrue(unmod.descendingSet().contains(4)); + + ensureNotDirectlyModifiable(unmod); + ensureNotDirectlyModifiable(unmod.descendingSet()); + ensureNotDirectlyModifiable(unmod.headSet(2)); + ensureNotDirectlyModifiable(unmod.headSet(2, true)); + ensureNotDirectlyModifiable(unmod.tailSet(2)); + ensureNotDirectlyModifiable(unmod.tailSet(2, true)); + ensureNotDirectlyModifiable(unmod.subSet(1, 3)); + ensureNotDirectlyModifiable(unmod.subSet(1, true, 3, true)); + + /* UnsupportedOperationException on indirect modifications. */ + NavigableSet<Integer> reverse = unmod.descendingSet(); + try { + reverse.add(4); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + reverse.addAll(Collections.singleton(4)); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + reverse.remove(4); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + } + void ensureNotDirectlyModifiable(SortedSet<Integer> unmod) { try { unmod.add(4); @@ -1052,4 +1135,47 @@ public class SetsTest extends TestCase { } catch (UnsupportedOperationException expected) { } } + + @GwtIncompatible("NavigableSet") + void ensureNotDirectlyModifiable(NavigableSet<Integer> unmod) { + try { + unmod.add(4); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.remove(4); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.addAll(Collections.singleton(4)); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.pollFirst(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + unmod.pollLast(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + Iterator<Integer> iterator = unmod.iterator(); + iterator.next(); + iterator.remove(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + try { + Iterator<Integer> iterator = unmod.descendingIterator(); + iterator.next(); + iterator.remove(); + fail("UnsupportedOperationException expected"); + } catch (UnsupportedOperationException expected) { + } + } } diff --git a/guava-tests/test/com/google/common/collect/SingletonImmutableTableTest.java b/guava-tests/test/com/google/common/collect/SingletonImmutableTableTest.java index 8fba12984..f16498bf5 100644 --- a/guava-tests/test/com/google/common/collect/SingletonImmutableTableTest.java +++ b/guava-tests/test/com/google/common/collect/SingletonImmutableTableTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -126,7 +126,7 @@ public class SingletonImmutableTableTest extends AbstractImmutableTableTest { } public void testValues() { - ASSERT.that(testTable.values()).has().item("blah"); + assertThat(testTable.values()).has().item("blah"); } @Override Iterable<ImmutableTable<Character, Integer, String>> getTestInstances() { diff --git a/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java b/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java new file mode 100644 index 000000000..4e9928060 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/SynchronizedDequeTest.java @@ -0,0 +1,296 @@ +/* + * Copyright (C) 2013 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.collect; + +import junit.framework.TestCase; + +import java.util.Collection; +import java.util.Deque; +import java.util.Iterator; + +/** + * Tests for {@link Synchronized#deque} and {@link Queues#synchronizedDeque}. + * + * @author Kurt Alfred Kluever + */ +public class SynchronizedDequeTest extends TestCase { + + protected Deque<String> create() { + TestDeque<String> inner = new TestDeque<String>(); + Deque<String> outer = Synchronized.deque(inner, inner.mutex); + outer.add("foo"); // necessary because we try to remove elements later on + return outer; + } + + private static final class TestDeque<E> implements Deque<E> { + private final Deque<E> delegate = Lists.newLinkedList(); + public final Object mutex = new Integer(1); // something Serializable + + @Override + public boolean offer(E o) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.offer(o); + } + + @Override + public E poll() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.poll(); + } + + @Override + public E remove() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.remove(); + } + + @Override + public E peek() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.peek(); + } + + @Override + public E element() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.element(); + } + + @Override + public Iterator<E> iterator() { + // We explicitly don't lock for iterator() + assertFalse(Thread.holdsLock(mutex)); + return delegate.iterator(); + } + + @Override + public int size() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.size(); + } + + @Override + public boolean removeAll(Collection<?> collection) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.removeAll(collection); + } + + @Override + public boolean isEmpty() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.isEmpty(); + } + + @Override + public boolean contains(Object object) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.contains(object); + } + + @Override + public boolean add(E element) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.add(element); + } + + @Override + public boolean remove(Object object) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.remove(object); + } + + @Override + public boolean containsAll(Collection<?> collection) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.containsAll(collection); + } + + @Override + public boolean addAll(Collection<? extends E> collection) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.addAll(collection); + } + + @Override + public boolean retainAll(Collection<?> collection) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.retainAll(collection); + } + + @Override + public void clear() { + assertTrue(Thread.holdsLock(mutex)); + delegate.clear(); + } + + @Override + public Object[] toArray() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.toArray(); + } + + @Override + public <T> T[] toArray(T[] array) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.toArray(array); + } + + @Override + public void addFirst(E e) { + assertTrue(Thread.holdsLock(mutex)); + delegate.addFirst(e); + } + + @Override + public void addLast(E e) { + assertTrue(Thread.holdsLock(mutex)); + delegate.addLast(e); + } + + @Override + public boolean offerFirst(E e) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.offerFirst(e); + } + + @Override + public boolean offerLast(E e) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.offerLast(e); + } + + @Override + public E removeFirst() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.removeFirst(); + } + + @Override + public E removeLast() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.removeLast(); + } + + @Override + public E pollFirst() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.pollFirst(); + } + + @Override + public E pollLast() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.pollLast(); + } + + @Override + public E getFirst() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.getFirst(); + } + + @Override + public E getLast() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.getLast(); + } + + @Override + public E peekFirst() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.peekFirst(); + } + + @Override + public E peekLast() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.peekLast(); + } + + @Override + public boolean removeFirstOccurrence(Object o) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.removeFirstOccurrence(o); + } + + @Override + public boolean removeLastOccurrence(Object o) { + assertTrue(Thread.holdsLock(mutex)); + return delegate.removeLastOccurrence(o); + } + + @Override + public void push(E e) { + assertTrue(Thread.holdsLock(mutex)); + delegate.push(e); + } + + @Override + public E pop() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.pop(); + } + + @Override + public Iterator<E> descendingIterator() { + assertTrue(Thread.holdsLock(mutex)); + return delegate.descendingIterator(); + } + + private static final long serialVersionUID = 0; + } + + public void testHoldsLockOnAllOperations() { + create().element(); + create().offer("foo"); + create().peek(); + create().poll(); + create().remove(); + create().add("foo"); + create().addAll(ImmutableList.of("foo")); + create().clear(); + create().contains("foo"); + create().containsAll(ImmutableList.of("foo")); + create().equals(ImmutableList.of("foo")); + create().hashCode(); + create().isEmpty(); + create().iterator(); + create().remove("foo"); + create().removeAll(ImmutableList.of("foo")); + create().retainAll(ImmutableList.of("foo")); + create().size(); + create().toArray(); + create().toArray(new String[] { "foo" }); + create().addFirst("e"); + create().addLast("e"); + create().offerFirst("e"); + create().offerLast("e"); + create().removeFirst(); + create().removeLast(); + create().pollFirst(); + create().pollLast(); + create().getFirst(); + create().getLast(); + create().peekFirst(); + create().peekLast(); + create().removeFirstOccurrence("e"); + create().removeLastOccurrence("e"); + create().push("e"); + create().pop(); + create().descendingIterator(); + } +} diff --git a/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java b/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java index 2b85d7d73..e7a6aac0d 100644 --- a/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/SynchronizedMultimapTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; @@ -204,11 +204,11 @@ public class SynchronizedMultimapTest extends TestCase { ArrayListMultimap.<String, Integer>create()); multimap.putAll("foo", Arrays.asList(3, -1, 2, 4, 1)); multimap.putAll("bar", Arrays.asList(1, 2, 3, 1)); - ASSERT.that(multimap.removeAll("foo")).has().exactly(3, -1, 2, 4, 1).inOrder(); + assertThat(multimap.removeAll("foo")).has().exactly(3, -1, 2, 4, 1).inOrder(); assertFalse(multimap.containsKey("foo")); - ASSERT.that(multimap.replaceValues("bar", Arrays.asList(6, 5))) + assertThat(multimap.replaceValues("bar", Arrays.asList(6, 5))) .has().exactly(1, 2, 3, 1).inOrder(); - ASSERT.that(multimap.get("bar")).has().exactly(6, 5).inOrder(); + assertThat(multimap.get("bar")).has().exactly(6, 5).inOrder(); } public void testSynchronizedSortedSetMultimap() { @@ -217,11 +217,11 @@ public class SynchronizedMultimapTest extends TestCase { TreeMultimap.<String, Integer>create()); multimap.putAll("foo", Arrays.asList(3, -1, 2, 4, 1)); multimap.putAll("bar", Arrays.asList(1, 2, 3, 1)); - ASSERT.that(multimap.removeAll("foo")).has().exactly(-1, 1, 2, 3, 4).inOrder(); + assertThat(multimap.removeAll("foo")).has().exactly(-1, 1, 2, 3, 4).inOrder(); assertFalse(multimap.containsKey("foo")); - ASSERT.that(multimap.replaceValues("bar", Arrays.asList(6, 5))) + assertThat(multimap.replaceValues("bar", Arrays.asList(6, 5))) .has().exactly(1, 2, 3).inOrder(); - ASSERT.that(multimap.get("bar")).has().exactly(5, 6).inOrder(); + assertThat(multimap.get("bar")).has().exactly(5, 6).inOrder(); } public void testSynchronizedArrayListMultimapRandomAccess() { diff --git a/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java b/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java new file mode 100644 index 000000000..5b78e9b8f --- /dev/null +++ b/guava-tests/test/com/google/common/collect/SynchronizedNavigableMapTest.java @@ -0,0 +1,393 @@ +/* + * 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; + +import com.google.common.collect.Synchronized.SynchronizedNavigableMap; +import com.google.common.collect.Synchronized.SynchronizedNavigableSet; +import com.google.common.collect.Synchronized.SynchronizedSortedMap; +import com.google.common.collect.testing.NavigableMapTestSuiteBuilder; +import com.google.common.collect.testing.SafeTreeMap; +import com.google.common.collect.testing.TestStringSortedMapGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; +import com.google.common.testing.SerializableTester; + +import junit.framework.TestSuite; + +import java.io.Serializable; +import java.util.Comparator; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.NavigableSet; +import java.util.SortedMap; + +/** + * Tests for {@link Maps#synchronizedNavigableMap(NavigableMap)}. + * + * @author Louis Wasserman + */ +public class SynchronizedNavigableMapTest extends SynchronizedMapTest { + @Override protected <K, V> NavigableMap<K, V> create() { + @SuppressWarnings("unchecked") + NavigableMap<K, V> innermost = new SafeTreeMap<K, V>( + (Comparator<? super K>) Ordering.natural().nullsFirst()); + TestMap<K, V> inner = new TestMap<K, V>(innermost, mutex); + NavigableMap<K, V> outer = Synchronized.navigableMap(inner, mutex); + return outer; + } + + static class TestEntry<K, V> extends ForwardingMapEntry<K, V> + implements Serializable { + private final Entry<K, V> delegate; + private final Object mutex; + + TestEntry(Entry<K, V> delegate, Object mutex) { + this.delegate = delegate; + this.mutex = mutex; + } + + @Override protected Entry<K, V> delegate() { + return delegate; + } + + @Override public boolean equals(Object object) { + assertTrue(Thread.holdsLock(mutex)); + return super.equals(object); + } + + @Override public K getKey() { + assertTrue(Thread.holdsLock(mutex)); + return super.getKey(); + } + + @Override public V getValue() { + assertTrue(Thread.holdsLock(mutex)); + return super.getValue(); + } + + @Override public int hashCode() { + assertTrue(Thread.holdsLock(mutex)); + return super.hashCode(); + } + + @Override public V setValue(V value) { + assertTrue(Thread.holdsLock(mutex)); + return super.setValue(value); + } + + private static final long serialVersionUID = 0; + } + + static class TestMap<K, V> extends SynchronizedMapTest.TestMap<K, V> + implements NavigableMap<K, V> { + + public TestMap(NavigableMap<K, V> delegate, Object mutex) { + super(delegate, mutex); + } + + @Override protected NavigableMap<K, V> delegate() { + return (NavigableMap<K, V>) super.delegate(); + } + + @Override public Entry<K, V> ceilingEntry(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().ceilingEntry(key); + } + + @Override public K ceilingKey(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().ceilingKey(key); + } + + @Override public NavigableSet<K> descendingKeySet() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().descendingKeySet(); + } + + @Override public NavigableMap<K, V> descendingMap() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().descendingMap(); + } + + @Override public Entry<K, V> firstEntry() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().firstEntry(); + } + + @Override public Entry<K, V> floorEntry(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().floorEntry(key); + } + + @Override public K floorKey(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().floorKey(key); + } + + @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().headMap(toKey, inclusive); + } + + @Override public SortedMap<K, V> headMap(K toKey) { + return headMap(toKey, false); + } + + @Override public Entry<K, V> higherEntry(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().higherEntry(key); + } + + @Override public K higherKey(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().higherKey(key); + } + + @Override public Entry<K, V> lastEntry() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().lastEntry(); + } + + @Override public Entry<K, V> lowerEntry(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().lowerEntry(key); + } + + @Override public K lowerKey(K key) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().lowerKey(key); + } + + @Override public NavigableSet<K> navigableKeySet() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().navigableKeySet(); + } + + @Override public Entry<K, V> pollFirstEntry() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().pollFirstEntry(); + } + + @Override public Entry<K, V> pollLastEntry() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().pollLastEntry(); + } + + @Override public NavigableMap<K, V> subMap( + K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive); + } + + @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { + return delegate().subMap(fromKey, true, toKey, false); + } + + @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().tailMap(fromKey, inclusive); + } + + @Override public SortedMap<K, V> tailMap(K fromKey) { + return tailMap(fromKey, true); + } + + @Override public Comparator<? super K> comparator() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().comparator(); + } + + @Override public K firstKey() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().firstKey(); + } + + @Override public K lastKey() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().lastKey(); + } + + private static final long serialVersionUID = 0; + } + + public static TestSuite suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(SynchronizedNavigableMapTest.class); + suite.addTest( + NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() { + private final Object mutex = new Integer(1); + + @Override protected SortedMap<String, String> create( + Entry<String, String>[] entries) { + NavigableMap<String, String> innermost = + new SafeTreeMap<String, String>(); + for (Entry<String, String> entry : entries) { + innermost.put(entry.getKey(), entry.getValue()); + } + TestMap<String, String> inner = + new TestMap<String, String>(innermost, mutex); + NavigableMap<String, String> outer = + Synchronized.navigableMap(inner, mutex); + return outer; + } + }).named("Maps.synchronizedNavigableMap[SafeTreeMap]") + .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, + MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_VALUES, + CollectionFeature.SUPPORTS_ITERATOR_REMOVE) + .createTestSuite()); + + return suite; + } + + public void testComparator() { + create().comparator(); + } + + public void testCeilingEntry() { + create().ceilingEntry("a"); + } + + public void testCeilingKey() { + create().ceilingKey("a"); + } + + public void testDescendingKeySet() { + NavigableMap<String, Integer> map = create(); + NavigableSet<String> descendingKeySet = map.descendingKeySet(); + assertTrue(descendingKeySet instanceof SynchronizedNavigableSet); + assertSame( + mutex, ((SynchronizedNavigableSet<String>) descendingKeySet).mutex); + } + + public void testDescendingMap() { + NavigableMap<String, Integer> map = create(); + NavigableMap<String, Integer> descendingMap = map.descendingMap(); + assertTrue(descendingMap instanceof SynchronizedNavigableMap); + assertSame(mutex, + ((SynchronizedNavigableMap<String, Integer>) descendingMap).mutex); + } + + public void testFirstEntry() { + create().firstEntry(); + } + + public void testFirstKey() { + NavigableMap<String, Integer> map = create(); + map.put("a", 1); + map.firstKey(); + } + + public void testFloorEntry() { + create().floorEntry("a"); + } + + public void testFloorKey() { + create().floorKey("a"); + } + + public void testHeadMap_K() { + NavigableMap<String, Integer> map = create(); + SortedMap<String, Integer> headMap = map.headMap("a"); + assertTrue(headMap instanceof SynchronizedSortedMap); + assertSame(mutex, ((SynchronizedSortedMap<String, Integer>) headMap).mutex); + } + + public void testHeadMap_K_B() { + NavigableMap<String, Integer> map = create(); + NavigableMap<String, Integer> headMap = map.headMap("a", true); + assertTrue(headMap instanceof SynchronizedNavigableMap); + assertSame( + mutex, ((SynchronizedNavigableMap<String, Integer>) headMap).mutex); + } + + public void testHigherEntry() { + create().higherEntry("a"); + } + + public void testHigherKey() { + create().higherKey("a"); + } + + public void testLastEntry() { + create().lastEntry(); + } + + public void testLastKey() { + NavigableMap<String, Integer> map = create(); + map.put("a", 1); + map.lastKey(); + } + + public void testLowerEntry() { + create().lowerEntry("a"); + } + + public void testLowerKey() { + create().lowerKey("a"); + } + + public void testNavigableKeySet() { + NavigableMap<String, Integer> map = create(); + NavigableSet<String> navigableKeySet = map.navigableKeySet(); + assertTrue(navigableKeySet instanceof SynchronizedNavigableSet); + assertSame( + mutex, ((SynchronizedNavigableSet<String>) navigableKeySet).mutex); + } + + public void testPollFirstEntry() { + create().pollFirstEntry(); + } + + public void testPollLastEntry() { + create().pollLastEntry(); + } + + public void testSubMap_K_K() { + NavigableMap<String, Integer> map = create(); + SortedMap<String, Integer> subMap = map.subMap("a", "b"); + assertTrue(subMap instanceof SynchronizedSortedMap); + assertSame(mutex, ((SynchronizedSortedMap<String, Integer>) subMap).mutex); + } + + public void testSubMap_K_B_K_B() { + NavigableMap<String, Integer> map = create(); + NavigableMap<String, Integer> subMap = map.subMap("a", true, "b", false); + assertTrue(subMap instanceof SynchronizedNavigableMap); + assertSame( + mutex, ((SynchronizedNavigableMap<String, Integer>) subMap).mutex); + } + + public void testTailMap_K() { + NavigableMap<String, Integer> map = create(); + SortedMap<String, Integer> subMap = map.tailMap("a"); + assertTrue(subMap instanceof SynchronizedSortedMap); + assertSame(mutex, ((SynchronizedSortedMap<String, Integer>) subMap).mutex); + } + + public void testTailMap_K_B() { + NavigableMap<String, Integer> map = create(); + NavigableMap<String, Integer> subMap = map.tailMap("a", true); + assertTrue(subMap instanceof SynchronizedNavigableMap); + assertSame( + mutex, ((SynchronizedNavigableMap<String, Integer>) subMap).mutex); + } + + @Override public void testSerialization() { + SerializableTester.reserializeAndAssert(create()); + } +} diff --git a/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java b/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java new file mode 100644 index 000000000..5bf965abb --- /dev/null +++ b/guava-tests/test/com/google/common/collect/SynchronizedNavigableSetTest.java @@ -0,0 +1,225 @@ +/* + * 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; + +import com.google.common.collect.Synchronized.SynchronizedNavigableSet; +import com.google.common.collect.Synchronized.SynchronizedSortedSet; +import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; +import com.google.common.collect.testing.SafeTreeSet; +import com.google.common.collect.testing.TestStringSortedSetGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.NavigableSet; +import java.util.SortedSet; +import java.util.TreeSet; + +/** + * Tests for {@link Sets#synchronizedNavigableSet(NavigableSet)}. + * + * @author Louis Wasserman + */ +public class SynchronizedNavigableSetTest extends TestCase { + private static final Object MUTEX = new Integer(1); // something Serializable + + @SuppressWarnings("unchecked") + protected <E> NavigableSet<E> create() { + TestSet<E> inner = new TestSet<E>( + new TreeSet<E>((Comparator<E>) Ordering.natural().nullsFirst()), MUTEX); + NavigableSet<E> outer = + Synchronized.navigableSet(inner, MUTEX); + return outer; + } + + static class TestSet<E> extends SynchronizedSetTest.TestSet<E> + implements NavigableSet<E> { + + TestSet(NavigableSet<E> delegate, Object mutex) { + super(delegate, mutex); + } + + @Override protected NavigableSet<E> delegate() { + return (NavigableSet<E>) super.delegate(); + } + + @Override public E ceiling(E e) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().ceiling(e); + } + + @Override public Iterator<E> descendingIterator() { + return delegate().descendingIterator(); + } + + @Override public NavigableSet<E> descendingSet() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().descendingSet(); + } + + @Override public E floor(E e) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().floor(e); + } + + @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().headSet(toElement, inclusive); + } + + @Override public SortedSet<E> headSet(E toElement) { + return headSet(toElement, false); + } + + @Override public E higher(E e) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().higher(e); + } + + @Override public E lower(E e) { + return delegate().lower(e); + } + + @Override public E pollFirst() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().pollFirst(); + } + + @Override public E pollLast() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().pollLast(); + } + + @Override public NavigableSet<E> subSet(E fromElement, + boolean fromInclusive, E toElement, boolean toInclusive) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().subSet( + fromElement, fromInclusive, toElement, toInclusive); + } + + @Override public SortedSet<E> subSet(E fromElement, E toElement) { + return subSet(fromElement, true, toElement, false); + } + + @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { + assertTrue(Thread.holdsLock(mutex)); + return delegate().tailSet(fromElement, inclusive); + } + + @Override public SortedSet<E> tailSet(E fromElement) { + return tailSet(fromElement, true); + } + + @Override public Comparator<? super E> comparator() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().comparator(); + } + + @Override public E first() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().first(); + } + + @Override public E last() { + assertTrue(Thread.holdsLock(mutex)); + return delegate().last(); + } + + private static final long serialVersionUID = 0; + } + + public static TestSuite suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(SynchronizedNavigableSetTest.class); + suite.addTest( + NavigableSetTestSuiteBuilder.using(new TestStringSortedSetGenerator() { + + @Override protected NavigableSet<String> create(String[] elements) { + NavigableSet<String> innermost = new SafeTreeSet<String>(); + Collections.addAll(innermost, elements); + TestSet<String> inner = new TestSet<String>(innermost, MUTEX); + NavigableSet<String> outer = + Synchronized.navigableSet(inner, MUTEX); + return outer; + } + + @Override public List<String> order(List<String> insertionOrder) { + return Ordering.natural().sortedCopy(insertionOrder); + } + }).named("Sets.synchronizedNavigableSet[SafeTreeSet]") + .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, + CollectionFeature.GENERAL_PURPOSE, CollectionFeature.SERIALIZABLE) + .createTestSuite()); + + return suite; + } + + public void testDescendingSet() { + NavigableSet<String> map = create(); + NavigableSet<String> descendingSet = map.descendingSet(); + assertTrue(descendingSet instanceof SynchronizedNavigableSet); + assertSame(MUTEX, ((SynchronizedNavigableSet<String>) descendingSet).mutex); + } + + public void testHeadSet_E() { + NavigableSet<String> map = create(); + SortedSet<String> headSet = map.headSet("a"); + assertTrue(headSet instanceof SynchronizedSortedSet); + assertSame(MUTEX, ((SynchronizedSortedSet<String>) headSet).mutex); + } + + public void testHeadSet_E_B() { + NavigableSet<String> map = create(); + NavigableSet<String> headSet = map.headSet("a", true); + assertTrue(headSet instanceof SynchronizedNavigableSet); + assertSame(MUTEX, ((SynchronizedNavigableSet<String>) headSet).mutex); + } + + public void testSubSet_E_E() { + NavigableSet<String> map = create(); + SortedSet<String> subSet = map.subSet("a", "b"); + assertTrue(subSet instanceof SynchronizedSortedSet); + assertSame(MUTEX, ((SynchronizedSortedSet<String>) subSet).mutex); + } + + public void testSubSet_E_B_E_B() { + NavigableSet<String> map = create(); + NavigableSet<String> subSet = map.subSet("a", false, "b", true); + assertTrue(subSet instanceof SynchronizedNavigableSet); + assertSame(MUTEX, ((SynchronizedNavigableSet<String>) subSet).mutex); + } + + public void testTailSet_E() { + NavigableSet<String> map = create(); + SortedSet<String> tailSet = map.tailSet("a"); + assertTrue(tailSet instanceof SynchronizedSortedSet); + assertSame(MUTEX, ((SynchronizedSortedSet<String>) tailSet).mutex); + } + + public void testTailSet_E_B() { + NavigableSet<String> map = create(); + NavigableSet<String> tailSet = map.tailSet("a", true); + assertTrue(tailSet instanceof SynchronizedNavigableSet); + assertSame(MUTEX, ((SynchronizedNavigableSet<String>) tailSet).mutex); + } +} diff --git a/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java b/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java index 1e12b1771..292a3b7c9 100644 --- a/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java +++ b/guava-tests/test/com/google/common/collect/TreeBasedTableTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -154,8 +154,8 @@ public class TreeBasedTableTest extends AbstractTableTest { table.put("foo", 12, 'b'); table.put("bar", 5, 'c'); table.put("cat", 8, 'd'); - ASSERT.that(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); - ASSERT.that(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); + assertThat(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); + assertThat(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); } public void testCreateCopy() { @@ -166,8 +166,8 @@ public class TreeBasedTableTest extends AbstractTableTest { original.put("bar", 5, 'c'); original.put("cat", 8, 'd'); table = TreeBasedTable.create(original); - ASSERT.that(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); - ASSERT.that(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); + assertThat(table.rowKeySet()).has().exactly("foo", "cat", "bar").inOrder(); + assertThat(table.row("foo").keySet()).has().exactly(12, 3).inOrder(); assertEquals(original, table); } diff --git a/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java b/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java index 68b4fd9f7..c6ec282d9 100644 --- a/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java +++ b/guava-tests/test/com/google/common/collect/TreeMultimapExplicitTest.java @@ -16,7 +16,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -99,13 +99,13 @@ public class TreeMultimapExplicitTest extends TestCase { tree.put("google", 6); tree.put("tree", 0); tree.put("tree", 3); - ASSERT.that(tree.keySet()).has().exactly("tree", "google").inOrder(); - ASSERT.that(tree.get("google")).has().exactly(6, 2).inOrder(); + assertThat(tree.keySet()).has().exactly("tree", "google").inOrder(); + assertThat(tree.get("google")).has().exactly(6, 2).inOrder(); TreeMultimap<String, Integer> copy = TreeMultimap.create(tree); assertEquals(tree, copy); - ASSERT.that(copy.keySet()).has().exactly("google", "tree").inOrder(); - ASSERT.that(copy.get("google")).has().exactly(2, 6).inOrder(); + assertThat(copy.keySet()).has().exactly("google", "tree").inOrder(); + assertThat(copy.get("google")).has().exactly(2, 6).inOrder(); assertEquals(Ordering.natural(), copy.keyComparator()); assertEquals(Ordering.natural(), copy.valueComparator()); assertEquals(Ordering.natural(), copy.get("google").comparator()); @@ -130,14 +130,14 @@ public class TreeMultimapExplicitTest extends TestCase { public void testOrderedGet() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.get(null)).has().exactly(7, 3, 1).inOrder(); - ASSERT.that(multimap.get("google")).has().exactly(6, 2).inOrder(); - ASSERT.that(multimap.get("tree")).has().exactly(null, 0).inOrder(); + assertThat(multimap.get(null)).has().exactly(7, 3, 1).inOrder(); + assertThat(multimap.get("google")).has().exactly(6, 2).inOrder(); + assertThat(multimap.get("tree")).has().exactly(null, 0).inOrder(); } public void testOrderedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.keySet()).has().exactly(null, "tree", "google").inOrder(); + assertThat(multimap.keySet()).has().exactly(null, "tree", "google").inOrder(); } public void testOrderedAsMapEntries() { @@ -146,18 +146,18 @@ public class TreeMultimapExplicitTest extends TestCase { multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = iterator.next(); assertEquals(null, entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(7, 3, 1); + assertThat(entry.getValue()).has().exactly(7, 3, 1); entry = iterator.next(); assertEquals("tree", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(null, 0); + assertThat(entry.getValue()).has().exactly(null, 0); entry = iterator.next(); assertEquals("google", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(6, 2); + assertThat(entry.getValue()).has().exactly(6, 2); } public void testOrderedEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.entries()).has().exactly( + assertThat(multimap.entries()).has().exactly( Maps.immutableEntry((String) null, 7), Maps.immutableEntry((String) null, 3), Maps.immutableEntry((String) null, 1), @@ -169,7 +169,7 @@ public class TreeMultimapExplicitTest extends TestCase { public void testOrderedValues() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.values()).has().exactly(7, 3, 1, null, 0, 6, 2).inOrder(); + assertThat(multimap.values()).has().exactly(7, 3, 1, null, 0, 6, 2).inOrder(); } public void testComparator() { @@ -211,8 +211,8 @@ public class TreeMultimapExplicitTest extends TestCase { TreeMultimap<String, Integer> multimap = createPopulate(); TreeMultimap<String, Integer> copy = SerializableTester.reserializeAndAssert(multimap); - ASSERT.that(copy.values()).has().exactly(7, 3, 1, null, 0, 6, 2).inOrder(); - ASSERT.that(copy.keySet()).has().exactly(null, "tree", "google").inOrder(); + assertThat(copy.values()).has().exactly(7, 3, 1, null, 0, 6, 2).inOrder(); + assertThat(copy.keySet()).has().exactly(null, "tree", "google").inOrder(); assertEquals(multimap.keyComparator(), copy.keyComparator()); assertEquals(multimap.valueComparator(), copy.valueComparator()); } diff --git a/guava-tests/test/com/google/common/collect/TreeMultimapNaturalTest.java b/guava-tests/test/com/google/common/collect/TreeMultimapNaturalTest.java index f1f52f611..b0edc7164 100644 --- a/guava-tests/test/com/google/common/collect/TreeMultimapNaturalTest.java +++ b/guava-tests/test/com/google/common/collect/TreeMultimapNaturalTest.java @@ -16,11 +16,19 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.DerivedComparable; +import com.google.common.collect.testing.Helpers; +import com.google.common.collect.testing.NavigableMapTestSuiteBuilder; +import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.TestSortedMapGenerator; +import com.google.common.collect.testing.TestStringSetGenerator; +import com.google.common.collect.testing.TestStringSortedSetGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; @@ -40,6 +48,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; @@ -92,6 +102,153 @@ public class TreeMultimapNaturalTest extends TestCase { CollectionFeature.SERIALIZABLE, CollectionSize.ANY) .createTestSuite()); + suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSortedSetGenerator() { + @Override + protected NavigableSet<String> create(String[] elements) { + TreeMultimap<String, Integer> multimap = TreeMultimap.create( + Ordering.natural().nullsFirst(), Ordering.natural()); + for (int i = 0; i < elements.length; i++) { + multimap.put(elements[i], i); + } + return multimap.keySet(); + } + + @Override + public List<String> order(List<String> insertionOrder) { + return Ordering.natural().nullsFirst().sortedCopy(insertionOrder); + } + }) + .named("TreeMultimap.keySet") + .withFeatures( + CollectionFeature.ALLOWS_NULL_VALUES, + CollectionFeature.REMOVE_OPERATIONS, + CollectionFeature.KNOWN_ORDER, + CollectionSize.ANY) + .createTestSuite()); + suite.addTest(NavigableMapTestSuiteBuilder.using( + new TestSortedMapGenerator<String, Collection<String>>() { + + @Override + public String[] createKeyArray(int length) { + return new String[length]; + } + + @SuppressWarnings("unchecked") + @Override + public Collection<String>[] createValueArray(int length) { + return new Collection[length]; + } + + @Override + public SampleElements<Entry<String, Collection<String>>> samples() { + return new SampleElements<Entry<String, Collection<String>>>( + Helpers.mapEntry("a", (Collection<String>) ImmutableSortedSet.of("alex")), + Helpers.mapEntry("b", (Collection<String>) ImmutableSortedSet.of("bob", "bagel")), + Helpers.mapEntry("c", (Collection<String>) ImmutableSortedSet.of("carl", "carol")), + Helpers.mapEntry("d", (Collection<String>) ImmutableSortedSet.of("david", "dead")), + Helpers.mapEntry("e", (Collection<String>) ImmutableSortedSet.of("eric", "elaine"))); + } + + @SuppressWarnings("unchecked") + @Override + public Entry<String, Collection<String>>[] createArray(int length) { + return new Entry[length]; + } + + @Override + public Iterable<Entry<String, Collection<String>>> order( + List<Entry<String, Collection<String>>> insertionOrder) { + return new Ordering<Entry<String, ?>>() { + @Override + public int compare(Entry<String, ?> left, Entry<String, ?> right) { + return left.getKey().compareTo(right.getKey()); + } + }.sortedCopy(insertionOrder); + } + + @Override + public NavigableMap<String, Collection<String>> create(Object... elements) { + TreeMultimap<String, String> multimap = TreeMultimap.create(); + for (Object o : elements) { + @SuppressWarnings("unchecked") + Entry<String, Collection<String>> entry = (Entry<String, Collection<String>>) o; + checkArgument(!multimap.containsKey(entry.getKey())); + multimap.putAll(entry.getKey(), entry.getValue()); + } + return multimap.asMap(); + } + + @Override + public Entry<String, Collection<String>> belowSamplesLesser() { + return Helpers.mapEntry("-- a", (Collection<String>) ImmutableSortedSet.of("--below")); + } + + @Override + public Entry<String, Collection<String>> belowSamplesGreater() { + return Helpers.mapEntry("-- b", (Collection<String>) ImmutableSortedSet.of("--below")); + } + + @Override + public Entry<String, Collection<String>> aboveSamplesLesser() { + return Helpers.mapEntry("~~ b", (Collection<String>) ImmutableSortedSet.of("~above")); + } + + @Override + public Entry<String, Collection<String>> aboveSamplesGreater() { + return Helpers.mapEntry("~~ c", (Collection<String>) ImmutableSortedSet.of("~above")); + } + }) + .named("TreeMultimap.asMap") + .withFeatures( + MapFeature.SUPPORTS_REMOVE, + MapFeature.REJECTS_DUPLICATES_AT_CREATION, + CollectionFeature.SUPPORTS_ITERATOR_REMOVE, + CollectionFeature.KNOWN_ORDER, + CollectionSize.ANY) + .createTestSuite()); + suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { + @Override + protected Set<String> create(String[] elements) { + TreeMultimap<Integer, String> multimap = TreeMultimap.create( + Ordering.natural(), Ordering.natural().nullsFirst()); + multimap.putAll(1, Arrays.asList(elements)); + return multimap.get(1); + } + + @Override + public List<String> order(List<String> insertionOrder) { + return Ordering.natural().nullsFirst().sortedCopy(insertionOrder); + } + }) + .named("TreeMultimap.get") + .withFeatures( + CollectionFeature.ALLOWS_NULL_VALUES, + CollectionFeature.GENERAL_PURPOSE, + CollectionFeature.KNOWN_ORDER, + CollectionSize.ANY) + .createTestSuite()); + suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { + @Override + protected Set<String> create(String[] elements) { + TreeMultimap<Integer, String> multimap = TreeMultimap.create( + Ordering.natural(), Ordering.natural().nullsFirst()); + multimap.putAll(1, Arrays.asList(elements)); + return (Set<String>) multimap.asMap().entrySet().iterator().next().getValue(); + } + + @Override + public List<String> order(List<String> insertionOrder) { + return Ordering.natural().nullsFirst().sortedCopy(insertionOrder); + } + }) + .named("TreeMultimap.asMap.entrySet collection") + .withFeatures( + CollectionFeature.ALLOWS_NULL_VALUES, + CollectionFeature.GENERAL_PURPOSE, + CollectionFeature.KNOWN_ORDER, + CollectionSize.ONE, + CollectionSize.SEVERAL) + .createTestSuite()); suite.addTestSuite(TreeMultimapNaturalTest.class); return suite; } @@ -126,14 +283,14 @@ public class TreeMultimapNaturalTest extends TestCase { public void testOrderedGet() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.get("foo")).has().exactly(1, 3, 7).inOrder(); - ASSERT.that(multimap.get("google")).has().exactly(2, 6).inOrder(); - ASSERT.that(multimap.get("tree")).has().exactly(0, 4).inOrder(); + assertThat(multimap.get("foo")).has().exactly(1, 3, 7).inOrder(); + assertThat(multimap.get("google")).has().exactly(2, 6).inOrder(); + assertThat(multimap.get("tree")).has().exactly(0, 4).inOrder(); } public void testOrderedKeySet() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.keySet()).has().exactly("foo", "google", "tree").inOrder(); + assertThat(multimap.keySet()).has().exactly("foo", "google", "tree").inOrder(); } public void testOrderedAsMapEntries() { @@ -142,18 +299,18 @@ public class TreeMultimapNaturalTest extends TestCase { multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = iterator.next(); assertEquals("foo", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(1, 3, 7); + assertThat(entry.getValue()).has().exactly(1, 3, 7); entry = iterator.next(); assertEquals("google", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(2, 6); + assertThat(entry.getValue()).has().exactly(2, 6); entry = iterator.next(); assertEquals("tree", entry.getKey()); - ASSERT.that(entry.getValue()).has().exactly(0, 4); + assertThat(entry.getValue()).has().exactly(0, 4); } public void testOrderedEntries() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.entries()).has().exactly( + assertThat(multimap.entries()).has().exactly( Maps.immutableEntry("foo", 1), Maps.immutableEntry("foo", 3), Maps.immutableEntry("foo", 7), @@ -165,7 +322,7 @@ public class TreeMultimapNaturalTest extends TestCase { public void testOrderedValues() { TreeMultimap<String, Integer> multimap = createPopulate(); - ASSERT.that(multimap.values()).has().exactly( + assertThat(multimap.values()).has().exactly( 1, 3, 7, 2, 6, 0, 4).inOrder(); } @@ -248,8 +405,8 @@ public class TreeMultimapNaturalTest extends TestCase { TreeMultimap<String, Integer> multimap = createPopulate(); TreeMultimap<String, Integer> copy = SerializableTester.reserializeAndAssert(multimap); - ASSERT.that(copy.values()).has().exactly(1, 3, 7, 2, 6, 0, 4).inOrder(); - ASSERT.that(copy.keySet()).has().exactly("foo", "google", "tree").inOrder(); + assertThat(copy.values()).has().exactly(1, 3, 7, 2, 6, 0, 4).inOrder(); + assertThat(copy.keySet()).has().exactly("foo", "google", "tree").inOrder(); assertEquals(multimap.keyComparator(), copy.keyComparator()); assertEquals(multimap.valueComparator(), copy.valueComparator()); } @@ -264,9 +421,9 @@ public class TreeMultimapNaturalTest extends TestCase { multimap.put(new DerivedComparable("bar"), new DerivedComparable("b")); multimap.put(new DerivedComparable("bar"), new DerivedComparable("a")); multimap.put(new DerivedComparable("bar"), new DerivedComparable("r")); - ASSERT.that(multimap.keySet()).has().exactly( + assertThat(multimap.keySet()).has().exactly( new DerivedComparable("bar"), new DerivedComparable("foo")).inOrder(); - ASSERT.that(multimap.values()).has().exactly( + assertThat(multimap.values()).has().exactly( new DerivedComparable("a"), new DerivedComparable("b"), new DerivedComparable("r"), new DerivedComparable("f"), new DerivedComparable("o")).inOrder(); assertEquals(Ordering.natural(), multimap.keyComparator()); @@ -285,9 +442,9 @@ public class TreeMultimapNaturalTest extends TestCase { multimap.put(new LegacyComparable("bar"), new LegacyComparable("b")); multimap.put(new LegacyComparable("bar"), new LegacyComparable("a")); multimap.put(new LegacyComparable("bar"), new LegacyComparable("r")); - ASSERT.that(multimap.keySet()).has().exactly( + assertThat(multimap.keySet()).has().exactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); - ASSERT.that(multimap.values()).has().exactly( + assertThat(multimap.values()).has().exactly( new LegacyComparable("a"), new LegacyComparable("b"), new LegacyComparable("r"), diff --git a/guava-tests/test/com/google/common/collect/TreeMultisetTest.java b/guava-tests/test/com/google/common/collect/TreeMultisetTest.java index 8cb98ab5d..86a21972a 100644 --- a/guava-tests/test/com/google/common/collect/TreeMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/TreeMultisetTest.java @@ -17,13 +17,13 @@ package com.google.common.collect; import static com.google.common.collect.BoundType.CLOSED; +import static com.google.common.truth.Truth.assertThat; import static java.util.Collections.sort; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers.NullsBeforeB; -import com.google.common.collect.testing.SortedSetTestSuiteBuilder; +import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; import com.google.common.collect.testing.TestStringSetGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; @@ -95,7 +95,7 @@ public class TreeMultisetTest extends TestCase { MultisetFeature.ENTRIES_ARE_VIEWS) .named("TreeMultiset, NullsBeforeB") .createTestSuite()); - suite.addTest(SortedSetTestSuiteBuilder.using(new TestStringSetGenerator() { + suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { return TreeMultiset.create(Arrays.asList(elements)).elementSet(); @@ -163,9 +163,9 @@ public class TreeMultisetTest extends TestCase { assertEquals("c", elementSet.last()); assertEquals(Ordering.natural(), elementSet.comparator()); - ASSERT.that(elementSet.headSet("b")).has().exactly("a").inOrder(); - ASSERT.that(elementSet.tailSet("b")).has().exactly("b", "c").inOrder(); - ASSERT.that(elementSet.subSet("a", "c")).has().exactly("a", "b").inOrder(); + assertThat(elementSet.headSet("b")).has().exactly("a").inOrder(); + assertThat(elementSet.tailSet("b")).has().exactly("b", "c").inOrder(); + assertThat(elementSet.subSet("a", "c")).has().exactly("a", "b").inOrder(); } public void testElementSetSubsetRemove() { @@ -178,18 +178,18 @@ public class TreeMultisetTest extends TestCase { ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); - ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); - ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); + assertThat(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.remove("c")); - ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); - ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); + assertThat(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); + assertThat(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); assertFalse(subset.remove("a")); - ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); - ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); + assertThat(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); + assertThat(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); } @@ -203,13 +203,13 @@ public class TreeMultisetTest extends TestCase { ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); - ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); - ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); + assertThat(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.removeAll(Arrays.asList("a", "c"))); - ASSERT.that(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); - ASSERT.that(subset).has().exactly("b", "d", "e").inOrder(); + assertThat(elementSet).has().exactly("a", "b", "d", "e", "f").inOrder(); + assertThat(subset).has().exactly("b", "d", "e").inOrder(); assertEquals(10, ms.size()); } @@ -223,13 +223,13 @@ public class TreeMultisetTest extends TestCase { ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); - ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); - ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); + assertThat(subset).has().exactly("b", "c", "d", "e").inOrder(); assertTrue(subset.retainAll(Arrays.asList("a", "c"))); - ASSERT.that(elementSet).has().exactly("a", "c", "f").inOrder(); - ASSERT.that(subset).has().exactly("c").inOrder(); + assertThat(elementSet).has().exactly("a", "c", "f").inOrder(); + assertThat(subset).has().exactly("c").inOrder(); assertEquals(5, ms.size()); } @@ -243,13 +243,13 @@ public class TreeMultisetTest extends TestCase { ms.add("f", 2); SortedSet<String> elementSet = ms.elementSet(); - ASSERT.that(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); + assertThat(elementSet).has().exactly("a", "b", "c", "d", "e", "f").inOrder(); SortedSet<String> subset = elementSet.subSet("b", "f"); - ASSERT.that(subset).has().exactly("b", "c", "d", "e").inOrder(); + assertThat(subset).has().exactly("b", "c", "d", "e").inOrder(); subset.clear(); - ASSERT.that(elementSet).has().exactly("a", "f").inOrder(); - ASSERT.that(subset).isEmpty(); + assertThat(elementSet).has().exactly("a", "f").inOrder(); + assertThat(subset).isEmpty(); assertEquals(3, ms.size()); } @@ -268,7 +268,7 @@ public class TreeMultisetTest extends TestCase { ms.add("b"); ms.add("d"); - ASSERT.that(ms).has().exactly("d", "c", "b", "b", "a").inOrder(); + assertThat(ms).has().exactly("d", "c", "b", "b", "a").inOrder(); SortedSet<String> elementSet = ms.elementSet(); assertEquals("d", elementSet.first()); @@ -286,7 +286,7 @@ public class TreeMultisetTest extends TestCase { ms.add("b"); ms.add(null, 2); - ASSERT.that(ms).has().exactly(null, null, null, "a", "b", "b").inOrder(); + assertThat(ms).has().exactly(null, null, null, "a", "b", "b").inOrder(); assertEquals(3, ms.count(null)); SortedSet<String> elementSet = ms.elementSet(); diff --git a/guava-tests/test/com/google/common/collect/TreeRangeMapTest.java b/guava-tests/test/com/google/common/collect/TreeRangeMapTest.java new file mode 100644 index 000000000..02dbbc479 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/TreeRangeMapTest.java @@ -0,0 +1,479 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.common.collect; + +import static com.google.common.collect.BoundType.OPEN; +import static com.google.common.collect.testing.Helpers.mapEntry; + +import com.google.common.annotations.GwtIncompatible; +import com.google.common.collect.testing.MapTestSuiteBuilder; +import com.google.common.collect.testing.SampleElements; +import com.google.common.collect.testing.TestMapGenerator; +import com.google.common.collect.testing.features.CollectionFeature; +import com.google.common.collect.testing.features.CollectionSize; +import com.google.common.collect.testing.features.MapFeature; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; + +/** + * Tests for {@code TreeRangeMap}. + * + * @author Louis Wasserman + */ +@GwtIncompatible("NavigableMap") +public class TreeRangeMapTest extends TestCase { + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(TreeRangeMapTest.class); + suite.addTest(MapTestSuiteBuilder.using(new TestMapGenerator<Range<Integer>, String>() { + @Override + public SampleElements<Entry<Range<Integer>, String>> samples() { + return new SampleElements<Entry<Range<Integer>, String>>( + mapEntry(Range.singleton(0), "banana"), + mapEntry(Range.closedOpen(3, 5), "frisbee"), + mapEntry(Range.atMost(-1), "fruitcake"), + mapEntry(Range.open(10, 15), "elephant"), + mapEntry(Range.closed(20, 22), "umbrella")); + } + + @Override + public Map<Range<Integer>, String> create(Object... elements) { + RangeMap<Integer, String> rangeMap = TreeRangeMap.create(); + for (Object o : elements) { + @SuppressWarnings("unchecked") + Entry<Range<Integer>, String> entry = (Entry<Range<Integer>, String>) o; + rangeMap.put(entry.getKey(), entry.getValue()); + } + return rangeMap.asMapOfRanges(); + } + + @SuppressWarnings("unchecked") + @Override + public Entry<Range<Integer>, String>[] createArray(int length) { + return new Entry[length]; + } + + @Override + public Iterable<Entry<Range<Integer>, String>> order( + List<Entry<Range<Integer>, String>> insertionOrder) { + return Range.RANGE_LEX_ORDERING.<Range<Integer>>onKeys() + .sortedCopy(insertionOrder); + } + + @SuppressWarnings("unchecked") + @Override + public Range<Integer>[] createKeyArray(int length) { + return new Range[length]; + } + + @Override + public String[] createValueArray(int length) { + return new String[length]; + } + }) + .named("TreeRangeMap.asMapOfRanges") + .withFeatures( + CollectionSize.ANY, + MapFeature.SUPPORTS_REMOVE, + MapFeature.ALLOWS_ANY_NULL_QUERIES, + CollectionFeature.KNOWN_ORDER, + CollectionFeature.SUPPORTS_ITERATOR_REMOVE) + .createTestSuite()); + + suite.addTest(MapTestSuiteBuilder.using(new TestMapGenerator<Range<Integer>, String>() { + @Override + public SampleElements<Entry<Range<Integer>, String>> samples() { + return new SampleElements<Entry<Range<Integer>, String>>( + mapEntry(Range.singleton(0), "banana"), + mapEntry(Range.closedOpen(3, 5), "frisbee"), + mapEntry(Range.atMost(-1), "fruitcake"), + mapEntry(Range.open(10, 15), "elephant"), + mapEntry(Range.closed(20, 22), "umbrella")); + } + + @Override + public Map<Range<Integer>, String> create(Object... elements) { + RangeMap<Integer, String> rangeMap = TreeRangeMap.create(); + for (Object o : elements) { + @SuppressWarnings("unchecked") + Entry<Range<Integer>, String> entry = (Entry<Range<Integer>, String>) o; + rangeMap.put(entry.getKey(), entry.getValue()); + } + return rangeMap.subRangeMap(Range.atMost(22)).asMapOfRanges(); + } + + @SuppressWarnings("unchecked") + @Override + public Entry<Range<Integer>, String>[] createArray(int length) { + return new Entry[length]; + } + + @Override + public Iterable<Entry<Range<Integer>, String>> order( + List<Entry<Range<Integer>, String>> insertionOrder) { + return Range.RANGE_LEX_ORDERING.<Range<Integer>>onKeys() + .sortedCopy(insertionOrder); + } + + @SuppressWarnings("unchecked") + @Override + public Range<Integer>[] createKeyArray(int length) { + return new Range[length]; + } + + @Override + public String[] createValueArray(int length) { + return new String[length]; + } + }) + .named("TreeRangeMap.subRangeMap.asMapOfRanges") + .withFeatures( + CollectionSize.ANY, + MapFeature.SUPPORTS_REMOVE, + MapFeature.ALLOWS_ANY_NULL_QUERIES, + CollectionFeature.KNOWN_ORDER) + .createTestSuite()); + return suite; + } + + private static final ImmutableList<Range<Integer>> RANGES; + private static final int MIN_BOUND = -2; + private static final int MAX_BOUND = 2; + static { + ImmutableList.Builder<Range<Integer>> builder = ImmutableList.builder(); + + builder.add(Range.<Integer>all()); + + // Add one-ended ranges + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + for (BoundType type : BoundType.values()) { + builder.add(Range.upTo(i, type)); + builder.add(Range.downTo(i, type)); + } + } + + // Add two-ended ranges + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + for (int j = i; j <= MAX_BOUND; j++) { + for (BoundType lowerType : BoundType.values()) { + for (BoundType upperType : BoundType.values()) { + if (i == j & lowerType == OPEN & upperType == OPEN) { + continue; + } + builder.add(Range.range(i, lowerType, j, upperType)); + } + } + } + } + RANGES = builder.build(); + } + + public void testSpanSingleRange() { + for (Range<Integer> range : RANGES) { + RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create(); + rangeMap.put(range, 1); + + try { + assertEquals(range, rangeMap.span()); + assertFalse(range.isEmpty()); + } catch (NoSuchElementException e) { + assertTrue(range.isEmpty()); + } + } + } + + public void testSpanTwoRanges() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create(); + rangeMap.put(range1, 1); + rangeMap.put(range2, 2); + + Range<Integer> expected; + if (range1.isEmpty()) { + if (range2.isEmpty()) { + expected = null; + } else { + expected = range2; + } + } else { + if (range2.isEmpty()) { + expected = range1; + } else { + expected = range1.span(range2); + } + } + + try { + assertEquals(expected, rangeMap.span()); + assertNotNull(expected); + } catch (NoSuchElementException e) { + assertNull(expected); + } + } + } + } + + public void testAllRangesAlone() { + for (Range<Integer> range : RANGES) { + Map<Integer, Integer> model = Maps.newHashMap(); + putModel(model, range, 1); + RangeMap<Integer, Integer> test = TreeRangeMap.create(); + test.put(range, 1); + verify(model, test); + } + } + + public void testAllRangePairs() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + Map<Integer, Integer> model = Maps.newHashMap(); + putModel(model, range1, 1); + putModel(model, range2, 2); + RangeMap<Integer, Integer> test = TreeRangeMap.create(); + test.put(range1, 1); + test.put(range2, 2); + verify(model, test); + } + } + } + + public void testAllRangeTriples() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + for (Range<Integer> range3 : RANGES) { + Map<Integer, Integer> model = Maps.newHashMap(); + putModel(model, range1, 1); + putModel(model, range2, 2); + putModel(model, range3, 3); + RangeMap<Integer, Integer> test = TreeRangeMap.create(); + test.put(range1, 1); + test.put(range2, 2); + test.put(range3, 3); + verify(model, test); + } + } + } + } + + public void testPutAll() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + for (Range<Integer> range3 : RANGES) { + Map<Integer, Integer> model = Maps.newHashMap(); + putModel(model, range1, 1); + putModel(model, range2, 2); + putModel(model, range3, 3); + RangeMap<Integer, Integer> test = TreeRangeMap.create(); + RangeMap<Integer, Integer> test2 = TreeRangeMap.create(); + // put range2 and range3 into test2, and then put test2 into test + test.put(range1, 1); + test2.put(range2, 2); + test2.put(range3, 3); + test.putAll(test2); + verify(model, test); + } + } + } + } + + public void testPutAndRemove() { + for (Range<Integer> rangeToPut : RANGES) { + for (Range<Integer> rangeToRemove : RANGES) { + Map<Integer, Integer> model = Maps.newHashMap(); + putModel(model, rangeToPut, 1); + removeModel(model, rangeToRemove); + RangeMap<Integer, Integer> test = TreeRangeMap.create(); + test.put(rangeToPut, 1); + test.remove(rangeToRemove); + verify(model, test); + } + } + } + + public void testPutTwoAndRemove() { + for (Range<Integer> rangeToPut1 : RANGES) { + for (Range<Integer> rangeToPut2 : RANGES) { + for (Range<Integer> rangeToRemove : RANGES) { + Map<Integer, Integer> model = Maps.newHashMap(); + putModel(model, rangeToPut1, 1); + putModel(model, rangeToPut2, 2); + removeModel(model, rangeToRemove); + RangeMap<Integer, Integer> test = TreeRangeMap.create(); + test.put(rangeToPut1, 1); + test.put(rangeToPut2, 2); + test.remove(rangeToRemove); + verify(model, test); + } + } + } + } + + public void testSubRangeMapExhaustive() { + for (Range<Integer> range1 : RANGES) { + for (Range<Integer> range2 : RANGES) { + RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create(); + rangeMap.put(range1, 1); + rangeMap.put(range2, 2); + + for (Range<Integer> subRange : RANGES) { + RangeMap<Integer, Integer> expected = TreeRangeMap.create(); + for (Map.Entry<Range<Integer>, Integer> entry : rangeMap.asMapOfRanges().entrySet()) { + if (entry.getKey().isConnected(subRange)) { + expected.put(entry.getKey().intersection(subRange), entry.getValue()); + } + } + RangeMap<Integer, Integer> subRangeMap = rangeMap.subRangeMap(subRange); + assertEquals(expected, subRangeMap); + assertEquals(expected.asMapOfRanges(), subRangeMap.asMapOfRanges()); + + if (!expected.asMapOfRanges().isEmpty()) { + assertEquals(expected.span(), subRangeMap.span()); + } + + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + assertEquals(expected.get(i), subRangeMap.get(i)); + } + + for (Range<Integer> query : RANGES) { + assertEquals( + expected.asMapOfRanges().get(query), + subRangeMap.asMapOfRanges().get(query)); + } + } + } + } + } + + public void testSubSubRangeMap() { + RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create(); + rangeMap.put(Range.open(3, 7), 1); + rangeMap.put(Range.closed(9, 10), 2); + rangeMap.put(Range.closed(12, 16), 3); + RangeMap<Integer, Integer> sub1 = rangeMap.subRangeMap(Range.closed(5, 11)); + assertEquals(ImmutableMap.of(Range.closedOpen(5, 7), 1, Range.closed(9, 10), 2), + sub1.asMapOfRanges()); + RangeMap<Integer, Integer> sub2 = sub1.subRangeMap(Range.open(6, 15)); + assertEquals(ImmutableMap.of(Range.open(6, 7), 1, Range.closed(9, 10), 2), + sub2.asMapOfRanges()); + } + + public void testSubRangeMapPut() { + RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create(); + rangeMap.put(Range.open(3, 7), 1); + rangeMap.put(Range.closed(9, 10), 2); + rangeMap.put(Range.closed(12, 16), 3); + RangeMap<Integer, Integer> sub = rangeMap.subRangeMap(Range.closed(5, 11)); + assertEquals(ImmutableMap.of(Range.closedOpen(5, 7), 1, Range.closed(9, 10), 2), + sub.asMapOfRanges()); + sub.put(Range.closed(7, 9), 4); + assertEquals( + ImmutableMap.of( + Range.closedOpen(5, 7), 1, Range.closed(7, 9), 4, Range.openClosed(9, 10), 2), + sub.asMapOfRanges()); + assertEquals( + ImmutableMap.of(Range.open(3, 7), 1, Range.closed(7, 9), 4, Range.openClosed(9, 10), 2, + Range.closed(12, 16), 3), + rangeMap.asMapOfRanges()); + + try { + sub.put(Range.open(9, 12), 5); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + } + + sub = sub.subRangeMap(Range.closedOpen(5, 5)); + sub.put(Range.closedOpen(5, 5), 6); // should be a no-op + assertEquals( + ImmutableMap.of(Range.open(3, 7), 1, Range.closed(7, 9), 4, Range.openClosed(9, 10), 2, + Range.closed(12, 16), 3), + rangeMap.asMapOfRanges()); + } + + public void testSubRangeMapRemove() { + RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create(); + rangeMap.put(Range.open(3, 7), 1); + rangeMap.put(Range.closed(9, 10), 2); + rangeMap.put(Range.closed(12, 16), 3); + RangeMap<Integer, Integer> sub = rangeMap.subRangeMap(Range.closed(5, 11)); + assertEquals(ImmutableMap.of(Range.closedOpen(5, 7), 1, Range.closed(9, 10), 2), + sub.asMapOfRanges()); + sub.remove(Range.closed(7, 9)); + assertEquals( + ImmutableMap.of(Range.closedOpen(5, 7), 1, Range.openClosed(9, 10), 2), + sub.asMapOfRanges()); + assertEquals( + ImmutableMap.of(Range.open(3, 7), 1, Range.openClosed(9, 10), 2, Range.closed(12, 16), 3), + rangeMap.asMapOfRanges()); + + sub.remove(Range.closed(3, 9)); + assertEquals( + ImmutableMap.of(Range.openClosed(9, 10), 2), + sub.asMapOfRanges()); + assertEquals( + ImmutableMap.of(Range.open(3, 5), 1, Range.openClosed(9, 10), 2, Range.closed(12, 16), 3), + rangeMap.asMapOfRanges()); + } + + public void testSubRangeMapClear() { + RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create(); + rangeMap.put(Range.open(3, 7), 1); + rangeMap.put(Range.closed(9, 10), 2); + rangeMap.put(Range.closed(12, 16), 3); + RangeMap<Integer, Integer> sub = rangeMap.subRangeMap(Range.closed(5, 11)); + sub.clear(); + assertEquals( + ImmutableMap.of(Range.open(3, 5), 1, Range.closed(12, 16), 3), + rangeMap.asMapOfRanges()); + } + + private void verify(Map<Integer, Integer> model, RangeMap<Integer, Integer> test) { + for (int i = MIN_BOUND - 1; i <= MAX_BOUND + 1; i++) { + assertEquals(model.get(i), test.get(i)); + + Map.Entry<Range<Integer>, Integer> entry = test.getEntry(i); + assertEquals(model.containsKey(i), entry != null); + if (entry != null) { + assertTrue(test.asMapOfRanges().entrySet().contains(entry)); + } + } + for (Range<Integer> range : test.asMapOfRanges().keySet()) { + assertFalse(range.isEmpty()); + } + } + + private void putModel(Map<Integer, Integer> model, Range<Integer> range, int value) { + for (int i = MIN_BOUND - 1; i <= MAX_BOUND + 1; i++) { + if (range.contains(i)) { + model.put(i, value); + } + } + } + + private void removeModel(Map<Integer, Integer> model, Range<Integer> range) { + for (int i = MIN_BOUND - 1; i <= MAX_BOUND + 1; i++) { + if (range.contains(i)) { + model.remove(i); + } + } + } +} diff --git a/guava-tests/test/com/google/common/collect/TreeRangeSetTest.java b/guava-tests/test/com/google/common/collect/TreeRangeSetTest.java new file mode 100644 index 000000000..55a618e6f --- /dev/null +++ b/guava-tests/test/com/google/common/collect/TreeRangeSetTest.java @@ -0,0 +1,571 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.common.collect; + +import static com.google.common.collect.BoundType.OPEN; +import static com.google.common.collect.Range.range; +import static com.google.common.truth.Truth.assertThat; + +import com.google.common.annotations.GwtIncompatible; + +import java.util.List; +import java.util.NavigableMap; + +/** + * Tests for {@link TreeRangeSet}. + * + * @author Louis Wasserman + * @author Chris Povirk + */ +@GwtIncompatible("TreeRangeSet") +public class TreeRangeSetTest extends AbstractRangeSetTest { + // TODO(cpovirk): test all of these with the ranges added in the reverse order + + private static final ImmutableList<Range<Integer>> QUERY_RANGES; + + private static final int MIN_BOUND = -1; + private static final int MAX_BOUND = 1; + + static { + ImmutableList.Builder<Range<Integer>> queryBuilder = ImmutableList.builder(); + + queryBuilder.add(Range.<Integer>all()); + + for (int i = MIN_BOUND; i <= MAX_BOUND; i++) { + for (BoundType boundType : BoundType.values()) { + queryBuilder.add(Range.upTo(i, boundType)); + queryBuilder.add(Range.downTo(i, boundType)); + } + queryBuilder.add(Range.singleton(i)); + queryBuilder.add(Range.openClosed(i, i)); + queryBuilder.add(Range.closedOpen(i, i)); + + for (BoundType lowerBoundType : BoundType.values()) { + for (int j = i + 1; j <= MAX_BOUND; j++) { + for (BoundType upperBoundType : BoundType.values()) { + queryBuilder.add(Range.range(i, lowerBoundType, j, upperBoundType)); + } + } + } + } + QUERY_RANGES = queryBuilder.build(); + } + + void testViewAgainstExpected(RangeSet<Integer> expected, RangeSet<Integer> view) { + assertEquals(expected, view); + assertEquals(expected.asRanges(), view.asRanges()); + assertEquals(expected.isEmpty(), view.isEmpty()); + + if (!expected.isEmpty()) { + assertEquals(expected.span(), view.span()); + } + + for (int i = MIN_BOUND - 1; i <= MAX_BOUND + 1; i++) { + assertEquals(expected.contains(i), view.contains(i)); + assertEquals(expected.rangeContaining(i), view.rangeContaining(i)); + } + testEnclosing(view); + if (view instanceof TreeRangeSet) { + testRangesByLowerBounds((TreeRangeSet<Integer>) view, expected.asRanges()); + } + } + + private static final ImmutableList<Cut<Integer>> CUTS_TO_TEST; + + static { + List<Cut<Integer>> cutsToTest = Lists.newArrayList(); + for (int i = MIN_BOUND - 1; i <= MAX_BOUND + 1; i++) { + cutsToTest.add(Cut.belowValue(i)); + cutsToTest.add(Cut.aboveValue(i)); + } + cutsToTest.add(Cut.<Integer>aboveAll()); + cutsToTest.add(Cut.<Integer>belowAll()); + CUTS_TO_TEST = ImmutableList.copyOf(cutsToTest); + } + + private void testRangesByLowerBounds( + TreeRangeSet<Integer> rangeSet, Iterable<Range<Integer>> expectedRanges) { + NavigableMap<Cut<Integer>, Range<Integer>> expectedRangesByLowerBound = Maps.newTreeMap(); + for (Range<Integer> range : expectedRanges) { + expectedRangesByLowerBound.put(range.lowerBound, range); + } + + NavigableMap<Cut<Integer>, Range<Integer>> rangesByLowerBound = rangeSet.rangesByLowerBound; + testNavigationAgainstExpected(expectedRangesByLowerBound, rangesByLowerBound, CUTS_TO_TEST); + } + + <K, V> void testNavigationAgainstExpected( + NavigableMap<K, V> expected, NavigableMap<K, V> navigableMap, Iterable<K> keysToTest) { + for (K key : keysToTest) { + assertEquals(expected.lowerEntry(key), navigableMap.lowerEntry(key)); + assertEquals(expected.floorEntry(key), navigableMap.floorEntry(key)); + assertEquals(expected.ceilingEntry(key), navigableMap.ceilingEntry(key)); + assertEquals(expected.higherEntry(key), navigableMap.higherEntry(key)); + for (boolean inclusive : new boolean[] {false, true}) { + assertThat(navigableMap.headMap(key, inclusive).entrySet()) + .has().exactlyAs(expected.headMap(key, inclusive).entrySet()).inOrder(); + assertThat(navigableMap.tailMap(key, inclusive).entrySet()) + .has().exactlyAs(expected.tailMap(key, inclusive).entrySet()).inOrder(); + assertThat(navigableMap.headMap(key, inclusive).descendingMap().entrySet()) + .has().exactlyAs(expected.headMap(key, inclusive).descendingMap().entrySet()).inOrder(); + assertThat(navigableMap.tailMap(key, inclusive).descendingMap().entrySet()) + .has().exactlyAs(expected.tailMap(key, inclusive).descendingMap().entrySet()).inOrder(); + } + } + } + + public void testEnclosing(RangeSet<Integer> rangeSet) { + for (Range<Integer> query : QUERY_RANGES) { + boolean expectEnclose = false; + for (Range<Integer> expectedRange : rangeSet.asRanges()) { + if (expectedRange.encloses(query)) { + expectEnclose = true; + break; + } + } + + assertEquals(rangeSet + " was incorrect on encloses(" + query + ")", expectEnclose, + rangeSet.encloses(query)); + } + } + + public void testAllSingleRangesComplementAgainstRemove() { + for (Range<Integer> range : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range); + + TreeRangeSet<Integer> complement = TreeRangeSet.create(); + complement.add(Range.<Integer>all()); + complement.remove(range); + + assertEquals(complement, rangeSet.complement()); + assertThat(rangeSet.complement().asRanges()) + .has().exactlyAs(complement.asRanges()).inOrder(); + } + } + + public void testInvariantsEmpty() { + testInvariants(TreeRangeSet.create()); + } + + public void testAllSingleRangesEnclosing() { + for (Range<Integer> range : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range); + testEnclosing(rangeSet); + testEnclosing(rangeSet.complement()); + } + } + + public void testAllTwoRangesEnclosing() { + for (Range<Integer> range1 : QUERY_RANGES) { + for (Range<Integer> range2 : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range1); + rangeSet.add(range2); + testEnclosing(rangeSet); + testEnclosing(rangeSet.complement()); + } + } + } + + public void testCreateCopy() { + for (Range<Integer> range1 : QUERY_RANGES) { + for (Range<Integer> range2 : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range1); + rangeSet.add(range2); + + assertEquals(rangeSet, TreeRangeSet.create(rangeSet)); + } + } + } + + private RangeSet<Integer> expectedSubRangeSet( + RangeSet<Integer> rangeSet, Range<Integer> subRange) { + RangeSet<Integer> expected = TreeRangeSet.create(); + for (Range<Integer> range : rangeSet.asRanges()) { + if (range.isConnected(subRange)) { + expected.add(range.intersection(subRange)); + } + } + return expected; + } + + private RangeSet<Integer> expectedComplement(RangeSet<Integer> rangeSet) { + RangeSet<Integer> expected = TreeRangeSet.create(); + expected.add(Range.<Integer>all()); + expected.removeAll(rangeSet); + return expected; + } + + public void testSubRangeSet() { + for (Range<Integer> range1 : QUERY_RANGES) { + for (Range<Integer> range2 : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range1); + rangeSet.add(range2); + for (Range<Integer> subRange : QUERY_RANGES) { + testViewAgainstExpected( + expectedSubRangeSet(rangeSet, subRange), rangeSet.subRangeSet(subRange)); + } + } + } + } + + public void testComplement() { + for (Range<Integer> range1 : QUERY_RANGES) { + for (Range<Integer> range2 : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range1); + rangeSet.add(range2); + testViewAgainstExpected(expectedComplement(rangeSet), rangeSet.complement()); + } + } + } + + public void testSubRangeSetOfComplement() { + for (Range<Integer> range1 : QUERY_RANGES) { + for (Range<Integer> range2 : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range1); + rangeSet.add(range2); + for (Range<Integer> subRange : QUERY_RANGES) { + testViewAgainstExpected( + expectedSubRangeSet(expectedComplement(rangeSet), subRange), + rangeSet.complement().subRangeSet(subRange)); + } + } + } + } + + public void testComplementOfSubRangeSet() { + for (Range<Integer> range1 : QUERY_RANGES) { + for (Range<Integer> range2 : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range1); + rangeSet.add(range2); + for (Range<Integer> subRange : QUERY_RANGES) { + testViewAgainstExpected( + expectedComplement(expectedSubRangeSet(rangeSet, subRange)), + rangeSet.subRangeSet(subRange).complement()); + } + } + } + } + + public void testRangesByUpperBound() { + for (Range<Integer> range1 : QUERY_RANGES) { + for (Range<Integer> range2 : QUERY_RANGES) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(range1); + rangeSet.add(range2); + + NavigableMap<Cut<Integer>, Range<Integer>> expectedRangesByUpperBound = Maps.newTreeMap(); + for (Range<Integer> range : rangeSet.asRanges()) { + expectedRangesByUpperBound.put(range.upperBound, range); + } + testNavigationAgainstExpected(expectedRangesByUpperBound, + new TreeRangeSet.RangesByUpperBound<Integer>(rangeSet.rangesByLowerBound), + CUTS_TO_TEST); + } + } + } + + public void testMergesConnectedWithOverlap() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 4)); + rangeSet.add(Range.open(2, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closedOpen(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.atLeast(6)).inOrder(); + } + + public void testMergesConnectedDisjoint() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 4)); + rangeSet.add(Range.open(4, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closedOpen(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.atLeast(6)).inOrder(); + } + + public void testIgnoresSmallerSharingNoBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 6)); + rangeSet.add(Range.open(2, 4)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testIgnoresSmallerSharingLowerBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 6)); + rangeSet.add(Range.closed(1, 4)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testIgnoresSmallerSharingUpperBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 6)); + rangeSet.add(Range.closed(3, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testIgnoresEqual() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 6)); + rangeSet.add(Range.closed(1, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testExtendSameLowerBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 4)); + rangeSet.add(Range.closed(1, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testExtendSameUpperBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.add(Range.closed(1, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testExtendBothDirections() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 4)); + rangeSet.add(Range.closed(1, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testAddEmpty() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closedOpen(3, 3)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).isEmpty(); + assertThat(rangeSet.complement().asRanges()).has().exactly(Range.<Integer>all()).inOrder(); + } + + public void testFillHoleExactly() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closedOpen(1, 3)); + rangeSet.add(Range.closedOpen(4, 6)); + rangeSet.add(Range.closedOpen(3, 4)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closedOpen(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.atLeast(6)).inOrder(); + } + + public void testFillHoleWithOverlap() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closedOpen(1, 3)); + rangeSet.add(Range.closedOpen(4, 6)); + rangeSet.add(Range.closedOpen(2, 5)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closedOpen(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.atLeast(6)).inOrder(); + } + + public void testAddManyPairs() { + for (int aLow = 0; aLow < 6; aLow++) { + for (int aHigh = 0; aHigh < 6; aHigh++) { + for (BoundType aLowType : BoundType.values()) { + for (BoundType aHighType : BoundType.values()) { + if ((aLow == aHigh && aLowType == OPEN && aHighType == OPEN) || aLow > aHigh) { + continue; + } + for (int bLow = 0; bLow < 6; bLow++) { + for (int bHigh = 0; bHigh < 6; bHigh++) { + for (BoundType bLowType : BoundType.values()) { + for (BoundType bHighType : BoundType.values()) { + if ((bLow == bHigh && bLowType == OPEN && bHighType == OPEN) || bLow > bHigh) { + continue; + } + doPairTest(range(aLow, aLowType, aHigh, aHighType), + range(bLow, bLowType, bHigh, bHighType)); + } + } + } + } + } + } + } + } + } + + private static void doPairTest(Range<Integer> a, Range<Integer> b) { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(a); + rangeSet.add(b); + if (a.isEmpty() && b.isEmpty()) { + assertThat(rangeSet.asRanges()).isEmpty(); + } else if (a.isEmpty()) { + assertThat(rangeSet.asRanges()).has().item(b); + } else if (b.isEmpty()) { + assertThat(rangeSet.asRanges()).has().item(a); + } else if (a.isConnected(b)) { + assertThat(rangeSet.asRanges()).has().exactly(a.span(b)).inOrder(); + } else { + if (a.lowerEndpoint() < b.lowerEndpoint()) { + assertThat(rangeSet.asRanges()).has().exactly(a, b).inOrder(); + } else { + assertThat(rangeSet.asRanges()).has().exactly(b, a).inOrder(); + } + } + } + + public void testRemoveEmpty() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(1, 6)); + rangeSet.remove(Range.closedOpen(3, 3)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.closed(1, 6)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(1), Range.greaterThan(6)).inOrder(); + } + + public void testRemovePartSharingLowerBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 5)); + rangeSet.remove(Range.closedOpen(3, 5)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.singleton(5)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(5), Range.greaterThan(5)).inOrder(); + } + + public void testRemovePartSharingUpperBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 5)); + rangeSet.remove(Range.openClosed(3, 5)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().item(Range.singleton(3)); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.lessThan(3), Range.greaterThan(3)).inOrder(); + } + + public void testRemoveMiddle() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.atMost(6)); + rangeSet.remove(Range.closedOpen(3, 4)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().exactly(Range.lessThan(3), Range.closed(4, 6)).inOrder(); + assertThat(rangeSet.complement().asRanges()) + .has().exactly(Range.closedOpen(3, 4), Range.greaterThan(6)).inOrder(); + } + + public void testRemoveNoOverlap() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.remove(Range.closedOpen(1, 3)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().exactly(Range.closed(3, 6)).inOrder(); + } + + public void testRemovePartFromBelowLowerBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.remove(Range.closed(1, 3)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().exactly(Range.openClosed(3, 6)).inOrder(); + } + + public void testRemovePartFromAboveUpperBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.remove(Range.closed(6, 9)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).has().exactly(Range.closedOpen(3, 6)).inOrder(); + } + + public void testRemoveExact() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.remove(Range.closed(3, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).isEmpty(); + } + + public void testRemoveAllFromBelowLowerBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.remove(Range.closed(2, 6)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).isEmpty(); + } + + public void testRemoveAllFromAboveUpperBound() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.remove(Range.closed(3, 7)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).isEmpty(); + } + + public void testRemoveAllExtendingBothDirections() { + TreeRangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 6)); + rangeSet.remove(Range.closed(2, 7)); + testInvariants(rangeSet); + assertThat(rangeSet.asRanges()).isEmpty(); + } + + public void testRangeContaining1() { + RangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 10)); + assertEquals(Range.closed(3, 10), rangeSet.rangeContaining(5)); + assertTrue(rangeSet.contains(5)); + assertNull(rangeSet.rangeContaining(1)); + assertFalse(rangeSet.contains(1)); + } + + public void testRangeContaining2() { + RangeSet<Integer> rangeSet = TreeRangeSet.create(); + rangeSet.add(Range.closed(3, 10)); + rangeSet.remove(Range.open(5, 7)); + assertEquals(Range.closed(3, 5), rangeSet.rangeContaining(5)); + assertTrue(rangeSet.contains(5)); + assertEquals(Range.closed(7, 10), rangeSet.rangeContaining(8)); + assertTrue(rangeSet.contains(8)); + assertNull(rangeSet.rangeContaining(6)); + assertFalse(rangeSet.contains(6)); + } +} diff --git a/guava-tests/test/com/google/common/collect/TreeTraverserTest.java b/guava-tests/test/com/google/common/collect/TreeTraverserTest.java index 37c98591c..b5438e17a 100644 --- a/guava-tests/test/com/google/common/collect/TreeTraverserTest.java +++ b/guava-tests/test/com/google/common/collect/TreeTraverserTest.java @@ -14,7 +14,7 @@ package com.google.common.collect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -128,22 +128,22 @@ public class TreeTraverserTest extends TestCase { } public void testPreOrder() { - ASSERT.that(iterationOrder(ADAPTER.preOrderTraversal(h))).is("hdabcegf"); - ASSERT.that(binaryIterationOrder(BIN_ADAPTER.preOrderTraversal(bd))).is("dbacefg"); + assertThat(iterationOrder(ADAPTER.preOrderTraversal(h))).isEqualTo("hdabcegf"); + assertThat(binaryIterationOrder(BIN_ADAPTER.preOrderTraversal(bd))).isEqualTo("dbacefg"); } public void testPostOrder() { - ASSERT.that(iterationOrder(ADAPTER.postOrderTraversal(h))).is("abcdefgh"); - ASSERT.that(binaryIterationOrder(BIN_ADAPTER.postOrderTraversal(bd))).is("acbgfed"); + assertThat(iterationOrder(ADAPTER.postOrderTraversal(h))).isEqualTo("abcdefgh"); + assertThat(binaryIterationOrder(BIN_ADAPTER.postOrderTraversal(bd))).isEqualTo("acbgfed"); } public void testBreadthOrder() { - ASSERT.that(iterationOrder(ADAPTER.breadthFirstTraversal(h))).is("hdegabcf"); - ASSERT.that(binaryIterationOrder(BIN_ADAPTER.breadthFirstTraversal(bd))).is("dbeacfg"); + assertThat(iterationOrder(ADAPTER.breadthFirstTraversal(h))).isEqualTo("hdegabcf"); + assertThat(binaryIterationOrder(BIN_ADAPTER.breadthFirstTraversal(bd))).isEqualTo("dbeacfg"); } public void testInOrder() { - ASSERT.that(binaryIterationOrder(BIN_ADAPTER.inOrderTraversal(bd))).is("abcdegf"); + assertThat(binaryIterationOrder(BIN_ADAPTER.inOrderTraversal(bd))).isEqualTo("abcdegf"); } @GwtIncompatible("NullPointerTester") diff --git a/guava-tests/test/com/google/common/eventbus/EventBusTest.java b/guava-tests/test/com/google/common/eventbus/EventBusTest.java index 30fa0da52..35cb2f1e7 100644 --- a/guava-tests/test/com/google/common/eventbus/EventBusTest.java +++ b/guava-tests/test/com/google/common/eventbus/EventBusTest.java @@ -27,6 +27,7 @@ import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicInteger; /** * Test case for {@link EventBus}. @@ -285,13 +286,35 @@ public class EventBusTest extends TestCase { } } + /** + * Tests that bridge methods are not subscribed to events. In Java 8, + * annotations are included on the bridge method in addition to the original + * method, which causes both the original and bridge methods to be subscribed + * (since both are annotated @Subscribe) without specifically checking for + * bridge methods. + */ + public void testRegistrationWithBridgeMethod() { + final AtomicInteger calls = new AtomicInteger(); + bus.register(new Callback<String>() { + @Subscribe + @Override + public void call(String s) { + calls.incrementAndGet(); + } + }); + + bus.post("hello"); + + assertEquals(1, calls.get()); + } + private <T> void assertContains(T element, Collection<T> collection) { assertTrue("Collection must contain " + element, collection.contains(element)); } /** - * Records a thrown exception information. + * Records thrown exception information. */ private static final class RecordingSubscriberExceptionHandler implements SubscriberExceptionHandler { @@ -304,7 +327,6 @@ public class EventBusTest extends TestCase { SubscriberExceptionContext context) { this.exception = exception; this.context = context; - } } @@ -348,22 +370,25 @@ public class EventBusTest extends TestCase { } } - public interface HierarchyFixtureInterface { + private interface HierarchyFixtureInterface { // Exists only for hierarchy mapping; no members. } - public interface HierarchyFixtureSubinterface + private interface HierarchyFixtureSubinterface extends HierarchyFixtureInterface { // Exists only for hierarchy mapping; no members. } - public static class HierarchyFixtureParent + private static class HierarchyFixtureParent implements HierarchyFixtureSubinterface { // Exists only for hierarchy mapping; no members. } - public static class HierarchyFixture extends HierarchyFixtureParent { + private static class HierarchyFixture extends HierarchyFixtureParent { // Exists only for hierarchy mapping; no members. } + private interface Callback<T> { + void call(T t); + } } diff --git a/guava-tests/test/com/google/common/eventbus/outside/AnnotatedSubscriberFinderTests.java b/guava-tests/test/com/google/common/eventbus/outside/AnnotatedSubscriberFinderTests.java index 922b95699..b22eefd20 100644 --- a/guava-tests/test/com/google/common/eventbus/outside/AnnotatedSubscriberFinderTests.java +++ b/guava-tests/test/com/google/common/eventbus/outside/AnnotatedSubscriberFinderTests.java @@ -16,7 +16,7 @@ package com.google.common.eventbus.outside; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.Lists; import com.google.common.eventbus.EventBus; @@ -79,11 +79,11 @@ public class AnnotatedSubscriberFinderTests { } public void testNonSubscriber() { - ASSERT.that(getSubscriber().nonSubscriberEvents).isEmpty(); + assertThat(getSubscriber().nonSubscriberEvents).isEmpty(); } public void testSubscriber() { - ASSERT.that(getSubscriber().subscriberEvents).has().item(EVENT); + assertThat(getSubscriber().subscriberEvents).has().item(EVENT); } @Override @@ -119,11 +119,11 @@ public class AnnotatedSubscriberFinderTests { } public void testOverriddenAndAnnotatedInSubclass() { - ASSERT.that(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); + assertThat(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); } public void testOverriddenNotAnnotatedInSubclass() { - ASSERT.that(getSubscriber().overriddenInSubclassEvents).has().item(EVENT); + assertThat(getSubscriber().overriddenInSubclassEvents).has().item(EVENT); } @Override @@ -199,29 +199,27 @@ public class AnnotatedSubscriberFinderTests { } public void testNotOverriddenInSubclass() { - ASSERT.that(getSubscriber().notOverriddenInSubclassEvents).has().item(EVENT); + assertThat(getSubscriber().notOverriddenInSubclassEvents).has().item(EVENT); } public void testOverriddenNotAnnotatedInSubclass() { - ASSERT.that(getSubscriber().overriddenNotAnnotatedInSubclassEvents).has().item(EVENT); + assertThat(getSubscriber().overriddenNotAnnotatedInSubclassEvents).has().item(EVENT); } public void testDifferentlyOverriddenNotAnnotatedInSubclass() { - ASSERT - .that(getSubscriber().differentlyOverriddenNotAnnotatedInSubclassGoodEvents) + assertThat(getSubscriber().differentlyOverriddenNotAnnotatedInSubclassGoodEvents) .has().item(EVENT); - ASSERT.that(getSubscriber().differentlyOverriddenNotAnnotatedInSubclassBadEvents).isEmpty(); + assertThat(getSubscriber().differentlyOverriddenNotAnnotatedInSubclassBadEvents).isEmpty(); } public void testOverriddenAndAnnotatedInSubclass() { - ASSERT.that(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); + assertThat(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); } public void testDifferentlyOverriddenAndAnnotatedInSubclass() { - ASSERT - .that(getSubscriber().differentlyOverriddenAnnotatedInSubclassGoodEvents) + assertThat(getSubscriber().differentlyOverriddenAnnotatedInSubclassGoodEvents) .has().item(EVENT); - ASSERT.that(getSubscriber().differentlyOverriddenAnnotatedInSubclassBadEvents).isEmpty(); + assertThat(getSubscriber().differentlyOverriddenAnnotatedInSubclassBadEvents).isEmpty(); } @Override @@ -255,11 +253,11 @@ public class AnnotatedSubscriberFinderTests { } public void testOverriddenAndAnnotatedInSubclass() { - ASSERT.that(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); + assertThat(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); } public void testOverriddenInSubclassNowhereAnnotated() { - ASSERT.that(getSubscriber().overriddenInSubclassNowhereAnnotatedEvents).isEmpty(); + assertThat(getSubscriber().overriddenInSubclassNowhereAnnotatedEvents).isEmpty(); } @Override @@ -302,15 +300,15 @@ public class AnnotatedSubscriberFinderTests { } public void testNeitherOverriddenNorAnnotated() { - ASSERT.that(getSubscriber().neitherOverriddenNorAnnotatedEvents).isEmpty(); + assertThat(getSubscriber().neitherOverriddenNorAnnotatedEvents).isEmpty(); } public void testOverriddenInSubclassNowhereAnnotated() { - ASSERT.that(getSubscriber().overriddenInSubclassNowhereAnnotatedEvents).isEmpty(); + assertThat(getSubscriber().overriddenInSubclassNowhereAnnotatedEvents).isEmpty(); } public void testOverriddenAndAnnotatedInSubclass() { - ASSERT.that(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); + assertThat(getSubscriber().overriddenAndAnnotatedInSubclassEvents).has().item(EVENT); } @Override @@ -412,35 +410,35 @@ public class AnnotatedSubscriberFinderTests { } public void testAnnotatedIn1() { - ASSERT.that(getSubscriber().annotatedIn1Events).has().item(EVENT); + assertThat(getSubscriber().annotatedIn1Events).has().item(EVENT); } public void testAnnotatedIn2() { - ASSERT.that(getSubscriber().annotatedIn2Events).has().item(EVENT); + assertThat(getSubscriber().annotatedIn2Events).has().item(EVENT); } public void testAnnotatedIn1And2() { - ASSERT.that(getSubscriber().annotatedIn1And2Events).has().item(EVENT); + assertThat(getSubscriber().annotatedIn1And2Events).has().item(EVENT); } public void testAnnotatedIn1And2AndClass() { - ASSERT.that(getSubscriber().annotatedIn1And2AndClassEvents).has().item(EVENT); + assertThat(getSubscriber().annotatedIn1And2AndClassEvents).has().item(EVENT); } public void testDeclaredIn1AnnotatedIn2() { - ASSERT.that(getSubscriber().declaredIn1AnnotatedIn2Events).has().item(EVENT); + assertThat(getSubscriber().declaredIn1AnnotatedIn2Events).has().item(EVENT); } public void testDeclaredIn1AnnotatedInClass() { - ASSERT.that(getSubscriber().declaredIn1AnnotatedInClassEvents).has().item(EVENT); + assertThat(getSubscriber().declaredIn1AnnotatedInClassEvents).has().item(EVENT); } public void testDeclaredIn2AnnotatedInClass() { - ASSERT.that(getSubscriber().declaredIn2AnnotatedInClassEvents).has().item(EVENT); + assertThat(getSubscriber().declaredIn2AnnotatedInClassEvents).has().item(EVENT); } public void testNowhereAnnotated() { - ASSERT.that(getSubscriber().nowhereAnnotatedEvents).isEmpty(); + assertThat(getSubscriber().nowhereAnnotatedEvents).isEmpty(); } @Override diff --git a/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java b/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java index cfcdff7bf..c7626c28c 100644 --- a/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java +++ b/guava-tests/test/com/google/common/hash/AbstractByteHasherTest.java @@ -20,7 +20,6 @@ import static org.junit.Assert.assertArrayEquals; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; import java.util.Random; /** @@ -65,15 +64,15 @@ public class AbstractByteHasherTest extends TestCase { hasher.assertBytes(new byte[]{1, 2}); } - public void testString() throws UnsupportedEncodingException { + public void testString() { Random random = new Random(); for (int i = 0; i < 100; i++) { byte[] bytes = new byte[64]; random.nextBytes(bytes); - String s = new String(bytes, UTF_16LE.name()); // so all random strings are valid + String s = new String(bytes, UTF_16LE); // so all random strings are valid assertEquals( new TestHasher().putUnencodedChars(s).hash(), - new TestHasher().putBytes(s.getBytes(UTF_16LE.name())).hash()); + new TestHasher().putBytes(s.getBytes(UTF_16LE)).hash()); assertEquals( new TestHasher().putUnencodedChars(s).hash(), new TestHasher().putString(s, UTF_16LE).hash()); diff --git a/guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java b/guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java index a26be17dc..0c8ddf35b 100644 --- a/guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java +++ b/guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java @@ -18,15 +18,13 @@ package com.google.common.hash; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashTestUtils.RandomHasherAction; -import com.google.common.jdk5backport.Arrays; - -import junit.framework.TestCase; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.charset.Charset; +import java.util.Arrays; import java.util.List; import java.util.Random; diff --git a/guava-tests/test/com/google/common/hash/AbstractStreamingHasherTest.java b/guava-tests/test/com/google/common/hash/AbstractStreamingHasherTest.java index 75eb13f37..901fcc09b 100644 --- a/guava-tests/test/com/google/common/hash/AbstractStreamingHasherTest.java +++ b/guava-tests/test/com/google/common/hash/AbstractStreamingHasherTest.java @@ -22,15 +22,14 @@ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.hash.AbstractStreamingHashFunction.AbstractStreamingHasher; import com.google.common.hash.HashTestUtils.RandomHasherAction; -import com.google.common.jdk5backport.Arrays; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; @@ -86,15 +85,15 @@ public class AbstractStreamingHasherTest extends TestCase { sink.assertBytes(new byte[] { 1, 2, 0, 0 }); // padded with zeros } - public void testString() throws UnsupportedEncodingException { + public void testString() { Random random = new Random(); for (int i = 0; i < 100; i++) { byte[] bytes = new byte[64]; random.nextBytes(bytes); - String s = new String(bytes, UTF_16LE.name()); // so all random strings are valid + String s = new String(bytes, UTF_16LE); // so all random strings are valid assertEquals( new Sink(4).putUnencodedChars(s).hash(), - new Sink(4).putBytes(s.getBytes(UTF_16LE.name())).hash()); + new Sink(4).putBytes(s.getBytes(UTF_16LE)).hash()); assertEquals( new Sink(4).putUnencodedChars(s).hash(), new Sink(4).putString(s, UTF_16LE).hash()); diff --git a/guava-tests/test/com/google/common/hash/BloomFilterTest.java b/guava-tests/test/com/google/common/hash/BloomFilterTest.java index be8c6146d..4f54d1079 100644 --- a/guava-tests/test/com/google/common/hash/BloomFilterTest.java +++ b/guava-tests/test/com/google/common/hash/BloomFilterTest.java @@ -16,6 +16,7 @@ package com.google.common.hash; +import static com.google.common.base.Charsets.UTF_8; import static com.google.common.hash.BloomFilterStrategies.BitArray; import com.google.common.collect.ImmutableSet; @@ -27,6 +28,8 @@ import com.google.common.testing.SerializableTester; import junit.framework.TestCase; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.math.RoundingMode; import java.util.Random; @@ -53,7 +56,7 @@ public class BloomFilterTest extends TestCase { public void testCreateAndCheckMitz32BloomFilterWithKnownFalsePositives() { int numInsertions = 1000000; - BloomFilter<CharSequence> bf = BloomFilter.create( + BloomFilter<String> bf = BloomFilter.create( Funnels.unencodedCharsFunnel(), numInsertions, 0.03, BloomFilterStrategies.MURMUR128_MITZ_32); @@ -94,7 +97,7 @@ public class BloomFilterTest extends TestCase { public void testCreateAndCheckBloomFilterWithKnownFalsePositives64() { int numInsertions = 1000000; - BloomFilter<CharSequence> bf = BloomFilter.create( + BloomFilter<String> bf = BloomFilter.create( Funnels.unencodedCharsFunnel(), numInsertions, 0.03, BloomFilterStrategies.MURMUR128_MITZ_64); @@ -133,6 +136,47 @@ public class BloomFilterTest extends TestCase { assertEquals(actualFpp, expectedFpp, 0.00033); } + public void testCreateAndCheckBloomFilterWithKnownUtf8FalsePositives64() { + int numInsertions = 1000000; + BloomFilter<String> bf = BloomFilter.create( + Funnels.stringFunnel(UTF_8), numInsertions, 0.03, + BloomFilterStrategies.MURMUR128_MITZ_64); + + // Insert "numInsertions" even numbers into the BF. + for (int i = 0; i < numInsertions * 2; i += 2) { + bf.put(Integer.toString(i)); + } + + // Assert that the BF "might" have all of the even numbers. + for (int i = 0; i < numInsertions * 2; i += 2) { + assertTrue(bf.mightContain(Integer.toString(i))); + } + + // Now we check for known false positives using a set of known false positives. + // (These are all of the false positives under 900.) + ImmutableSet<Integer> falsePositives = + ImmutableSet.of(129, 471, 723, 89, 751, 835, 871); + for (int i = 1; i < 900; i += 2) { + if (!falsePositives.contains(i)) { + assertFalse("BF should not contain " + i, bf.mightContain(Integer.toString(i))); + } + } + + // Check that there are exactly 29763 false positives for this BF. + int knownNumberOfFalsePositives = 29763; + int numFpp = 0; + for (int i = 1; i < numInsertions * 2; i += 2) { + if (bf.mightContain(Integer.toString(i))) { + numFpp++; + } + } + assertEquals(knownNumberOfFalsePositives, numFpp); + double actualFpp = (double) knownNumberOfFalsePositives / numInsertions; + double expectedFpp = bf.expectedFpp(); + // The normal order of (expected, actual) is reversed here on purpose. + assertEquals(actualFpp, expectedFpp, 0.00033); + } + /** * Sanity checking with many combinations of false positive rates and expected insertions */ @@ -189,6 +233,11 @@ public class BloomFilterTest extends TestCase { } } + // https://code.google.com/p/guava-libraries/issues/detail?id=1781 + public void testOptimalNumOfHashFunctionsRounding() { + assertEquals(7, BloomFilter.optimalNumOfHashFunctions(319, 3072)); + } + /** * Tests that we always get a non-negative optimal size. */ @@ -228,8 +277,8 @@ public class BloomFilterTest extends TestCase { } public void testCopy() { - BloomFilter<CharSequence> original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); - BloomFilter<CharSequence> copy = original.copy(); + BloomFilter<String> original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); + BloomFilter<String> copy = original.copy(); assertNotSame(original, copy); assertEquals(original, copy); } @@ -273,11 +322,11 @@ public class BloomFilterTest extends TestCase { } public void testEquals() { - BloomFilter<CharSequence> bf1 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); + BloomFilter<String> bf1 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); bf1.put("1"); bf1.put("2"); - BloomFilter<CharSequence> bf2 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); + BloomFilter<String> bf2 = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); bf2.put("1"); bf2.put("2"); @@ -320,7 +369,7 @@ public class BloomFilterTest extends TestCase { public void testPutReturnValue() { for (int i = 0; i < 10; i++) { - BloomFilter<CharSequence> bf = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); + BloomFilter<String> bf = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100); for (int j = 0; j < 10; j++) { String value = new Object().toString(); boolean mightContain = bf.mightContain(value); @@ -396,6 +445,19 @@ public class BloomFilterTest extends TestCase { SerializableTester.reserializeAndAssert(bf); } + public void testCustomSerialization() throws Exception { + Funnel<byte[]> funnel = Funnels.byteArrayFunnel(); + BloomFilter<byte[]> bf = BloomFilter.create(funnel, 100); + for (int i = 0; i < 100; i++) { + bf.put(Ints.toByteArray(i)); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bf.writeTo(out); + + assertEquals(bf, BloomFilter.readFrom(new ByteArrayInputStream(out.toByteArray()), funnel)); + } + /** * This test will fail whenever someone updates/reorders the BloomFilterStrategies constants. * Only appending a new constant is allowed. @@ -405,23 +467,4 @@ public class BloomFilterTest extends TestCase { assertEquals(BloomFilterStrategies.MURMUR128_MITZ_32, BloomFilterStrategies.values()[0]); assertEquals(BloomFilterStrategies.MURMUR128_MITZ_64, BloomFilterStrategies.values()[1]); } - - public void testGetDefaultStrategyFromSystemProperty() { - // clear the property to test the case when the property is not set (the default) - System.clearProperty(BloomFilter.USE_MITZ32_PROPERTY); - assertEquals(BloomFilterStrategies.MURMUR128_MITZ_64, - BloomFilter.getDefaultStrategyFromSystemProperty()); - - System.setProperty(BloomFilter.USE_MITZ32_PROPERTY, "true"); - assertEquals(BloomFilterStrategies.MURMUR128_MITZ_32, - BloomFilter.getDefaultStrategyFromSystemProperty()); - - System.setProperty(BloomFilter.USE_MITZ32_PROPERTY, "TRUE"); - assertEquals(BloomFilterStrategies.MURMUR128_MITZ_32, - BloomFilter.getDefaultStrategyFromSystemProperty()); - - System.setProperty(BloomFilter.USE_MITZ32_PROPERTY, "false"); - assertEquals(BloomFilterStrategies.MURMUR128_MITZ_64, - BloomFilter.getDefaultStrategyFromSystemProperty()); - } } diff --git a/guava-tests/test/com/google/common/hash/Crc32cHashFunctionTest.java b/guava-tests/test/com/google/common/hash/Crc32cHashFunctionTest.java new file mode 100644 index 000000000..b36f7235d --- /dev/null +++ b/guava-tests/test/com/google/common/hash/Crc32cHashFunctionTest.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.common.hash; + +import static com.google.common.base.Charsets.UTF_8; + +import junit.framework.TestCase; + +import java.util.Arrays; + +/** + * Unit tests for {@link Crc32c}. Known test values are from RFC 3720, Section B.4. + * + * @author Patrick Costello + * @author Kurt Alfred Kluever + */ +public class Crc32cHashFunctionTest extends TestCase { + + public void testZeros() { + // Test 32 byte array of 0x00. + byte[] zeros = new byte[32]; + Arrays.fill(zeros, (byte) 0x00); + assertCrc(0x8a9136aa, zeros); + } + + public void testFull() { + // Test 32 byte array of 0xFF. + byte[] fulls = new byte[32]; + Arrays.fill(fulls, (byte) 0xFF); + assertCrc(0x62a8ab43, fulls); + } + + public void testAscending() { + // Test 32 byte arrays of ascending. + byte[] ascending = new byte[32]; + for (int i = 0; i < 32; i++) { + ascending[i] = (byte) i; + } + assertCrc(0x46dd794e, ascending); + } + + public void testDescending() { + // Test 32 byte arrays of descending. + byte[] descending = new byte[32]; + for (int i = 0; i < 32; i++) { + descending[i] = (byte) (31 - i); + } + assertCrc(0x113fdb5c, descending); + } + + public void testScsiReadCommad() { + // Test SCSI read command. + byte[] scsiReadCommand = new byte[] { + 0x01, (byte) 0xc0, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x14, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x14, + 0x00, 0x00, 0x00, 0x18, + 0x28, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00 }; + assertCrc(0xd9963a56, scsiReadCommand); + } + + // Known values from http://www.evanjones.ca/crc32c.html + public void testSomeOtherKnownValues() { + assertCrc(0x22620404, "The quick brown fox jumps over the lazy dog".getBytes(UTF_8)); + assertCrc(0xE3069283, "123456789".getBytes(UTF_8)); + assertCrc(0xf3dbd4fe, "1234567890".getBytes(UTF_8)); + assertCrc(0xBFE92A83, "23456789".getBytes(UTF_8)); + } + + /** + * Verfies that the crc of an array of byte data matches the expected value. + * + * @param expectedCrc the expected crc value. + * @param data the data to run the checksum on. + */ + private static void assertCrc(int expectedCrc, byte[] data) { + int actualCrc = Hashing.crc32c().hashBytes(data).asInt(); + assertEquals(expectedCrc, actualCrc); + } + + // From RFC 3720, Section 12.1, the polynomial generator is 0x11EDC6F41. + // We calculate the constant below by: + // 1. Omitting the most significant bit (because it's always 1). => 0x1EDC6F41 + // 2. Flipping the bits of the constant so we can process a byte at a time. => 0x82F63B78 + private static final int CRC32C_GENERATOR = 0x1EDC6F41; // 0x11EDC6F41 + private static final int CRC32C_GENERATOR_FLIPPED = Integer.reverse(CRC32C_GENERATOR); + + public void testCrc32cLookupTable() { + // See Hacker's Delight 2nd Edition, Figure 14-7. + int[] expected = new int[256]; + for (int i = 0; i < expected.length; i++) { + int crc = i; + for (int j = 7; j >= 0; j--) { + int mask = -(crc & 1); + crc = ((crc >>> 1) ^ (CRC32C_GENERATOR_FLIPPED & mask)); + } + expected[i] = crc; + } + + int[] actual = Crc32cHashFunction.Crc32cHasher.CRC_TABLE; + assertTrue( + "Expected: \n" + Arrays.toString(expected) + "\nActual:\n" + Arrays.toString(actual), + Arrays.equals(expected, actual)); + } +} diff --git a/guava-tests/test/com/google/common/hash/HashCodeTest.java b/guava-tests/test/com/google/common/hash/HashCodeTest.java index 196ef0267..a15a57bd4 100644 --- a/guava-tests/test/com/google/common/hash/HashCodeTest.java +++ b/guava-tests/test/com/google/common/hash/HashCodeTest.java @@ -21,11 +21,12 @@ import static com.google.common.io.BaseEncoding.base16; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; -import com.google.common.jdk5backport.Arrays; import com.google.common.testing.ClassSanityTester; import junit.framework.TestCase; +import java.util.Arrays; + /** * Unit tests for {@link HashCode}. * diff --git a/guava-tests/test/com/google/common/hash/HashTestUtils.java b/guava-tests/test/com/google/common/hash/HashTestUtils.java index 5427513a4..886ad912e 100644 --- a/guava-tests/test/com/google/common/hash/HashTestUtils.java +++ b/guava-tests/test/com/google/common/hash/HashTestUtils.java @@ -21,13 +21,13 @@ import static org.junit.Assert.assertEquals; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -import com.google.common.jdk5backport.Arrays; import com.google.common.primitives.Ints; import com.google.common.testing.EqualsTester; import org.junit.Assert; import java.nio.charset.Charset; +import java.util.Arrays; import java.util.Random; import java.util.Set; @@ -227,7 +227,7 @@ final class HashTestUtils { return actions[random.nextInt(actions.length)]; } } - + /** * Test that the hash function contains no funnels. A funnel is a situation where a set of input * (key) bits 'affects' a strictly smaller set of output bits. Funneling is bad because it can diff --git a/guava-tests/test/com/google/common/hash/HashingInputStreamTest.java b/guava-tests/test/com/google/common/hash/HashingInputStreamTest.java index f6709ceb3..326cc8e3e 100644 --- a/guava-tests/test/com/google/common/hash/HashingInputStreamTest.java +++ b/guava-tests/test/com/google/common/hash/HashingInputStreamTest.java @@ -24,6 +24,7 @@ import junit.framework.TestCase; import org.easymock.EasyMock; import java.io.ByteArrayInputStream; +import java.util.Arrays; /** * Tests for {@link HashingInputStream}. @@ -76,7 +77,7 @@ public class HashingInputStreamTest extends TestCase { } public void testRead_putByteArrayAtPos() throws Exception { - EasyMock.expect(hasher.putBytes(aryEq(new byte[] {'y', 'a', 'm'}), eq(0), eq(3))) + EasyMock.expect(hasher.putBytes(aryEq(Arrays.copyOfRange(testBytes, 0, 3)), eq(0), eq(3))) .andReturn(hasher).once(); EasyMock.replay(hasher); HashingInputStream in = new HashingInputStream(hashFunction, buffer); diff --git a/guava-tests/test/com/google/common/hash/HashingTest.java b/guava-tests/test/com/google/common/hash/HashingTest.java index 89a239755..74b43c9cf 100644 --- a/guava-tests/test/com/google/common/hash/HashingTest.java +++ b/guava-tests/test/com/google/common/hash/HashingTest.java @@ -414,6 +414,9 @@ public class HashingTest extends TestCase { .put(Hashing.sipHash24(), EMPTY_STRING, "310e0edd47db6f72") .put(Hashing.sipHash24(), TQBFJOTLD, "e46f1fdc05612752") .put(Hashing.sipHash24(), TQBFJOTLDP, "9b602581fce4d4f8") + .put(Hashing.crc32c(), EMPTY_STRING, "00000000") + .put(Hashing.crc32c(), TQBFJOTLD, "04046222") + .put(Hashing.crc32c(), TQBFJOTLDP, "b3970019") .build(); public void testAllHashFunctionsHaveKnownHashes() throws Exception { diff --git a/guava-tests/test/com/google/common/hash/MessageDigestHashFunctionTest.java b/guava-tests/test/com/google/common/hash/MessageDigestHashFunctionTest.java index 2a625d672..4ff932a5f 100644 --- a/guava-tests/test/com/google/common/hash/MessageDigestHashFunctionTest.java +++ b/guava-tests/test/com/google/common/hash/MessageDigestHashFunctionTest.java @@ -19,12 +19,13 @@ package com.google.common.hash; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.jdk5backport.Arrays; import junit.framework.TestCase; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + /** * Tests for the MessageDigestHashFunction. * diff --git a/guava-tests/test/com/google/common/io/ByteSinkTester.java b/guava-tests/test/com/google/common/io/ByteSinkTester.java index 5222a184a..a743be59e 100644 --- a/guava-tests/test/com/google/common/io/ByteSinkTester.java +++ b/guava-tests/test/com/google/common/io/ByteSinkTester.java @@ -28,7 +28,6 @@ import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.util.Map; @@ -56,12 +55,7 @@ public class ByteSinkTester extends SourceSinkTester<ByteSink, byte[], ByteSinkF private static TestSuite suiteForString(String name, ByteSinkFactory factory, String string, String desc) { - byte[] bytes; - try { - bytes = string.getBytes(Charsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + byte[] bytes = string.getBytes(Charsets.UTF_8); TestSuite suite = suiteForBytes(name, factory, desc, bytes); CharSinkFactory charSinkFactory = SourceSinkFactories.asCharSinkFactory(factory); suite.addTest(CharSinkTester.suiteForString(name + ".asCharSink[Charset]", charSinkFactory, diff --git a/guava-tests/test/com/google/common/io/ByteSourceTest.java b/guava-tests/test/com/google/common/io/ByteSourceTest.java index c40fcdd3e..24aaeedfe 100644 --- a/guava-tests/test/com/google/common/io/ByteSourceTest.java +++ b/guava-tests/test/com/google/common/io/ByteSourceTest.java @@ -164,7 +164,7 @@ public class ByteSourceTest extends IoTestCase { } public void testHash() throws IOException { - ByteSource byteSource = new TestByteSource("hamburger\n".getBytes(Charsets.US_ASCII.name())); + ByteSource byteSource = new TestByteSource("hamburger\n".getBytes(Charsets.US_ASCII)); // Pasted this expected string from `echo hamburger | md5sum` assertEquals("cfa0c5002275c90508338a5cdb2a9781", byteSource.hash(Hashing.md5()).toString()); @@ -219,8 +219,8 @@ public class ByteSourceTest extends IoTestCase { /** * @param input the size of the input source - * @param offset the first argument to {@link ByteStreams#slice} - * @param length the second argument to {@link ByteStreams#slice} + * @param offset the first argument to {@link ByteSource#slice} + * @param length the second argument to {@link ByteSource#slice} * @param expectRead the number of bytes we expect to read */ private static void assertCorrectSlice( diff --git a/guava-tests/test/com/google/common/io/ByteSourceTester.java b/guava-tests/test/com/google/common/io/ByteSourceTester.java index 789cb8f37..f9a735e86 100644 --- a/guava-tests/test/com/google/common/io/ByteSourceTester.java +++ b/guava-tests/test/com/google/common/io/ByteSourceTester.java @@ -32,7 +32,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.util.Map; import java.util.Random; @@ -56,12 +55,8 @@ public class ByteSourceTester extends SourceSinkTester<ByteSource, byte[], ByteS if (testAsCharSource) { suite.addTest(suiteForString(factory, entry.getValue(), name, entry.getKey())); } else { - try { - suite.addTest(suiteForBytes(factory, entry.getValue().getBytes(Charsets.UTF_8.name()), - name, entry.getKey(), true)); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + suite.addTest(suiteForBytes( + factory, entry.getValue().getBytes(Charsets.UTF_8), name, entry.getKey(), true)); } } return suite; @@ -69,12 +64,7 @@ public class ByteSourceTester extends SourceSinkTester<ByteSource, byte[], ByteS private static TestSuite suiteForString(ByteSourceFactory factory, String string, String name, String desc) { - TestSuite suite; - try { - suite = suiteForBytes(factory, string.getBytes(Charsets.UTF_8.name()), name, desc, true); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + TestSuite suite = suiteForBytes(factory, string.getBytes(Charsets.UTF_8), name, desc, true); CharSourceFactory charSourceFactory = SourceSinkFactories.asCharSourceFactory(factory); suite.addTest(CharSourceTester.suiteForString(charSourceFactory, string, name + ".asCharSource[Charset]", desc)); diff --git a/guava-tests/test/com/google/common/io/ByteStreamsTest.java b/guava-tests/test/com/google/common/io/ByteStreamsTest.java index fc5b99d7d..484b48d1d 100644 --- a/guava-tests/test/com/google/common/io/ByteStreamsTest.java +++ b/guava-tests/test/com/google/common/io/ByteStreamsTest.java @@ -16,9 +16,7 @@ package com.google.common.io; -import static com.google.common.base.Charsets.UTF_16; import com.google.common.base.Charsets; -import com.google.common.jdk5backport.Arrays; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -27,10 +25,10 @@ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; +import java.util.Arrays; /** * Unit test for {@link ByteStreams}. @@ -181,9 +179,9 @@ public class ByteStreamsTest extends IoTestCase { assertEquals(bytes[1], actual[3]); } - public void testNewDataInput_readLine() throws UnsupportedEncodingException { + public void testNewDataInput_readLine() { ByteArrayDataInput in = ByteStreams.newDataInput( - "This is a line\r\nThis too\rand this\nand also this".getBytes(Charsets.UTF_8.name())); + "This is a line\r\nThis too\rand this\nand also this".getBytes(Charsets.UTF_8)); assertEquals("This is a line", in.readLine()); assertEquals("This too", in.readLine()); assertEquals("and this", in.readLine()); @@ -203,16 +201,16 @@ public class ByteStreamsTest extends IoTestCase { assertEquals(Double.longBitsToDouble(0x1234567876543210L), in.readDouble(), 0.0); } - public void testNewDataInput_readUTF() throws UnsupportedEncodingException { + public void testNewDataInput_readUTF() { byte[] data = new byte[17]; data[1] = 15; - System.arraycopy("Kilroy was here".getBytes(Charsets.UTF_8.name()), 0, data, 2, 15); + System.arraycopy("Kilroy was here".getBytes(Charsets.UTF_8), 0, data, 2, 15); ByteArrayDataInput in = ByteStreams.newDataInput(data); assertEquals("Kilroy was here", in.readUTF()); } - public void testNewDataInput_readChar() throws UnsupportedEncodingException { - byte[] data = "qed".getBytes(Charsets.UTF_16BE.name()); + public void testNewDataInput_readChar() { + byte[] data = "qed".getBytes(Charsets.UTF_16BE); ByteArrayDataInput in = ByteStreams.newDataInput(data); assertEquals('q', in.readChar()); assertEquals('e', in.readChar()); @@ -346,18 +344,18 @@ public class ByteStreamsTest extends IoTestCase { assertEquals(new byte[] {0, 97}, out.toByteArray()); } - public void testNewDataOutput_writeChars() throws UnsupportedEncodingException { + public void testNewDataOutput_writeChars() { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeChars("r\u00C9sum\u00C9"); // need to remove byte order mark before comparing - byte[] expected = Arrays.copyOfRange("r\u00C9sum\u00C9".getBytes(UTF_16.name()), 2, 14); + byte[] expected = Arrays.copyOfRange("r\u00C9sum\u00C9".getBytes(Charsets.UTF_16), 2, 14); assertEquals(expected, out.toByteArray()); } - public void testNewDataOutput_writeUTF() throws UnsupportedEncodingException { + public void testNewDataOutput_writeUTF() { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("r\u00C9sum\u00C9"); - byte[] expected ="r\u00C9sum\u00C9".getBytes(Charsets.UTF_8.name()); + byte[] expected ="r\u00C9sum\u00C9".getBytes(Charsets.UTF_8); byte[] actual = out.toByteArray(); // writeUTF writes the length of the string in 2 bytes assertEquals(0, actual[0]); diff --git a/guava-tests/test/com/google/common/io/CharSourceTester.java b/guava-tests/test/com/google/common/io/CharSourceTester.java index 8d5bc79a1..f2882cdf2 100644 --- a/guava-tests/test/com/google/common/io/CharSourceTester.java +++ b/guava-tests/test/com/google/common/io/CharSourceTester.java @@ -139,7 +139,7 @@ public class CharSourceTester extends SourceSinkTester<CharSource, String, CharS } public void testIsEmpty() throws IOException { - assertEquals(expected.length() == 0, source.isEmpty()); + assertEquals(expected.isEmpty(), source.isEmpty()); } public void testReadLines_withProcessor() throws IOException { diff --git a/guava-tests/test/com/google/common/io/CloserTest.java b/guava-tests/test/com/google/common/io/CloserTest.java index 9481ca5d3..c33a4b8b5 100644 --- a/guava-tests/test/com/google/common/io/CloserTest.java +++ b/guava-tests/test/com/google/common/io/CloserTest.java @@ -16,6 +16,7 @@ package com.google.common.io; +import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Splitter; import com.google.common.base.Throwables; @@ -422,7 +423,7 @@ public class CloserTest extends TestCase { @Override public String toString() { - return Objects.toStringHelper(this) + return MoreObjects.toStringHelper(this) .add("closeable", closeable) .add("thrown", thrown) .add("suppressed", suppressed) diff --git a/guava-tests/test/com/google/common/io/FilesTest.java b/guava-tests/test/com/google/common/io/FilesTest.java index f8eb3d029..5a4dd68f0 100644 --- a/guava-tests/test/com/google/common/io/FilesTest.java +++ b/guava-tests/test/com/google/common/io/FilesTest.java @@ -18,7 +18,7 @@ package com.google.common.io; import static com.google.common.io.Files.createTempDir; import static com.google.common.io.Files.touch; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; @@ -73,11 +73,11 @@ public class FilesTest extends IoTestCase { public void testToByteArray() throws IOException { File asciiFile = getTestFile("ascii.txt"); File i18nFile = getTestFile("i18n.txt"); - assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII.name()), + assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), Files.toByteArray(asciiFile))); - assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8.name()), + assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.toByteArray(i18nFile))); - assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8.name()), + assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.asByteSource(i18nFile).read())); } @@ -88,7 +88,7 @@ public class FilesTest extends IoTestCase { try { InputStream in = closer.register(new FileInputStream(asciiFile)); byte[] bytes = Files.readFile(in, asciiFile.length()); - assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII.name()), bytes)); + assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), bytes)); } catch (Throwable e) { throw closer.rethrow(e); } finally { @@ -103,7 +103,7 @@ public class FilesTest extends IoTestCase { try { InputStream in = closer.register(new FileInputStream(asciiFile)); byte[] bytes = Files.readFile(in, 10); - assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII.name()), bytes)); + assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), bytes)); } catch (Throwable e) { throw closer.rethrow(e); } finally { @@ -118,7 +118,7 @@ public class FilesTest extends IoTestCase { try { InputStream in = closer.register(new FileInputStream(asciiFile)); byte[] bytes = Files.readFile(in, 500); - assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII.name()), bytes)); + assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), bytes)); } catch (Throwable e) { throw closer.rethrow(e); } finally { @@ -133,7 +133,7 @@ public class FilesTest extends IoTestCase { try { InputStream in = closer.register(new FileInputStream(asciiFile)); byte[] bytes = Files.readFile(in, 0); - assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII.name()), bytes)); + assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), bytes)); } catch (Throwable e) { throw closer.rethrow(e); } finally { @@ -166,26 +166,10 @@ public class FilesTest extends IoTestCase { File i18nFile = getTestFile("i18n.txt"); assertEquals(ASCII, Files.toString(asciiFile, Charsets.US_ASCII)); assertEquals(I18N, Files.toString(i18nFile, Charsets.UTF_8)); - ASSERT.that(Files.toString(i18nFile, Charsets.US_ASCII)) + assertThat(Files.toString(i18nFile, Charsets.US_ASCII)) .isNotEqualTo(I18N); } - public void testCopyCharacters() throws IOException { - File i18nFile = getTestFile("i18n.txt"); - File temp = createTempFile(); - Files.copy(i18nFile, Charsets.UTF_8, - Files.asCharSink(temp, Charsets.UTF_8)); - assertEquals(I18N, Files.toString(temp, Charsets.UTF_8)); - - Files.copy(Files.asCharSource(i18nFile, Charsets.UTF_8), temp, - Charsets.UTF_8); - assertEquals(I18N, Files.toString(temp, Charsets.UTF_8)); - - Files.copy(i18nFile, Charsets.UTF_8, - Files.asCharSink(temp, Charsets.UTF_16LE)); - assertEquals(I18N, Files.toString(temp, Charsets.UTF_16LE)); - } - public void testWriteString() throws IOException { File temp = createTempFile(); Files.write(I18N, temp, Charsets.UTF_16LE); @@ -229,20 +213,6 @@ public class FilesTest extends IoTestCase { assertEquals(I18N, sb.toString()); } - public void testCopyToByteSink() throws IOException { - File i18nFile = getTestFile("i18n.txt"); - File temp = createTempFile(); - Files.copy(i18nFile, Files.asByteSink(temp)); - assertEquals(I18N, Files.toString(temp, Charsets.UTF_8)); - } - - public void testCopyFromByteSource() throws IOException { - File i18nFile = getTestFile("i18n.txt"); - File temp = createTempFile(); - Files.copy(Files.asByteSource(i18nFile), temp); - assertEquals(I18N, Files.toString(temp, Charsets.UTF_8)); - } - public void testCopyFile() throws IOException { File i18nFile = getTestFile("i18n.txt"); File temp = createTempFile(); @@ -387,7 +357,7 @@ public class FilesTest extends IoTestCase { temp.setLastModified(0); assertEquals(0, temp.lastModified()); Files.touch(temp); - ASSERT.that(temp.lastModified()).isNotEqualTo(0); + assertThat(temp.lastModified()).isNotEqualTo(0); } public void testCreateParentDirs_root() throws IOException { @@ -562,7 +532,7 @@ public class FilesTest extends IoTestCase { return collector; } }; - ASSERT.that(Files.readLines(temp, Charsets.UTF_8, collect)).isEmpty(); + assertThat(Files.readLines(temp, Charsets.UTF_8, collect)).isEmpty(); PrintWriter w = new PrintWriter(Files.newWriter(temp, Charsets.UTF_8)); w.println("hello"); @@ -571,7 +541,7 @@ public class FilesTest extends IoTestCase { w.println(""); w.close(); Files.readLines(temp, Charsets.UTF_8, collect); - ASSERT.that(collect.getResult()) + assertThat(collect.getResult()) .has().exactly("hello", "", " world ", "").inOrder(); LineProcessor<List<String>> collectNonEmptyLines = @@ -592,7 +562,7 @@ public class FilesTest extends IoTestCase { } }; Files.readLines(temp, Charsets.UTF_8, collectNonEmptyLines); - ASSERT.that(collectNonEmptyLines.getResult()).has().exactly( + assertThat(collectNonEmptyLines.getResult()).has().exactly( "hello", " world ").inOrder(); assertTrue(temp.delete()); diff --git a/guava-tests/test/com/google/common/io/LittleEndianDataOutputStreamTest.java b/guava-tests/test/com/google/common/io/LittleEndianDataOutputStreamTest.java index 109bf0e14..93e98093d 100644 --- a/guava-tests/test/com/google/common/io/LittleEndianDataOutputStreamTest.java +++ b/guava-tests/test/com/google/common/io/LittleEndianDataOutputStreamTest.java @@ -34,9 +34,9 @@ import java.io.IOException; */ public class LittleEndianDataOutputStreamTest extends TestCase { - private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - private final LittleEndianDataOutputStream out = new LittleEndianDataOutputStream(baos); - + private ByteArrayOutputStream baos = new ByteArrayOutputStream(); + private LittleEndianDataOutputStream out = new LittleEndianDataOutputStream(baos); + public void testWriteLittleEndian() throws IOException { /* Write out various test values in LITTLE ENDIAN FORMAT */ @@ -79,10 +79,10 @@ public class LittleEndianDataOutputStreamTest extends TestCase { assertEquals(0xBEBAFECA, Float.floatToIntBits(in.readFloat())); assertEquals(0xBEBAFECAEFBEADDEL, Double.doubleToLongBits(in.readDouble())); } - + @SuppressWarnings("deprecation") // testing a deprecated method public void testWriteBytes() throws IOException { - + /* Write out various test values in LITTLE ENDIAN FORMAT */ out.writeBytes("r\u00C9sum\u00C9"); @@ -94,12 +94,12 @@ public class LittleEndianDataOutputStreamTest extends TestCase { /* Read in various values NORMALLY */ byte[] b = new byte[6]; in.readFully(b); - assertEquals("r\u00C9sum\u00C9".getBytes(Charsets.ISO_8859_1.name()), b); + assertEquals("r\u00C9sum\u00C9".getBytes(Charsets.ISO_8859_1), b); } - + @SuppressWarnings("deprecation") // testing a deprecated method public void testWriteBytes_discardHighOrderBytes() throws IOException { - + /* Write out various test values in LITTLE ENDIAN FORMAT */ out.writeBytes("\uAAAA\uAABB\uAACC"); diff --git a/guava-tests/test/com/google/common/io/ResourcesTest.java b/guava-tests/test/com/google/common/io/ResourcesTest.java index dac1d80af..3bf17accb 100644 --- a/guava-tests/test/com/google/common/io/ResourcesTest.java +++ b/guava-tests/test/com/google/common/io/ResourcesTest.java @@ -17,7 +17,7 @@ package com.google.common.io; import static com.google.common.base.CharMatcher.WHITESPACE; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; @@ -56,7 +56,7 @@ public class ResourcesTest extends IoTestCase { public void testToString() throws IOException { URL resource = getClass().getResource("testdata/i18n.txt"); assertEquals(I18N, Resources.toString(resource, Charsets.UTF_8)); - ASSERT.that(Resources.toString(resource, Charsets.US_ASCII)) + assertThat(Resources.toString(resource, Charsets.US_ASCII)) .isNotEqualTo(I18N); } diff --git a/guava-tests/test/com/google/common/io/SourceSinkFactories.java b/guava-tests/test/com/google/common/io/SourceSinkFactories.java index 56c73e2d8..0165bf816 100644 --- a/guava-tests/test/com/google/common/io/SourceSinkFactories.java +++ b/guava-tests/test/com/google/common/io/SourceSinkFactories.java @@ -23,7 +23,6 @@ import static com.google.common.io.SourceSinkFactory.CharSinkFactory; import static com.google.common.io.SourceSinkFactory.CharSourceFactory; import com.google.common.base.Charsets; -import com.google.common.jdk5backport.Arrays; import java.io.ByteArrayOutputStream; import java.io.File; @@ -35,9 +34,9 @@ import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; -import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.CharBuffer; +import java.util.Arrays; import java.util.logging.Logger; import javax.annotation.Nullable; @@ -77,11 +76,7 @@ public class SourceSinkFactories { public static ByteSinkFactory appendingFileByteSinkFactory() { String initialString = IoTestCase.ASCII + IoTestCase.I18N; - try { - return new FileByteSinkFactory(initialString.getBytes(Charsets.UTF_8.name())); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + return new FileByteSinkFactory(initialString.getBytes(Charsets.UTF_8)); } public static CharSourceFactory fileCharSourceFactory() { @@ -110,18 +105,13 @@ public class SourceSinkFactories { return new CharSourceFactory() { @Override public CharSource createSource(String string) throws IOException { - return factory.createSource(string.getBytes(Charsets.UTF_8.name())) + return factory.createSource(string.getBytes(Charsets.UTF_8)) .asCharSource(Charsets.UTF_8); } @Override public String getExpected(String data) { - try { - return new String(factory.getExpected(data.getBytes(Charsets.UTF_8.name())), - Charsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(); - } + return new String(factory.getExpected(data.getBytes(Charsets.UTF_8)), Charsets.UTF_8); } @Override @@ -141,7 +131,7 @@ public class SourceSinkFactories { @Override public String getSinkContents() throws IOException { - return new String(factory.getSinkContents(), Charsets.UTF_8.name()); + return new String(factory.getSinkContents(), Charsets.UTF_8); } @Override @@ -151,11 +141,7 @@ public class SourceSinkFactories { * string to that. */ byte[] factoryExpectedForNothing = factory.getExpected(new byte[0]); - try { - return new String(factoryExpectedForNothing, Charsets.UTF_8.name()) + checkNotNull(data); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(); - } + return new String(factoryExpectedForNothing, Charsets.UTF_8) + checkNotNull(data); } @Override diff --git a/guava-tests/test/com/google/common/io/TestCharSink.java b/guava-tests/test/com/google/common/io/TestCharSink.java index c14b747b7..6f7686f76 100644 --- a/guava-tests/test/com/google/common/io/TestCharSink.java +++ b/guava-tests/test/com/google/common/io/TestCharSink.java @@ -21,7 +21,6 @@ import static com.google.common.base.Charsets.UTF_8; import java.io.FilterWriter; import java.io.IOException; import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; import java.io.Writer; /** @@ -38,11 +37,7 @@ public class TestCharSink extends CharSink implements TestStreamSupplier { } public String getString() { - try { - return new String(byteSink.getBytes(), UTF_8.name()); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(); - } + return new String(byteSink.getBytes(), UTF_8); } @Override diff --git a/guava-tests/test/com/google/common/io/TestCharSource.java b/guava-tests/test/com/google/common/io/TestCharSource.java index 38bb71655..37ee8dcd4 100644 --- a/guava-tests/test/com/google/common/io/TestCharSource.java +++ b/guava-tests/test/com/google/common/io/TestCharSource.java @@ -21,7 +21,6 @@ import static com.google.common.base.Charsets.UTF_8; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; -import java.io.UnsupportedEncodingException; /** * A char source for testing that has configurable options. @@ -33,11 +32,7 @@ public class TestCharSource extends CharSource implements TestStreamSupplier { private final TestByteSource byteSource; public TestCharSource(String content, TestOption... options) { - try { - this.byteSource = new TestByteSource(content.getBytes(UTF_8.name()), options); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(e); - } + this.byteSource = new TestByteSource(content.getBytes(UTF_8), options); } @Override diff --git a/guava-tests/test/com/google/common/jdk5backport/Arrays.java b/guava-tests/test/com/google/common/jdk5backport/Arrays.java deleted file mode 100644 index adb934b4e..000000000 --- a/guava-tests/test/com/google/common/jdk5backport/Arrays.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.google.common.jdk5backport; - -/** - * An Arrays alternative containing JDK 1.6 method equivalents used - * to support JDK 1.5 with a few pass-through methods to reduce import - * conflicts. - */ -public final class Arrays { - public static byte[] copyOf(byte[] original, int newLength) { - return copyOfRange(original, 0, newLength); - } - - public static byte[] copyOfRange(byte[] original, int from, int to) { - int newLength = to - from; - if (newLength >= 0) { - byte[] copy = new byte[newLength]; - System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); - return copy; - } - throw new IllegalArgumentException(); - } - - public static void fill(byte[] array, byte val) { - java.util.Arrays.fill(array, val); - } - - public static boolean equals(byte[] a, byte[] a2) { - return java.util.Arrays.equals(a, a2); - } -} diff --git a/guava-tests/test/com/google/common/math/DoubleMathTest.java b/guava-tests/test/com/google/common/math/DoubleMathTest.java index 1231142cf..a23400795 100644 --- a/guava-tests/test/com/google/common/math/DoubleMathTest.java +++ b/guava-tests/test/com/google/common/math/DoubleMathTest.java @@ -29,6 +29,9 @@ import static com.google.common.math.MathTesting.POSITIVE_FINITE_DOUBLE_CANDIDAT import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.DOWN; import static java.math.RoundingMode.FLOOR; +import static java.math.RoundingMode.HALF_DOWN; +import static java.math.RoundingMode.HALF_EVEN; +import static java.math.RoundingMode.HALF_UP; import static java.math.RoundingMode.UNNECESSARY; import static java.math.RoundingMode.UP; import static java.util.Arrays.asList; @@ -62,8 +65,6 @@ public class DoubleMathTest extends TestCase { private static final BigDecimal MAX_LONG_AS_BIG_DECIMAL = BigDecimal.valueOf(Long.MAX_VALUE); private static final BigDecimal MIN_LONG_AS_BIG_DECIMAL = BigDecimal.valueOf(Long.MIN_VALUE); - private static final double MIN_NORMAL = 2.2250738585072014E-308; // Doubles.MIN_NORMAL from 1.6 - public void testConstantsMaxFactorial() { BigInteger maxDoubleValue = BigDecimal.valueOf(Double.MAX_VALUE).toBigInteger(); assertTrue(BigIntegerMath.factorial(DoubleMath.MAX_FACTORIAL).compareTo(maxDoubleValue) <= 0); @@ -365,6 +366,38 @@ public class DoubleMathTest extends TestCase { } @GwtIncompatible("DoubleMath.log2(double, RoundingMode)") + public void testRoundLog2Half() { + // We don't expect perfect rounding accuracy. + for (int exp : asList(-1022, -50, -1, 0, 1, 2, 3, 4, 100, 1022, 1023)) { + for (RoundingMode mode : asList(HALF_EVEN, HALF_UP, HALF_DOWN)) { + double x = Math.scalb(Math.sqrt(2) + 0.001, exp); + double y = Math.scalb(Math.sqrt(2) - 0.001, exp); + if (exp < 0) { + assertEquals(exp + 1, DoubleMath.log2(x, mode)); + assertEquals(exp, DoubleMath.log2(y, mode)); + } else { + assertEquals(exp + 1, DoubleMath.log2(x, mode)); + assertEquals(exp, DoubleMath.log2(y, mode)); + } + } + } + } + + @GwtIncompatible("DoubleMath.log2(double, RoundingMode)") + public void testRoundLog2Exact() { + for (double x : POSITIVE_FINITE_DOUBLE_CANDIDATES) { + boolean isPowerOfTwo = StrictMath.pow(2.0, DoubleMath.log2(x, FLOOR)) == x; + try { + int log2 = DoubleMath.log2(x, UNNECESSARY); + assertEquals(x, Math.scalb(1.0, log2)); + assertTrue(isPowerOfTwo); + } catch (ArithmeticException e) { + assertFalse(isPowerOfTwo); + } + } + } + + @GwtIncompatible("DoubleMath.log2(double, RoundingMode)") public void testRoundLog2ThrowsOnZerosInfinitiesAndNaN() { for (RoundingMode mode : ALL_ROUNDING_MODES) { for (double d : @@ -405,6 +438,15 @@ public class DoubleMathTest extends TestCase { } } + @GwtIncompatible("#trueLog2, Math.ulp") + public void testLog2Accuracy() { + for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) { + double dmLog2 = DoubleMath.log2(d); + double trueLog2 = trueLog2(d); + assertTrue(Math.abs(dmLog2 - trueLog2) <= Math.ulp(trueLog2)); + } + } + public void testLog2SemiMonotonic() { for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) { assertTrue(DoubleMath.log2(d + 0.01) >= DoubleMath.log2(d)); @@ -428,6 +470,23 @@ public class DoubleMathTest extends TestCase { assertTrue(Double.isNaN(DoubleMath.log2(Double.NaN))); } + @GwtIncompatible("StrictMath") + private strictfp double trueLog2(double d) { + double trueLog2 = StrictMath.log(d) / StrictMath.log(2); + // increment until it's >= the true value + while (StrictMath.pow(2.0, trueLog2) < d) { + trueLog2 = StrictMath.nextUp(trueLog2); + } + // decrement until it's <= the true value + while (StrictMath.pow(2.0, trueLog2) > d) { + trueLog2 = StrictMath.nextAfter(trueLog2, Double.NEGATIVE_INFINITY); + } + if (StrictMath.abs(StrictMath.pow(2.0, trueLog2) - d) + > StrictMath.abs(StrictMath.pow(2.0, StrictMath.nextUp(trueLog2)) - d)) { + trueLog2 = StrictMath.nextUp(trueLog2); + } + return trueLog2; + } @GwtIncompatible("DoubleMath.isMathematicalInteger") public void testIsMathematicalIntegerIntegral() { @@ -481,7 +540,7 @@ public class DoubleMathTest extends TestCase { Iterables.concat(FINITE_TOLERANCE_CANDIDATES, ImmutableList.of(Double.POSITIVE_INFINITY)); private static final List<Double> BAD_TOLERANCE_CANDIDATES = - Doubles.asList(-Double.MIN_VALUE, -MIN_NORMAL, -1, -20, Double.NaN, + Doubles.asList(-Double.MIN_VALUE, -Double.MIN_NORMAL, -1, -20, Double.NaN, Double.NEGATIVE_INFINITY, -0.001); public void testFuzzyEqualsFinite() { diff --git a/guava-tests/test/com/google/common/math/IntMathTest.java b/guava-tests/test/com/google/common/math/IntMathTest.java index aba46c384..841a7fcae 100644 --- a/guava-tests/test/com/google/common/math/IntMathTest.java +++ b/guava-tests/test/com/google/common/math/IntMathTest.java @@ -95,7 +95,7 @@ public class IntMathTest extends TestCase { public void testPowersSqrtMaxInt() { assertEquals(IntMath.sqrt(Integer.MAX_VALUE, FLOOR), IntMath.FLOOR_SQRT_MAX_INT); } - + public void testLessThanBranchFree() { for (int x : ALL_INTEGER_CANDIDATES) { for (int y : ALL_INTEGER_CANDIDATES) { diff --git a/guava-tests/test/com/google/common/math/MathBenchmarking.java b/guava-tests/test/com/google/common/math/MathBenchmarking.java index 09e57b21f..455d10caa 100644 --- a/guava-tests/test/com/google/common/math/MathBenchmarking.java +++ b/guava-tests/test/com/google/common/math/MathBenchmarking.java @@ -22,6 +22,11 @@ import java.util.Random; /** * Utilities for benchmarks. * + * In many cases, we wish to vary the order of magnitude of the input as much as we + * want to vary the input itself, so most methods which generate values use + * an exponential distribution varying the order of magnitude of the generated values + * uniformly at random. + * * @author Louis Wasserman */ final class MathBenchmarking { @@ -40,28 +45,71 @@ final class MathBenchmarking { 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, 67, 67, 66, 66, 66, 66}; + /** + * Generates values in a distribution equivalent to randomNonNegativeBigInteger + * but omitting zero. + */ static BigInteger randomPositiveBigInteger(int numBits) { - int digits = RANDOM_SOURCE.nextInt(numBits) + 1; - return new BigInteger(digits, RANDOM_SOURCE).add(BigInteger.ONE); + BigInteger result; + do { + result = randomNonNegativeBigInteger(numBits); + } while (result.signum() == 0); + return result; } + /** + * Generates a number in [0, 2^numBits) with an exponential distribution. + * The floor of the log2 of the result is chosen uniformly at random in + * [0, numBits), and then the result is chosen in that range uniformly at random. + * Zero is treated as having log2 == 0. + */ static BigInteger randomNonNegativeBigInteger(int numBits) { - int digits = RANDOM_SOURCE.nextInt(numBits) + 1; - return new BigInteger(digits, RANDOM_SOURCE); + int digits = RANDOM_SOURCE.nextInt(numBits); + if (digits == 0) { + return new BigInteger(1, RANDOM_SOURCE); + } else { + return new BigInteger(digits, RANDOM_SOURCE) + .setBit(digits); + } } + /** + * Equivalent to calling randomPositiveBigInteger(numBits) and then flipping + * the sign with 50% probability. + */ static BigInteger randomNonZeroBigInteger(int numBits) { BigInteger result = randomPositiveBigInteger(numBits); return RANDOM_SOURCE.nextBoolean() ? result : result.negate(); } + /** + * Chooses a number in (-2^numBits, 2^numBits) at random, with density + * concentrated in numbers of lower magnitude. + */ static BigInteger randomBigInteger(int numBits) { - BigInteger result = randomNonNegativeBigInteger(numBits); - return RANDOM_SOURCE.nextBoolean() ? result : result.negate(); + while (true) { + if (RANDOM_SOURCE.nextBoolean()) { + return randomNonNegativeBigInteger(numBits); + } + BigInteger neg = randomNonNegativeBigInteger(numBits).negate(); + if (neg.signum() != 0) { + return neg; + } + } } + /** + * Generates a number in [0, 2^numBits) with an exponential distribution. + * The floor of the log2 of the absolute value of the result is chosen uniformly + * at random in [0, numBits), and then the result is chosen from those possibilities + * uniformly at random. + * + * Zero is treated as having log2 == 0. + */ static double randomDouble(int maxExponent) { - return RANDOM_SOURCE.nextDouble(); + double result = RANDOM_SOURCE.nextDouble(); + result = Math.scalb(result, RANDOM_SOURCE.nextInt(maxExponent + 1)); + return RANDOM_SOURCE.nextBoolean() ? result : -result; } /** diff --git a/guava-tests/test/com/google/common/math/MathTesting.java b/guava-tests/test/com/google/common/math/MathTesting.java index 6b69d5f47..a4bc6a98e 100644 --- a/guava-tests/test/com/google/common/math/MathTesting.java +++ b/guava-tests/test/com/google/common/math/MathTesting.java @@ -149,6 +149,7 @@ public class MathTesting { longValues.addAll(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, TO_LONG)); // Add boundary values manually to avoid over/under flow (this covers 2^N for 31 and 63). longValues.add(Integer.MAX_VALUE + 1L, Long.MAX_VALUE - 1L, Long.MAX_VALUE); + // Now add values near 2^N for lots of values of N. for (int exponent : asList(32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57)) { long x = 1L << exponent; @@ -176,10 +177,6 @@ public class MathTesting { static final Iterable<BigInteger> ALL_BIGINTEGER_CANDIDATES; - static final int MAX_EXPONENT = 1023; // Double.MAX_EXPONENT not present in JDK5 - - static final double MIN_NORMAL = 2.2250738585072014E-308; - static { ImmutableSet.Builder<BigInteger> bigValues = ImmutableSet.builder(); // First of all add all the long candidate values. @@ -188,7 +185,7 @@ public class MathTesting { bigValues.add(BigInteger.valueOf(Long.MAX_VALUE).add(ONE)); // Now add values near 2^N for lots of values of N. for (int exponent : asList(64, 65, 71, 72, 73, 79, 80, 81, 255, 256, 257, 511, 512, 513, - MAX_EXPONENT - 1, MAX_EXPONENT, MAX_EXPONENT + 1)) { + Double.MAX_EXPONENT - 1, Double.MAX_EXPONENT, Double.MAX_EXPONENT + 1)) { BigInteger x = ONE.shiftLeft(exponent); bigValues.add(x, x.add(ONE), x.subtract(ONE)); } @@ -219,11 +216,11 @@ public class MathTesting { integralBuilder.addAll(Doubles.asList(0.0, -0.0, Double.MAX_VALUE, -Double.MAX_VALUE)); // Add small multiples of MIN_VALUE and MIN_NORMAL for (int scale = 1; scale <= 4; scale++) { - for (double d : Doubles.asList(Double.MIN_VALUE, MIN_NORMAL)) { + for (double d : Doubles.asList(Double.MIN_VALUE, Double.MIN_NORMAL)) { fractionalBuilder.add(d * scale).add(-d * scale); } } - for (double d : Doubles.asList(0, 1, 2, 7, 51, 102, Integer.MIN_VALUE, + for (double d : Doubles.asList(0, 1, 2, 7, 51, 102, Math.scalb(1.0, 53), Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE)) { for (double delta : Doubles.asList(0.0, 1.0, 2.0)) { integralBuilder.addAll(Doubles.asList(d + delta, d - delta, -d - delta, -d + delta)); diff --git a/guava-tests/test/com/google/common/net/HttpHeadersTest.java b/guava-tests/test/com/google/common/net/HttpHeadersTest.java index 282f41fee..3b42aff25 100644 --- a/guava-tests/test/com/google/common/net/HttpHeadersTest.java +++ b/guava-tests/test/com/google/common/net/HttpHeadersTest.java @@ -62,7 +62,7 @@ public class HttpHeadersTest extends TestCase { * fields, they will cause similar problems, and we may want to switch * this check to isAccessible(). */ - if (!field.isSynthetic()) { + if (!field.isSynthetic() && field.getType() == String.class) { builder.add(field); } } diff --git a/guava-tests/test/com/google/common/net/InetAddressesTest.java b/guava-tests/test/com/google/common/net/InetAddressesTest.java index 90d328524..79781559b 100644 --- a/guava-tests/test/com/google/common/net/InetAddressesTest.java +++ b/guava-tests/test/com/google/common/net/InetAddressesTest.java @@ -724,4 +724,51 @@ public class InetAddressesTest extends TestCase { fail(); } catch (IllegalArgumentException expected) {} } + + public void testDecrementIPv4() throws UnknownHostException { + InetAddress address660 = InetAddress.getByName("172.24.66.0"); + InetAddress address66255 = InetAddress.getByName("172.24.66.255"); + InetAddress address670 = InetAddress.getByName("172.24.67.0"); + + InetAddress address = address670; + address = InetAddresses.decrement(address); + + assertEquals(address66255, address); + + for (int i = 0; i < 255; i++) { + address = InetAddresses.decrement(address); + } + assertEquals(address660, address); + + InetAddress address0000 = InetAddress.getByName("0.0.0.0"); + address = address0000; + try { + address = InetAddresses.decrement(address); + fail(); + } catch (IllegalArgumentException expected) {} + } + + public void testDecrementIPv6() throws UnknownHostException { + InetAddress addressV6660 = InetAddress.getByName("2001:db8::6600"); + InetAddress addressV666ff = InetAddress.getByName("2001:db8::66ff"); + InetAddress addressV6670 = InetAddress.getByName("2001:db8::6700"); + + InetAddress address = addressV6670; + address = InetAddresses.decrement(address); + + assertEquals(addressV666ff, address); + + for (int i = 0; i < 255; i++) { + address = InetAddresses.decrement(address); + } + assertEquals(addressV6660, address); + + InetAddress addressV6000000 = + InetAddress.getByName("0:0:0:0:0:0:0:0"); + address = addressV6000000; + try { + address = InetAddresses.decrement(address); + fail(); + } catch (IllegalArgumentException expected) {} + } } diff --git a/guava-tests/test/com/google/common/net/InternetDomainNameTest.java b/guava-tests/test/com/google/common/net/InternetDomainNameTest.java index a63c147b8..91a434724 100644 --- a/guava-tests/test/com/google/common/net/InternetDomainNameTest.java +++ b/guava-tests/test/com/google/common/net/InternetDomainNameTest.java @@ -367,9 +367,9 @@ public final class InternetDomainNameTest extends TestCase { } public void testExclusion() { - InternetDomainName domain = InternetDomainName.from("foo.nic.uk"); + InternetDomainName domain = InternetDomainName.from("foo.teledata.mz"); assertTrue(domain.hasPublicSuffix()); - assertEquals("uk", domain.publicSuffix().toString()); + assertEquals("mz", domain.publicSuffix().toString()); // Behold the weirdness! assertFalse(domain.publicSuffix().isPublicSuffix()); diff --git a/guava-tests/test/com/google/common/primitives/DoublesTest.java b/guava-tests/test/com/google/common/primitives/DoublesTest.java index 9f04471bc..3ee962f3b 100644 --- a/guava-tests/test/com/google/common/primitives/DoublesTest.java +++ b/guava-tests/test/com/google/common/primitives/DoublesTest.java @@ -16,8 +16,8 @@ package com.google.common.primitives; +import static com.google.common.truth.Truth.assertThat; import static java.lang.Double.NaN; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -50,11 +50,10 @@ public class DoublesTest extends TestCase { private static final double LEAST = Double.NEGATIVE_INFINITY; private static final double GREATEST = Double.POSITIVE_INFINITY; - private static final double MIN_NORMAL = 2.2250738585072014E-308; // Doubles.MIN_NORMAL from 1.6 private static final double[] NUMBERS = new double[] { LEAST, -Double.MAX_VALUE, -1.0, -0.5, -0.1, -0.0, 0.0, 0.1, 0.5, 1.0, - Double.MAX_VALUE, GREATEST, MIN_NORMAL, -MIN_NORMAL, + Double.MAX_VALUE, GREATEST, Double.MIN_NORMAL, -Double.MIN_NORMAL, Double.MIN_VALUE, -Double.MIN_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE }; @@ -370,7 +369,7 @@ public class DoublesTest extends TestCase { list.set(0, (double) 2); assertTrue(Arrays.equals(new double[] {(double) 2, (double) 1}, array)); array[1] = (double) 3; - ASSERT.that(list).has().exactly((double) 2, (double) 3).inOrder(); + assertThat(list).has().exactly((double) 2, (double) 3).inOrder(); } public void testAsList_toArray_roundTrip() { diff --git a/guava-tests/test/com/google/common/primitives/FloatsTest.java b/guava-tests/test/com/google/common/primitives/FloatsTest.java index 2b0c44166..2584328dc 100644 --- a/guava-tests/test/com/google/common/primitives/FloatsTest.java +++ b/guava-tests/test/com/google/common/primitives/FloatsTest.java @@ -16,8 +16,8 @@ package com.google.common.primitives; +import static com.google.common.truth.Truth.assertThat; import static java.lang.Float.NaN; -import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -50,11 +50,10 @@ public class FloatsTest extends TestCase { private static final float LEAST = Float.NEGATIVE_INFINITY; private static final float GREATEST = Float.POSITIVE_INFINITY; - private static final float MIN_NORMAL = 1.17549435E-38f; // Doubles.MIN_NORMAL from 1.6 private static final float[] NUMBERS = new float[] { LEAST, -Float.MAX_VALUE, -1f, -0f, 0f, 1f, Float.MAX_VALUE, GREATEST, - MIN_NORMAL, -MIN_NORMAL, Float.MIN_VALUE, -Float.MIN_VALUE, + Float.MIN_NORMAL, -Float.MIN_NORMAL, Float.MIN_VALUE, -Float.MIN_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE }; @@ -361,7 +360,7 @@ public class FloatsTest extends TestCase { list.set(0, (float) 2); assertTrue(Arrays.equals(new float[] {(float) 2, (float) 1}, array)); array[1] = (float) 3; - ASSERT.that(list).has().exactly((float) 2, (float) 3).inOrder(); + assertThat(list).has().exactly((float) 2, (float) 3).inOrder(); } public void testAsList_toArray_roundTrip() { diff --git a/guava-tests/test/com/google/common/primitives/IntsTest.java b/guava-tests/test/com/google/common/primitives/IntsTest.java index a47573942..58279e666 100644 --- a/guava-tests/test/com/google/common/primitives/IntsTest.java +++ b/guava-tests/test/com/google/common/primitives/IntsTest.java @@ -463,7 +463,6 @@ public class IntsTest extends TestCase { tester.testAllPublicInstanceMethods(Ints.stringConverter()); } - @GwtIncompatible("AndroidInteger") public void testTryParse() { tryParseAndAssertEquals(0, "0"); tryParseAndAssertEquals(0, "-0"); @@ -479,8 +478,14 @@ public class IntsTest extends TestCase { assertNull(Ints.tryParse("9999999999999999")); assertNull("Max integer + 1", Ints.tryParse(Long.toString(((long) GREATEST) + 1))); + assertNull("Max integer * 10", + Ints.tryParse(Long.toString(((long) GREATEST) * 10))); assertNull("Min integer - 1", Ints.tryParse(Long.toString(((long) LEAST) - 1))); + assertNull("Min integer * 10", + Ints.tryParse(Long.toString(((long) LEAST) * 10))); + assertNull("Max long", Ints.tryParse(Long.toString(Long.MAX_VALUE))); + assertNull("Min long", Ints.tryParse(Long.toString(Long.MIN_VALUE))); assertNull(Ints.tryParse("\u0662\u06f3")); } @@ -488,7 +493,6 @@ public class IntsTest extends TestCase { * Applies {@link Ints#tryParse(String)} to the given string and asserts that * the result is as expected. */ - @GwtIncompatible("AndroidInteger") private static void tryParseAndAssertEquals(Integer expected, String value) { assertEquals(expected, Ints.tryParse(value)); } diff --git a/guava-tests/test/com/google/common/primitives/LongsTest.java b/guava-tests/test/com/google/common/primitives/LongsTest.java index 6f490d723..7575a14bd 100644 --- a/guava-tests/test/com/google/common/primitives/LongsTest.java +++ b/guava-tests/test/com/google/common/primitives/LongsTest.java @@ -446,7 +446,6 @@ public class LongsTest extends TestCase { tester.testAllPublicInstanceMethods(Longs.stringConverter()); } - @GwtIncompatible("AndroidInteger") public void testTryParse() { tryParseAndAssertEquals(0L, "0"); tryParseAndAssertEquals(0L, "-0"); @@ -460,10 +459,14 @@ public class LongsTest extends TestCase { assertNull(Longs.tryParse("-")); assertNull(Longs.tryParse("+1")); assertNull(Longs.tryParse("999999999999999999999999")); - assertNull("Max integer + 1", + assertNull("Max long + 1", Longs.tryParse(BigInteger.valueOf(MAX_VALUE).add(BigInteger.ONE).toString())); - assertNull("Min integer - 1", + assertNull("Max long * 10", + Longs.tryParse(BigInteger.valueOf(MAX_VALUE).multiply(BigInteger.TEN).toString())); + assertNull("Min long - 1", Longs.tryParse(BigInteger.valueOf(MIN_VALUE).subtract(BigInteger.ONE).toString())); + assertNull("Min long * 10", + Longs.tryParse(BigInteger.valueOf(MIN_VALUE).multiply(BigInteger.TEN).toString())); assertNull(Longs.tryParse("\u0662\u06f3")); } diff --git a/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java b/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java index c74e8a215..575eb7e73 100644 --- a/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java +++ b/guava-tests/test/com/google/common/primitives/UnsignedBytesTest.java @@ -226,9 +226,9 @@ public class UnsignedBytesTest extends TestCase { public void testLexicographicalComparatorDefaultChoice() { Comparator<byte[]> defaultComparator = UnsignedBytes.lexicographicalComparator(); - Comparator<byte[]> pureJavaComparator = - UnsignedBytes.LexicographicalComparatorHolder.PureJavaComparator.INSTANCE; - assertSame(defaultComparator, pureJavaComparator); + Comparator<byte[]> unsafeComparator = + UnsignedBytes.LexicographicalComparatorHolder.UnsafeComparator.INSTANCE; + assertSame(defaultComparator, unsafeComparator); } public void testLexicographicalComparator() { diff --git a/guava-tests/test/com/google/common/reflect/ClassPathTest.java b/guava-tests/test/com/google/common/reflect/ClassPathTest.java index bd636355e..f49240947 100644 --- a/guava-tests/test/com/google/common/reflect/ClassPathTest.java +++ b/guava-tests/test/com/google/common/reflect/ClassPathTest.java @@ -16,7 +16,7 @@ package com.google.common.reflect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; @@ -31,6 +31,7 @@ import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import junit.framework.TestCase; + import org.junit.Test; import java.io.ByteArrayInputStream; @@ -60,20 +61,19 @@ public class ClassPathTest extends TestCase { Map<String, ResourceInfo> byToString = Maps.newHashMap(); ClassPath classpath = ClassPath.from(getClass().getClassLoader()); for (ResourceInfo resource : classpath.getResources()) { - ASSERT.that(resource.getResourceName()).isNotEqualTo(JarFile.MANIFEST_NAME); - ASSERT.that(resource.toString()).isNotEqualTo(JarFile.MANIFEST_NAME); + assertThat(resource.getResourceName()).isNotEqualTo(JarFile.MANIFEST_NAME); + assertThat(resource.toString()).isNotEqualTo(JarFile.MANIFEST_NAME); byName.put(resource.getResourceName(), resource); byToString.put(resource.toString(), resource); - // TODO: This will fail on maven resources in the classes directory on a mac. - // assertNotNull(resource.url()); + assertNotNull(resource.url()); } String testResourceName = "com/google/common/reflect/test.txt"; - ASSERT.that(byName.keySet()).has().allOf( + assertThat(byName.keySet()).has().allOf( "com/google/common/reflect/ClassPath.class", "com/google/common/reflect/ClassPathTest.class", "com/google/common/reflect/ClassPathTest$Nested.class", testResourceName); - ASSERT.that(byToString.keySet()).has().allOf( + assertThat(byToString.keySet()).has().allOf( "com.google.common.reflect.ClassPath", "com.google.common.reflect.ClassPathTest", "com.google.common.reflect.ClassPathTest$Nested", @@ -101,14 +101,14 @@ public class ClassPathTest extends TestCase { } class LocalClass {} Class<?> anonymousClass = new Object() {}.getClass(); - ASSERT.that(names).has().allOf(anonymousClass.getName(), LocalClass.class.getName(), + assertThat(names).has().allOf(anonymousClass.getName(), LocalClass.class.getName(), ClassPath.class.getName(), ClassPathTest.class.getName()); - ASSERT.that(strings).has().allOf(anonymousClass.getName(), LocalClass.class.getName(), + assertThat(strings).has().allOf(anonymousClass.getName(), LocalClass.class.getName(), ClassPath.class.getName(), ClassPathTest.class.getName()); - ASSERT.that(classes).has().allOf(anonymousClass, LocalClass.class, ClassPath.class, + assertThat(classes).has().allOf(anonymousClass, LocalClass.class, ClassPath.class, ClassPathTest.class); - ASSERT.that(packageNames).has().exactly(ClassPath.class.getPackage().getName()); - ASSERT.that(simpleNames).has().allOf("", "Local", "ClassPath", "ClassPathTest"); + assertThat(packageNames).has().exactly(ClassPath.class.getPackage().getName()); + assertThat(simpleNames).has().allOf("", "Local", "ClassPath", "ClassPathTest"); } public void testGetTopLevelClasses() throws Exception { @@ -126,11 +126,11 @@ public class ClassPathTest extends TestCase { packageNames.add(classInfo.getPackageName()); simpleNames.add(classInfo.getSimpleName()); } - ASSERT.that(names).has().allOf(ClassPath.class.getName(), ClassPathTest.class.getName()); - ASSERT.that(strings).has().allOf(ClassPath.class.getName(), ClassPathTest.class.getName()); - ASSERT.that(classes).has().allOf(ClassPath.class, ClassPathTest.class); - ASSERT.that(packageNames).has().item(ClassPath.class.getPackage().getName()); - ASSERT.that(simpleNames).has().allOf("ClassPath", "ClassPathTest"); + assertThat(names).has().allOf(ClassPath.class.getName(), ClassPathTest.class.getName()); + assertThat(strings).has().allOf(ClassPath.class.getName(), ClassPathTest.class.getName()); + assertThat(classes).has().allOf(ClassPath.class, ClassPathTest.class); + assertThat(packageNames).has().item(ClassPath.class.getPackage().getName()); + assertThat(simpleNames).has().allOf("ClassPath", "ClassPathTest"); assertFalse(classes.contains(ClassInSubPackage.class)); } @@ -144,7 +144,7 @@ public class ClassPathTest extends TestCase { } classes.add(classInfo.load()); } - ASSERT.that(classes).has().allOf(ClassPathTest.class, ClassInSubPackage.class); + assertThat(classes).has().allOf(ClassPathTest.class, ClassInSubPackage.class); } public void testGetTopLevelClasses_diamond() throws Exception { @@ -168,7 +168,7 @@ public class ClassPathTest extends TestCase { } public void testClassPathEntries_emptyURLClassLoader_noParent() { - ASSERT.that(ClassPath.getClassPathEntries(new URLClassLoader(new URL[0], null)).keySet()) + assertThat(ClassPath.getClassPathEntries(new URLClassLoader(new URL[0], null)).keySet()) .isEmpty(); } @@ -188,7 +188,7 @@ public class ClassPathTest extends TestCase { URLClassLoader child = new URLClassLoader(new URL[] {url2}, parent) {}; ImmutableMap<URI, ClassLoader> classPathEntries = ClassPath.getClassPathEntries(child); assertEquals(ImmutableMap.of(url1.toURI(), parent, url2.toURI(), child), classPathEntries); - ASSERT.that(classPathEntries.keySet()).has().exactly(url1.toURI(), url2.toURI()).inOrder(); + assertThat(classPathEntries.keySet()).has().exactly(url1.toURI(), url2.toURI()).inOrder(); } public void testClassPathEntries_duplicateUri_parentWins() throws Exception { @@ -199,7 +199,7 @@ public class ClassPathTest extends TestCase { } public void testClassPathEntries_notURLClassLoader_noParent() { - ASSERT.that(ClassPath.getClassPathEntries(new ClassLoader(null) {}).keySet()).isEmpty(); + assertThat(ClassPath.getClassPathEntries(new ClassLoader(null) {}).keySet()).isEmpty(); } public void testClassPathEntries_notURLClassLoader_withParent() throws Exception { @@ -245,7 +245,7 @@ public class ClassPathTest extends TestCase { ClassLoader classLoader = ClassPathTest.class.getClassLoader(); ClassPath.Scanner scanner = new ClassPath.Scanner(); scanner.scanFrom(new File("no/such/file/anywhere"), classLoader); - ASSERT.that(scanner.getResources()).isEmpty(); + assertThat(scanner.getResources()).isEmpty(); } public void testScanFromFile_notJarFile() throws IOException { @@ -257,7 +257,7 @@ public class ClassPathTest extends TestCase { } finally { notJar.delete(); } - ASSERT.that(scanner.getResources()).isEmpty(); + assertThat(scanner.getResources()).isEmpty(); } public void testGetClassPathEntry() throws URISyntaxException { @@ -273,25 +273,25 @@ public class ClassPathTest extends TestCase { } public void testGetClassPathFromManifest_nullManifest() { - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(new File("some.jar"), null)).isEmpty(); + assertThat(ClassPath.Scanner.getClassPathFromManifest(new File("some.jar"), null)).isEmpty(); } public void testGetClassPathFromManifest_noClassPath() throws IOException { File jarFile = new File("base.jar"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest(""))) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest(""))) .isEmpty(); } public void testGetClassPathFromManifest_emptyClassPath() throws IOException { File jarFile = new File("base.jar"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifestClasspath(""))) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifestClasspath(""))) .isEmpty(); } public void testGetClassPathFromManifest_badClassPath() throws IOException { File jarFile = new File("base.jar"); Manifest manifest = manifestClasspath("an_invalid^path"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .isEmpty(); } @@ -299,7 +299,7 @@ public class ClassPathTest extends TestCase { File jarFile = new File("base/some.jar"); // with/relative/directory is the Class-Path value in the mf file. Manifest manifest = manifestClasspath("with/relative/dir"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly(new File("base/with/relative/dir").toURI()).inOrder(); } @@ -307,7 +307,7 @@ public class ClassPathTest extends TestCase { File jarFile = new File("base/some.jar"); // with/relative/directory is the Class-Path value in the mf file. Manifest manifest = manifestClasspath("with/relative.jar"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly(new File("base/with/relative.jar").toURI()).inOrder(); } @@ -315,28 +315,28 @@ public class ClassPathTest extends TestCase { File jarFile = new File("base/some.jar"); // with/relative/directory is the Class-Path value in the mf file. Manifest manifest = manifestClasspath("current.jar"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly(new File("base/current.jar").toURI()).inOrder(); } public void testGetClassPathFromManifest_absoluteDirectory() throws IOException { File jarFile = new File("base/some.jar"); Manifest manifest = manifestClasspath("file:/with/absolute/dir"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly(new File("/with/absolute/dir").toURI()).inOrder(); } public void testGetClassPathFromManifest_absoluteJar() throws IOException { File jarFile = new File("base/some.jar"); Manifest manifest = manifestClasspath("file:/with/absolute.jar"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly(new File("/with/absolute.jar").toURI()).inOrder(); } public void testGetClassPathFromManifest_multiplePaths() throws IOException { File jarFile = new File("base/some.jar"); Manifest manifest = manifestClasspath("file:/with/absolute.jar relative.jar relative/dir"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly( new File("/with/absolute.jar").toURI(), new File("base/relative.jar").toURI(), @@ -347,14 +347,14 @@ public class ClassPathTest extends TestCase { public void testGetClassPathFromManifest_leadingBlanks() throws IOException { File jarFile = new File("base/some.jar"); Manifest manifest = manifestClasspath(" relative.jar"); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly(new File("base/relative.jar").toURI()).inOrder(); } public void testGetClassPathFromManifest_trailingBlanks() throws IOException { File jarFile = new File("base/some.jar"); Manifest manifest = manifestClasspath("relative.jar "); - ASSERT.that(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) + assertThat(ClassPath.Scanner.getClassPathFromManifest(jarFile, manifest)) .has().exactly(new File("base/relative.jar").toURI()).inOrder(); } @@ -451,7 +451,7 @@ public class ClassPathTest extends TestCase { } private static Manifest manifest(String content) throws IOException { - InputStream in = new ByteArrayInputStream(content.getBytes(Charsets.US_ASCII.name())); + InputStream in = new ByteArrayInputStream(content.getBytes(Charsets.US_ASCII)); Manifest manifest = new Manifest(); manifest.read(in); return manifest; diff --git a/guava-tests/test/com/google/common/reflect/ImmutableTypeToInstanceMapTest.java b/guava-tests/test/com/google/common/reflect/ImmutableTypeToInstanceMapTest.java index d3937dafe..d622b226a 100644 --- a/guava-tests/test/com/google/common/reflect/ImmutableTypeToInstanceMapTest.java +++ b/guava-tests/test/com/google/common/reflect/ImmutableTypeToInstanceMapTest.java @@ -16,7 +16,7 @@ package com.google.common.reflect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; @@ -109,7 +109,7 @@ public class ImmutableTypeToInstanceMapTest extends TestCase { .put(type, array) .build(); assertEquals(1, map.size()); - ASSERT.that(map.getInstance(type)).has().exactly(array[0]).inOrder(); + assertThat(map.getInstance(type)).asList().has().exactly(array[0]).inOrder(); } public void testWildcardType() { diff --git a/guava-tests/test/com/google/common/reflect/MutableTypeToInstanceMapTest.java b/guava-tests/test/com/google/common/reflect/MutableTypeToInstanceMapTest.java index f2bd5b099..26f702e15 100644 --- a/guava-tests/test/com/google/common/reflect/MutableTypeToInstanceMapTest.java +++ b/guava-tests/test/com/google/common/reflect/MutableTypeToInstanceMapTest.java @@ -16,7 +16,7 @@ package com.google.common.reflect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -194,13 +194,13 @@ public class MutableTypeToInstanceMapTest extends TestCase { assertEquals(ImmutableList.of(1), map.getInstance(type)); } - public void testGeneriArrayType() { + public void testGenericArrayType() { @SuppressWarnings("unchecked") // Trying to test generic array ImmutableList<Integer>[] array = new ImmutableList[] {ImmutableList.of(1)}; TypeToken<ImmutableList<Integer>[]> type = new TypeToken<ImmutableList<Integer>[]>() {}; map.putInstance(type, array); assertEquals(1, map.size()); - ASSERT.that(map.getInstance(type)).has().exactly(array[0]).inOrder(); + assertThat(map.getInstance(type)).asList().has().exactly(array[0]).inOrder(); } public void testWildcardType() { diff --git a/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java b/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java index 2c7e050ae..bf9dd11a4 100644 --- a/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java +++ b/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java @@ -16,7 +16,7 @@ package com.google.common.reflect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Predicate; import com.google.common.base.Supplier; @@ -124,7 +124,7 @@ public class TypeTokenResolutionTest extends TestCase { parameterized.parameterizedType()); assertEquals(TypeTokenResolutionTest.class, resolved.getOwnerType()); assertEquals(Bar.class, resolved.getRawType()); - ASSERT.that(resolved.getActualTypeArguments()).has().item(String.class); + assertThat(resolved.getActualTypeArguments()).asList().has().item(String.class); } private interface StringListPredicate extends Predicate<List<String>> {} diff --git a/guava-tests/test/com/google/common/reflect/TypeTokenTest.java b/guava-tests/test/com/google/common/reflect/TypeTokenTest.java index a4a869c59..893a054ab 100644 --- a/guava-tests/test/com/google/common/reflect/TypeTokenTest.java +++ b/guava-tests/test/com/google/common/reflect/TypeTokenTest.java @@ -16,7 +16,7 @@ package com.google.common.reflect; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; @@ -27,11 +27,10 @@ import com.google.common.primitives.Primitives; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import com.google.common.testing.SerializableTester; +import com.google.common.truth.CollectionSubject; import junit.framework.TestCase; -import org.truth0.subjects.CollectionSubject; - import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.GenericArrayType; @@ -161,39 +160,39 @@ public class TypeTokenTest extends TestCase { public void testGetTypes_noSuperclass() { TypeToken<Object>.TypeSet types = new TypeToken<Object>() {}.getTypes(); - ASSERT.that(types).has().item(TypeToken.of(Object.class)); - ASSERT.that(types.rawTypes()).has().item(Object.class); - ASSERT.that(types.interfaces()).isEmpty(); - ASSERT.that(types.interfaces().rawTypes()).isEmpty(); - ASSERT.that(types.classes()).has().item(TypeToken.of(Object.class)); - ASSERT.that(types.classes().rawTypes()).has().item(Object.class); + assertThat(types).has().item(TypeToken.of(Object.class)); + assertThat(types.rawTypes()).has().item(Object.class); + assertThat(types.interfaces()).isEmpty(); + assertThat(types.interfaces().rawTypes()).isEmpty(); + assertThat(types.classes()).has().item(TypeToken.of(Object.class)); + assertThat(types.classes().rawTypes()).has().item(Object.class); } public void testGetTypes_fromInterface() { TypeToken<Interface1>.TypeSet types = new TypeToken<Interface1>() {}.getTypes(); - ASSERT.that(types).has().item(TypeToken.of(Interface1.class)); - ASSERT.that(types.rawTypes()).has().item(Interface1.class); - ASSERT.that(types.interfaces()).has().item(TypeToken.of(Interface1.class)); - ASSERT.that(types.interfaces().rawTypes()).has().item(Interface1.class); - ASSERT.that(types.classes()).isEmpty(); - ASSERT.that(types.classes().rawTypes()).isEmpty(); + assertThat(types).has().item(TypeToken.of(Interface1.class)); + assertThat(types.rawTypes()).has().item(Interface1.class); + assertThat(types.interfaces()).has().item(TypeToken.of(Interface1.class)); + assertThat(types.interfaces().rawTypes()).has().item(Interface1.class); + assertThat(types.classes()).isEmpty(); + assertThat(types.classes().rawTypes()).isEmpty(); } public void testGetTypes_fromPrimitive() { TypeToken<Integer>.TypeSet types = TypeToken.of(int.class).getTypes(); - ASSERT.that(types).has().item(TypeToken.of(int.class)); - ASSERT.that(types.rawTypes()).has().item(int.class); - ASSERT.that(types.interfaces()).isEmpty(); - ASSERT.that(types.interfaces().rawTypes()).isEmpty(); - ASSERT.that(types.classes()).has().item(TypeToken.of(int.class)); - ASSERT.that(types.classes().rawTypes()).has().item(int.class); + assertThat(types).has().item(TypeToken.of(int.class)); + assertThat(types.rawTypes()).has().item(int.class); + assertThat(types.interfaces()).isEmpty(); + assertThat(types.interfaces().rawTypes()).isEmpty(); + assertThat(types.classes()).has().item(TypeToken.of(int.class)); + assertThat(types.classes().rawTypes()).has().item(int.class); } public void testGetTypes_withInterfacesAndSuperclasses() { abstract class Class2 extends Class1 implements Interface12 {} abstract class Class3<T> extends Class2 implements Interface3<T> {} TypeToken<Class3<String>>.TypeSet types = new TypeToken<Class3<String>>() {}.getTypes(); - assertThat(types).has().exactly( + makeUnmodifiable(types).has().exactly( new TypeToken<Class3<String>>() {}, new TypeToken<Interface3<String>>() {}, new TypeToken<Iterable<String>>() {}, @@ -203,13 +202,13 @@ public class TypeTokenTest extends TestCase { TypeToken.of(Interface2.class), TypeToken.of(Class1.class), TypeToken.of(Object.class)); - assertThat(types.interfaces()).has().exactly( + makeUnmodifiable(types.interfaces()).has().exactly( new TypeToken<Interface3<String>>() {}, TypeToken.of(Interface12.class), TypeToken.of(Interface1.class), TypeToken.of(Interface2.class), new TypeToken<Iterable<String>>() {}); - assertThat(types.classes()).has().exactly( + makeUnmodifiable(types.classes()).has().exactly( new TypeToken<Class3<String>>() {}, TypeToken.of(Class2.class), TypeToken.of(Class1.class), @@ -221,7 +220,7 @@ public class TypeTokenTest extends TestCase { abstract class Class2 extends Class1 implements Interface12 {} abstract class Class3<T> extends Class2 implements Interface3<T> {} TypeToken<Class3<String>>.TypeSet types = new TypeToken<Class3<String>>() {}.getTypes(); - assertThat(types.rawTypes()).has().exactly( + makeUnmodifiable(types.rawTypes()).has().exactly( Class3.class, Interface3.class, Iterable.class, Class2.class, @@ -230,13 +229,13 @@ public class TypeTokenTest extends TestCase { Interface2.class, Class1.class, Object.class); - assertThat(types.interfaces().rawTypes()).has().exactly( + makeUnmodifiable(types.interfaces().rawTypes()).has().exactly( Interface3.class, Interface12.class, Interface1.class, Interface2.class, Iterable.class); - assertThat(types.classes().rawTypes()).has().exactly( + makeUnmodifiable(types.classes().rawTypes()).has().exactly( Class3.class, Class2.class, Class1.class, @@ -247,14 +246,14 @@ public class TypeTokenTest extends TestCase { public <A extends Class1 & Interface1, B extends A> void testGetTypes_ignoresTypeVariablesByDefault() { TypeToken<?>.TypeSet types = TypeToken.of(new TypeCapture<B>() {}.capture()).getTypes(); - assertThat(types).has().exactly( + makeUnmodifiable(types).has().exactly( TypeToken.of(Interface1.class), TypeToken.of(Class1.class), TypeToken.of(Object.class)); assertSubtypeFirst(types); - assertThat(types.interfaces()) + makeUnmodifiable(types.interfaces()) .has().exactly(TypeToken.of(Interface1.class)) .inOrder(); - assertThat(types.classes()) + makeUnmodifiable(types.classes()) .has().exactly(TypeToken.of(Class1.class), TypeToken.of(Object.class)) .inOrder(); } @@ -262,12 +261,12 @@ public class TypeTokenTest extends TestCase { public <A extends Class1 & Interface1, B extends A> void testGetTypes_rawTypes_ignoresTypeVariablesByDefault() { TypeToken<?>.TypeSet types = TypeToken.of(new TypeCapture<B>() {}.capture()).getTypes(); - assertThat(types.rawTypes()) + makeUnmodifiable(types.rawTypes()) .has().exactly(Interface1.class, Class1.class, Object.class); - assertThat(types.interfaces().rawTypes()) + makeUnmodifiable(types.interfaces().rawTypes()) .has().exactly(Interface1.class) .inOrder(); - assertThat(types.classes().rawTypes()) + makeUnmodifiable(types.classes().rawTypes()) .has().exactly(Class1.class, Object.class) .inOrder(); } @@ -275,7 +274,7 @@ public class TypeTokenTest extends TestCase { public <A extends Interface1 & Interface2 & Interface3<String>> void testGetTypes_manyBounds() { TypeToken<?>.TypeSet types = TypeToken.of(new TypeCapture<A>() {}.capture()).getTypes(); - assertThat(types.rawTypes()) + makeUnmodifiable(types.rawTypes()) .has().exactly(Interface1.class, Interface2.class, Interface3.class, Iterable.class); } @@ -466,75 +465,75 @@ public class TypeTokenTest extends TestCase { } public <T> void testGetGenericInterfaces_typeVariable_unbounded() { - ASSERT.that(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()).isEmpty(); + assertThat(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()).isEmpty(); assertHasArrayInterfaces(new TypeToken<T[]>() {}); } public <T extends NoInterface> void testGetGenericInterfaces_typeVariable_boundIsClass() { - ASSERT.that(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()).isEmpty(); + assertThat(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()).isEmpty(); assertHasArrayInterfaces(new TypeToken<T[]>() {}); } public <T extends NoInterface&Iterable<String>> void testGetGenericInterfaces_typeVariable_boundsAreClassWithInterface() { - assertThat(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) + makeUnmodifiable(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) .has().exactly(new TypeToken<Iterable<String>>() {}); assertHasArrayInterfaces(new TypeToken<T[]>() {}); } public <T extends CharSequence&Iterable<String>> void testGetGenericInterfaces_typeVariable_boundsAreInterfaces() { - assertThat(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) + makeUnmodifiable(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) .has().exactly(TypeToken.of(CharSequence.class), new TypeToken<Iterable<String>>() {}); assertHasArrayInterfaces(new TypeToken<T[]>() {}); } public <T extends CharSequence&Iterable<T>> void testGetGenericInterfaces_typeVariable_boundsAreFBoundedInterfaces() { - assertThat(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) + makeUnmodifiable(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) .has().exactly(TypeToken.of(CharSequence.class), new TypeToken<Iterable<T>>() {}); assertHasArrayInterfaces(new TypeToken<T[]>() {}); } public <T extends Base&Iterable<T>> void testGetGenericInterfaces_typeVariable_boundsAreClassWithFBoundedInterface() { - assertThat(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) + makeUnmodifiable(TypeToken.of(new TypeCapture<T>() {}.capture()).getGenericInterfaces()) .has().exactly(new TypeToken<Iterable<T>>() {}); assertHasArrayInterfaces(new TypeToken<T[]>() {}); } public <T extends NoInterface, T1 extends T, T2 extends T1> void testGetGenericInterfaces_typeVariable_boundIsTypeVariableAndClass() { - ASSERT.that(TypeToken.of(new TypeCapture<T2>() {}.capture()).getGenericInterfaces()).isEmpty(); + assertThat(TypeToken.of(new TypeCapture<T2>() {}.capture()).getGenericInterfaces()).isEmpty(); assertHasArrayInterfaces(new TypeToken<T2[]>() {}); } public <T extends Iterable<T>, T1 extends T, T2 extends T1> void testGetGenericInterfaces_typeVariable_boundIsTypeVariableAndInterface() { - assertThat(TypeToken.of(new TypeCapture<T2>() {}.capture()).getGenericInterfaces()) + makeUnmodifiable(TypeToken.of(new TypeCapture<T2>() {}.capture()).getGenericInterfaces()) .has().exactly(TypeToken.of(new TypeCapture<T1>() {}.capture())); assertHasArrayInterfaces(new TypeToken<T2[]>() {}); } public void testGetGenericInterfaces_wildcard_lowerBounded() { - ASSERT.that(TypeToken.of(Types.supertypeOf(String.class)).getGenericInterfaces()).isEmpty(); - ASSERT.that(TypeToken.of(Types.supertypeOf(String[].class)).getGenericInterfaces()).isEmpty(); + assertThat(TypeToken.of(Types.supertypeOf(String.class)).getGenericInterfaces()).isEmpty(); + assertThat(TypeToken.of(Types.supertypeOf(String[].class)).getGenericInterfaces()).isEmpty(); } public void testGetGenericInterfaces_wildcard_boundIsClass() { - ASSERT.that(TypeToken.of(Types.subtypeOf(Object.class)).getGenericInterfaces()).isEmpty(); - ASSERT.that(TypeToken.of(Types.subtypeOf(Object[].class)).getGenericInterfaces()).isEmpty(); + assertThat(TypeToken.of(Types.subtypeOf(Object.class)).getGenericInterfaces()).isEmpty(); + assertThat(TypeToken.of(Types.subtypeOf(Object[].class)).getGenericInterfaces()).isEmpty(); } public void testGetGenericInterfaces_wildcard_boundIsInterface() { TypeToken<Iterable<String>> interfaceType = new TypeToken<Iterable<String>>() {}; - assertThat(TypeToken.of(Types.subtypeOf(interfaceType.getType())).getGenericInterfaces()) + makeUnmodifiable(TypeToken.of(Types.subtypeOf(interfaceType.getType())).getGenericInterfaces()) .has().exactly(interfaceType); assertHasArrayInterfaces(new TypeToken<Iterable<String>[]>() {}); } public void testGetGenericInterfaces_noInterface() { - ASSERT.that(new TypeToken<NoInterface>() {}.getGenericInterfaces()).isEmpty(); + assertThat(new TypeToken<NoInterface>() {}.getGenericInterfaces()).isEmpty(); assertHasArrayInterfaces(new TypeToken<NoInterface[]>() {}); } @@ -1204,7 +1203,7 @@ public class TypeTokenTest extends TestCase { TypeToken<?> matrixType = type.resolveType( Holder.class.getDeclaredField("matrix").getGenericType()); assertEquals(List[].class, matrixType.getRawType()); - ASSERT.that(matrixType.getType()) + assertThat(matrixType.getType()) .isNotEqualTo(new TypeToken<List<?>[]>() {}.getType()); } @@ -1278,7 +1277,7 @@ public class TypeTokenTest extends TestCase { throws NoSuchMethodException { Method failMethod = Loser.class.getMethod("lose"); Invokable<T, ?> invokable = new TypeToken<T>(getClass()) {}.method(failMethod); - ASSERT.that(invokable.getExceptionTypes()).has().item(TypeToken.of(AssertionError.class)); + assertThat(invokable.getExceptionTypes()).has().item(TypeToken.of(AssertionError.class)); } public void testConstructor_getOwnerType() throws NoSuchMethodException { @@ -1344,7 +1343,7 @@ public class TypeTokenTest extends TestCase { @SuppressWarnings("rawtypes") // Reflection API skew Constructor<CannotConstruct> constructor = CannotConstruct.class.getConstructor(); Invokable<T, ?> invokable = new TypeToken<T>(getClass()) {}.constructor(constructor); - ASSERT.that(invokable.getExceptionTypes()).has().item(TypeToken.of(AssertionError.class)); + assertThat(invokable.getExceptionTypes()).has().item(TypeToken.of(AssertionError.class)); } public void testRejectTypeVariable_class() { @@ -1509,7 +1508,7 @@ public class TypeTokenTest extends TestCase { private static <T, X> TypeToken<T> substitute(TypeToken<T> type, Class<X> arg) { return type.where(new TypeParameter<X>() {}, arg); } - + private abstract static class ToReproduceGenericSignatureFormatError<V> { private abstract class BaseOuter { abstract class BaseInner {} @@ -1659,7 +1658,7 @@ public class TypeTokenTest extends TestCase { private static class Base implements BaseInterface {} private static class Sub extends Base {} - private static CollectionSubject<?, Object, ?> assertThat(Collection<?> actual) { - return ASSERT.that(Collections.<Object>unmodifiableCollection(actual)); + private static CollectionSubject<?, Object, ?> makeUnmodifiable(Collection<?> actual) { + return assertThat(Collections.<Object>unmodifiableCollection(actual)); } } diff --git a/guava-tests/test/com/google/common/reflect/TypesTest.java b/guava-tests/test/com/google/common/reflect/TypesTest.java index a41b6a98b..8e223bc60 100644 --- a/guava-tests/test/com/google/common/reflect/TypesTest.java +++ b/guava-tests/test/com/google/common/reflect/TypesTest.java @@ -16,8 +16,8 @@ package com.google.common.reflect; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; -import static org.truth0.Truth.ASSERT; import com.google.common.collect.Lists; import com.google.common.testing.EqualsTester; @@ -66,8 +66,8 @@ public class TypesTest extends TestCase { assertEquals(jvmType.toString(), ourType.toString()); assertEquals(jvmType.hashCode(), ourType.hashCode()); assertEquals(HashMap.class, ourType.getRawType()); - ASSERT.that(ourType.getActualTypeArguments()) - .iteratesOverSequence(jvmType.getActualTypeArguments()); + assertThat(ourType.getActualTypeArguments()).asList() + .has().exactlyAs(asList(jvmType.getActualTypeArguments())).inOrder(); assertEquals(Arrays.asList( String.class, Types.newArrayType(Types.newArrayType(int.class))), @@ -107,8 +107,8 @@ public class TypesTest extends TestCase { assertEquals(jvmType.toString(), ourType.toString()); assertEquals(Map.class, ourType.getOwnerType()); assertEquals(Map.Entry.class, ourType.getRawType()); - ASSERT.that(ourType.getActualTypeArguments()) - .iteratesOverSequence(jvmType.getActualTypeArguments()); + assertThat(ourType.getActualTypeArguments()).asList() + .has().exactlyAs(asList(jvmType.getActualTypeArguments())).inOrder(); } public void testNewParameterizedType_serializable() { @@ -268,9 +268,9 @@ public class TypesTest extends TestCase { WildcardType expected, WildcardType actual) { assertEquals(expected.toString(), actual.toString()); assertEquals(actual.toString(), expected.hashCode(), actual.hashCode()); - ASSERT.that(actual.getLowerBounds()) + assertThat(actual.getLowerBounds()).asList() .has().exactlyAs(asList(expected.getLowerBounds())).inOrder(); - ASSERT.that(actual.getUpperBounds()) + assertThat(actual.getUpperBounds()).asList() .has().exactlyAs(asList(expected.getUpperBounds())).inOrder(); } @@ -366,7 +366,8 @@ public class TypesTest extends TestCase { if (!Types.NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY) { assertEquals(actual.toString(), expected.hashCode(), actual.hashCode()); } - ASSERT.that(actual.getBounds()).has().exactlyAs(asList(expected.getBounds())).inOrder(); + assertThat(actual.getBounds()).asList() + .has().exactlyAs(asList(expected.getBounds())).inOrder(); } /** diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java index 4024a8e6d..166be3d50 100644 --- a/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java @@ -16,7 +16,7 @@ package com.google.common.util.concurrent; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import junit.framework.AssertionFailedError; import junit.framework.TestCase; @@ -153,11 +153,11 @@ public class AbstractFutureTest extends TestCase { int index = findStackFrame( e, getClass().getName(), "getExpectingExecutionException"); - ASSERT.that(index).isNotEqualTo(0); + assertThat(index).isNotEqualTo(0); // Above our method should be the call to get(). Don't assert on the class // because it could be some superclass. - ASSERT.that(e.getStackTrace()[index - 1].getMethodName()).isEqualTo("get"); + assertThat(e.getStackTrace()[index - 1].getMethodName()).isEqualTo("get"); } private static int findStackFrame( diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java index eb159dfc2..2dfad5c5d 100644 --- a/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java @@ -16,7 +16,8 @@ package com.google.common.util.concurrent; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import com.google.common.collect.Lists; @@ -93,7 +94,7 @@ public class AbstractIdleServiceTest extends TestCase { service.startAsync().awaitRunning(); assertEquals(1, service.startUpCalled); assertEquals(Service.State.RUNNING, service.state()); - ASSERT.that(service.transitionStates).has().exactly(Service.State.STARTING).inOrder(); + assertThat(service.transitionStates).has().exactly(Service.State.STARTING).inOrder(); } public void testStart_failed() { @@ -113,7 +114,7 @@ public class AbstractIdleServiceTest extends TestCase { } assertEquals(1, service.startUpCalled); assertEquals(Service.State.FAILED, service.state()); - ASSERT.that(service.transitionStates).has().exactly(Service.State.STARTING).inOrder(); + assertThat(service.transitionStates).has().exactly(Service.State.STARTING).inOrder(); } public void testStop_withoutStart() { @@ -122,7 +123,7 @@ public class AbstractIdleServiceTest extends TestCase { assertEquals(0, service.startUpCalled); assertEquals(0, service.shutDownCalled); assertEquals(Service.State.TERMINATED, service.state()); - ASSERT.that(service.transitionStates).isEmpty(); + assertThat(service.transitionStates).isEmpty(); } public void testStop_afterStart() { @@ -134,7 +135,7 @@ public class AbstractIdleServiceTest extends TestCase { assertEquals(1, service.startUpCalled); assertEquals(1, service.shutDownCalled); assertEquals(Service.State.TERMINATED, service.state()); - ASSERT.that(service.transitionStates) + assertThat(service.transitionStates) .has().exactly(Service.State.STARTING, Service.State.STOPPING).inOrder(); } @@ -158,7 +159,7 @@ public class AbstractIdleServiceTest extends TestCase { assertEquals(1, service.startUpCalled); assertEquals(1, service.shutDownCalled); assertEquals(Service.State.FAILED, service.state()); - ASSERT.that(service.transitionStates) + assertThat(service.transitionStates) .has().exactly(Service.State.STARTING, Service.State.STOPPING).inOrder(); } @@ -184,7 +185,7 @@ public class AbstractIdleServiceTest extends TestCase { service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS); fail("Expected timeout"); } catch (TimeoutException e) { - ASSERT.that(e.getMessage()).contains(Service.State.STARTING.toString()); + assertThat(e.getMessage()).contains(Service.State.STARTING.toString()); } } @@ -209,7 +210,7 @@ public class AbstractIdleServiceTest extends TestCase { @Override protected Executor executor() { transitionStates.add(state()); - return MoreExecutors.sameThreadExecutor(); + return directExecutor(); } } } diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java index 59ed10e4d..7c01d41f2 100644 --- a/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java @@ -21,7 +21,6 @@ import com.google.common.util.concurrent.Service.State; import junit.framework.TestCase; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; @@ -32,6 +31,7 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; /** * Unit test for {@link AbstractScheduledService}. @@ -149,71 +149,53 @@ public class AbstractScheduledServiceTest extends TestCase { } public void testDefaultExecutorIsShutdownWhenServiceIsStopped() throws Exception { - final CountDownLatch terminationLatch = new CountDownLatch(1); + final AtomicReference<ScheduledExecutorService> executor = Atomics.newReference(); AbstractScheduledService service = new AbstractScheduledService() { - volatile ScheduledExecutorService executorService; @Override protected void runOneIteration() throws Exception {} @Override protected ScheduledExecutorService executor() { - if (executorService == null) { - executorService = super.executor(); - // Add a listener that will be executed after the listener that shuts down the executor. - addListener(new Listener() { - @Override public void terminated(State from) { - terminationLatch.countDown(); - } - }, MoreExecutors.sameThreadExecutor()); - } - return executorService; + executor.set(super.executor()); + return executor.get(); } @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule(0, 1, TimeUnit.MILLISECONDS); - }}; + } + }; - service.startAsync(); - assertFalse(service.executor().isShutdown()); - service.awaitRunning(); - service.stopAsync(); - terminationLatch.await(); - assertTrue(service.executor().isShutdown()); - assertTrue(service.executor().awaitTermination(100, TimeUnit.MILLISECONDS)); + service.startAsync(); + assertFalse(service.executor().isShutdown()); + service.awaitRunning(); + service.stopAsync(); + service.awaitTerminated(); + assertTrue(executor.get().awaitTermination(100, TimeUnit.MILLISECONDS)); } public void testDefaultExecutorIsShutdownWhenServiceFails() throws Exception { - final CountDownLatch failureLatch = new CountDownLatch(1); + final AtomicReference<ScheduledExecutorService> executor = Atomics.newReference(); AbstractScheduledService service = new AbstractScheduledService() { - volatile ScheduledExecutorService executorService; - @Override protected void runOneIteration() throws Exception {} - @Override protected void startUp() throws Exception { throw new Exception("Failed"); } + @Override protected void runOneIteration() throws Exception {} + @Override protected ScheduledExecutorService executor() { - if (executorService == null) { - executorService = super.executor(); - // Add a listener that will be executed after the listener that shuts down the executor. - addListener(new Listener() { - @Override public void failed(State from, Throwable failure) { - failureLatch.countDown(); - } - }, MoreExecutors.sameThreadExecutor()); - } - return executorService; + executor.set(super.executor()); + return executor.get(); } @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule(0, 1, TimeUnit.MILLISECONDS); - }}; + } + }; - try { - service.startAsync().awaitRunning(); - fail("Expected service to fail during startup"); - } catch (IllegalStateException expected) {} - failureLatch.await(); - assertTrue(service.executor().isShutdown()); - assertTrue(service.executor().awaitTermination(100, TimeUnit.MILLISECONDS)); + try { + service.startAsync().awaitRunning(); + fail("Expected service to fail during startup"); + } catch (IllegalStateException expected) {} + + assertTrue(executor.get().awaitTermination(100, TimeUnit.MILLISECONDS)); } public void testSchedulerOnlyCalledOnce() throws Exception { diff --git a/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java index 5ebd205db..1fdac3853 100644 --- a/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java @@ -16,6 +16,7 @@ package com.google.common.util.concurrent; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.lang.Thread.currentThread; import static java.util.concurrent.TimeUnit.SECONDS; @@ -258,7 +259,7 @@ public class AbstractServiceTest extends TestCase { @Override public void stopping(State from) { stopppingCount.incrementAndGet(); } - }, MoreExecutors.sameThreadExecutor()); + }, directExecutor()); service.startAsync(); service.stopAsync(); @@ -686,7 +687,7 @@ public class AbstractServiceTest extends TestCase { final StartFailingService service = new StartFailingService(); service.startAsync(); assertEquals(State.FAILED, service.state()); - service.addListener(new RecordingListener(service), MoreExecutors.sameThreadExecutor()); + service.addListener(new RecordingListener(service), directExecutor()); Thread thread = new Thread() { @Override public void run() { // Internally stopAsync() grabs a lock, this could be any such method on AbstractService. @@ -704,7 +705,7 @@ public class AbstractServiceTest extends TestCase { @Override public void running() { service.awaitRunning(); } - }, MoreExecutors.sameThreadExecutor()); + }, directExecutor()); service.startAsync().awaitRunning(LONG_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); service.stopAsync(); } @@ -715,7 +716,7 @@ public class AbstractServiceTest extends TestCase { @Override public void terminated(State from) { service.stopAsync().awaitTerminated(); } - }, MoreExecutors.sameThreadExecutor()); + }, directExecutor()); service.startAsync().awaitRunning(); Thread thread = new Thread() { @@ -812,7 +813,7 @@ public class AbstractServiceTest extends TestCase { private static class RecordingListener extends Listener { static RecordingListener record(Service service) { RecordingListener listener = new RecordingListener(service); - service.addListener(listener, MoreExecutors.sameThreadExecutor()); + service.addListener(listener, directExecutor()); return listener; } diff --git a/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java b/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java new file mode 100644 index 000000000..162d68753 --- /dev/null +++ b/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java @@ -0,0 +1,578 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.util.concurrent; + +import com.google.common.base.Joiner; +import com.google.common.util.concurrent.CycleDetectingLockFactory.Policies; +import com.google.common.util.concurrent.CycleDetectingLockFactory.Policy; +import com.google.common.util.concurrent.CycleDetectingLockFactory.PotentialDeadlockException; + +import junit.framework.TestCase; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Unittests for {@link CycleDetectingLockFactory}. + * + * @author Darick Tong + */ +public class CycleDetectingLockFactoryTest extends TestCase { + + private ReentrantLock lockA; + private ReentrantLock lockB; + private ReentrantLock lockC; + private ReentrantReadWriteLock.ReadLock readLockA; + private ReentrantReadWriteLock.ReadLock readLockB; + private ReentrantReadWriteLock.ReadLock readLockC; + private ReentrantReadWriteLock.WriteLock writeLockA; + private ReentrantReadWriteLock.WriteLock writeLockB; + private ReentrantReadWriteLock.WriteLock writeLockC; + private ReentrantLock lock1; + private ReentrantLock lock2; + private ReentrantLock lock3; + private ReentrantLock lock01; + private ReentrantLock lock02; + private ReentrantLock lock03; + + @Override + protected void setUp() throws Exception { + super.setUp(); + CycleDetectingLockFactory factory = + CycleDetectingLockFactory.newInstance(Policies.THROW); + lockA = factory.newReentrantLock("LockA"); + lockB = factory.newReentrantLock("LockB"); + lockC = factory.newReentrantLock("LockC"); + ReentrantReadWriteLock readWriteLockA = + factory.newReentrantReadWriteLock("ReadWriteA"); + ReentrantReadWriteLock readWriteLockB = + factory.newReentrantReadWriteLock("ReadWriteB"); + ReentrantReadWriteLock readWriteLockC = + factory.newReentrantReadWriteLock("ReadWriteC"); + readLockA = readWriteLockA.readLock(); + readLockB = readWriteLockB.readLock(); + readLockC = readWriteLockC.readLock(); + writeLockA = readWriteLockA.writeLock(); + writeLockB = readWriteLockB.writeLock(); + writeLockC = readWriteLockC.writeLock(); + + CycleDetectingLockFactory.WithExplicitOrdering<MyOrder> factory2 = + newInstanceWithExplicitOrdering(MyOrder.class, Policies.THROW); + lock1 = factory2.newReentrantLock(MyOrder.FIRST); + lock2 = factory2.newReentrantLock(MyOrder.SECOND); + lock3 = factory2.newReentrantLock(MyOrder.THIRD); + + CycleDetectingLockFactory.WithExplicitOrdering<OtherOrder> factory3 = + newInstanceWithExplicitOrdering(OtherOrder.class, Policies.THROW); + lock01 = factory3.newReentrantLock(OtherOrder.FIRST); + lock02 = factory3.newReentrantLock(OtherOrder.SECOND); + lock03 = factory3.newReentrantLock(OtherOrder.THIRD); + } + + // In the unittest, create each ordered factory with its own set of lock + // graph nodes (as opposed to using the static per-Enum map) to avoid + // conflicts across different test runs. + private <E extends Enum<E>> CycleDetectingLockFactory.WithExplicitOrdering<E> + newInstanceWithExplicitOrdering(Class<E> enumClass, Policy policy) { + return new CycleDetectingLockFactory.WithExplicitOrdering<E>( + policy, CycleDetectingLockFactory.createNodes(enumClass)); + } + + public void testDeadlock_twoLocks() { + // Establish an acquisition order of lockA -> lockB. + lockA.lock(); + lockB.lock(); + lockA.unlock(); + lockB.unlock(); + + // The opposite order should fail (Policies.THROW). + PotentialDeadlockException firstException = null; + lockB.lock(); + try { + lockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage(expected, "LockB -> LockA", "LockA -> LockB"); + firstException = expected; + } + + // Second time should also fail, with a cached causal chain. + try { + lockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage(expected, "LockB -> LockA", "LockA -> LockB"); + // The causal chain should be cached. + assertSame(firstException.getCause(), expected.getCause()); + } + + // lockA should work after lockB is released. + lockB.unlock(); + lockA.lock(); + } + + // Tests transitive deadlock detection. + public void testDeadlock_threeLocks() { + // Establish an ordering from lockA -> lockB. + lockA.lock(); + lockB.lock(); + lockB.unlock(); + lockA.unlock(); + + // Establish an ordering from lockB -> lockC. + lockB.lock(); + lockC.lock(); + lockB.unlock(); + + // lockC -> lockA should fail. + try { + lockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, "LockC -> LockA", "LockB -> LockC", "LockA -> LockB"); + } + } + + public void testReentrancy_noDeadlock() { + lockA.lock(); + lockB.lock(); + lockA.lock(); // Should not assert on lockB -> reentrant(lockA) + } + + public void testExplicitOrdering_noViolations() { + lock1.lock(); + lock3.lock(); + lock3.unlock(); + lock2.lock(); + lock3.lock(); + } + + public void testExplicitOrdering_violations() { + lock3.lock(); + try { + lock2.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage(expected, "MyOrder.THIRD -> MyOrder.SECOND"); + } + + try { + lock1.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage(expected, "MyOrder.THIRD -> MyOrder.FIRST"); + } + + lock3.unlock(); + lock2.lock(); + + try { + lock1.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage(expected, "MyOrder.SECOND -> MyOrder.FIRST"); + } + } + + public void testDifferentOrderings_noViolations() { + lock3.lock(); // MyOrder, ordinal() == 3 + lock01.lock(); // OtherOrder, ordinal() == 1 + } + + public void testExplicitOrderings_generalCycleDetection() { + lock3.lock(); // MyOrder, ordinal() == 3 + lock01.lock(); // OtherOrder, ordinal() == 1 + + lock3.unlock(); + try { + lock3.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, + "OtherOrder.FIRST -> MyOrder.THIRD", + "MyOrder.THIRD -> OtherOrder.FIRST"); + } + + lockA.lock(); + lock01.unlock(); + lockB.lock(); + lockA.unlock(); + + try { + lock01.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, + "LockB -> OtherOrder.FIRST", + "LockA -> LockB", + "OtherOrder.FIRST -> LockA"); + } + } + + public void testExplicitOrdering_cycleWithUnorderedLock() { + Lock myLock = CycleDetectingLockFactory.newInstance(Policies.THROW) + .newReentrantLock("MyLock"); + lock03.lock(); + myLock.lock(); + lock03.unlock(); + + try { + lock01.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, + "MyLock -> OtherOrder.FIRST", + "OtherOrder.THIRD -> MyLock", + "OtherOrder.FIRST -> OtherOrder.THIRD"); + } + } + + public void testExplicitOrdering_reentrantAcquisition() { + CycleDetectingLockFactory.WithExplicitOrdering<OtherOrder> factory = + newInstanceWithExplicitOrdering(OtherOrder.class, Policies.THROW); + Lock lockA = factory.newReentrantReadWriteLock(OtherOrder.FIRST).readLock(); + Lock lockB = factory.newReentrantLock(OtherOrder.SECOND); + + lockA.lock(); + lockA.lock(); + lockB.lock(); + lockB.lock(); + lockA.unlock(); + lockA.unlock(); + lockB.unlock(); + lockB.unlock(); + } + + public void testExplicitOrdering_acquiringMultipleLocksWithSameRank() { + CycleDetectingLockFactory.WithExplicitOrdering<OtherOrder> factory = + newInstanceWithExplicitOrdering(OtherOrder.class, Policies.THROW); + Lock lockA = factory.newReentrantLock(OtherOrder.FIRST); + Lock lockB = factory.newReentrantReadWriteLock(OtherOrder.FIRST).readLock(); + + lockA.lock(); + try { + lockB.lock(); + fail("Expected IllegalStateException"); + } catch (IllegalStateException expected) { + } + + lockA.unlock(); + lockB.lock(); + } + + public void testReadLock_deadlock() { + readLockA.lock(); // Establish an ordering from readLockA -> lockB. + lockB.lock(); + lockB.unlock(); + readLockA.unlock(); + + lockB.lock(); + try { + readLockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); + } + } + + public void testReadLock_transitive() { + readLockA.lock(); // Establish an ordering from readLockA -> lockB. + lockB.lock(); + lockB.unlock(); + readLockA.unlock(); + + // Establish an ordering from lockB -> readLockC. + lockB.lock(); + readLockC.lock(); + lockB.unlock(); + readLockC.unlock(); + + // readLockC -> readLockA + readLockC.lock(); + try { + readLockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, + "ReadWriteC -> ReadWriteA", + "LockB -> ReadWriteC", + "ReadWriteA -> LockB"); + } + } + + public void testWriteLock_threeLockDeadLock() { + // Establish an ordering from writeLockA -> writeLockB. + writeLockA.lock(); + writeLockB.lock(); + writeLockB.unlock(); + writeLockA.unlock(); + + // Establish an ordering from writeLockB -> writeLockC. + writeLockB.lock(); + writeLockC.lock(); + writeLockB.unlock(); + + // writeLockC -> writeLockA should fail. + try { + writeLockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, + "ReadWriteC -> ReadWriteA", + "ReadWriteB -> ReadWriteC", + "ReadWriteA -> ReadWriteB"); + } + } + + public void testWriteToReadLockDowngrading() { + writeLockA.lock(); // writeLockA downgrades to readLockA + readLockA.lock(); + writeLockA.unlock(); + + lockB.lock(); // readLockA -> lockB + readLockA.unlock(); + + // lockB -> writeLockA should fail + try { + writeLockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); + } + } + + public void testReadWriteLockDeadlock() { + writeLockA.lock(); // Establish an ordering from writeLockA -> lockB + lockB.lock(); + writeLockA.unlock(); + lockB.unlock(); + + // lockB -> readLockA should fail. + lockB.lock(); + try { + readLockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); + } + } + + public void testReadWriteLockDeadlock_transitive() { + readLockA.lock(); // Establish an ordering from readLockA -> lockB + lockB.lock(); + readLockA.unlock(); + lockB.unlock(); + + // Establish an ordering from lockB -> lockC + lockB.lock(); + lockC.lock(); + lockB.unlock(); + lockC.unlock(); + + // lockC -> writeLockA should fail. + lockC.lock(); + try { + writeLockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, + "LockC -> ReadWriteA", + "LockB -> LockC", + "ReadWriteA -> LockB"); + } + } + + public void testReadWriteLockDeadlock_treatedEquivalently() { + readLockA.lock(); // readLockA -> writeLockB + writeLockB.lock(); + readLockA.unlock(); + writeLockB.unlock(); + + // readLockB -> writeLockA should fail. + readLockB.lock(); + try { + writeLockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage( + expected, "ReadWriteB -> ReadWriteA", "ReadWriteA -> ReadWriteB"); + } + } + + public void testDifferentLockFactories() { + CycleDetectingLockFactory otherFactory = + CycleDetectingLockFactory.newInstance(Policies.WARN); + ReentrantLock lockD = otherFactory.newReentrantLock("LockD"); + + // lockA -> lockD + lockA.lock(); + lockD.lock(); + lockA.unlock(); + lockD.unlock(); + + // lockD -> lockA should fail even though lockD is from a different factory. + lockD.lock(); + try { + lockA.lock(); + fail("Expected PotentialDeadlockException"); + } catch (PotentialDeadlockException expected) { + checkMessage(expected, "LockD -> LockA", "LockA -> LockD"); + } + } + + public void testDifferentLockFactories_policyExecution() { + CycleDetectingLockFactory otherFactory = + CycleDetectingLockFactory.newInstance(Policies.WARN); + ReentrantLock lockD = otherFactory.newReentrantLock("LockD"); + + // lockD -> lockA + lockD.lock(); + lockA.lock(); + lockA.unlock(); + lockD.unlock(); + + // lockA -> lockD should warn but otherwise succeed because lockD was + // created by a factory with the WARN policy. + lockA.lock(); + lockD.lock(); + } + + public void testReentrantLock_tryLock() throws Exception { + LockingThread thread = new LockingThread(lockA); + thread.start(); + + thread.waitUntilHoldingLock(); + assertFalse(lockA.tryLock()); + + thread.releaseLockAndFinish(); + assertTrue(lockA.tryLock()); + } + + public void testReentrantWriteLock_tryLock() throws Exception { + LockingThread thread = new LockingThread(writeLockA); + thread.start(); + + thread.waitUntilHoldingLock(); + assertFalse(writeLockA.tryLock()); + assertFalse(readLockA.tryLock()); + + thread.releaseLockAndFinish(); + assertTrue(writeLockA.tryLock()); + assertTrue(readLockA.tryLock()); + } + + public void testReentrantReadLock_tryLock() throws Exception { + LockingThread thread = new LockingThread(readLockA); + thread.start(); + + thread.waitUntilHoldingLock(); + assertFalse(writeLockA.tryLock()); + assertTrue(readLockA.tryLock()); + readLockA.unlock(); + + thread.releaseLockAndFinish(); + assertTrue(writeLockA.tryLock()); + assertTrue(readLockA.tryLock()); + } + + private static class LockingThread extends Thread { + final CountDownLatch locked = new CountDownLatch(1); + final CountDownLatch finishLatch = new CountDownLatch(1); + final Lock lock; + + LockingThread(Lock lock) { + this.lock = lock; + } + + @Override + public void run() { + lock.lock(); + try { + locked.countDown(); + finishLatch.await(1, TimeUnit.MINUTES); + } catch (InterruptedException e) { + fail(e.toString()); + } finally { + lock.unlock(); + } + } + + void waitUntilHoldingLock() throws InterruptedException { + locked.await(1, TimeUnit.MINUTES); + } + + void releaseLockAndFinish() throws InterruptedException { + finishLatch.countDown(); + this.join(10000); + assertFalse(this.isAlive()); + } + } + + public void testReentrantReadWriteLock_implDoesNotExposeShadowedLocks() { + assertEquals( + "Unexpected number of public methods in ReentrantReadWriteLock. " + + "The correctness of CycleDetectingReentrantReadWriteLock depends on " + + "the fact that the shadowed ReadLock and WriteLock are never used or " + + "exposed by the superclass implementation. If the implementation has " + + "changed, the code must be re-inspected to ensure that the " + + "assumption is still valid.", + 24, ReentrantReadWriteLock.class.getMethods().length); + } + + private enum MyOrder { + FIRST, SECOND, THIRD; + } + + private enum OtherOrder { + FIRST, SECOND, THIRD; + } + + // Given a sequence of lock acquisition descriptions + // (e.g. "LockA -> LockB", "LockB -> LockC", ...) + // Checks that the exception.getMessage() matches a regex of the form: + // "LockA -> LockB \b.*\b LockB -> LockC \b.*\b LockC -> LockA" + private void checkMessage( + IllegalStateException exception, String... expectedLockCycle) { + String regex = Joiner.on("\\b.*\\b").join(expectedLockCycle); + assertContainsRegex(regex, exception.getMessage()); + } + + // TODO(cpovirk): consider adding support for regex to Truth + private static void assertContainsRegex(String expectedRegex, String actual) { + Pattern pattern = Pattern.compile(expectedRegex); + Matcher matcher = pattern.matcher(actual); + if (!matcher.find()) { + String actualDesc = (actual == null) ? "null" : ('<' + actual + '>'); + fail("expected to contain regex:<" + expectedRegex + "> but was:" + + actualDesc); + } + } +} diff --git a/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java b/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java index 4340c608d..dd4799bb8 100644 --- a/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/ExecutionListTest.java @@ -16,10 +16,9 @@ package com.google.common.util.concurrent; -import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import com.google.common.testing.NullPointerTester; -import com.google.common.util.concurrent.ExecutionList; import junit.framework.TestCase; @@ -59,7 +58,7 @@ public class ExecutionListTest extends TestCase { @Override public void run() { runCalled.getAndIncrement(); } - }, MoreExecutors.sameThreadExecutor()); + }, directExecutor()); list.execute(); assertEquals(1, runCalled.get()); list.execute(); @@ -79,7 +78,7 @@ public class ExecutionListTest extends TestCase { } runCalled.getAndIncrement(); } - }, MoreExecutors.sameThreadExecutor()); + }, directExecutor()); Runnable execute = new Runnable() { @Override public void run() { list.execute(); @@ -116,7 +115,7 @@ public class ExecutionListTest extends TestCase { integer.compareAndSet(expectedCount, expectedCount + 1); } }, - MoreExecutors.sameThreadExecutor()); + MoreExecutors.directExecutor()); } list.execute(); assertEquals(10, integer.get()); @@ -135,9 +134,9 @@ public class ExecutionListTest extends TestCase { } public void testExceptionsCaught() { - list.add(THROWING_RUNNABLE, sameThreadExecutor()); + list.add(THROWING_RUNNABLE, directExecutor()); list.execute(); - list.add(THROWING_RUNNABLE, sameThreadExecutor()); + list.add(THROWING_RUNNABLE, directExecutor()); } public void testNulls() { diff --git a/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java b/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java new file mode 100644 index 000000000..14e0179d4 --- /dev/null +++ b/guava-tests/test/com/google/common/util/concurrent/FutureCallbackTest.java @@ -0,0 +1,256 @@ +/* + * Copyright (C) 2011 The Guava Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.util.concurrent; + +import com.google.common.base.Preconditions; + +import junit.framework.TestCase; + +import org.mockito.Mockito; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.Executor; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import javax.annotation.Nullable; + +/** + * Test for {@link FutureCallback}. + * + * @author Anthony Zana + */ +public class FutureCallbackTest extends TestCase { + public void testSameThreadSuccess() { + SettableFuture<String> f = SettableFuture.create(); + MockCallback callback = new MockCallback("foo"); + Futures.addCallback(f, callback); + f.set("foo"); + } + + public void testExecutorSuccess() { + CountingSameThreadExecutor ex = new CountingSameThreadExecutor(); + SettableFuture<String> f = SettableFuture.create(); + MockCallback callback = new MockCallback("foo"); + Futures.addCallback(f, callback, ex); + f.set("foo"); + assertEquals(1, ex.runCount); + } + + // Error cases + public void testSameThreadExecutionException() { + SettableFuture<String> f = SettableFuture.create(); + Exception e = new IllegalArgumentException("foo not found"); + MockCallback callback = new MockCallback(e); + Futures.addCallback(f, callback); + f.setException(e); + } + + public void testCancel() { + SettableFuture<String> f = SettableFuture.create(); + FutureCallback<String> callback = + new FutureCallback<String>() { + private boolean called = false; + @Override + public void onSuccess(String result) { + fail("Was not expecting onSuccess() to be called."); + } + + @Override + public synchronized void onFailure(Throwable t) { + assertFalse(called); + assertTrue(t instanceof CancellationException); + called = true; + } + }; + Futures.addCallback(f, callback); + f.cancel(true); + } + + public void testThrowErrorFromGet() { + Error error = new AssertionError("ASSERT!"); + ListenableFuture<String> f = ThrowingFuture.throwingError(error); + MockCallback callback = new MockCallback(error); + Futures.addCallback(f, callback); + } + + public void testRuntimeExeceptionFromGet() { + RuntimeException e = new IllegalArgumentException("foo not found"); + ListenableFuture<String> f = ThrowingFuture.throwingRuntimeException(e); + MockCallback callback = new MockCallback(e); + Futures.addCallback(f, callback); + } + + public void testOnSuccessThrowsRuntimeException() throws Exception { + RuntimeException exception = new RuntimeException(); + String result = "result"; + SettableFuture<String> future = SettableFuture.create(); + @SuppressWarnings("unchecked") // Safe for a mock + FutureCallback<String> callback = Mockito.mock(FutureCallback.class); + Futures.addCallback(future, callback); + Mockito.doThrow(exception).when(callback).onSuccess(result); + future.set(result); + assertEquals(result, future.get()); + Mockito.verify(callback).onSuccess(result); + Mockito.verifyNoMoreInteractions(callback); + } + + public void testOnSuccessThrowsError() throws Exception { + class TestError extends Error {} + TestError error = new TestError(); + String result = "result"; + SettableFuture<String> future = SettableFuture.create(); + @SuppressWarnings("unchecked") // Safe for a mock + FutureCallback<String> callback = Mockito.mock(FutureCallback.class); + Futures.addCallback(future, callback); + Mockito.doThrow(error).when(callback).onSuccess(result); + try { + future.set(result); + fail("Should have thrown"); + } catch (TestError e) { + assertSame(error, e); + } + assertEquals(result, future.get()); + Mockito.verify(callback).onSuccess(result); + Mockito.verifyNoMoreInteractions(callback); + } + + public void testWildcardFuture() { + SettableFuture<String> settable = SettableFuture.create(); + ListenableFuture<?> f = settable; + FutureCallback<Object> callback = new FutureCallback<Object>() { + @Override + public void onSuccess(Object result) {} + + @Override + public void onFailure(Throwable t) {} + }; + Futures.addCallback(f, callback); + } + + private class CountingSameThreadExecutor implements Executor { + int runCount = 0; + @Override + public void execute(Runnable command) { + command.run(); + runCount++; + } + } + + // TODO(user): Move to testing, unify with RuntimeExceptionThrowingFuture + + /** + * A {@link Future} implementation which always throws directly from calls to + * get() (i.e. not wrapped in ExecutionException. + * For just a normal Future failure, use {@link SettableFuture}). + * + * <p>Useful for testing the behavior of Future utilities against odd futures. + * + * @author Anthony Zana + */ + private static class ThrowingFuture<V> implements ListenableFuture<V> { + private final Error error; + private final RuntimeException runtime; + + public static <V> ListenableFuture<V> throwingError(Error error) { + return new ThrowingFuture<V>(error); + } + + public static <V> ListenableFuture<V> + throwingRuntimeException(RuntimeException e) { + return new ThrowingFuture<V>(e); + } + + private ThrowingFuture(Error error) { + this.error = Preconditions.checkNotNull(error); + this.runtime = null; + } + + public ThrowingFuture(RuntimeException e) { + this.runtime = Preconditions.checkNotNull(e); + this.error = null; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public V get() { + throwOnGet(); + throw new AssertionError("Unreachable"); + } + + @Override + public V get(long timeout, TimeUnit unit) { + throwOnGet(); + throw new AssertionError("Unreachable"); + } + + @Override + public void addListener(Runnable listener, Executor executor) { + executor.execute(listener); + } + + private void throwOnGet() { + if (error != null) { + throw error; + } else { + throw runtime; + } + } + } + + private final class MockCallback implements FutureCallback<String> { + @Nullable private String value = null; + @Nullable private Throwable failure = null; + private boolean wasCalled = false; + + MockCallback(String expectedValue) { + this.value = expectedValue; + } + + public MockCallback(Throwable expectedFailure) { + this.failure = expectedFailure; + } + + @Override + public synchronized void onSuccess(String result) { + assertFalse(wasCalled); + wasCalled = true; + assertEquals(value, result); + } + + @Override + public synchronized void onFailure(Throwable t) { + assertFalse(wasCalled); + wasCalled = true; + assertEquals(failure, t); + } + } +} diff --git a/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java b/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java index 87367b267..b39dac04a 100644 --- a/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java @@ -17,18 +17,19 @@ package com.google.common.util.concurrent; import static com.google.common.base.Throwables.propagateIfInstanceOf; +import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.Futures.allAsList; import static com.google.common.util.concurrent.Futures.get; import static com.google.common.util.concurrent.Futures.getUnchecked; import static com.google.common.util.concurrent.Futures.immediateFailedFuture; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.Futures.successfulAsList; -import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; +import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService; import static java.util.concurrent.Executors.newSingleThreadExecutor; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.easymock.EasyMock.expect; -import static org.truth0.Truth.ASSERT; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -60,6 +61,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Handler; @@ -277,6 +279,22 @@ public class FuturesTest extends TestCase { assertTrue(secondary.wasInterrupted()); } + public void testTransform_rejectionPropagatesToOutput() + throws Exception { + SettableFuture<Foo> input = SettableFuture.create(); + ExecutorService executor = newDirectExecutorService(); + ListenableFuture<String> transformed = + Futures.transform(input, Functions.toStringFunction(), executor); + executor.shutdown(); + input.set(new Foo()); + try { + transformed.get(5, TimeUnit.SECONDS); + fail(); + } catch (ExecutionException expected) { + assertTrue(expected.getCause() instanceof RejectedExecutionException); + } + } + /** * Tests that the function is invoked only once, even if it throws an * exception. @@ -420,7 +438,7 @@ public class FuturesTest extends TestCase { public void testTransform_Executor() throws Exception { Object value = new Object(); - ExecutorSpy spy = new ExecutorSpy(MoreExecutors.sameThreadExecutor()); + ExecutorSpy spy = new ExecutorSpy(directExecutor()); assertFalse(spy.wasExecuted); @@ -807,7 +825,7 @@ public class FuturesTest extends TestCase { // Attach a listener SingleCallListener listener = new SingleCallListener(); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); // Satisfy each input and check the output assertFalse(compound.isDone()); @@ -821,7 +839,7 @@ public class FuturesTest extends TestCase { assertTrue(listener.wasCalled()); List<String> results = compound.get(); - ASSERT.that(results).has().exactly(DATA1, DATA2, DATA3).inOrder(); + assertThat(results).has().exactly(DATA1, DATA2, DATA3).inOrder(); } public void testAllAsList_emptyList() throws Exception { @@ -829,7 +847,7 @@ public class FuturesTest extends TestCase { listener.expectCall(); List<ListenableFuture<String>> futures = ImmutableList.of(); ListenableFuture<List<String>> compound = Futures.allAsList(futures); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertTrue(compound.isDone()); assertTrue(compound.get().isEmpty()); assertTrue(listener.wasCalled()); @@ -840,7 +858,7 @@ public class FuturesTest extends TestCase { listener.expectCall(); @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.allAsList(); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertTrue(compound.isDone()); assertTrue(compound.get().isEmpty()); assertTrue(listener.wasCalled()); @@ -853,7 +871,7 @@ public class FuturesTest extends TestCase { @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.allAsList(future1, future2); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); listener.expectCall(); Throwable exception = new Throwable("failed1"); @@ -919,7 +937,7 @@ public class FuturesTest extends TestCase { @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.allAsList(future1, future2); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); listener.expectCall(); future1.cancel(true); @@ -990,13 +1008,13 @@ public class FuturesTest extends TestCase { // Attach a listener SingleCallListener listener = new SingleCallListener(); listener.expectCall(); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertTrue(compound.isDone()); assertTrue(listener.wasCalled()); List<String> results = compound.get(); - ASSERT.that(results).has().exactly(DATA1, DATA2, DATA3).inOrder(); + assertThat(results).has().exactly(DATA1, DATA2, DATA3).inOrder(); } /** @@ -1450,7 +1468,7 @@ public class FuturesTest extends TestCase { // Attach a listener SingleCallListener listener = new SingleCallListener(); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); // Satisfy each input and check the output assertFalse(compound.isDone()); @@ -1464,7 +1482,7 @@ public class FuturesTest extends TestCase { assertTrue(listener.wasCalled()); List<String> results = compound.get(); - ASSERT.that(results).has().exactly(DATA1, DATA2, DATA3).inOrder(); + assertThat(results).has().exactly(DATA1, DATA2, DATA3).inOrder(); } public void testSuccessfulAsList_emptyList() throws Exception { @@ -1472,7 +1490,7 @@ public class FuturesTest extends TestCase { listener.expectCall(); List<ListenableFuture<String>> futures = ImmutableList.of(); ListenableFuture<List<String>> compound = Futures.successfulAsList(futures); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertTrue(compound.isDone()); assertTrue(compound.get().isEmpty()); assertTrue(listener.wasCalled()); @@ -1483,7 +1501,7 @@ public class FuturesTest extends TestCase { listener.expectCall(); @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.successfulAsList(); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertTrue(compound.isDone()); assertTrue(compound.get().isEmpty()); assertTrue(listener.wasCalled()); @@ -1496,7 +1514,7 @@ public class FuturesTest extends TestCase { @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.successfulAsList(future1, future2); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertFalse(compound.isDone()); future1.setException(new Throwable("failed1")); @@ -1507,7 +1525,7 @@ public class FuturesTest extends TestCase { assertTrue(listener.wasCalled()); List<String> results = compound.get(); - ASSERT.that(results).has().exactly(null, DATA2).inOrder(); + assertThat(results).has().exactly(null, DATA2).inOrder(); } public void testSuccessfulAsList_totalFailure() throws Exception { @@ -1517,7 +1535,7 @@ public class FuturesTest extends TestCase { @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.successfulAsList(future1, future2); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertFalse(compound.isDone()); future1.setException(new Throwable("failed1")); @@ -1528,7 +1546,7 @@ public class FuturesTest extends TestCase { assertTrue(listener.wasCalled()); List<String> results = compound.get(); - ASSERT.that(results).has().exactly(null, null).inOrder(); + assertThat(results).has().exactly(null, null).inOrder(); } public void testSuccessfulAsList_cancelled() throws Exception { @@ -1538,7 +1556,7 @@ public class FuturesTest extends TestCase { @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.successfulAsList(future1, future2); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); assertFalse(compound.isDone()); future1.cancel(true); @@ -1549,7 +1567,7 @@ public class FuturesTest extends TestCase { assertTrue(listener.wasCalled()); List<String> results = compound.get(); - ASSERT.that(results).has().exactly(null, DATA2).inOrder(); + assertThat(results).has().exactly(null, DATA2).inOrder(); } public void testSuccessfulAsList_resultCancelled() throws Exception { @@ -1624,7 +1642,7 @@ public class FuturesTest extends TestCase { // Now attempt to trigger the exception: future2.set(DATA2); } - }, sameThreadExecutor()); + }, directExecutor()); assertTrue(compound.cancel(false)); assertTrue(compound.isCancelled()); assertTrue(future1.isCancelled()); @@ -1661,7 +1679,7 @@ public class FuturesTest extends TestCase { @SuppressWarnings("unchecked") // array is never modified ListenableFuture<List<String>> compound = Futures.successfulAsList(future1, future2, future3); - compound.addListener(listener, MoreExecutors.sameThreadExecutor()); + compound.addListener(listener, directExecutor()); // First is cancelled, second fails, third succeeds assertFalse(compound.isDone()); @@ -1675,7 +1693,7 @@ public class FuturesTest extends TestCase { assertTrue(listener.wasCalled()); List<String> results = compound.get(); - ASSERT.that(results).has().exactly(null, null, DATA3).inOrder(); + assertThat(results).has().exactly(null, null, DATA3).inOrder(); } /** Non-Error exceptions are never logged. */ @@ -2337,7 +2355,7 @@ public class FuturesTest extends TestCase { ExceptionWithoutThrowableConstructor.class); fail(); } catch (ExceptionWithoutThrowableConstructor expected) { - ASSERT.that(expected.getMessage()).contains("mymessage"); + assertThat(expected.getMessage()).contains("mymessage"); assertEquals(CHECKED_EXCEPTION, expected.getCause()); } } diff --git a/guava-tests/test/com/google/common/util/concurrent/InterruptibleMonitorTest.java b/guava-tests/test/com/google/common/util/concurrent/InterruptibleMonitorTest.java new file mode 100644 index 000000000..6e08eb3e4 --- /dev/null +++ b/guava-tests/test/com/google/common/util/concurrent/InterruptibleMonitorTest.java @@ -0,0 +1,31 @@ +/* + * 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.util.concurrent; + +/** + * Tests for {@link Monitor}'s interruptible methods. + * + * @author Justin T. Sampson + */ + +public class InterruptibleMonitorTest extends MonitorTestCase { + + public InterruptibleMonitorTest() { + super(true); + } + +} diff --git a/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java b/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java index 5042d835d..1f41cf474 100644 --- a/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/JdkFutureAdaptersTest.java @@ -19,7 +19,7 @@ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkState; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.JdkFutureAdapters.listenInPoolThread; -import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.TimeUnit.SECONDS; @@ -56,7 +56,7 @@ public class JdkFutureAdaptersTest extends TestCase { NonListenableSettableFuture<String> abstractFuture = NonListenableSettableFuture.create(); abstractFuture.set(DATA1); - ExecutorSpy spy = new ExecutorSpy(sameThreadExecutor()); + ExecutorSpy spy = new ExecutorSpy(directExecutor()); ListenableFuture<String> listenableFuture = listenInPoolThread(abstractFuture, spy); @@ -69,7 +69,7 @@ public class JdkFutureAdaptersTest extends TestCase { // #addListener() will run the listener immediately because the Future is // already finished (we explicitly set the result of it above). - listenableFuture.addListener(singleCallListener, sameThreadExecutor()); + listenableFuture.addListener(singleCallListener, directExecutor()); assertEquals(DATA1, listenableFuture.get()); // 'spy' should have been ignored since 'abstractFuture' was done before @@ -128,7 +128,7 @@ public class JdkFutureAdaptersTest extends TestCase { assertFalse(singleCallListener.wasCalled()); assertFalse(listenableFuture.isDone()); - listenableFuture.addListener(singleCallListener, sameThreadExecutor()); + listenableFuture.addListener(singleCallListener, directExecutor()); /* * Don't shut down until the listenInPoolThread task has been accepted to * run. We want to see what happens when it's interrupted, not when it's @@ -235,7 +235,7 @@ public class JdkFutureAdaptersTest extends TestCase { * listenInPoolThread-spawned thread completes: */ RecordingRunnable earlyListener = new RecordingRunnable(); - listenable.addListener(earlyListener, sameThreadExecutor()); + listenable.addListener(earlyListener, directExecutor()); input.allowGetToComplete.countDown(); // Now give the get() thread time to finish: @@ -243,7 +243,7 @@ public class JdkFutureAdaptersTest extends TestCase { // Now test an additional addListener call, which will be run in-thread: RecordingRunnable lateListener = new RecordingRunnable(); - listenable.addListener(lateListener, sameThreadExecutor()); + listenable.addListener(lateListener, directExecutor()); assertTrue(lateListener.wasRun.await(1, SECONDS)); } diff --git a/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java b/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java index 479e569ab..cdc5fe38c 100644 --- a/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java @@ -16,6 +16,8 @@ package com.google.common.util.concurrent; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; + import junit.framework.TestCase; import java.util.concurrent.Callable; @@ -64,7 +66,7 @@ public class ListenableFutureTaskTest extends TestCase { public void run() { listenerLatch.countDown(); } - }, MoreExecutors.sameThreadExecutor()); + }, directExecutor()); } @Override diff --git a/guava-tests/test/com/google/common/util/concurrent/ListenerCallQueueTest.java b/guava-tests/test/com/google/common/util/concurrent/ListenerCallQueueTest.java index 651eb96c4..99fb92428 100644 --- a/guava-tests/test/com/google/common/util/concurrent/ListenerCallQueueTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/ListenerCallQueueTest.java @@ -16,6 +16,8 @@ package com.google.common.util.concurrent; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; + import com.google.common.util.concurrent.ListenerCallQueue.Callback; import junit.framework.TestCase; @@ -39,7 +41,7 @@ public class ListenerCallQueueTest extends TestCase { public void testAddAndExecute() { Object listenerInstance = new Object(); ListenerCallQueue<Object> queue = - new ListenerCallQueue<Object>(listenerInstance, MoreExecutors.sameThreadExecutor()); + new ListenerCallQueue<Object>(listenerInstance, directExecutor()); AtomicInteger counter = new AtomicInteger(); queue.add(incrementingCallback(counter, 1)); @@ -54,7 +56,7 @@ public class ListenerCallQueueTest extends TestCase { public void testAddAndExecute_withExceptions() { Object listenerInstance = new Object(); ListenerCallQueue<Object> queue = - new ListenerCallQueue<Object>(listenerInstance, MoreExecutors.sameThreadExecutor()); + new ListenerCallQueue<Object>(listenerInstance, directExecutor()); AtomicInteger counter = new AtomicInteger(); queue.add(incrementingCallback(counter, 1)); diff --git a/guava-tests/test/com/google/common/util/concurrent/MonitorTestCase.java b/guava-tests/test/com/google/common/util/concurrent/MonitorTestCase.java new file mode 100644 index 000000000..1fa270077 --- /dev/null +++ b/guava-tests/test/com/google/common/util/concurrent/MonitorTestCase.java @@ -0,0 +1,243 @@ +/* + * 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.util.concurrent; + +import com.google.common.testing.NullPointerTester; +import com.google.common.testing.TearDownStack; + +import junit.framework.TestCase; + +import java.util.Random; +import java.util.concurrent.TimeUnit; + +/** + * Tests for {@link Monitor}, either interruptible or uninterruptible. + * + * @author Justin T. Sampson + */ + +public abstract class MonitorTestCase extends TestCase { + + public class TestGuard extends Monitor.Guard { + private volatile boolean satisfied; + + public TestGuard(boolean satisfied) { + super(MonitorTestCase.this.monitor); + this.satisfied = satisfied; + } + + @Override public boolean isSatisfied() { + return this.satisfied; + } + + public void setSatisfied(boolean satisfied) { + this.satisfied = satisfied; + } + } + + private final boolean interruptible; + private Monitor monitor; + private final TearDownStack tearDownStack = new TearDownStack(true); + private TestThread<Monitor> thread1; + private TestThread<Monitor> thread2; + + protected MonitorTestCase(boolean interruptible) { + this.interruptible = interruptible; + } + + @Override protected final void setUp() throws Exception { + boolean fair = new Random().nextBoolean(); + monitor = new Monitor(fair); + tearDownStack.addTearDown(thread1 = new TestThread<Monitor>(monitor, "TestThread #1")); + tearDownStack.addTearDown(thread2 = new TestThread<Monitor>(monitor, "TestThread #2")); + } + + @Override protected final void tearDown() { + tearDownStack.runTearDown(); + } + + private String enter() { + return interruptible ? "enterInterruptibly" : "enter"; + } + + private String tryEnter() { + return "tryEnter"; + } + + private String enterIf() { + return interruptible ? "enterIfInterruptibly" : "enterIf"; + } + + private String tryEnterIf() { + return "tryEnterIf"; + } + + private String enterWhen() { + return interruptible ? "enterWhen" : "enterWhenUninterruptibly"; + } + + private String waitFor() { + return interruptible ? "waitFor" : "waitForUninterruptibly"; + } + + private String leave() { + return "leave"; + } + + public final void testMutualExclusion() throws Exception { + thread1.callAndAssertReturns(enter()); + thread2.callAndAssertBlocks(enter()); + thread1.callAndAssertReturns(leave()); + thread2.assertPriorCallReturns(enter()); + } + + public final void testTryEnter() throws Exception { + thread1.callAndAssertReturns(true, tryEnter()); + thread2.callAndAssertReturns(false, tryEnter()); + thread1.callAndAssertReturns(true, tryEnter()); + thread2.callAndAssertReturns(false, tryEnter()); + thread1.callAndAssertReturns(leave()); + thread2.callAndAssertReturns(false, tryEnter()); + thread1.callAndAssertReturns(leave()); + thread2.callAndAssertReturns(true, tryEnter()); + } + + public final void testSystemStateMethods() throws Exception { + checkSystemStateMethods(0); + thread1.callAndAssertReturns(enter()); + checkSystemStateMethods(1); + thread1.callAndAssertReturns(enter()); + checkSystemStateMethods(2); + thread1.callAndAssertReturns(leave()); + checkSystemStateMethods(1); + thread1.callAndAssertReturns(leave()); + checkSystemStateMethods(0); + } + + private void checkSystemStateMethods(int enterCount) throws Exception { + thread1.callAndAssertReturns(enterCount != 0, "isOccupied"); + thread1.callAndAssertReturns(enterCount != 0, "isOccupiedByCurrentThread"); + thread1.callAndAssertReturns(enterCount, "getOccupiedDepth"); + + thread2.callAndAssertReturns(enterCount != 0, "isOccupied"); + thread2.callAndAssertReturns(false, "isOccupiedByCurrentThread"); + thread2.callAndAssertReturns(0, "getOccupiedDepth"); + } + + public final void testEnterWhen_initiallyTrue() throws Exception { + TestGuard guard = new TestGuard(true); + thread1.callAndAssertReturns(enterWhen(), guard); + } + + public final void testEnterWhen_initiallyFalse() throws Exception { + TestGuard guard = new TestGuard(false); + thread1.callAndAssertWaits(enterWhen(), guard); + monitor.enter(); + guard.setSatisfied(true); + monitor.leave(); + thread1.assertPriorCallReturns(enterWhen()); + } + + public final void testEnterWhen_alreadyOccupied() throws Exception { + TestGuard guard = new TestGuard(true); + thread2.callAndAssertReturns(enter()); + thread1.callAndAssertBlocks(enterWhen(), guard); + thread2.callAndAssertReturns(leave()); + thread1.assertPriorCallReturns(enterWhen()); + } + + public final void testEnterIf_initiallyTrue() throws Exception { + TestGuard guard = new TestGuard(true); + thread1.callAndAssertReturns(true, enterIf(), guard); + thread2.callAndAssertBlocks(enter()); + } + + public final void testEnterIf_initiallyFalse() throws Exception { + TestGuard guard = new TestGuard(false); + thread1.callAndAssertReturns(false, enterIf(), guard); + thread2.callAndAssertReturns(enter()); + } + + public final void testEnterIf_alreadyOccupied() throws Exception { + TestGuard guard = new TestGuard(true); + thread2.callAndAssertReturns(enter()); + thread1.callAndAssertBlocks(enterIf(), guard); + thread2.callAndAssertReturns(leave()); + thread1.assertPriorCallReturns(true, enterIf()); + } + + public final void testTryEnterIf_initiallyTrue() throws Exception { + TestGuard guard = new TestGuard(true); + thread1.callAndAssertReturns(true, tryEnterIf(), guard); + thread2.callAndAssertBlocks(enter()); + } + + public final void testTryEnterIf_initiallyFalse() throws Exception { + TestGuard guard = new TestGuard(false); + thread1.callAndAssertReturns(false, tryEnterIf(), guard); + thread2.callAndAssertReturns(enter()); + } + + public final void testTryEnterIf_alreadyOccupied() throws Exception { + TestGuard guard = new TestGuard(true); + thread2.callAndAssertReturns(enter()); + thread1.callAndAssertReturns(false, tryEnterIf(), guard); + } + + public final void testWaitFor_initiallyTrue() throws Exception { + TestGuard guard = new TestGuard(true); + thread1.callAndAssertReturns(enter()); + thread1.callAndAssertReturns(waitFor(), guard); + } + + public final void testWaitFor_initiallyFalse() throws Exception { + TestGuard guard = new TestGuard(false); + thread1.callAndAssertReturns(enter()); + thread1.callAndAssertWaits(waitFor(), guard); + monitor.enter(); + guard.setSatisfied(true); + monitor.leave(); + thread1.assertPriorCallReturns(waitFor()); + } + + public final void testWaitFor_withoutEnter() throws Exception { + TestGuard guard = new TestGuard(true); + thread1.callAndAssertThrows(IllegalMonitorStateException.class, waitFor(), guard); + } + + public void testNulls() { + monitor.enter(); // Inhibit IllegalMonitorStateException + new NullPointerTester() + .setDefault(TimeUnit.class, TimeUnit.SECONDS) + .setDefault(Monitor.Guard.class, new TestGuard(true)) + .testAllPublicInstanceMethods(monitor); + } + + // TODO: Test enter(long, TimeUnit). + // TODO: Test enterWhen(Guard, long, TimeUnit). + // TODO: Test enterIf(Guard, long, TimeUnit). + // TODO: Test waitFor(Guard, long, TimeUnit). + // TODO: Test getQueueLength(). + // TODO: Test hasQueuedThreads(). + // TODO: Test getWaitQueueLength(Guard). + // TODO: Test automatic signaling before leave, waitFor, and reentrant enterWhen. + // TODO: Test blocking to re-enter monitor after being signaled. + // TODO: Test interrupts with both interruptible and uninterruptible monitor. + // TODO: Test multiple waiters: If guard is still satisfied, signal next waiter. + // TODO: Test multiple waiters: If guard is no longer satisfied, do not signal next waiter. + +} diff --git a/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java b/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java index 3b0af7f49..cb1898c06 100644 --- a/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java @@ -29,10 +29,12 @@ package com.google.common.util.concurrent; import static com.google.common.collect.Iterables.getOnlyElement; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static com.google.common.util.concurrent.MoreExecutors.invokeAnyImpl; import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator; +import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService; import static com.google.common.util.concurrent.MoreExecutors.renamingDecorator; -import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor; import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; @@ -40,7 +42,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.truth0.Truth.ASSERT; import com.google.common.base.Suppliers; import com.google.common.base.Throwables; @@ -85,10 +86,9 @@ public class MoreExecutorsTest extends JSR166TestCase { @Override public void run() {} }; - public void testSameThreadExecutorServiceInThreadExecution() + public void testDirectExecutorServiceServiceInThreadExecution() throws Exception { - final ListeningExecutorService executor = - MoreExecutors.sameThreadExecutor(); + final ListeningExecutorService executor = newDirectExecutorService(); final ThreadLocal<Integer> threadLocalCount = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { @@ -133,8 +133,8 @@ public class MoreExecutorsTest extends JSR166TestCase { throwableFromOtherThread.get()); } - public void testSameThreadExecutorInvokeAll() throws Exception { - final ExecutorService executor = MoreExecutors.sameThreadExecutor(); + public void testDirectExecutorServiceInvokeAll() throws Exception { + final ExecutorService executor = newDirectExecutorService(); final ThreadLocal<Integer> threadLocalCount = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { @@ -163,9 +163,9 @@ public class MoreExecutorsTest extends JSR166TestCase { assertEquals(10, threadLocalCount.get().intValue()); } - public void testSameThreadExecutorServiceTermination() + public void testDirectExecutorServiceServiceTermination() throws Exception { - final ExecutorService executor = MoreExecutors.sameThreadExecutor(); + final ExecutorService executor = newDirectExecutorService(); final CyclicBarrier barrier = new CyclicBarrier(2); final AtomicReference<Throwable> throwableFromOtherThread = new AtomicReference<Throwable>(null); @@ -243,14 +243,14 @@ public class MoreExecutorsTest extends JSR166TestCase { throwableFromOtherThread.get()); } - public void testSameThreadExecutor_shutdownNow() { - ExecutorService executor = MoreExecutors.sameThreadExecutor(); + public void testDirectExecutorService_shutdownNow() { + ExecutorService executor = newDirectExecutorService(); assertEquals(ImmutableList.of(), executor.shutdownNow()); assertTrue(executor.isShutdown()); } public void testExecuteAfterShutdown() { - ExecutorService executor = MoreExecutors.sameThreadExecutor(); + ExecutorService executor = newDirectExecutorService(); executor.shutdown(); try { executor.execute(EMPTY_RUNNABLE); @@ -260,7 +260,7 @@ public class MoreExecutorsTest extends JSR166TestCase { public <T> void testListeningExecutorServiceInvokeAllJavadocCodeCompiles() throws Exception { - ListeningExecutorService executor = MoreExecutors.sameThreadExecutor(); + ListeningExecutorService executor = newDirectExecutorService(); List<Callable<T>> tasks = ImmutableList.of(); @SuppressWarnings("unchecked") // guaranteed by invokeAll contract List<ListenableFuture<T>> futures = (List) executor.invokeAll(tasks); @@ -268,17 +268,17 @@ public class MoreExecutorsTest extends JSR166TestCase { public void testListeningDecorator() throws Exception { ListeningExecutorService service = - listeningDecorator(MoreExecutors.sameThreadExecutor()); + listeningDecorator(newDirectExecutorService()); assertSame(service, listeningDecorator(service)); List<Callable<String>> callables = ImmutableList.of(Callables.returning("x")); List<Future<String>> results; results = service.invokeAll(callables); - ASSERT.that(getOnlyElement(results)).isA(ListenableFutureTask.class); + assertThat(getOnlyElement(results)).isA(ListenableFutureTask.class); results = service.invokeAll(callables, 1, SECONDS); - ASSERT.that(getOnlyElement(results)).isA(ListenableFutureTask.class); + assertThat(getOnlyElement(results)).isA(ListenableFutureTask.class); /* * TODO(cpovirk): move ForwardingTestCase somewhere common, and use it to @@ -361,7 +361,7 @@ public class MoreExecutorsTest extends JSR166TestCase { @Override public void run() {} }; - future = service.schedule(runnable, 5 * 60, TimeUnit.SECONDS); + future = service.schedule(runnable, 5, TimeUnit.MINUTES); future.cancel(true); assertTrue(future.isCancelled()); delegateFuture = (ScheduledFuture<?>) delegateQueue.element(); @@ -369,7 +369,7 @@ public class MoreExecutorsTest extends JSR166TestCase { delegateQueue.clear(); - future = service.scheduleAtFixedRate(runnable, 5 * 60, 5 * 60, TimeUnit.SECONDS); + future = service.scheduleAtFixedRate(runnable, 5, 5, TimeUnit.MINUTES); future.cancel(true); assertTrue(future.isCancelled()); delegateFuture = (ScheduledFuture<?>) delegateQueue.element(); @@ -377,7 +377,7 @@ public class MoreExecutorsTest extends JSR166TestCase { delegateQueue.clear(); - future = service.scheduleWithFixedDelay(runnable, 5 * 60, 5 * 60, TimeUnit.SECONDS); + future = service.scheduleWithFixedDelay(runnable, 5, 5, TimeUnit.MINUTES); future.cancel(true); assertTrue(future.isCancelled()); delegateFuture = (ScheduledFuture<?>) delegateQueue.element(); @@ -416,7 +416,7 @@ public class MoreExecutorsTest extends JSR166TestCase { * invokeAny(null) throws NPE */ public void testInvokeAnyImpl_nullTasks() throws Exception { - ListeningExecutorService e = sameThreadExecutor(); + ListeningExecutorService e = newDirectExecutorService(); try { invokeAnyImpl(e, null, false, 0); shouldThrow(); @@ -430,7 +430,7 @@ public class MoreExecutorsTest extends JSR166TestCase { * invokeAny(empty collection) throws IAE */ public void testInvokeAnyImpl_emptyTasks() throws Exception { - ListeningExecutorService e = sameThreadExecutor(); + ListeningExecutorService e = newDirectExecutorService(); try { invokeAnyImpl(e, new ArrayList<Callable<String>>(), false, 0); shouldThrow(); @@ -444,7 +444,7 @@ public class MoreExecutorsTest extends JSR166TestCase { * invokeAny(c) throws NPE if c has null elements */ public void testInvokeAnyImpl_nullElement() throws Exception { - ListeningExecutorService e = sameThreadExecutor(); + ListeningExecutorService e = newDirectExecutorService(); List<Callable<Integer>> l = new ArrayList<Callable<Integer>>(); l.add(new Callable<Integer>() { @Override public Integer call() { @@ -465,7 +465,7 @@ public class MoreExecutorsTest extends JSR166TestCase { * invokeAny(c) throws ExecutionException if no task in c completes */ public void testInvokeAnyImpl_noTaskCompletes() throws Exception { - ListeningExecutorService e = sameThreadExecutor(); + ListeningExecutorService e = newDirectExecutorService(); List<Callable<String>> l = new ArrayList<Callable<String>>(); l.add(new NPETask()); try { @@ -482,7 +482,7 @@ public class MoreExecutorsTest extends JSR166TestCase { * invokeAny(c) returns result of some task in c if at least one completes */ public void testInvokeAnyImpl() throws Exception { - ListeningExecutorService e = sameThreadExecutor(); + ListeningExecutorService e = newDirectExecutorService(); try { List<Callable<String>> l = new ArrayList<Callable<String>>(); l.add(new StringTask()); @@ -496,7 +496,7 @@ public class MoreExecutorsTest extends JSR166TestCase { private static void assertListenerRunImmediately(ListenableFuture<?> future) { CountingRunnable listener = new CountingRunnable(); - future.addListener(listener, sameThreadExecutor()); + future.addListener(listener, directExecutor()); assertEquals(1, listener.count); } @@ -591,7 +591,7 @@ public class MoreExecutorsTest extends JSR166TestCase { } public void testThreadRenaming() { - Executor renamingExecutor = renamingDecorator(sameThreadExecutor(), + Executor renamingExecutor = renamingDecorator(newDirectExecutorService(), Suppliers.ofInstance("FooBar")); String oldName = Thread.currentThread().getName(); renamingExecutor.execute(new Runnable() { diff --git a/guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java b/guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java index d79b7b941..669e54799 100644 --- a/guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java +++ b/guava-tests/test/com/google/common/util/concurrent/PackageSanityTests.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import com.google.common.testing.AbstractPackageSanityTests; +import com.google.common.util.concurrent.RateLimiter.SleepingStopwatch; /** * Basic sanity tests for the entire package. @@ -25,7 +26,20 @@ import com.google.common.testing.AbstractPackageSanityTests; */ public class PackageSanityTests extends AbstractPackageSanityTests { + private static final SleepingStopwatch NO_OP_STOPWATCH = new SleepingStopwatch() { + @Override + long readMicros() { + return 0; + } + + @Override + void sleepMicrosUninterruptibly(long micros) { + } + }; + public PackageSanityTests() { setDefault(RateLimiter.class, RateLimiter.create(1.0)); + setDefault(SleepingStopwatch.class, NO_OP_STOPWATCH); + setDefault(long.class, 0L); } } diff --git a/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java b/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java index 93fff447e..62ced5c03 100644 --- a/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java @@ -16,12 +16,25 @@ package com.google.common.util.concurrent; +import static java.lang.reflect.Modifier.isStatic; +import static java.util.concurrent.TimeUnit.MICROSECONDS; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +import com.google.common.collect.ImmutableClassToInstanceMap; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.testing.NullPointerTester; import com.google.common.testing.NullPointerTester.Visibility; +import com.google.common.util.concurrent.RateLimiter.SleepingStopwatch; import junit.framework.TestCase; +import org.easymock.EasyMock; +import org.mockito.Mockito; + +import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Random; @@ -35,15 +48,10 @@ import java.util.concurrent.TimeUnit; public class RateLimiterTest extends TestCase { private static final double EPSILON = 1e-8; - /** - * The ticker gathers events and presents them as strings. - * R0.6 means a delay of 0.6 seconds caused by the (R)ateLimiter - * U1.0 means the (U)ser caused the ticker to sleep for a second. - */ - private final FakeTicker ticker = new FakeTicker(); + private final FakeStopwatch stopwatch = new FakeStopwatch(); public void testSimple() { - RateLimiter limiter = RateLimiter.create(ticker, 5.0); + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); limiter.acquire(); // R0.00, since it's the first request limiter.acquire(); // R0.20 limiter.acquire(); // R0.20 @@ -57,7 +65,7 @@ public class RateLimiterTest extends TestCase { } public void testSimpleRateUpdate() { - RateLimiter limiter = RateLimiter.create(5.0, 5, TimeUnit.SECONDS); + RateLimiter limiter = RateLimiter.create(5.0, 5, SECONDS); assertEquals(5.0, limiter.getRate()); limiter.setRate(10.0); assertEquals(10.0, limiter.getRate()); @@ -65,35 +73,78 @@ public class RateLimiterTest extends TestCase { try { limiter.setRate(0.0); fail(); - } catch (IllegalArgumentException ok) {} + } catch (IllegalArgumentException expected) {} try { limiter.setRate(-10.0); fail(); - } catch (IllegalArgumentException ok) {} + } catch (IllegalArgumentException expected) {} + } + + public void testAcquireParameterValidation() { + RateLimiter limiter = RateLimiter.create(999); + try { + limiter.acquire(0); + fail(); + } catch (IllegalArgumentException expected) { + } + try { + limiter.acquire(-1); + fail(); + } catch (IllegalArgumentException expected) { + } + try { + limiter.tryAcquire(0); + fail(); + } catch (IllegalArgumentException expected) { + } + try { + limiter.tryAcquire(-1); + fail(); + } catch (IllegalArgumentException expected) { + } + try { + limiter.tryAcquire(0, 1, SECONDS); + fail(); + } catch (IllegalArgumentException expected) { + } + try { + limiter.tryAcquire(-1, 1, SECONDS); + fail(); + } catch (IllegalArgumentException expected) { + } } public void testSimpleWithWait() { - RateLimiter limiter = RateLimiter.create(ticker, 5.0); + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); limiter.acquire(); // R0.00 - ticker.sleepMillis(200); // U0.20, we are ready for the next request... + stopwatch.sleepMillis(200); // U0.20, we are ready for the next request... limiter.acquire(); // R0.00, ...which is granted immediately limiter.acquire(); // R0.20 assertEvents("R0.00", "U0.20", "R0.00", "R0.20"); } public void testSimpleAcquireReturnValues() { - RateLimiter limiter = RateLimiter.create(ticker, 5.0); + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); assertEquals(0.0, limiter.acquire(), EPSILON); // R0.00 - ticker.sleepMillis(200); // U0.20, we are ready for the next request... + stopwatch.sleepMillis(200); // U0.20, we are ready for the next request... assertEquals(0.0, limiter.acquire(), EPSILON); // R0.00, ...which is granted immediately assertEquals(0.2, limiter.acquire(), EPSILON); // R0.20 assertEvents("R0.00", "U0.20", "R0.00", "R0.20"); } + public void testSimpleAcquireEarliestAvailableIsInPast() { + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); + assertEquals(0.0, limiter.acquire(), EPSILON); + stopwatch.sleepMillis(400); + assertEquals(0.0, limiter.acquire(), EPSILON); + assertEquals(0.0, limiter.acquire(), EPSILON); + assertEquals(0.2, limiter.acquire(), EPSILON); + } + public void testOneSecondBurst() { - RateLimiter limiter = RateLimiter.create(ticker, 5.0); - ticker.sleepMillis(1000); // max capacity reached - ticker.sleepMillis(1000); // this makes no difference + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); + stopwatch.sleepMillis(1000); // max capacity reached + stopwatch.sleepMillis(1000); // this makes no difference limiter.acquire(1); // R0.00, since it's the first request limiter.acquire(1); // R0.00, from capacity @@ -106,18 +157,35 @@ public class RateLimiterTest extends TestCase { "R0.20"); } + public void testCreateWarmupParameterValidation() { + RateLimiter.create(1.0, 1, NANOSECONDS); + RateLimiter.create(1.0, 0, NANOSECONDS); + + try { + RateLimiter.create(0.0, 1, NANOSECONDS); + fail(); + } catch (IllegalArgumentException expected) { + } + + try { + RateLimiter.create(1.0, -1, NANOSECONDS); + fail(); + } catch (IllegalArgumentException expected) { + } + } + public void testWarmUp() { - RateLimiter limiter = RateLimiter.create(ticker, 2.0, 4000, TimeUnit.MILLISECONDS); + RateLimiter limiter = RateLimiter.create(stopwatch, 2.0, 4000, MILLISECONDS); for (int i = 0; i < 8; i++) { limiter.acquire(); // #1 } - ticker.sleepMillis(500); // #2: to repay for the last acquire - ticker.sleepMillis(4000); // #3: becomes cold again + stopwatch.sleepMillis(500); // #2: to repay for the last acquire + stopwatch.sleepMillis(4000); // #3: becomes cold again for (int i = 0; i < 8; i++) { limiter.acquire(); // // #4 } - ticker.sleepMillis(500); // #5: to repay for the last acquire - ticker.sleepMillis(2000); // #6: didn't get cold! It would take another 2 seconds to go cold + stopwatch.sleepMillis(500); // #5: to repay for the last acquire + stopwatch.sleepMillis(2000); // #6: didn't get cold! It would take another 2 seconds to go cold for (int i = 0; i < 8; i++) { limiter.acquire(); // #7 } @@ -132,11 +200,11 @@ public class RateLimiterTest extends TestCase { } public void testWarmUpAndUpdate() { - RateLimiter limiter = RateLimiter.create(ticker, 2.0, 4000, TimeUnit.MILLISECONDS); + RateLimiter limiter = RateLimiter.create(stopwatch, 2.0, 4000, MILLISECONDS); for (int i = 0; i < 8; i++) { limiter.acquire(); // // #1 } - ticker.sleepMillis(4500); // #2: back to cold state (warmup period + repay last acquire) + stopwatch.sleepMillis(4500); // #2: back to cold state (warmup period + repay last acquire) for (int i = 0; i < 3; i++) { // only three steps, we're somewhere in the warmup period limiter.acquire(); // #3 } @@ -146,7 +214,7 @@ public class RateLimiterTest extends TestCase { for (int i = 0; i < 4; i++) { limiter.acquire(); // #5 } - ticker.sleepMillis(4250); // #6, back to cold state (warmup period + repay last acquire) + stopwatch.sleepMillis(4250); // #6, back to cold state (warmup period + repay last acquire) for (int i = 0; i < 11; i++) { limiter.acquire(); // #7, showing off the warmup starting from totally cold } @@ -163,26 +231,8 @@ public class RateLimiterTest extends TestCase { "R0.34, R0.28, R0.25, R0.25"); // #7 (cont.), note, this matches #5 } - public void testBursty() { - RateLimiter limiter = RateLimiter.createWithCapacity(ticker, 1.0, 10, TimeUnit.SECONDS); - ticker.sleepMillis(10000); // reach full capacity - limiter.acquire(11); // all these are served in a burst (10 + 1 by borrowing from the future) - limiter.acquire(1); // out of capacity, we have to wait - limiter.acquire(1); // and wait - ticker.sleepMillis(3000); // fill up 3 permits - limiter.acquire(5); // we had 3 ready, thus we borrow 2 permits - limiter.acquire(1); // this acquire() will also repay for the previous acquire() - assertEvents( - "U10.00", - "R0.00", // 10 permits grabbed - "R1.00", "R1.00", // 1 and 1 - "U3.00", "R0.00", // 5 grabbed - "R3.00" // 1 grabbed - ); - } - public void testBurstyAndUpdate() { - RateLimiter rateLimiter = RateLimiter.create(ticker, 1.0); + RateLimiter rateLimiter = RateLimiter.create(stopwatch, 1.0); rateLimiter.acquire(1); // no wait rateLimiter.acquire(1); // R1.00, to repay previous @@ -195,29 +245,42 @@ public class RateLimiterTest extends TestCase { assertEvents("R0.00", "R1.00", "R1.00", "R0.50", "R1.00", "R2.00"); } - public void testTimeWrapping() { - ticker.instant = Long.MAX_VALUE - TimeUnit.SECONDS.toNanos(1); // 1 second before max value - RateLimiter limiter = RateLimiter.create(ticker, 1.0); - for (int i = 0; i < 4; i++) { - limiter.acquire(); - } - // Without protection from overflow, the last wait value would have been huge, - // because "now" would have wrapped into a value near MIN_VALUE, and the limiter would think - // that the next request should be admitted far into the future - assertEvents("R0.00", "R1.00", "R1.00", "R1.00"); + public void testTryAcquire_noWaitAllowed() { + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); + assertTrue(limiter.tryAcquire(0, SECONDS)); + assertFalse(limiter.tryAcquire(0, SECONDS)); + assertFalse(limiter.tryAcquire(0, SECONDS)); + stopwatch.sleepMillis(100); + assertFalse(limiter.tryAcquire(0, SECONDS)); + } + + public void testTryAcquire_someWaitAllowed() { + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); + assertTrue(limiter.tryAcquire(0, SECONDS)); + assertTrue(limiter.tryAcquire(200, MILLISECONDS)); + assertFalse(limiter.tryAcquire(100, MILLISECONDS)); + stopwatch.sleepMillis(100); + assertTrue(limiter.tryAcquire(100, MILLISECONDS)); + } + + public void testTryAcquire_overflow() { + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); + assertTrue(limiter.tryAcquire(0, MICROSECONDS)); + stopwatch.sleepMillis(100); + assertTrue(limiter.tryAcquire(Long.MAX_VALUE, MICROSECONDS)); } - public void testTryGate() { - RateLimiter limiter = RateLimiter.create(ticker, 5.0); - assertTrue(limiter.tryAcquire(0, TimeUnit.SECONDS)); - assertFalse(limiter.tryAcquire(0, TimeUnit.SECONDS)); - assertFalse(limiter.tryAcquire(0, TimeUnit.SECONDS)); - ticker.sleepMillis(100); - assertFalse(limiter.tryAcquire(0, TimeUnit.SECONDS)); + public void testTryAcquire_negative() { + RateLimiter limiter = RateLimiter.create(stopwatch, 5.0); + assertTrue(limiter.tryAcquire(5, 0, SECONDS)); + stopwatch.sleepMillis(900); + assertFalse(limiter.tryAcquire(1, Long.MIN_VALUE, SECONDS)); + stopwatch.sleepMillis(100); + assertTrue(limiter.tryAcquire(1, -1, SECONDS)); } public void testSimpleWeights() { - RateLimiter rateLimiter = RateLimiter.create(ticker, 1.0); + RateLimiter rateLimiter = RateLimiter.create(stopwatch, 1.0); rateLimiter.acquire(1); // no wait rateLimiter.acquire(1); // R1.00, to repay previous rateLimiter.acquire(2); // R1.00, to repay previous @@ -228,29 +291,51 @@ public class RateLimiterTest extends TestCase { } public void testInfinity_Bursty() { - RateLimiter limiter = RateLimiter.create(ticker, Double.POSITIVE_INFINITY); + RateLimiter limiter = RateLimiter.create(stopwatch, Double.POSITIVE_INFINITY); limiter.acquire(Integer.MAX_VALUE / 4); limiter.acquire(Integer.MAX_VALUE / 2); limiter.acquire(Integer.MAX_VALUE); assertEvents("R0.00", "R0.00", "R0.00"); // no wait, infinite rate! - limiter.setRate(1.0); + limiter.setRate(2.0); + limiter.acquire(); limiter.acquire(); limiter.acquire(); limiter.acquire(); - assertEvents("R0.00", "R1.00", "R1.00"); // we repay the last request (but that had no cost) - // and then we go to 1 second per request mode + limiter.acquire(); + assertEvents( + "R0.00", // First comes the saved-up burst, which defaults to a 1-second burst (2 requests). + "R0.00", + "R0.00", // Now comes the free request. + "R0.50", // Now it's 0.5 seconds per request. + "R0.50"); limiter.setRate(Double.POSITIVE_INFINITY); limiter.acquire(); limiter.acquire(); limiter.acquire(); - assertEvents("R1.00", "R0.00", "R0.00"); // we repay the last request (1sec), then back to +oo + assertEvents("R0.50", "R0.00", "R0.00"); // we repay the last request (.5sec), then back to +oo + } + + /** https://code.google.com/p/guava-libraries/issues/detail?id=1791 */ + public void testInfinity_BustyTimeElapsed() { + RateLimiter limiter = RateLimiter.create(stopwatch, Double.POSITIVE_INFINITY); + stopwatch.instant += 1000000; + limiter.setRate(2.0); + for (int i = 0; i < 5; i++) { + limiter.acquire(); + } + assertEvents( + "R0.00", // First comes the saved-up burst, which defaults to a 1-second burst (2 requests). + "R0.00", + "R0.00", // Now comes the free request. + "R0.50", // Now it's 0.5 seconds per request. + "R0.50"); } public void testInfinity_WarmUp() { RateLimiter limiter = RateLimiter.create( - ticker, Double.POSITIVE_INFINITY, 10, TimeUnit.SECONDS); + stopwatch, Double.POSITIVE_INFINITY, 10, SECONDS); limiter.acquire(Integer.MAX_VALUE / 4); limiter.acquire(Integer.MAX_VALUE / 2); limiter.acquire(Integer.MAX_VALUE); @@ -269,16 +354,26 @@ public class RateLimiterTest extends TestCase { assertEvents("R1.00", "R0.00", "R0.00"); } + public void testInfinity_WarmUpTimeElapsed() { + RateLimiter limiter = RateLimiter.create(stopwatch, Double.POSITIVE_INFINITY, 10, SECONDS); + stopwatch.instant += 1000000; + limiter.setRate(1.0); + for (int i = 0; i < 5; i++) { + limiter.acquire(); + } + assertEvents("R0.00", "R1.00", "R1.00", "R1.00", "R1.00"); + } + /** * Make sure that bursts can never go above 1-second-worth-of-work for the current * rate, even when we change the rate. */ public void testWeNeverGetABurstMoreThanOneSec() { - RateLimiter limiter = RateLimiter.create(ticker, 1.0); + RateLimiter limiter = RateLimiter.create(stopwatch, 1.0); int[] rates = { 1000, 1, 10, 1000000, 10, 1}; for (int rate : rates) { int oneSecWorthOfWork = rate; - ticker.sleepMillis(rate * 1000); + stopwatch.sleepMillis(rate * 1000); limiter.setRate(rate); long burst = measureTotalTimeMillis(limiter, oneSecWorthOfWork, new Random()); // we allow one second worth of work to go in a burst (i.e. take less than a second) @@ -307,7 +402,7 @@ public class RateLimiterTest extends TestCase { // warmupSeconds = 20 / qps long warmupMillis = (long) ((2 * maxPermits / qps) * 1000.0); RateLimiter rateLimiter = RateLimiter.create( - ticker, qps, warmupMillis, TimeUnit.MILLISECONDS); + stopwatch, qps, warmupMillis, MILLISECONDS); assertEquals(warmupMillis, measureTotalTimeMillis(rateLimiter, maxPermits, random)); } } @@ -315,41 +410,47 @@ public class RateLimiterTest extends TestCase { public void testNulls() { NullPointerTester tester = new NullPointerTester() - .setDefault(RateLimiter.SleepingTicker.class, ticker); + .setDefault(SleepingStopwatch.class, stopwatch) + .setDefault(int.class, 1); tester.testStaticMethods(RateLimiter.class, Visibility.PACKAGE); - tester.testInstanceMethods(RateLimiter.create(ticker, 5.0), Visibility.PACKAGE); + tester.testInstanceMethods(RateLimiter.create(stopwatch, 5.0), Visibility.PACKAGE); } private long measureTotalTimeMillis(RateLimiter rateLimiter, int permits, Random random) { - long startTime = ticker.instant; + long startTime = stopwatch.instant; while (permits > 0) { int nextPermitsToAcquire = Math.max(1, random.nextInt(permits)); permits -= nextPermitsToAcquire; rateLimiter.acquire(nextPermitsToAcquire); } rateLimiter.acquire(1); // to repay for any pending debt - return TimeUnit.NANOSECONDS.toMillis(ticker.instant - startTime); + return NANOSECONDS.toMillis(stopwatch.instant - startTime); } private void assertEvents(String... events) { - assertEquals(Arrays.toString(events), ticker.readEventsAndClear()); + assertEquals(Arrays.toString(events), stopwatch.readEventsAndClear()); } - private static class FakeTicker extends RateLimiter.SleepingTicker { + /** + * The stopwatch gathers events and presents them as strings. + * R0.6 means a delay of 0.6 seconds caused by the (R)ateLimiter + * U1.0 means the (U)ser caused the stopwatch to sleep for a second. + */ + static class FakeStopwatch extends SleepingStopwatch { long instant = 0L; final List<String> events = Lists.newArrayList(); @Override - public long read() { - return instant; + public long readMicros() { + return NANOSECONDS.toMicros(instant); } void sleepMillis(int millis) { - sleepMicros("U", TimeUnit.MILLISECONDS.toMicros(millis)); + sleepMicros("U", MILLISECONDS.toMicros(millis)); } void sleepMicros(String caption, long micros) { - instant += TimeUnit.MICROSECONDS.toNanos(micros); + instant += MICROSECONDS.toNanos(micros); events.add(caption + String.format("%3.2f", (micros / 1000000.0))); } @@ -371,4 +472,39 @@ public class RateLimiterTest extends TestCase { return events.toString(); } } + + public void testMocking() throws Exception { + RateLimiter mockito = Mockito.mock(RateLimiter.class); + RateLimiter easyMock = EasyMock.createNiceMock(RateLimiter.class); + EasyMock.replay(easyMock); + for (Method method : RateLimiter.class.getMethods()) { + if (!isStatic(method.getModifiers()) + && !NOT_WORKING_ON_MOCKS.contains(method.getName()) + && !method.getDeclaringClass().equals(Object.class)) { + method.invoke(mockito, arbitraryParameters(method)); + method.invoke(easyMock, arbitraryParameters(method)); + } + } + } + + private static Object[] arbitraryParameters(Method method) { + Class<?>[] parameterTypes = method.getParameterTypes(); + Object[] params = new Object[parameterTypes.length]; + for (int i = 0; i < parameterTypes.length; i++) { + params[i] = PARAMETER_VALUES.get(parameterTypes[i]); + } + return params; + } + + private static final ImmutableSet<String> NOT_WORKING_ON_MOCKS = + ImmutableSet.of("latestPermitAgeSec", "setRate"); + + // We would use ArbitraryInstances, but it returns 0, invalid for many RateLimiter methods. + private static final ImmutableClassToInstanceMap<Object> PARAMETER_VALUES = + ImmutableClassToInstanceMap.builder() + .put(int.class, 1) + .put(long.class, 1L) + .put(double.class, 1.0) + .put(TimeUnit.class, SECONDS) + .build(); } diff --git a/guava-tests/test/com/google/common/util/concurrent/SerializingExecutorTest.java b/guava-tests/test/com/google/common/util/concurrent/SerializingExecutorTest.java index 01efd245c..f055fe476 100644 --- a/guava-tests/test/com/google/common/util/concurrent/SerializingExecutorTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/SerializingExecutorTest.java @@ -18,6 +18,7 @@ package com.google.common.util.concurrent; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; +import com.google.common.collect.Queues; import junit.framework.TestCase; @@ -39,7 +40,7 @@ import java.util.concurrent.atomic.AtomicInteger; */ public class SerializingExecutorTest extends TestCase { private static class FakeExecutor implements Executor { - Queue<Runnable> tasks = Lists.newLinkedList(); + Queue<Runnable> tasks = Queues.newArrayDeque(); @Override public void execute(Runnable command) { tasks.add(command); } diff --git a/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java b/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java index 1fc87566f..302b7d19f 100644 --- a/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java @@ -15,6 +15,7 @@ */ package com.google.common.util.concurrent; +import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import com.google.common.collect.ImmutableMap; @@ -62,10 +63,10 @@ public class ServiceManagerTest extends TestCase { * A NoOp service that will delay the startup and shutdown notification for a configurable amount * of time. */ - private static class NoOpDelayedSerivce extends NoOpService { + private static class NoOpDelayedService extends NoOpService { private long delay; - public NoOpDelayedSerivce(long delay) { + public NoOpDelayedService(long delay) { this.delay = delay; } @@ -108,14 +109,44 @@ public class ServiceManagerTest extends TestCase { } public void testServiceStartupTimes() { - Service a = new NoOpDelayedSerivce(150); - Service b = new NoOpDelayedSerivce(353); + Service a = new NoOpDelayedService(150); + Service b = new NoOpDelayedService(353); ServiceManager serviceManager = new ServiceManager(asList(a, b)); serviceManager.startAsync().awaitHealthy(); ImmutableMap<Service, Long> startupTimes = serviceManager.startupTimes(); assertEquals(2, startupTimes.size()); - assertTrue(startupTimes.get(a) >= 150); - assertTrue(startupTimes.get(b) >= 353); + assertThat(startupTimes.get(a)).isInclusivelyInRange(150, Long.MAX_VALUE); + assertThat(startupTimes.get(b)).isInclusivelyInRange(353, Long.MAX_VALUE); + } + + public void testServiceStartupTimes_selfStartingServices() { + // This tests to ensure that: + // 1. service times are accurate when the service is started by the manager + // 2. service times are recorded when the service is not started by the manager (but they may + // not be accurate). + final Service b = new NoOpDelayedService(353) { + @Override protected void doStart() { + super.doStart(); + // This will delay service listener execution at least 150 milliseconds + Uninterruptibles.sleepUninterruptibly(150, TimeUnit.MILLISECONDS); + } + }; + Service a = new NoOpDelayedService(150) { + @Override protected void doStart() { + b.startAsync(); + super.doStart(); + } + }; + ServiceManager serviceManager = new ServiceManager(asList(a, b)); + serviceManager.startAsync().awaitHealthy(); + ImmutableMap<Service, Long> startupTimes = serviceManager.startupTimes(); + assertEquals(2, startupTimes.size()); + assertThat(startupTimes.get(a)).isInclusivelyInRange(150, Long.MAX_VALUE); + // Service b startup takes at least 353 millis, but starting the timer is delayed by at least + // 150 milliseconds. so in a perfect world the timing would be 353-150=203ms, but since either + // of our sleep calls can be arbitrarily delayed we should just assert that there is a time + // recorded. + assertThat(startupTimes.get(b)).isNotNull(); } public void testServiceStartStop() { @@ -217,7 +248,7 @@ public class ServiceManagerTest extends TestCase { } public void testTimeouts() throws Exception { - Service a = new NoOpDelayedSerivce(50); + Service a = new NoOpDelayedService(50); ServiceManager manager = new ServiceManager(asList(a)); manager.startAsync(); try { @@ -311,7 +342,7 @@ public class ServiceManagerTest extends TestCase { logger.addHandler(logHandler); ServiceManager manager = new ServiceManager(Arrays.<Service>asList()); RecordingListener listener = new RecordingListener(); - manager.addListener(listener, MoreExecutors.sameThreadExecutor()); + manager.addListener(listener); manager.startAsync().awaitHealthy(); assertTrue(manager.isHealthy()); assertTrue(listener.healthyCalled); @@ -369,7 +400,7 @@ public class ServiceManagerTest extends TestCase { // block until after the service manager is shutdown Uninterruptibles.awaitUninterruptibly(failLeave); } - }, MoreExecutors.sameThreadExecutor()); + }); manager.startAsync(); afterStarted.countDown(); // We do not call awaitHealthy because, due to races, that method may throw an exception. But diff --git a/guava-tests/test/com/google/common/util/concurrent/TestThread.java b/guava-tests/test/com/google/common/util/concurrent/TestThread.java new file mode 100644 index 000000000..1a7c1a306 --- /dev/null +++ b/guava-tests/test/com/google/common/util/concurrent/TestThread.java @@ -0,0 +1,296 @@ +/* + * 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.util.concurrent; + +import static com.google.common.base.Preconditions.checkNotNull; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertNull; +import static junit.framework.Assert.assertSame; + +import com.google.common.testing.TearDown; + +import junit.framework.AssertionFailedError; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import javax.annotation.Nullable; + +/** + * A helper for concurrency testing. One or more {@code TestThread} instances are instantiated + * in a test with reference to the same "lock-like object", and then their interactions with that + * object are choreographed via the various methods on this class. + * + * <p>A "lock-like object" is really any object that may be used for concurrency control. If the + * {@link #callAndAssertBlocks} method is ever called in a test, the lock-like object must have a + * method equivalent to {@link java.util.concurrent.locks.ReentrantLock#hasQueuedThread(Thread)}. If + * the {@link #callAndAssertWaits} method is ever called in a test, the lock-like object must have a + * method equivalent to {@link + * java.util.concurrent.locks.ReentrantLock#hasWaiters(java.util.concurrent.locks.Condition)}, + * except that the method parameter must accept whatever condition-like object is passed into + * {@code callAndAssertWaits} by the test. + * + * @param <L> the type of the lock-like object to be used + * @author Justin T. Sampson + */ +public final class TestThread<L> extends Thread implements TearDown { + + private static final long DUE_DILIGENCE_MILLIS = 50; + private static final long TIMEOUT_MILLIS = 5000; + + private final L lockLikeObject; + + private final SynchronousQueue<Request> requestQueue = new SynchronousQueue<Request>(); + private final SynchronousQueue<Response> responseQueue = new SynchronousQueue<Response>(); + + private Throwable uncaughtThrowable = null; + + public TestThread(L lockLikeObject, String threadName) { + super(threadName); + this.lockLikeObject = checkNotNull(lockLikeObject); + start(); + } + + // Thread.stop() is okay because all threads started by a test are dying at the end of the test, + // so there is no object state put at risk by stopping the threads abruptly. In some cases a test + // may put a thread into an uninterruptible operation intentionally, so there is no other way to + // clean up these threads. + @SuppressWarnings("deprecation") + @Override public void tearDown() throws Exception { + stop(); + join(); + + if (uncaughtThrowable != null) { + throw (AssertionFailedError) new AssertionFailedError("Uncaught throwable in " + getName()) + .initCause(uncaughtThrowable); + } + } + + /** + * Causes this thread to call the named void method, and asserts that the call returns normally. + */ + public void callAndAssertReturns(String methodName, Object... arguments) throws Exception { + checkNotNull(methodName); + checkNotNull(arguments); + sendRequest(methodName, arguments); + assertSame(null, getResponse(methodName).getResult()); + } + + /** + * Causes this thread to call the named method, and asserts that the call returns the expected + * boolean value. + */ + public void callAndAssertReturns(boolean expected, String methodName, Object... arguments) + throws Exception { + checkNotNull(methodName); + checkNotNull(arguments); + sendRequest(methodName, arguments); + assertEquals(expected, getResponse(methodName).getResult()); + } + + /** + * Causes this thread to call the named method, and asserts that the call returns the expected + * int value. + */ + public void callAndAssertReturns(int expected, String methodName, Object... arguments) + throws Exception { + checkNotNull(methodName); + checkNotNull(arguments); + sendRequest(methodName, arguments); + assertEquals(expected, getResponse(methodName).getResult()); + } + + /** + * Causes this thread to call the named method, and asserts that the call throws the expected + * type of throwable. + */ + public void callAndAssertThrows(Class<? extends Throwable> expected, + String methodName, Object... arguments) throws Exception { + checkNotNull(expected); + checkNotNull(methodName); + checkNotNull(arguments); + sendRequest(methodName, arguments); + assertEquals(expected, getResponse(methodName).getThrowable().getClass()); + } + + /** + * Causes this thread to call the named method, and asserts that this thread becomes blocked on + * the lock-like object. The lock-like object must have a method equivalent to {@link + * java.util.concurrent.locks.ReentrantLock#hasQueuedThread(Thread)}. + */ + public void callAndAssertBlocks(String methodName, Object... arguments) throws Exception { + checkNotNull(methodName); + checkNotNull(arguments); + assertEquals(false, invokeMethod("hasQueuedThread", this)); + sendRequest(methodName, arguments); + Thread.sleep(DUE_DILIGENCE_MILLIS); + assertEquals(true, invokeMethod("hasQueuedThread", this)); + assertNull(responseQueue.poll()); + } + + /** + * Causes this thread to call the named method, and asserts that this thread thereby waits on + * the given condition-like object. The lock-like object must have a method equivalent to {@link + * java.util.concurrent.locks.ReentrantLock#hasWaiters(java.util.concurrent.locks.Condition)}, + * except that the method parameter must accept whatever condition-like object is passed into + * this method. + */ + public void callAndAssertWaits(String methodName, Object conditionLikeObject) + throws Exception { + checkNotNull(methodName); + checkNotNull(conditionLikeObject); + // TODO: Restore the following line when Monitor.hasWaiters() no longer acquires the lock. + // assertEquals(false, invokeMethod("hasWaiters", conditionLikeObject)); + sendRequest(methodName, conditionLikeObject); + Thread.sleep(DUE_DILIGENCE_MILLIS); + assertEquals(true, invokeMethod("hasWaiters", conditionLikeObject)); + assertNull(responseQueue.poll()); + } + + /** + * Asserts that a prior call that had caused this thread to block or wait has since returned + * normally. + */ + public void assertPriorCallReturns(@Nullable String methodName) throws Exception { + assertEquals(null, getResponse(methodName).getResult()); + } + + /** + * Asserts that a prior call that had caused this thread to block or wait has since returned + * the expected boolean value. + */ + public void assertPriorCallReturns(boolean expected, @Nullable String methodName) + throws Exception { + assertEquals(expected, getResponse(methodName).getResult()); + } + + /** + * Sends the given method call to this thread. + * + * @throws TimeoutException if this thread does not accept the request within a resonable amount + * of time + */ + private void sendRequest(String methodName, Object... arguments) throws Exception { + if (!requestQueue.offer( + new Request(methodName, arguments), TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { + throw new TimeoutException(); + } + } + + /** + * Receives a response from this thread. + * + * @throws TimeoutException if this thread does not offer a response within a resonable amount of + * time + * @throws AssertionFailedError if the given method name does not match the name of the method + * this thread has called most recently + */ + private Response getResponse(String methodName) throws Exception { + Response response = responseQueue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + if (response == null) { + throw new TimeoutException(); + } + assertEquals(methodName, response.methodName); + return response; + } + + private Object invokeMethod(String methodName, Object... arguments) throws Exception { + return getMethod(methodName, arguments).invoke(lockLikeObject, arguments); + } + + private Method getMethod(String methodName, Object... arguments) throws Exception { + METHODS: for (Method method : lockLikeObject.getClass().getMethods()) { + Class<?>[] parameterTypes = method.getParameterTypes(); + if (method.getName().equals(methodName) && (parameterTypes.length == arguments.length)) { + for (int i = 0; i < arguments.length; i++) { + if (!parameterTypes[i].isAssignableFrom(arguments[i].getClass())) { + continue METHODS; + } + } + return method; + } + } + throw new NoSuchMethodError(methodName); + } + + @Override public void run() { + assertSame(this, Thread.currentThread()); + try { + while (true) { + Request request = requestQueue.take(); + Object result; + try { + result = invokeMethod(request.methodName, request.arguments); + } catch (ThreadDeath death) { + return; + } catch (InvocationTargetException exception) { + responseQueue.put( + new Response(request.methodName, null, exception.getTargetException())); + continue; + } catch (Throwable throwable) { + responseQueue.put(new Response(request.methodName, null, throwable)); + continue; + } + responseQueue.put(new Response(request.methodName, result, null)); + } + } catch (ThreadDeath death) { + return; + } catch (InterruptedException ignored) { + // SynchronousQueue sometimes throws InterruptedException while the threads are stopping. + } catch (Throwable uncaught) { + this.uncaughtThrowable = uncaught; + } + } + + private static class Request { + final String methodName; + final Object[] arguments; + + Request(String methodName, Object[] arguments) { + this.methodName = checkNotNull(methodName); + this.arguments = checkNotNull(arguments); + } + } + + private static class Response { + final String methodName; + final Object result; + final Throwable throwable; + + Response(String methodName, Object result, Throwable throwable) { + this.methodName = methodName; + this.result = result; + this.throwable = throwable; + } + + Object getResult() { + if (throwable != null) { + throw (AssertionFailedError) new AssertionFailedError().initCause(throwable); + } + return result; + } + + Throwable getThrowable() { + assertNotNull(throwable); + return throwable; + } + } +} diff --git a/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java b/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java index d26ba63c4..358241596 100644 --- a/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java @@ -16,7 +16,7 @@ package com.google.common.util.concurrent; -import static org.truth0.Truth.ASSERT; +import static com.google.common.truth.Truth.assertThat; import com.google.common.testing.NullPointerTester; @@ -83,7 +83,7 @@ public class ThreadFactoryBuilderTest extends TestCase { ThreadFactory threadFactory2 = builder.build(); Thread thread3 = threadFactory2.newThread(monitoredRunnable); checkThreadPoolName(thread3, 1); - ASSERT.that( + assertThat( thread2.getName().substring(0, thread.getName().lastIndexOf('-'))) .isNotEqualTo( thread3.getName().substring(0, thread.getName().lastIndexOf('-'))); diff --git a/guava-tests/test/com/google/common/util/concurrent/UninterruptibleMonitorTest.java b/guava-tests/test/com/google/common/util/concurrent/UninterruptibleMonitorTest.java new file mode 100644 index 000000000..17690addb --- /dev/null +++ b/guava-tests/test/com/google/common/util/concurrent/UninterruptibleMonitorTest.java @@ -0,0 +1,31 @@ +/* + * 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.util.concurrent; + +/** + * Tests for {@link Monitor}'s uninterruptible methods. + * + * @author Justin T. Sampson + */ + +public class UninterruptibleMonitorTest extends MonitorTestCase { + + public UninterruptibleMonitorTest() { + super(false); + } + +} diff --git a/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java index 48e605dfe..900bd5d78 100644 --- a/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/WrappingExecutorServiceTest.java @@ -16,6 +16,9 @@ package com.google.common.util.concurrent; +import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService; +import static com.google.common.util.concurrent.Runnables.doNothing; + import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; @@ -40,12 +43,6 @@ import java.util.concurrent.TimeoutException; */ public class WrappingExecutorServiceTest extends TestCase { private static final String RESULT_VALUE = "ran"; - private static final Runnable DO_NOTHING = new Runnable() { - @Override - public void run() { - } - }; - // Uninteresting delegations public void testDelegations() throws InterruptedException { MockExecutor mock = new MockExecutor(); @@ -66,7 +63,7 @@ public class WrappingExecutorServiceTest extends TestCase { public void testExecute() { MockExecutor mock = new MockExecutor(); TestExecutor testExecutor = new TestExecutor(mock); - testExecutor.execute(DO_NOTHING); + testExecutor.execute(doNothing()); mock.assertLastMethodCalled("execute"); } @@ -74,14 +71,14 @@ public class WrappingExecutorServiceTest extends TestCase { { MockExecutor mock = new MockExecutor(); TestExecutor testExecutor = new TestExecutor(mock); - Future<?> f = testExecutor.submit(DO_NOTHING); + Future<?> f = testExecutor.submit(doNothing()); mock.assertLastMethodCalled("submit"); f.get(); } { MockExecutor mock = new MockExecutor(); TestExecutor testExecutor = new TestExecutor(mock); - Future<String> f = testExecutor.submit(DO_NOTHING, RESULT_VALUE); + Future<String> f = testExecutor.submit(doNothing(), RESULT_VALUE); mock.assertLastMethodCalled("submit"); assertEquals(RESULT_VALUE, f.get()); } @@ -195,7 +192,7 @@ public class WrappingExecutorServiceTest extends TestCase { private static final class MockExecutor implements ExecutorService { private String lastMethodCalled = ""; private long lastTimeoutInMillis = -1; - private ExecutorService inline = MoreExecutors.sameThreadExecutor(); + private ExecutorService inline = newDirectExecutorService(); public void assertLastMethodCalled(String method) { assertEquals(method, lastMethodCalled); diff --git a/guava-tests/test/com/google/common/util/concurrent/WrappingScheduledExecutorServiceTest.java b/guava-tests/test/com/google/common/util/concurrent/WrappingScheduledExecutorServiceTest.java index 479fa8c40..9beadb487 100644 --- a/guava-tests/test/com/google/common/util/concurrent/WrappingScheduledExecutorServiceTest.java +++ b/guava-tests/test/com/google/common/util/concurrent/WrappingScheduledExecutorServiceTest.java @@ -45,8 +45,8 @@ public class WrappingScheduledExecutorServiceTest extends TestCase { MockExecutor mock = new MockExecutor(); TestExecutor testExecutor = new TestExecutor(mock); - testExecutor.schedule(DO_NOTHING, 10, TimeUnit.SECONDS); - mock.assertLastMethodCalled("scheduleRunnable", 10, TimeUnit.SECONDS); + testExecutor.schedule(DO_NOTHING, 10, TimeUnit.MINUTES); + mock.assertLastMethodCalled("scheduleRunnable", 10, TimeUnit.MINUTES); testExecutor.schedule(Executors.callable(DO_NOTHING), 5, TimeUnit.SECONDS); mock.assertLastMethodCalled("scheduleCallable", 5, TimeUnit.SECONDS); @@ -55,8 +55,8 @@ public class WrappingScheduledExecutorServiceTest extends TestCase { public void testSchedule_repeating() { MockExecutor mock = new MockExecutor(); TestExecutor testExecutor = new TestExecutor(mock); - testExecutor.scheduleWithFixedDelay(DO_NOTHING, 100, 10, TimeUnit.SECONDS); - mock.assertLastMethodCalled("scheduleWithFixedDelay", 100, 10, TimeUnit.SECONDS); + testExecutor.scheduleWithFixedDelay(DO_NOTHING, 100, 10, TimeUnit.MINUTES); + mock.assertLastMethodCalled("scheduleWithFixedDelay", 100, 10, TimeUnit.MINUTES); testExecutor.scheduleAtFixedRate(DO_NOTHING, 3, 7, TimeUnit.SECONDS); mock.assertLastMethodCalled("scheduleAtFixedRate", 3, 7, TimeUnit.SECONDS); diff --git a/guava-tests/test/com/google/common/xml/XmlEscapersTest.java b/guava-tests/test/com/google/common/xml/XmlEscapersTest.java index 148a71907..50529629d 100644 --- a/guava-tests/test/com/google/common/xml/XmlEscapersTest.java +++ b/guava-tests/test/com/google/common/xml/XmlEscapersTest.java @@ -82,8 +82,8 @@ public class XmlEscapersTest extends TestCase { assertUnescaped(xmlEscaper, ch); } } else { - // and everything else is removed. - assertEscaping(xmlEscaper, "", ch); + // and everything else is replaced with FFFD. + assertEscaping(xmlEscaper, "\uFFFD", ch); } } @@ -109,18 +109,13 @@ public class XmlEscapersTest extends TestCase { } } - // TODO(user): Change once this escaper forbids \uFFFE and \uFFFF. + // Test that 0xFFFE and 0xFFFF are replaced with 0xFFFD + assertEscaping(xmlEscaper, "\uFFFD", '\uFFFE'); + assertEscaping(xmlEscaper, "\uFFFD", '\uFFFF'); - assertUnescaped(xmlEscaper, '\uFFFE'); - assertUnescaped(xmlEscaper, '\uFFFF'); - - // Test that 0xFFFE and 0xFFFF are removed - // assertEscaping(xmlEscaper, "", '\uFFFE'); - // assertEscaping(xmlEscaper, "", '\uFFFF'); - - // assertEquals("0xFFFE is forbidden and should be removed during escaping", - // "[]", XmlEscapers.xmlEscaper().escape("[\ufffe]")); - // assertEquals("0xFFFF is forbidden and should be removed during escaping", - // "[]", XmlEscapers.xmlEscaper().escape("[\uffff]")); + assertEquals("0xFFFE is forbidden and should be replaced during escaping", + "[\uFFFD]", xmlEscaper.escape("[\ufffe]")); + assertEquals("0xFFFF is forbidden and should be replaced during escaping", + "[\uFFFD]", xmlEscaper.escape("[\uffff]")); } } |