Use backported JUnit exceptThrows and assertThrows in metrics library

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=176584707
This commit is contained in:
jianglai 2017-11-21 17:26:07 -08:00
parent 6eb0d8689d
commit a92cdbe8c3
17 changed files with 325 additions and 226 deletions

View file

@ -15,22 +15,18 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import org.joda.time.Instant; import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link Counter}. */ /** Unit tests for {@link Counter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class CounterTest { public class CounterTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testGetCardinality_reflectsCurrentCardinality() { public void testGetCardinality_reflectsCurrentCardinality() {
Counter counter = Counter counter =
@ -59,11 +55,12 @@ public class CounterTest {
ImmutableSet.of( ImmutableSet.of(
LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar"))); LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(IllegalArgumentException.class, () -> counter.increment("blah"));
assertThat(thrown)
.hasMessageThat()
.contains(
"The count of labelValues must be equal to the underlying Metric's count of labels."); "The count of labelValues must be equal to the underlying Metric's count of labels.");
counter.increment("blah");
} }
@Test @Test
@ -122,9 +119,9 @@ public class CounterTest {
"vdn", "vdn",
ImmutableSet.of(LabelDescriptor.create("label1", "bar"))); ImmutableSet.of(LabelDescriptor.create("label1", "bar")));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("The offset provided must be non-negative"); expectThrows(IllegalArgumentException.class, () -> counter.incrementBy(-1L, "foo"));
counter.incrementBy(-1L, "foo"); assertThat(thrown).hasMessageThat().contains("The offset provided must be non-negative");
} }
@Test @Test

View file

@ -15,35 +15,31 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Tests for {@link CustomFitter}. */ /** Tests for {@link CustomFitter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class CustomFitterTest { public class CustomFitterTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testCreateCustomFitter_emptyBounds_throwsException() throws Exception { public void testCreateCustomFitter_emptyBounds_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("boundaries must not be empty"); expectThrows(
IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.<Double>of()));
CustomFitter.create(ImmutableSet.<Double>of()); assertThat(thrown).hasMessageThat().contains("boundaries must not be empty");
} }
@Test @Test
public void testCreateCustomFitter_outOfOrderBounds_throwsException() throws Exception { public void testCreateCustomFitter_outOfOrderBounds_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("boundaries must be sorted"); expectThrows(
IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.of(2.0, 0.0)));
CustomFitter.create(ImmutableSet.of(2.0, 0.0)); assertThat(thrown).hasMessageThat().contains("boundaries must be sorted");
} }
@Test @Test

View file

@ -15,6 +15,7 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableRangeMap; import com.google.common.collect.ImmutableRangeMap;
@ -22,9 +23,7 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import org.joda.time.Instant; import org.joda.time.Instant;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -34,9 +33,6 @@ public class EventMetricTest {
private final DistributionFitter distributionFitter = CustomFitter.create(ImmutableSet.of(5.0)); private final DistributionFitter distributionFitter = CustomFitter.create(ImmutableSet.of(5.0));
private EventMetric metric; private EventMetric metric;
@Rule public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void setUp() { public void setUp() {
metric = metric =
@ -67,11 +63,12 @@ public class EventMetricTest {
@Test @Test
public void testIncrementBy_wrongLabelValueCount_throwsException() { public void testIncrementBy_wrongLabelValueCount_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(IllegalArgumentException.class, () -> metric.record(1.0, "blah", "blah"));
assertThat(thrown)
.hasMessageThat()
.contains(
"The count of labelValues must be equal to the underlying Metric's count of labels."); "The count of labelValues must be equal to the underlying Metric's count of labels.");
metric.record(1.0, "blah", "blah");
} }
@Test @Test

View file

@ -15,57 +15,49 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link ExponentialFitter}. */ /** Unit tests for {@link ExponentialFitter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ExponentialFitterTest { public class ExponentialFitterTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testCreateExponentialFitter_zeroNumIntervals_throwsException() throws Exception { public void testCreateExponentialFitter_zeroNumIntervals_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("numFiniteIntervals must be greater than 0"); expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(0, 3.0, 1.0));
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
ExponentialFitter.create(0, 3.0, 1.0);
} }
@Test @Test
public void testCreateExponentialFitter_negativeNumIntervals_throwsException() throws Exception { public void testCreateExponentialFitter_negativeNumIntervals_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("numFiniteIntervals must be greater than 0"); expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(-1, 3.0, 1.0));
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
ExponentialFitter.create(-1, 3.0, 1.0);
} }
@Test @Test
public void testCreateExponentialFitter_invalidBase_throwsException() throws Exception { public void testCreateExponentialFitter_invalidBase_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("base must be greater than 1"); expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 0.5, 1.0));
assertThat(thrown).hasMessageThat().contains("base must be greater than 1");
ExponentialFitter.create(3, 0.5, 1.0);
} }
@Test @Test
public void testCreateExponentialFitter_zeroScale_throwsException() throws Exception { public void testCreateExponentialFitter_zeroScale_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("scale must not be 0"); expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, 0.0));
assertThat(thrown).hasMessageThat().contains("scale must not be 0");
ExponentialFitter.create(3, 2.0, 0.0);
} }
@Test @Test
public void testCreateExponentialFitter_NanScale_throwsException() throws Exception { public void testCreateExponentialFitter_NanScale_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("value must be finite, not NaN, and not -0.0"); expectThrows(
IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, Double.NaN));
ExponentialFitter.create(3, 2.0, Double.NaN); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
} }
@Test @Test

View file

@ -15,7 +15,7 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail; import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import org.junit.Test; import org.junit.Test;
@ -28,23 +28,17 @@ public class FibonacciFitterTest {
@Test @Test
public void testCreate_maxBucketSizeNegative_throwsException() { public void testCreate_maxBucketSizeNegative_throwsException() {
try { IllegalArgumentException e =
FibonacciFitter.create(-1); expectThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(-1));
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0");
} }
}
@Test @Test
public void testCreate_maxBucketSizeZero_throwsException() { public void testCreate_maxBucketSizeZero_throwsException() {
try { IllegalArgumentException e =
FibonacciFitter.create(0); expectThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(0));
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0");
} }
}
@Test @Test
public void testCreate_maxBucketSizeOne_createsTwoBoundaries() { public void testCreate_maxBucketSizeOne_createsTwoBoundaries() {

View file

@ -0,0 +1,122 @@
package google.registry.monitoring.metrics;
/**
* A testing utility class that contains backports of useful but not yet released JUnit methods.
*
* <p>All of this code was taken directly from
* https://github.com/junit-team/junit4/blob/a832c5afe5b0e7c2590d057a1a49a344d207f8a0/src/main/java/org/junit/Assert.java
*/
public class JUnitBackports {
// TODO(b/68257761): Delete these and switch over to JUnit 4.13 methods upon release.
/**
* This interface facilitates the use of expectThrows from Java 8. It allows method references to
* void methods (that declare checked exceptions) to be passed directly into expectThrows without
* wrapping. It is not meant to be implemented directly.
*
* @since 4.13
*/
public interface ThrowingRunnable {
void run() throws Throwable;
}
/**
* Asserts that {@code runnable} throws an exception of type {@code expectedThrowable} when
* executed. If it does not throw an exception, an {@link AssertionError} is thrown. If it throws
* the wrong type of exception, an {@code AssertionError} is thrown describing the mismatch; the
* exception that was actually thrown can be obtained by calling {@link AssertionError#getCause}.
*
* @param expectedThrowable the expected type of the exception
* @param runnable a function that is expected to throw an exception when executed
* @since 4.13
*/
public static void assertThrows(
Class<? extends Throwable> expectedThrowable, ThrowingRunnable runnable) {
expectThrows(expectedThrowable, runnable);
}
/**
* Asserts that {@code runnable} throws an exception of type {@code expectedThrowable} when
* executed. If it does, the exception object is returned. If it does not throw an exception, an
* {@link AssertionError} is thrown. If it throws the wrong type of exception, an {@code
* AssertionError} is thrown describing the mismatch; the exception that was actually thrown can
* be obtained by calling {@link AssertionError#getCause}.
*
* @param expectedThrowable the expected type of the exception
* @param runnable a function that is expected to throw an exception when executed
* @return the exception thrown by {@code runnable}
* @since 4.13
*/
public static <T extends Throwable> T expectThrows(
Class<T> expectedThrowable, ThrowingRunnable runnable) {
try {
runnable.run();
} catch (Throwable actualThrown) {
if (expectedThrowable.isInstance(actualThrown)) {
@SuppressWarnings("unchecked")
T retVal = (T) actualThrown;
return retVal;
} else {
String expected = formatClass(expectedThrowable);
Class<? extends Throwable> actualThrowable = actualThrown.getClass();
String actual = formatClass(actualThrowable);
if (expected.equals(actual)) {
// There must be multiple class loaders. Add the identity hash code so the message
// doesn't say "expected: java.lang.String<my.package.MyException> ..."
expected += "@" + Integer.toHexString(System.identityHashCode(expectedThrowable));
actual += "@" + Integer.toHexString(System.identityHashCode(actualThrowable));
}
String mismatchMessage = format("unexpected exception type thrown;", expected, actual);
// The AssertionError(String, Throwable) ctor is only available on JDK7.
AssertionError assertionError = new AssertionError(mismatchMessage);
assertionError.initCause(actualThrown);
throw assertionError;
}
}
String message =
String.format(
"expected %s to be thrown, but nothing was thrown", formatClass(expectedThrowable));
throw new AssertionError(message);
}
static String format(String message, Object expected, Object actual) {
String formatted = "";
if (message != null && !"".equals(message)) {
formatted = message + " ";
}
String expectedString = String.valueOf(expected);
String actualString = String.valueOf(actual);
if (equalsRegardingNull(expectedString, actualString)) {
return formatted
+ "expected: "
+ formatClassAndValue(expected, expectedString)
+ " but was: "
+ formatClassAndValue(actual, actualString);
} else {
return formatted + "expected:<" + expectedString + "> but was:<" + actualString + ">";
}
}
private static String formatClass(Class<?> value) {
String className = value.getCanonicalName();
return className == null ? value.getName() : className;
}
private static String formatClassAndValue(Object value, String valueString) {
String className = value == null ? "null" : value.getClass().getName();
return className + "<" + valueString + ">";
}
private static boolean equalsRegardingNull(Object expected, Object actual) {
if (expected == null) {
return actual == null;
}
return isEquals(expected, actual);
}
private static boolean isEquals(Object expected, Object actual) {
return expected.equals(actual);
}
}

View file

@ -14,9 +14,10 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import org.junit.Rule; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -24,27 +25,26 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class LabelDescriptorTest { public class LabelDescriptorTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testCreate_invalidLabel_throwsException() { public void testCreate_invalidLabel_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Label name must match the regex"); expectThrows(
LabelDescriptor.create("@", "description"); IllegalArgumentException.class, () -> LabelDescriptor.create("@", "description"));
assertThat(thrown).hasMessageThat().contains("Label name must match the regex");
} }
@Test @Test
public void testCreate_blankNameField_throwsException() { public void testCreate_blankNameField_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Name must not be empty"); expectThrows(
LabelDescriptor.create("", "description"); IllegalArgumentException.class, () -> LabelDescriptor.create("", "description"));
assertThat(thrown).hasMessageThat().contains("Name must not be empty");
} }
@Test @Test
public void testCreate_blankDescriptionField_throwsException() { public void testCreate_blankDescriptionField_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Description must not be empty"); expectThrows(IllegalArgumentException.class, () -> LabelDescriptor.create("name", ""));
LabelDescriptor.create("name", ""); assertThat(thrown).hasMessageThat().contains("Description must not be empty");
} }
} }

View file

@ -15,65 +15,55 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link LinearFitter}. */ /** Unit tests for {@link LinearFitter}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class LinearFitterTest { public class LinearFitterTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testCreateLinearFitter_zeroNumIntervals_throwsException() throws Exception { public void testCreateLinearFitter_zeroNumIntervals_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("numFiniteIntervals must be greater than 0"); expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0));
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
LinearFitter.create(0, 3.0, 0.0);
} }
@Test @Test
public void testCreateLinearFitter_negativeNumIntervals_throwsException() throws Exception { public void testCreateLinearFitter_negativeNumIntervals_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("numFiniteIntervals must be greater than 0"); expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0));
assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0");
LinearFitter.create(0, 3.0, 0.0);
} }
@Test @Test
public void testCreateLinearFitter_zeroWidth_throwsException() throws Exception { public void testCreateLinearFitter_zeroWidth_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("width must be greater than 0"); expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0));
assertThat(thrown).hasMessageThat().contains("width must be greater than 0");
LinearFitter.create(3, 0.0, 0.0);
} }
@Test @Test
public void testCreateLinearFitter_negativeWidth_throwsException() throws Exception { public void testCreateLinearFitter_negativeWidth_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("width must be greater than 0"); expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0));
assertThat(thrown).hasMessageThat().contains("width must be greater than 0");
LinearFitter.create(3, 0.0, 0.0);
} }
@Test @Test
public void testCreateLinearFitter_NaNWidth_throwsException() throws Exception { public void testCreateLinearFitter_NaNWidth_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("width must be greater than 0"); expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, Double.NaN, 0.0));
assertThat(thrown).hasMessageThat().contains("width must be greater than 0");
LinearFitter.create(3, Double.NaN, 0.0);
} }
@Test @Test
public void testCreateLinearFitter_NaNOffset_throwsException() throws Exception { public void testCreateLinearFitter_NaNOffset_throwsException() throws Exception {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("value must be finite, not NaN, and not -0.0"); expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 1.0, Double.NaN));
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
LinearFitter.create(3, 1.0, Double.NaN);
} }
@Test @Test

View file

@ -15,6 +15,7 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -22,9 +23,7 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.monitoring.metrics.MetricSchema.Kind; import google.registry.monitoring.metrics.MetricSchema.Kind;
import org.junit.After; import org.junit.After;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -36,9 +35,6 @@ import org.junit.runners.JUnit4;
*/ */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class MetricRegistryImplTest { public class MetricRegistryImplTest {
@Rule public final ExpectedException thrown = ExpectedException.none();
private final LabelDescriptor label = private final LabelDescriptor label =
LabelDescriptor.create("test_labelname", "test_labeldescription"); LabelDescriptor.create("test_labelname", "test_labeldescription");
@ -162,8 +158,10 @@ public class MetricRegistryImplTest {
Boolean.class); Boolean.class);
MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric); MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric);
thrown.expect(IllegalStateException.class); IllegalStateException thrown =
thrown.expectMessage("Duplicate metric of same name"); expectThrows(
MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric); IllegalStateException.class,
() -> MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric));
assertThat(thrown).hasMessageThat().contains("Duplicate metric of same name");
} }
} }

View file

@ -14,11 +14,12 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.monitoring.metrics.MetricSchema.Kind; import google.registry.monitoring.metrics.MetricSchema.Kind;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -26,37 +27,59 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class MetricSchemaTest { public class MetricSchemaTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testCreate_blankNameField_throwsException() { public void testCreate_blankNameField_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Name must not be blank"); expectThrows(
IllegalArgumentException.class,
() ->
MetricSchema.create( MetricSchema.create(
"", "description", "valueDisplayName", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of()); "",
"description",
"valueDisplayName",
Kind.GAUGE,
ImmutableSet.<LabelDescriptor>of()));
assertThat(thrown).hasMessageThat().contains("Name must not be blank");
} }
@Test @Test
public void testCreate_blankDescriptionField_throwsException() { public void testCreate_blankDescriptionField_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Description must not be blank"); expectThrows(
IllegalArgumentException.class,
() ->
MetricSchema.create( MetricSchema.create(
"/name", "", "valueDisplayName", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of()); "/name",
"",
"valueDisplayName",
Kind.GAUGE,
ImmutableSet.<LabelDescriptor>of()));
assertThat(thrown).hasMessageThat().contains("Description must not be blank");
} }
@Test @Test
public void testCreate_blankValueDisplayNameField_throwsException() { public void testCreate_blankValueDisplayNameField_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Value Display Name must not be empty"); expectThrows(
MetricSchema.create("/name", "description", "", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of()); IllegalArgumentException.class,
() ->
MetricSchema.create(
"/name", "description", "", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of()));
assertThat(thrown).hasMessageThat().contains("Value Display Name must not be empty");
} }
@Test @Test
public void testCreate_nakedNames_throwsException() { public void testCreate_nakedNames_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("Name must be URL-like and start with a '/'"); expectThrows(
IllegalArgumentException.class,
() ->
MetricSchema.create( MetricSchema.create(
"foo", "description", "valueDisplayName", Kind.GAUGE, ImmutableSet.<LabelDescriptor>of()); "foo",
"description",
"valueDisplayName",
Kind.GAUGE,
ImmutableSet.<LabelDescriptor>of()));
assertThat(thrown).hasMessageThat().contains("Name must be URL-like and start with a '/'");
} }
} }

View file

@ -15,14 +15,13 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableRangeMap; import com.google.common.collect.ImmutableRangeMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -31,9 +30,6 @@ import org.junit.runners.JUnit4;
public class MutableDistributionTest { public class MutableDistributionTest {
private MutableDistribution distribution; private MutableDistribution distribution;
@Rule public final ExpectedException thrown = ExpectedException.none();
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
distribution = new MutableDistribution(CustomFitter.create(ImmutableSet.of(3.0, 5.0))); distribution = new MutableDistribution(CustomFitter.create(ImmutableSet.of(3.0, 5.0)));
@ -125,30 +121,34 @@ public class MutableDistributionTest {
@Test @Test
public void testAdd_negativeZero_throwsException() { public void testAdd_negativeZero_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("value must be finite, not NaN, and not -0.0"); expectThrows(
distribution.add(Double.longBitsToDouble(0x80000000)); IllegalArgumentException.class,
() -> distribution.add(Double.longBitsToDouble(0x80000000)));
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
} }
@Test @Test
public void testAdd_NaN_throwsException() { public void testAdd_NaN_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("value must be finite, not NaN, and not -0.0"); expectThrows(IllegalArgumentException.class, () -> distribution.add(Double.NaN));
distribution.add(Double.NaN); assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
} }
@Test @Test
public void testAdd_positiveInfinity_throwsException() { public void testAdd_positiveInfinity_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("value must be finite, not NaN, and not -0.0"); expectThrows(
distribution.add(Double.POSITIVE_INFINITY); IllegalArgumentException.class, () -> distribution.add(Double.POSITIVE_INFINITY));
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
} }
@Test @Test
public void testAdd_negativeInfinity_throwsException() { public void testAdd_negativeInfinity_throwsException() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage("value must be finite, not NaN, and not -0.0"); expectThrows(
distribution.add(Double.NEGATIVE_INFINITY); IllegalArgumentException.class, () -> distribution.add(Double.NEGATIVE_INFINITY));
assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0");
} }
@Test @Test

View file

@ -15,13 +15,12 @@
package google.registry.monitoring.metrics; package google.registry.monitoring.metrics;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import org.joda.time.Instant; import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -29,9 +28,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class StoredMetricTest { public class StoredMetricTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testGetCardinality_reflectsCurrentCardinality() { public void testGetCardinality_reflectsCurrentCardinality() {
StoredMetric<Boolean> smallMetric = StoredMetric<Boolean> smallMetric =
@ -68,11 +64,12 @@ public class StoredMetricTest {
LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")), LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")),
Boolean.class); Boolean.class);
thrown.expect(IllegalArgumentException.class); IllegalArgumentException thrown =
thrown.expectMessage( expectThrows(IllegalArgumentException.class, () -> dimensionalMetric.set(true, "foo"));
assertThat(thrown)
.hasMessageThat()
.contains(
"The count of labelValues must be equal to the underlying Metric's count of labels."); "The count of labelValues must be equal to the underlying Metric's count of labels.");
dimensionalMetric.set(true, "foo");
} }
@Test @Test

View file

@ -13,7 +13,7 @@ java_library(
deps = [ deps = [
"//java/google/registry/monitoring/metrics", "//java/google/registry/monitoring/metrics",
"//java/google/registry/monitoring/metrics/contrib", "//java/google/registry/monitoring/metrics/contrib",
"//javatests/google/registry/testing", "//javatests/google/registry/monitoring/metrics",
"@com_google_guava", "@com_google_guava",
"@com_google_truth", "@com_google_truth",
"@com_google_truth_extensions_truth_java8_extension", "@com_google_truth_extensions_truth_java8_extension",

View file

@ -15,8 +15,8 @@
package google.registry.monitoring.metrics.contrib; package google.registry.monitoring.metrics.contrib;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat; import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat;
import static google.registry.testing.JUnitBackports.expectThrows;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.monitoring.metrics.EventMetric; import google.registry.monitoring.metrics.EventMetric;

View file

@ -15,8 +15,8 @@
package google.registry.monitoring.metrics.contrib; package google.registry.monitoring.metrics.contrib;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.expectThrows;
import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat; import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.monitoring.metrics.IncrementableMetric; import google.registry.monitoring.metrics.IncrementableMetric;
@ -52,17 +52,15 @@ public class LongMetricSubjectTest {
@Test @Test
public void testWrongNumberOfLabels_fails() { public void testWrongNumberOfLabels_fails() {
try { AssertionError e =
assertThat(metric).hasValueForLabels(1, "Domestic"); expectThrows(
fail("Expected assertion error"); AssertionError.class, () -> assertThat(metric).hasValueForLabels(1, "Domestic"));
} catch (AssertionError e) {
assertThat(e) assertThat(e)
.hasMessageThat() .hasMessageThat()
.isEqualTo( .isEqualTo(
"Not true that </test/incrementable/sheep> has a value for labels <Domestic>." "Not true that </test/incrementable/sheep> has a value for labels <Domestic>."
+ " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>"); + " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>");
} }
}
@Test @Test
public void testDoesNotHaveWrongNumberOfLabels_succeeds() { public void testDoesNotHaveWrongNumberOfLabels_succeeds() {
@ -96,38 +94,40 @@ public class LongMetricSubjectTest {
@Test @Test
public void testDoesNotHaveValueForLabels_failure() { public void testDoesNotHaveValueForLabels_failure() {
try { AssertionError e =
assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green"); expectThrows(
fail("Expected assertion error"); AssertionError.class,
} catch (AssertionError e) { () -> assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green"));
assertThat(e) assertThat(e)
.hasMessageThat() .hasMessageThat()
.isEqualTo( .isEqualTo(
"Not true that </test/incrementable/sheep> has no value for labels <Domestic:Green>." "Not true that </test/incrementable/sheep> has no value for labels <Domestic:Green>."
+ " It has a value of <1>"); + " It has a value of <1>");
} }
}
@Test @Test
public void testWrongValue_failure() { public void testWrongValue_failure() {
try { AssertionError e =
assertThat(metric).hasValueForLabels(2, "Domestic", "Green"); expectThrows(
fail("Expected assertion error"); AssertionError.class,
} catch (AssertionError e) { () -> assertThat(metric).hasValueForLabels(2, "Domestic", "Green"));
assertThat(e) assertThat(e)
.hasMessageThat() .hasMessageThat()
.isEqualTo( .isEqualTo(
"Not true that </test/incrementable/sheep> has a value of 2" "Not true that </test/incrementable/sheep> has a value of 2"
+ " for labels <Domestic:Green>. It has a value of <1>"); + " for labels <Domestic:Green>. It has a value of <1>");
} }
}
@Test @Test
public void testUnexpectedValue_failure() { public void testUnexpectedValue_failure() {
try { AssertionError e =
assertThat(metric).hasValueForLabels(1, "Domestic", "Green").and().hasNoOtherValues(); expectThrows(
fail("Expected assertion error"); AssertionError.class,
} catch (AssertionError e) { () ->
assertThat(metric)
.hasValueForLabels(1, "Domestic", "Green")
.and()
.hasNoOtherValues());
assertThat(e) assertThat(e)
.hasMessageThat() .hasMessageThat()
.isEqualTo( .isEqualTo(
@ -135,4 +135,3 @@ public class LongMetricSubjectTest {
+ " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>"); + " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>");
} }
} }
}

View file

@ -13,6 +13,7 @@ java_library(
deps = [ deps = [
"//java/google/registry/monitoring/metrics", "//java/google/registry/monitoring/metrics",
"//java/google/registry/monitoring/metrics/stackdriver", "//java/google/registry/monitoring/metrics/stackdriver",
"//javatests/google/registry/monitoring/metrics",
"@com_google_api_client", "@com_google_api_client",
"@com_google_apis_google_api_services_monitoring", "@com_google_apis_google_api_services_monitoring",
"@com_google_guava", "@com_google_guava",

View file

@ -15,8 +15,8 @@
package google.registry.monitoring.metrics.stackdriver; package google.registry.monitoring.metrics.stackdriver;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.monitoring.metrics.JUnitBackports.assertThrows;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
@ -184,10 +184,7 @@ public class StackdriverWriterTest {
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
for (MetricPoint<?> point : metric.getTimestampedValues()) { for (MetricPoint<?> point : metric.getTimestampedValues()) {
try { assertThrows(IOException.class, () -> writer.write(point));
writer.write(point);
fail("expected IllegalArgumentException");
} catch (IOException expected) {}
} }
} }
@ -272,13 +269,9 @@ public class StackdriverWriterTest {
StackdriverWriter writer = StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
try { assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric));
writer.registerMetric(metric);
fail("Expected GoogleJsonResponseException");
} catch (GoogleJsonResponseException expected) {
assertThat(exception.getStatusCode()).isEqualTo(404); assertThat(exception.getStatusCode()).isEqualTo(404);
} }
}
@Test @Test
public void getEncodedTimeSeries_nullLabels_encodes() throws Exception { public void getEncodedTimeSeries_nullLabels_encodes() throws Exception {