Skip to content

Commit

Permalink
Use assertThrows even in GWT/J2CL/J2KT-compatible code, `common.cac…
Browse files Browse the repository at this point in the history
…he`+`io`+`math`+`reflect`+`testing` edition.

(continuing the path started in cl/675634517)

And address a few other warnings.

RELNOTES=n/a
PiperOrigin-RevId: 687302660
  • Loading branch information
cpovirk authored and Google Java Core Libraries committed Oct 18, 2024
1 parent 6082782 commit b0461b7
Show file tree
Hide file tree
Showing 40 changed files with 2,070 additions and 1,494 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

package com.google.common.testing;

import static com.google.common.testing.ReflectionFreeAssertThrows.assertThrows;
import static com.google.common.truth.Truth.assertThat;

import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
Expand Down Expand Up @@ -51,29 +54,21 @@ public void setUp() throws Exception {

/** Test null reference yields error */
public void testAddNullReference() {
try {
equalsTester.addEqualityGroup((Object) null);
fail("Should fail on null reference");
} catch (NullPointerException e) {
}
assertThrows(NullPointerException.class, () -> equalsTester.addEqualityGroup((Object) null));
}

/** Test equalObjects after adding multiple instances at once with a null */
public void testAddTwoEqualObjectsAtOnceWithNull() {
try {
equalsTester.addEqualityGroup(reference, equalObject1, null);
fail("Should fail on null equal object");
} catch (NullPointerException e) {
}
assertThrows(
NullPointerException.class,
() -> equalsTester.addEqualityGroup(reference, equalObject1, null));
}

/** Test adding null equal object yields error */
public void testAddNullEqualObject() {
try {
equalsTester.addEqualityGroup(reference, (Object[]) null);
fail("Should fail on null equal object");
} catch (NullPointerException e) {
}
assertThrows(
NullPointerException.class,
() -> equalsTester.addEqualityGroup(reference, (Object[]) null));
}

/**
Expand Down Expand Up @@ -195,21 +190,14 @@ public void testInvalidHashCode() {

public void testNullEqualityGroup() {
EqualsTester tester = new EqualsTester();
try {
tester.addEqualityGroup((Object[]) null);
fail();
} catch (NullPointerException e) {
}
assertThrows(NullPointerException.class, () -> tester.addEqualityGroup((Object[]) null));
}

public void testNullObjectInEqualityGroup() {
EqualsTester tester = new EqualsTester();
try {
tester.addEqualityGroup(1, null, 3);
fail();
} catch (NullPointerException e) {
assertErrorMessage(e, "at index 1");
}
NullPointerException e =
assertThrows(NullPointerException.class, () -> tester.addEqualityGroup(1, null, 3));
assertErrorMessage(e, "at index 1");
}

public void testSymmetryBroken() {
Expand Down Expand Up @@ -274,12 +262,12 @@ public void testEqualityGroups() {
}

public void testEqualityBasedOnToString() {
try {
new EqualsTester().addEqualityGroup(new EqualsBasedOnToString("foo")).testEquals();
fail();
} catch (AssertionFailedError e) {
assertTrue(e.getMessage().contains("toString representation"));
}
AssertionFailedError e =
assertThrows(
AssertionFailedError.class,
() ->
new EqualsTester().addEqualityGroup(new EqualsBasedOnToString("foo")).testEquals());
assertThat(e).hasMessageThat().contains("toString representation");
}

private static void assertErrorMessage(Throwable e, String message) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.common.testing;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.testing.ReflectionFreeAssertThrows.assertThrows;
import static com.google.common.truth.Truth.assertThat;

import com.google.common.annotations.GwtCompatible;
Expand Down Expand Up @@ -46,11 +47,7 @@ public void setUp() throws Exception {

/** Test null reference yields error */
public void testOf_nullPointerException() {
try {
EquivalenceTester.of(null);
fail("Should fail on null reference");
} catch (NullPointerException expected) {
}
assertThrows(NullPointerException.class, () -> EquivalenceTester.of(null));
}

public void testTest_noData() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package com.google.common.testing;

import static com.google.common.testing.ReflectionFreeAssertThrows.assertThrows;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.time.Duration;
Expand Down Expand Up @@ -108,11 +110,9 @@ public void testAutoIncrementStep_resetToZero() {

public void testAutoIncrement_negative() {
FakeTicker ticker = new FakeTicker();
try {
ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
assertThrows(
IllegalArgumentException.class,
() -> ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS));
}

@GwtIncompatible // concurrency
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright (C) 2024 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/

package com.google.common.testing;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Predicate;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import junit.framework.AssertionFailedError;
import org.checkerframework.checker.nullness.qual.Nullable;

/** Replacements for JUnit's {@code assertThrows} that work under GWT/J2CL. */
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
final class ReflectionFreeAssertThrows {
interface ThrowingRunnable {
void run() throws Throwable;
}

interface ThrowingSupplier {
@Nullable Object get() throws Throwable;
}

@CanIgnoreReturnValue
static <T extends Throwable> T assertThrows(
Class<T> expectedThrowable, ThrowingSupplier supplier) {
return doAssertThrows(expectedThrowable, supplier, /* userPassedSupplier= */ true);
}

@CanIgnoreReturnValue
static <T extends Throwable> T assertThrows(
Class<T> expectedThrowable, ThrowingRunnable runnable) {
return doAssertThrows(
expectedThrowable,
() -> {
runnable.run();
return null;
},
/* userPassedSupplier= */ false);
}

private static <T extends Throwable> T doAssertThrows(
Class<T> expectedThrowable, ThrowingSupplier supplier, boolean userPassedSupplier) {
checkNotNull(expectedThrowable);
checkNotNull(supplier);
Predicate<Throwable> predicate = INSTANCE_OF.get(expectedThrowable);
if (predicate == null) {
throw new IllegalArgumentException(
expectedThrowable
+ " is not yet supported by ReflectionFreeAssertThrows. Add an entry for it in the"
+ " map in that class.");
}
Object result;
try {
result = supplier.get();
} catch (Throwable t) {
if (predicate.apply(t)) {
// We are careful to set up INSTANCE_OF to match each Predicate to its target Class.
@SuppressWarnings("unchecked")
T caught = (T) t;
return caught;
}
throw new AssertionError(
"expected to throw " + expectedThrowable.getSimpleName() + " but threw " + t, t);
}
if (userPassedSupplier) {
throw new AssertionError(
"expected to throw "
+ expectedThrowable.getSimpleName()
+ " but returned result: "
+ result);
} else {
throw new AssertionError("expected to throw " + expectedThrowable.getSimpleName());
}
}

private enum PlatformSpecificExceptionBatch {
PLATFORM {
@GwtIncompatible
@J2ktIncompatible
@Override
// returns the types available in "normal" environments
ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() {
return ImmutableMap.of(
InvocationTargetException.class,
e -> e instanceof InvocationTargetException,
StackOverflowError.class,
e -> e instanceof StackOverflowError);
}
};

// used under GWT, etc., since the override of this method does not exist there
ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() {
return ImmutableMap.of();
}
}

private static final ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> INSTANCE_OF =
ImmutableMap.<Class<? extends Throwable>, Predicate<Throwable>>builder()
.put(ArithmeticException.class, e -> e instanceof ArithmeticException)
.put(
ArrayIndexOutOfBoundsException.class,
e -> e instanceof ArrayIndexOutOfBoundsException)
.put(ArrayStoreException.class, e -> e instanceof ArrayStoreException)
.put(AssertionFailedError.class, e -> e instanceof AssertionFailedError)
.put(CancellationException.class, e -> e instanceof CancellationException)
.put(ClassCastException.class, e -> e instanceof ClassCastException)
.put(
ConcurrentModificationException.class,
e -> e instanceof ConcurrentModificationException)
.put(ExecutionError.class, e -> e instanceof ExecutionError)
.put(ExecutionException.class, e -> e instanceof ExecutionException)
.put(IllegalArgumentException.class, e -> e instanceof IllegalArgumentException)
.put(IllegalStateException.class, e -> e instanceof IllegalStateException)
.put(IndexOutOfBoundsException.class, e -> e instanceof IndexOutOfBoundsException)
.put(NoSuchElementException.class, e -> e instanceof NoSuchElementException)
.put(NullPointerException.class, e -> e instanceof NullPointerException)
.put(NumberFormatException.class, e -> e instanceof NumberFormatException)
.put(RuntimeException.class, e -> e instanceof RuntimeException)
.put(TimeoutException.class, e -> e instanceof TimeoutException)
.put(UncheckedExecutionException.class, e -> e instanceof UncheckedExecutionException)
.put(UnsupportedCharsetException.class, e -> e instanceof UnsupportedCharsetException)
.put(UnsupportedOperationException.class, e -> e instanceof UnsupportedOperationException)
.put(VerifyException.class, e -> e instanceof VerifyException)
.putAll(PlatformSpecificExceptionBatch.PLATFORM.exceptions())
.buildOrThrow();

private ReflectionFreeAssertThrows() {}
}
Loading

0 comments on commit b0461b7

Please sign in to comment.