@GwtIncompatible // propagate public void testPropagate_NoneDeclared_ErrorThrown() { Sample sample = new Sample() { @Override public void noneDeclared() { try { methodThatThrowsError(); } catch (Throwable t) { throw Throwables.propagate(t); } } }; // Expect the error to propagate as-is try { sample.noneDeclared(); fail(); } catch (SomeError expected) { } }
@GwtIncompatible // Class names are obfuscated in GWT public void testToString_ToStringTwice() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(new TestClass()) .add("field1", 1) .addValue("value1") .add("field2", "value2"); final String expected = "TestClass{field1=1, value1, field2=value2}"; assertEquals(expected, helper.toString()); // Call toString again assertEquals(expected, helper.toString()); // Make sure the cached value is reset when we modify the helper at all final String expected2 = "TestClass{field1=1, value1, field2=value2, 2}"; helper.addValue(2); assertEquals(expected2, helper.toString()); }
@GwtIncompatible // makeChecked public void testMakeChecked_listenersRunOnFailure() throws Exception { SettableFuture<String> future = SettableFuture.create(); CheckedFuture<String, TestException> checked = makeChecked( future, new Function<Exception, TestException>() { @Override public TestException apply(Exception from) { throw new NullPointerException(); } }); ListenableFutureTester tester = new ListenableFutureTester(checked); tester.setUp(); future.setException(new Exception("failed")); tester.testFailedFuture("failed"); tester.tearDown(); }
@GwtIncompatible // propagateIfPossible(Throwable, Class) public void testPropagateIfPossible_OneDeclared_UncheckedThrown() throws SomeCheckedException { Sample sample = new Sample() { @Override public void oneDeclared() throws SomeCheckedException { try { methodThatThrowsUnchecked(); } catch (Throwable t) { Throwables.propagateIfPossible(t, SomeCheckedException.class); throw new SomeChainingException(t); } } }; // Expect the unchecked exception to propagate as-is try { sample.oneDeclared(); fail(); } catch (SomeUncheckedException expected) { } }
/** * Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly. */ @GwtIncompatible // concurrency public static <E> E takeUninterruptibly(BlockingQueue<E> queue) { boolean interrupted = false; try { while (true) { try { return queue.take(); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
@GwtIncompatible // java serialization not supported in GWT. public void testImmutableEnumSet_deserializationMakesDefensiveCopy() throws Exception { ImmutableSet<SomeEnum> original = Sets.immutableEnumSet(SomeEnum.A, SomeEnum.B); int handleOffset = 6; byte[] serializedForm = serializeWithBackReference(original, handleOffset); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedForm)); ImmutableSet<?> deserialized = (ImmutableSet<?>) in.readObject(); EnumSet<?> delegate = (EnumSet<?>) in.readObject(); assertEquals(original, deserialized); assertTrue(delegate.remove(SomeEnum.A)); assertTrue(deserialized.contains(SomeEnum.A)); }
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class) public void testPropagateIfPossible_TwoDeclared_NoneThrown() throws SomeCheckedException, SomeOtherCheckedException { Sample sample = new Sample() { @Override public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { try { methodThatDoesntThrowAnything(); } catch (Throwable t) { Throwables.propagateIfPossible(t, SomeCheckedException.class, SomeOtherCheckedException.class); throw new SomeChainingException(t); } } }; // Expect no exception to be thrown sample.twoDeclared(); }
@GwtIncompatible // inCompletionOrder public void testCancellingADelegateDoesNotPropagate() throws Exception { SettableFuture<Long> future1 = SettableFuture.create(); SettableFuture<Long> future2 = SettableFuture.create(); ImmutableList<ListenableFuture<Long>> delegates = inCompletionOrder( ImmutableList.<ListenableFuture<Long>>of(future1, future2)); future1.set(1L); // Cannot cancel a complete delegate assertFalse(delegates.get(0).cancel(true)); // Cancel the delegate before the input future is done assertTrue(delegates.get(1).cancel(true)); // Setting the future still works since cancellation didn't propagate assertTrue(future2.set(2L)); // Second check to ensure the input future was not cancelled assertEquals((Long) 2L, getDone(future2)); }
@GwtIncompatible // suite private static Test testsForFilterFiltered() { return CollectionTestSuiteBuilder.using( new TestStringCollectionGenerator() { @Override public Collection<String> create(String[] elements) { List<String> unfiltered = newArrayList(); unfiltered.add("yyy"); unfiltered.addAll(ImmutableList.copyOf(elements)); unfiltered.add("zzz"); unfiltered.add("abc"); return Collections2.filter( Collections2.filter(unfiltered, LENGTH_1), NOT_YYY_ZZZ); } }) .named("Collections2.filter, filtered input") .withFeatures( CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionFeature.ALLOWS_NULL_QUERIES, CollectionSize.ANY) .createTestSuite(); }
@GwtIncompatible // lazyStackTrace(Throwable) public void testLazyStackTrace() { Exception e = new Exception(); StackTraceElement[] originalStackTrace = e.getStackTrace(); assertThat(lazyStackTrace(e)).containsExactly((Object[]) originalStackTrace).inOrder(); try { lazyStackTrace(e).set(0, null); fail(); } catch (UnsupportedOperationException expected) { } // Now we test a property that holds only for the lazy implementation. if (!lazyStackTraceIsLazy()) { return; } e.setStackTrace(new StackTraceElement[0]); assertThat(lazyStackTrace(e)).containsExactly((Object[]) originalStackTrace).inOrder(); }
@GwtIncompatible // Mockito 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); addCallback(future, callback, directExecutor()); 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); }
/** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n} */ @GwtIncompatible // need BigIntegerMath to adequately test public static int binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } if (k >= biggestBinomials.length || n > biggestBinomials[k]) { return Integer.MAX_VALUE; } switch (k) { case 0: return 1; case 1: return n; default: long result = 1; for (int i = 0; i < k; i++) { result *= n - i; result /= i + 1; } return (int) result; } }
@GwtIncompatible // mocks // TODO(cpovirk): eliminate use of mocks @SuppressWarnings("unchecked") public void testCatchingAsync_resultCancelledAfterFallback() throws Exception { final SettableFuture<Integer> secondary = SettableFuture.create(); final RuntimeException raisedException = new RuntimeException(); AsyncFunctionSpy<Throwable, Integer> fallback = spy(new AsyncFunction<Throwable, Integer>() { @Override public ListenableFuture<Integer> apply(Throwable t) throws Exception { assertThat(t).isSameAs(raisedException); return secondary; } }); ListenableFuture<Integer> failingFuture = immediateFailedFuture(raisedException); ListenableFuture<Integer> derived = catchingAsync(failingFuture, Throwable.class, fallback, directExecutor()); derived.cancel(false); assertTrue(secondary.isCancelled()); assertFalse(secondary.wasInterrupted()); fallback.verifyCallCount(1); }
@GwtIncompatible // propagateIfPossible public void testPropagateIfPossible_NoneDeclared_UncheckedThrown() { Sample sample = new Sample() { @Override public void noneDeclared() { try { methodThatThrowsUnchecked(); } catch (Throwable t) { Throwables.propagateIfPossible(t); throw new SomeChainingException(t); } } }; // Expect the unchecked exception to propagate as-is try { sample.noneDeclared(); fail(); } catch (SomeUncheckedException expected) { } }
@GwtIncompatible public void testAsAsyncCallable() throws Exception { final String expected = "MyCallableString"; Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { return expected; } }; AsyncCallable<String> asyncCallable = Callables.asAsyncCallable(callable, MoreExecutors.newDirectExecutorService()); ListenableFuture<String> future = asyncCallable.call(); assertSame(expected, future.get()); }
@GwtIncompatible // java.io.ObjectInputStream private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject Comparator<? super E> comparator = (Comparator<? super E>) stream.readObject(); Serialization.getFieldSetter(AbstractSortedMultiset.class, "comparator").set(this, comparator); Serialization.getFieldSetter(TreeMultiset.class, "range") .set(this, GeneralRange.all(comparator)); Serialization.getFieldSetter(TreeMultiset.class, "rootReference") .set(this, new Reference<AvlNode<E>>()); AvlNode<E> header = new AvlNode<E>(null, 1); Serialization.getFieldSetter(TreeMultiset.class, "header").set(this, header); successor(header, header); Serialization.populateMultiset(this, stream); }
@GwtIncompatible // NullPointerTester public void testNullPointerExceptions() { NullPointerTester tester = new NullPointerTester(); tester.testAllPublicStaticMethods(Ordering.class); // any Ordering<Object> instance that accepts nulls should be good enough tester.testAllPublicInstanceMethods(Ordering.usingToString().nullsFirst()); }
@GwtIncompatible // java.util.regex.Pattern public void testPatternSplitInvalidPattern() { try { Splitter.on(Pattern.compile("a*")); fail(); } catch (IllegalArgumentException expected) { } }
@GwtIncompatible // not present in emulated superclass @Override int copyIntoArray(Object[] dst, int offset) { for (Multiset.Entry<E> entry : entrySet()) { Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement()); offset += entry.getCount(); } return offset; }
@AndroidIncompatible // slow @GwtIncompatible // Floats.tryParse public void testTryParseAllCodePoints() { // Exercise non-ASCII digit test cases and the like. char[] tmp = new char[2]; for (int i = Character.MIN_CODE_POINT; i < Character.MAX_CODE_POINT; i++) { Character.toChars(i, tmp, 0); checkTryParse(String.copyValueOf(tmp, 0, Character.charCount(i))); } }
@GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { BitSet tmp1 = new BitSet(); first.setBits(tmp1); BitSet tmp2 = new BitSet(); second.setBits(tmp2); tmp1.and(tmp2); table.or(tmp1); }
@GwtIncompatible // Double.toString returns different value in GWT. public void testJoin() { assertEquals("", Doubles.join(",", EMPTY)); assertEquals("1.0", Doubles.join(",", ARRAY1)); assertEquals("1.0,2.0", Doubles.join(",", (double) 1, (double) 2)); assertEquals("1.02.03.0", Doubles.join("", (double) 1, (double) 2, (double) 3)); }
@GwtIncompatible // fairly slow (~50s) public void testPaddedPartition_general() { new IteratorTester<List<Integer>>(5, IteratorFeature.UNMODIFIABLE, ImmutableList.of( asList(1, 2, 3), asList(4, 5, 6), asList(7, null, null)), IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<List<Integer>> newTargetIterator() { Iterator<Integer> source = Iterators.forArray(1, 2, 3, 4, 5, 6, 7); return Iterators.paddedPartition(source, 3); } }.test(); }
/** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested * {@code numElements} elements are not available, it will wait for them up to the specified * timeout. * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting */ @Beta @CanIgnoreReturnValue @GwtIncompatible // BlockingQueue public static <E> int drain( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(buffer); /* * This code performs one System.nanoTime() more than necessary, and in return, the time to * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make * the timeout arbitrarily inaccurate, given a queue that is slow to drain). */ long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } return added; }
/** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered navigable map. */ @GwtIncompatible // NavigableMap private static <K, V> NavigableMap<K, V> filterFiltered( FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.entryPredicate, entryPredicate); return new FilteredEntryNavigableMap<K, V>(map.unfiltered, predicate); }
@GwtIncompatible // fairly slow (~50s) public void testPartition_general() { new IteratorTester<List<Integer>>(5, IteratorFeature.UNMODIFIABLE, ImmutableList.of( asList(1, 2, 3), asList(4, 5, 6), asList(7)), IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<List<Integer>> newTargetIterator() { Iterator<Integer> source = Iterators.forArray(1, 2, 3, 4, 5, 6, 7); return Iterators.partition(source, 3); } }.test(); }
@GwtIncompatible // Float.toString returns different value in GWT. public void testJoin() { assertEquals("", Floats.join(",", EMPTY)); assertEquals("1.0", Floats.join(",", ARRAY1)); assertEquals("1.0,2.0", Floats.join(",", (float) 1, (float) 2)); assertEquals("1.02.03.0", Floats.join("", (float) 1, (float) 2, (float) 3)); }
@GwtIncompatible // TODO public void testLog10MatchesBigInteger() { for (long x : POSITIVE_LONG_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { assertEquals(BigIntegerMath.log10(valueOf(x), mode), LongMath.log10(x, mode)); } } }
@GwtIncompatible // TODO public void testZeroDivIsAlwaysZero() { for (BigInteger q : NONZERO_BIGINTEGER_CANDIDATES) { for (RoundingMode mode : ALL_ROUNDING_MODES) { assertEquals(ZERO, BigIntegerMath.divide(ZERO, q, mode)); } } }
/** * @serialData the comparator, the number of distinct elements, the first element, its count, the * second element, its count, and so on */ @GwtIncompatible // java.io.ObjectOutputStream private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(elementSet().comparator()); Serialization.writeMultiset(this, stream); }
@GwtIncompatible // NullPointerTester public void testNullPointers() { NullPointerTester npTester = new NullPointerTester(); npTester.testAllPublicConstructors(Optional.class); npTester.testAllPublicStaticMethods(Optional.class); npTester.testAllPublicInstanceMethods(Optional.absent()); npTester.testAllPublicInstanceMethods(Optional.of("training")); }
@GwtIncompatible // Class names are obfuscated in GWT public void testToString_addValue() { String toTest = MoreObjects.toStringHelper(new TestClass()) .add("field1", 1) .addValue("value1") .add("field2", "value2") .addValue(2) .toString(); final String expected = "TestClass{field1=1, value1, field2=value2, 2}"; assertEquals(expected, toTest); }
@GwtIncompatible // slow (~35s) public void testSkip_iterator() { new IteratorTester<Integer>(5, MODIFIABLE, newArrayList(2, 3), IteratorTester.KnownOrder.KNOWN_ORDER) { @Override protected Iterator<Integer> newTargetIterator() { return skip(newLinkedHashSet(asList(1, 2, 3)), 1).iterator(); } }.test(); }
/** * Returns the {@code BigInteger} value that is equal to {@code x} rounded with the specified * rounding mode, if possible. * * @throws ArithmeticException if * <ul> * <li>{@code x} is infinite or NaN * <li>{@code x} is not a mathematical integer and {@code mode} is * {@link RoundingMode#UNNECESSARY} * </ul> */ // #roundIntermediate, java.lang.Math.getExponent, com.google.common.math.DoubleUtils @GwtIncompatible public static BigInteger roundToBigInteger(double x, RoundingMode mode) { x = roundIntermediate(x, mode); if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) { return BigInteger.valueOf((long) x); } int exponent = getExponent(x); long significand = getSignificand(x); BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS); return (x < 0) ? result.negate() : result; }
@GwtIncompatible // Too slow in GWT (~3min fully optimized) public void testDivideRemainderEuclideanProperty() { // Use a seed so that the test is deterministic: Random r = new Random(0L); for (int i = 0; i < 1000000; i++) { long dividend = r.nextLong(); long divisor = r.nextLong(); // Test that the Euclidean property is preserved: assertEquals(0, dividend - (divisor * UnsignedLongs.divide(dividend, divisor) + UnsignedLongs.remainder(dividend, divisor))); } }
@GwtIncompatible(value = "untested") public void testTransformValues() { SetMultimap<String, Integer> multimap = ImmutableSetMultimap.of("a", 2, "b", -3, "b", 3, "a", 4, "c", 6); Function<Integer, Integer> square = new Function<Integer, Integer>() { @Override public Integer apply(Integer in) { return in * in; } }; Multimap<String, Integer> transformed = Multimaps.transformValues(multimap, square); assertThat(transformed.entries()).containsExactly(immutableEntry("a", 4), immutableEntry("a", 16), immutableEntry("b", 9), immutableEntry("b", 9), immutableEntry("c", 36)).inOrder(); }
@GwtIncompatible // SerializableTester public void testSerialization() { Multimap<String, Integer> multimap = createMultimap(); SerializableTester.reserializeAndAssert(multimap); assertEquals(multimap.size(), SerializableTester.reserialize(multimap).size()); SerializableTester.reserializeAndAssert(multimap.get("foo")); LenientSerializableTester.reserializeAndAssertLenient(multimap.keySet()); LenientSerializableTester.reserializeAndAssertLenient(multimap.keys()); SerializableTester.reserializeAndAssert(multimap.asMap()); Collection<Integer> valuesCopy = SerializableTester.reserialize(multimap.values()); assertEquals(HashMultiset.create(multimap.values()), HashMultiset.create(valuesCopy)); }
@GwtIncompatible // SerializableTester public void testInverseSerialization() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( ImmutableMap.of(1, "one", 2, "two")).inverse(); ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap); assertEquals(Integer.valueOf(1), copy.get("one")); assertEquals("one", copy.inverse().get(1)); assertSame(copy, copy.inverse().inverse()); }
@GwtIncompatible // DoubleMath.log2(double, RoundingMode), StrictMath public void testRoundLog2Ceiling() { for (double d : POSITIVE_FINITE_DOUBLE_CANDIDATES) { int log2 = DoubleMath.log2(d, CEILING); assertTrue(StrictMath.pow(2.0, log2) >= d); double z = StrictMath.pow(2.0, log2 - 1); assertTrue(z < d); } }
@GwtIncompatible // TODO public void testConstantsFactorials() { long expected = 1; for (int i = 0; i < LongMath.factorials.length; i++, expected *= i) { assertEquals(expected, LongMath.factorials[i]); } try { LongMath.checkedMultiply( LongMath.factorials[LongMath.factorials.length - 1], LongMath.factorials.length); fail("Expected ArithmeticException"); } catch (ArithmeticException expect) {} }