From 5e282c85b95b6d3d131cef53958b4975baa11c0e Mon Sep 17 00:00:00 2001 From: Gregor Zeitlinger Date: Mon, 7 Oct 2024 15:30:09 +0200 Subject: [PATCH] convert to junit 5 / use assertj everywhere (#1092) * include common test dependencies by default Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to assertj Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger * convert to junit5 Signed-off-by: Gregor Zeitlinger --------- Signed-off-by: Gregor Zeitlinger --- .../ManualCompleteMetricsTest.java | 2 +- .../prometheus/client/it/common/Volume.java | 10 +- .../it-exporter/it-exporter-test/pom.xml | 13 +- .../metrics/it/exporter/test/ExporterIT.java | 168 ++++--- .../it/exporter/test/HttpServerIT.java | 10 + .../metrics/it/exporter/test/JettyIT.java | 10 + .../metrics/it/exporter/test/TomcatIT.java | 10 + integration-tests/it-pushgateway/pom.xml | 4 + .../it/pushgateway/PushGatewayTestApp.java | 2 +- .../metrics/it/pushgateway/PushGatewayIT.java | 35 +- pom.xml | 28 ++ prometheus-metrics-config/pom.xml | 10 - .../PrometheusPropertiesLoaderTests.java | 45 +- .../config/PrometheusPropertiesTest.java | 22 +- prometheus-metrics-core/pom.xml | 6 - .../metrics/core/datapoints/TimerApiTest.java | 2 +- .../core/exemplars/ExemplarSamplerTest.java | 19 +- .../exemplars/SpanContextSupplierTest.java | 23 +- .../core/metrics/CKMSQuantilesTest.java | 72 +-- .../metrics/core/metrics/CounterTest.java | 150 ++++--- .../core/metrics/CounterWithCallbackTest.java | 24 +- .../metrics/core/metrics/GaugeTest.java | 50 +-- .../core/metrics/GaugeWithCallbackTest.java | 23 +- .../metrics/core/metrics/HistogramTest.java | 267 +++++------ .../metrics/core/metrics/InfoTest.java | 45 +- .../core/metrics/SlidingWindowTest.java | 30 +- .../metrics/core/metrics/StateSetTest.java | 51 ++- .../core/metrics/StatefulMetricTest.java | 30 +- .../metrics/core/metrics/SummaryTest.java | 104 +++-- .../core/metrics/SummaryWithCallbackTest.java | 30 +- .../metrics/core/metrics/TestUtil.java | 10 +- .../metrics/core/metrics/TodoTest.java | 2 +- .../pom.xml | 6 - .../exporter/opentelemetry/ExemplarTest.java | 49 +- .../pom.xml | 23 +- .../pushgateway/BasicAuthPushGatewayTest.java | 22 +- .../BearerTokenPushGatewayTest.java | 21 +- .../exporter/pushgateway/PushGatewayTest.java | 103 +++-- prometheus-metrics-exposition-formats/pom.xml | 8 - .../ExpositionFormatsTest.java | 420 ++++++------------ .../pom.xml | 22 +- .../caffeine/CacheMetricsCollectorTest.java | 29 +- .../pom.xml | 21 +- .../dropwizard5/DropwizardExportsTest.java | 94 ++-- .../labels/CustomLabelMapperTest.java | 37 +- .../labels/GraphiteNamePatternTest.java | 21 +- .../dropwizard5/labels/MapperConfigTest.java | 33 +- .../pom.xml | 22 - .../guava/CacheMetricsCollectorTest.java | 14 +- .../pom.xml | 12 - .../jvm/ExampleExporterForManualTesting.java | 2 +- .../jvm/JvmBufferPoolMetricsTest.java | 15 +- .../jvm/JvmClassLoadingMetricsTest.java | 15 +- .../jvm/JvmCompilationMetricsTest.java | 17 +- .../jvm/JvmGarbageCollectorMetricsTest.java | 17 +- .../jvm/JvmMemoryMetricsTest.java | 15 +- .../JvmMemoryPoolAllocationMetricsTest.java | 23 +- .../instrumentation/jvm/JvmMetricsTest.java | 11 +- .../jvm/JvmNativeMemoryMetricsTest.java | 17 +- .../jvm/JvmRuntimeInfoMetricTest.java | 11 +- .../jvm/JvmThreadsMetricsTest.java | 23 +- .../jvm/ProcessMetricsTest.java | 29 +- .../metrics/instrumentation/jvm/TestUtil.java | 2 +- prometheus-metrics-model/pom.xml | 10 - .../model/registry/MetricNameFilterTest.java | 29 +- .../MultiCollectorNameFilterTest.java | 131 +++--- .../registry/PrometheusRegistryTest.java | 35 +- .../ClassicHistogramBucketsTest.java | 89 ++-- .../model/snapshots/CounterSnapshotTest.java | 59 +-- .../metrics/model/snapshots/ExemplarTest.java | 63 +-- .../model/snapshots/ExemplarsTest.java | 37 +- .../model/snapshots/GaugeSnapshotTest.java | 64 +-- .../snapshots/HistogramSnapshotTest.java | 143 +++--- .../model/snapshots/InfoSnapshotTest.java | 32 +- .../metrics/model/snapshots/LabelsTest.java | 84 ++-- .../model/snapshots/MetricMetadataTest.java | 53 ++- .../model/snapshots/MetricSnapshotTest.java | 56 +-- .../model/snapshots/MetricSnapshotsTest.java | 31 +- .../snapshots/NativeHistogramBucketsTest.java | 43 +- .../model/snapshots/PrometheusNamingTest.java | 116 ++--- .../model/snapshots/QuantilesTest.java | 40 +- .../model/snapshots/SnapshotTestUtil.java | 12 +- .../model/snapshots/StateSetSnapshotTest.java | 102 +++-- .../model/snapshots/SummarySnapshotTest.java | 59 +-- .../metrics/model/snapshots/UnitTest.java | 20 +- .../model/snapshots/UnknownSnapshotTest.java | 47 +- .../pom.xml | 6 - .../bridge/SimpleclientCollectorTest.java | 35 +- .../simpleclient_graphite_bridge/pom.xml | 7 - .../client/bridge/GraphiteTest.java | 2 +- .../simpleclient_hibernate/pom.xml | 17 +- .../HibernateStatisticsCollector.java | 2 +- .../HibernateStatisticsCollectorTest.java | 4 +- .../simpleclient_httpserver/pom.xml | 12 - .../client/exporter/TestDaemonFlags.java | 2 +- .../client/exporter/TestHTTPServer.java | 2 +- .../simpleclient_jetty/pom.xml | 6 - .../jetty/JettyStatisticsCollectorTest.java | 2 +- .../simpleclient_jetty_jdk8/pom.xml | 6 - ...euedThreadPoolStatisticsCollectorTest.java | 2 +- .../simpleclient_log4j/pom.xml | 14 - .../log4j/InstrumentedAppenderTest.java | 2 +- .../simpleclient_log4j2/pom.xml | 14 - .../log4j2/InstrumentedAppenderTest.java | 2 +- .../simpleclient_logback/pom.xml | 15 - .../logback/InstrumentedAppenderTest.java | 2 +- .../simpleclient_servlet/pom.xml | 18 - .../simpleclient_servlet_common/pom.xml | 13 - .../servlet/common/exporter/ExporterTest.java | 2 +- .../servlet/common/filter/FilterTest.java | 2 +- .../simpleclient_servlet_jakarta/pom.xml | 18 - .../simpleclient_spring_web/pom.xml | 6 - .../client/spring/web/MethodTimerAppTest.java | 4 +- .../client/spring/web/MethodTimerTest.java | 2 +- .../simpleclient_vertx/pom.xml | 13 - .../client/vertx/MetricsHandlerTest.java | 2 +- .../simpleclient_vertx4/pom.xml | 13 - .../client/vertx/MetricsHandlerTest.java | 2 +- 118 files changed, 1926 insertions(+), 2139 deletions(-) create mode 100644 integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/HttpServerIT.java create mode 100644 integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/JettyIT.java create mode 100644 integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/TomcatIT.java diff --git a/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java b/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java index b8b8ef98b..7a2715647 100644 --- a/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java +++ b/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java @@ -17,7 +17,7 @@ import java.util.Random; */ -public class ManualCompleteMetricsTest { +class ManualCompleteMetricsTest { // This contains a complete set of all metric types, and target_info and otel_scope_info. // I used this to expose in Prometheus format and OTLP format at the same time and compare the diff --git a/integration-tests/it-common/src/test/java/io/prometheus/client/it/common/Volume.java b/integration-tests/it-common/src/test/java/io/prometheus/client/it/common/Volume.java index 783ccb7a5..af5b0918e 100644 --- a/integration-tests/it-common/src/test/java/io/prometheus/client/it/common/Volume.java +++ b/integration-tests/it-common/src/test/java/io/prometheus/client/it/common/Volume.java @@ -1,6 +1,8 @@ package io.prometheus.client.it.common; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.File; import java.io.IOException; @@ -8,7 +10,6 @@ import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.function.Predicate; -import org.junit.Assert; /** Temporary directory in ./target/ to be mounted as a volume in Docker containers. */ public class Volume { @@ -21,8 +22,9 @@ private Volume(Path tmpDir) { public static Volume create(String prefix) throws IOException, URISyntaxException { Path targetDir = Paths.get(Volume.class.getResource("/").toURI()).getParent(); - Assert.assertEquals( - "failed to locate target/ directory", "target", targetDir.getFileName().toString()); + assertThat(targetDir.getFileName().toString()) + .as("failed to locate target/ directory") + .isEqualTo("target"); return new Volume(Files.createTempDirectory(targetDir, prefix + "-")); } @@ -59,7 +61,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) } }); } else { - Assert.fail(src + ": No such file or directory"); + fail(src + ": No such file or directory"); } return this; } diff --git a/integration-tests/it-exporter/it-exporter-test/pom.xml b/integration-tests/it-exporter/it-exporter-test/pom.xml index 899a17f10..5135e35e1 100644 --- a/integration-tests/it-exporter/it-exporter-test/pom.xml +++ b/integration-tests/it-exporter/it-exporter-test/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 @@ -15,6 +16,10 @@ Integration Tests for Exporters + + true + + The Apache Software License, Version 2.0 @@ -37,12 +42,6 @@ prometheus-metrics-exposition-formats ${project.version} - - junit - junit - 4.13.2 - test - org.testcontainers testcontainers diff --git a/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/ExporterIT.java b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/ExporterIT.java index 949f71840..b0e319190 100644 --- a/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/ExporterIT.java +++ b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/ExporterIT.java @@ -1,6 +1,8 @@ package io.prometheus.metrics.it.exporter.test; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import io.prometheus.client.it.common.LogConsumer; import io.prometheus.client.it.common.Volume; @@ -20,30 +22,17 @@ import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; import org.apache.commons.io.IOUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.GenericContainer; -@RunWith(Parameterized.class) -public class ExporterIT { +abstract class ExporterIT { private final GenericContainer sampleAppContainer; private final Volume sampleAppVolume; private final String sampleApp; - @Parameterized.Parameters(name = "{0}") - public static String[] sampleApps() { - return new String[] { - "exporter-httpserver-sample", - "exporter-servlet-tomcat-sample", - "exporter-servlet-jetty-sample", - }; - } - public ExporterIT(String sampleApp) throws IOException, URISyntaxException { this.sampleApp = sampleApp; this.sampleAppVolume = @@ -57,7 +46,7 @@ public ExporterIT(String sampleApp) throws IOException, URISyntaxException { .withExposedPorts(9400); } - @After + @AfterEach public void tearDown() throws IOException { sampleAppContainer.stop(); sampleAppVolume.remove(); @@ -70,22 +59,22 @@ public void testOpenMetricsTextFormat() throws IOException { .start(); Response response = scrape("GET", "", "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8"); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType( "application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type")); - Assert.assertNull(response.getHeader("Content-Encoding")); - Assert.assertNull(response.getHeader("Transfer-Encoding")); - Assert.assertEquals( - Integer.toString(response.body.length), response.getHeader("Content-Length")); + assertThat(response.getHeader("Content-Encoding")).isNull(); + assertThat(response.getHeader("Transfer-Encoding")).isNull(); + assertThat(response.getHeader("Content-Length")) + .isEqualTo(Integer.toString(response.body.length)); String bodyString = new String(response.body); - Assert.assertTrue( - bodyString.contains("integration_test_info{test_name=\"" + sampleApp + "\"} 1")); - Assert.assertTrue(bodyString.contains("temperature_celsius{location=\"inside\"} 23.0")); - Assert.assertTrue(bodyString.contains("temperature_celsius{location=\"outside\"} 27.0")); - Assert.assertTrue(bodyString.contains("uptime_seconds_total 17.0")); - // OpenMetrics text format has a UNIT. - Assert.assertTrue(bodyString.contains("# UNIT uptime_seconds seconds")); + assertThat(bodyString) + .contains("integration_test_info{test_name=\"" + sampleApp + "\"} 1") + .contains("temperature_celsius{location=\"inside\"} 23.0") + .contains("temperature_celsius{location=\"outside\"} 27.0") + .contains("uptime_seconds_total 17.0") + // OpenMetrics text format has a UNIT. + .contains("# UNIT uptime_seconds seconds"); } @Test @@ -94,21 +83,21 @@ public void testPrometheusTextFormat() throws IOException { .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success") .start(); Response response = scrape("GET", ""); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType( "text/plain; version=0.0.4; charset=utf-8", response.getHeader("Content-Type")); - Assert.assertNull(response.getHeader("Content-Encoding")); - Assert.assertNull(response.getHeader("Transfer-Encoding")); - Assert.assertEquals( - Integer.toString(response.body.length), response.getHeader("Content-Length")); + assertThat(response.getHeader("Content-Encoding")).isNull(); + assertThat(response.getHeader("Transfer-Encoding")).isNull(); + assertThat(response.getHeader("Content-Length")) + .isEqualTo(Integer.toString(response.body.length)); String bodyString = new String(response.body); - Assert.assertTrue( - bodyString.contains("integration_test_info{test_name=\"" + sampleApp + "\"} 1")); - Assert.assertTrue(bodyString.contains("temperature_celsius{location=\"inside\"} 23.0")); - Assert.assertTrue(bodyString.contains("temperature_celsius{location=\"outside\"} 27.0")); - Assert.assertTrue(bodyString.contains("uptime_seconds_total 17.0")); - // Prometheus text format does not have a UNIT. - Assert.assertFalse(bodyString.contains("# UNIT uptime_seconds seconds")); + assertThat(bodyString) + .contains("integration_test_info{test_name=\"" + sampleApp + "\"} 1") + .contains("temperature_celsius{location=\"inside\"} 23.0") + .contains("temperature_celsius{location=\"outside\"} 27.0") + .contains("uptime_seconds_total 17.0") + // Prometheus text format does not have a UNIT. + .doesNotContain("# UNIT uptime_seconds seconds"); } @Test @@ -122,24 +111,24 @@ public void testPrometheusProtobufFormat() throws IOException { "", "Accept", "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited"); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType( "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited", response.getHeader("Content-Type")); - Assert.assertNull(response.getHeader("Content-Encoding")); - Assert.assertNull(response.getHeader("Transfer-Encoding")); - Assert.assertEquals( - Integer.toString(response.body.length), response.getHeader("Content-Length")); + assertThat(response.getHeader("Content-Encoding")).isNull(); + assertThat(response.getHeader("Transfer-Encoding")).isNull(); + assertThat(response.getHeader("Content-Length")) + .isEqualTo(Integer.toString(response.body.length)); List metrics = new ArrayList<>(); InputStream in = new ByteArrayInputStream(response.body); while (in.available() > 0) { metrics.add(Metrics.MetricFamily.parseDelimitedFrom(in)); } - Assert.assertEquals(3, metrics.size()); + assertThat(metrics.size()).isEqualTo(3); // metrics are sorted by name - Assert.assertEquals("integration_test_info", metrics.get(0).getName()); - Assert.assertEquals("temperature_celsius", metrics.get(1).getName()); - Assert.assertEquals("uptime_seconds_total", metrics.get(2).getName()); + assertThat(metrics.get(0).getName()).isEqualTo("integration_test_info"); + assertThat(metrics.get(1).getName()).isEqualTo("temperature_celsius"); + assertThat(metrics.get(2).getName()).isEqualTo("uptime_seconds_total"); } @Test @@ -155,16 +144,16 @@ public void testCompression() throws IOException { "application/openmetrics-text; version=1.0.0; charset=utf-8", "Accept-Encoding", "gzip"); - Assert.assertEquals(200, response.status); - Assert.assertEquals("gzip", response.getHeader("Content-Encoding")); + assertThat(response.status).isEqualTo(200); + assertThat(response.getHeader("Content-Encoding")).isEqualTo("gzip"); if (response.getHeader("Content-Length") != null) { // The servlet container might set a content length as the body is very small. - Assert.assertEquals( - Integer.toString(response.body.length), response.getHeader("Content-Length")); - Assert.assertNull(response.getHeader("Transfer-Encoding")); + assertThat(response.getHeader("Content-Length")) + .isEqualTo(Integer.toString(response.body.length)); + assertThat(response.getHeader("Transfer-Encoding")).isNull(); } else { // If no content length is set, transfer-encoding chunked must be used. - Assert.assertEquals("chunked", response.getHeader("Transfer-Encoding")); + assertThat(response.getHeader("Transfer-Encoding")).isEqualTo("chunked"); } assertContentType( "application/openmetrics-text; version=1.0.0; charset=utf-8", @@ -173,7 +162,7 @@ public void testCompression() throws IOException { new String( IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8); - Assert.assertTrue(body.contains("uptime_seconds_total 17.0")); + assertThat(body).contains("uptime_seconds_total 17.0"); } @Test @@ -182,8 +171,8 @@ public void testErrorHandling() throws IOException { .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "error") .start(); Response response = scrape("GET", ""); - Assert.assertEquals(500, response.status); - Assert.assertTrue(new String(response.body, UTF_8).contains("Simulating an error.")); + assertThat(response.status).isEqualTo(500); + assertThat(new String(response.body, UTF_8)).contains("Simulating an error."); } @Test @@ -193,11 +182,11 @@ public void testHeadRequest() throws IOException { .start(); Response fullResponse = scrape("GET", ""); int size = fullResponse.body.length; - Assert.assertTrue(size > 0); + assertThat(size > 0).isTrue(); Response headResponse = scrape("HEAD", ""); - Assert.assertEquals(200, headResponse.status); - Assert.assertEquals(Integer.toString(size), headResponse.getHeader("Content-Length")); - Assert.assertEquals(0, headResponse.body.length); + assertThat(headResponse.status).isEqualTo(200); + assertThat(headResponse.getHeader("Content-Length")).isEqualTo(Integer.toString(size)); + assertThat(headResponse.body.length).isZero(); } @Test @@ -206,11 +195,12 @@ public void testDebug() throws IOException { .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success") .start(); Response response = scrape("GET", "debug=openmetrics"); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType("text/plain; charset=utf-8", response.getHeader("Content-Type")); String bodyString = new String(response.body, UTF_8); - Assert.assertTrue(bodyString.contains("uptime_seconds_total 17.0")); - Assert.assertTrue(bodyString.contains("# UNIT uptime_seconds seconds")); + assertThat(bodyString) + .contains("uptime_seconds_total 17.0") + .contains("# UNIT uptime_seconds seconds"); } @Test @@ -224,15 +214,15 @@ public void testNameFilter() throws IOException { nameParam("integration_test_info") + "&" + nameParam("uptime_seconds_total"), "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8"); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType( "application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type")); String bodyString = new String(response.body, UTF_8); - Assert.assertTrue( - bodyString.contains("integration_test_info{test_name=\"" + sampleApp + "\"} 1")); - Assert.assertTrue(bodyString.contains("uptime_seconds_total 17.0")); - Assert.assertFalse(bodyString.contains("temperature_celsius")); + assertThat(bodyString) + .contains("integration_test_info{test_name=\"" + sampleApp + "\"} 1") + .contains("uptime_seconds_total 17.0") + .doesNotContain("temperature_celsius"); } @Test @@ -246,13 +236,13 @@ public void testEmptyResponseOpenMetrics() throws IOException { nameParam("none_existing"), "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8"); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType( "application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type")); - Assert.assertEquals( - Integer.toString(response.body.length), response.getHeader("Content-Length")); - Assert.assertEquals("# EOF\n", new String(response.body, UTF_8)); + assertThat(response.getHeader("Content-Length")) + .isEqualTo(Integer.toString(response.body.length)); + assertThat(new String(response.body, UTF_8)).isEqualTo("# EOF\n"); } @Test @@ -261,14 +251,14 @@ public void testEmptyResponseText() throws IOException { .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success") .start(); Response response = scrape("GET", nameParam("none_existing")); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType( "text/plain; version=0.0.4; charset=utf-8", response.getHeader("Content-Type")); if (response.getHeader("Content-Length") != null) { // HTTPServer does not send a zero content length, which is ok - Assert.assertEquals("0", response.getHeader("Content-Length")); + assertThat(response.getHeader("Content-Length")).isEqualTo("0"); } - Assert.assertEquals(0, response.body.length); + assertThat(response.body.length).isZero(); } @Test @@ -282,11 +272,11 @@ public void testEmptyResponseProtobuf() throws IOException { nameParam("none_existing"), "Accept", "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited"); - Assert.assertEquals(200, response.status); + assertThat(response.status).isEqualTo(200); assertContentType( "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited", response.getHeader("Content-Type")); - Assert.assertEquals(0, response.body.length); + assertThat(response.body.length).isZero(); } @Test @@ -302,13 +292,13 @@ public void testEmptyResponseGzipOpenMetrics() throws IOException { "application/openmetrics-text; version=1.0.0; charset=utf-8", "Accept-Encoding", "gzip"); - Assert.assertEquals(200, response.status); - Assert.assertEquals("gzip", response.getHeader("Content-Encoding")); + assertThat(response.status).isEqualTo(200); + assertThat(response.getHeader("Content-Encoding")).isEqualTo("gzip"); String body = new String( IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8); - Assert.assertEquals("# EOF\n", body); + assertThat(body).isEqualTo("# EOF\n"); } @Test @@ -317,13 +307,13 @@ public void testEmptyResponseGzipText() throws IOException { .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success") .start(); Response response = scrape("GET", nameParam("none_existing"), "Accept-Encoding", "gzip"); - Assert.assertEquals(200, response.status); - Assert.assertEquals("gzip", response.getHeader("Content-Encoding")); + assertThat(response.status).isEqualTo(200); + assertThat(response.getHeader("Content-Encoding")).isEqualTo("gzip"); String body = new String( IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8); - Assert.assertEquals(0, body.length()); + assertThat(body.length()).isZero(); } private String nameParam(String name) throws UnsupportedEncodingException { @@ -336,13 +326,13 @@ public void testDebugUnknown() throws IOException { .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success") .start(); Response response = scrape("GET", "debug=unknown"); - Assert.assertEquals(500, response.status); + assertThat(response.status).isEqualTo(500); assertContentType("text/plain; charset=utf-8", response.getHeader("Content-Type")); } private void assertContentType(String expected, String actual) { if (!expected.replace(" ", "").equals(actual)) { - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } } @@ -386,7 +376,7 @@ private Response scrape(String method, String queryString, String... requestHead if (exception != null) { exception.printStackTrace(); } - Assert.fail("timeout while getting metrics from " + url); + fail("timeout while getting metrics from " + url); return null; // will not happen } diff --git a/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/HttpServerIT.java b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/HttpServerIT.java new file mode 100644 index 000000000..4c7e61472 --- /dev/null +++ b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/HttpServerIT.java @@ -0,0 +1,10 @@ +package io.prometheus.metrics.it.exporter.test; + +import java.io.IOException; +import java.net.URISyntaxException; + +class HttpServerIT extends ExporterIT { + public HttpServerIT() throws IOException, URISyntaxException { + super("exporter-httpserver-sample"); + } +} diff --git a/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/JettyIT.java b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/JettyIT.java new file mode 100644 index 000000000..a3d3e7da6 --- /dev/null +++ b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/JettyIT.java @@ -0,0 +1,10 @@ +package io.prometheus.metrics.it.exporter.test; + +import java.io.IOException; +import java.net.URISyntaxException; + +class JettyIT extends ExporterIT { + public JettyIT() throws IOException, URISyntaxException { + super("exporter-servlet-jetty-sample"); + } +} diff --git a/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/TomcatIT.java b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/TomcatIT.java new file mode 100644 index 000000000..ea5e6b69d --- /dev/null +++ b/integration-tests/it-exporter/it-exporter-test/src/test/java/io/prometheus/metrics/it/exporter/test/TomcatIT.java @@ -0,0 +1,10 @@ +package io.prometheus.metrics.it.exporter.test; + +import java.io.IOException; +import java.net.URISyntaxException; + +class TomcatIT extends ExporterIT { + public TomcatIT() throws IOException, URISyntaxException { + super("exporter-servlet-tomcat-sample"); + } +} diff --git a/integration-tests/it-pushgateway/pom.xml b/integration-tests/it-pushgateway/pom.xml index 25ce45b12..1956f1dad 100644 --- a/integration-tests/it-pushgateway/pom.xml +++ b/integration-tests/it-pushgateway/pom.xml @@ -16,6 +16,10 @@ Integration tests for the Pushgateway Exporter + + true + + The Apache Software License, Version 2.0 diff --git a/integration-tests/it-pushgateway/src/main/java/io/prometheus/metrics/it/pushgateway/PushGatewayTestApp.java b/integration-tests/it-pushgateway/src/main/java/io/prometheus/metrics/it/pushgateway/PushGatewayTestApp.java index 6376b03fb..61032600b 100644 --- a/integration-tests/it-pushgateway/src/main/java/io/prometheus/metrics/it/pushgateway/PushGatewayTestApp.java +++ b/integration-tests/it-pushgateway/src/main/java/io/prometheus/metrics/it/pushgateway/PushGatewayTestApp.java @@ -18,7 +18,7 @@ import javax.net.ssl.X509TrustManager; /** Example application using the {@link PushGateway}. */ -public class PushGatewayTestApp { +class PushGatewayTestApp { public static void main(String[] args) throws IOException { if (args.length != 1) { diff --git a/integration-tests/it-pushgateway/src/test/java/io/prometheus/metrics/it/pushgateway/PushGatewayIT.java b/integration-tests/it-pushgateway/src/test/java/io/prometheus/metrics/it/pushgateway/PushGatewayIT.java index 7e1198a55..cf11671f3 100644 --- a/integration-tests/it-pushgateway/src/test/java/io/prometheus/metrics/it/pushgateway/PushGatewayIT.java +++ b/integration-tests/it-pushgateway/src/test/java/io/prometheus/metrics/it/pushgateway/PushGatewayIT.java @@ -1,5 +1,9 @@ package io.prometheus.metrics.it.pushgateway; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.data.Offset.offset; + import com.jayway.jsonpath.Criteria; import com.jayway.jsonpath.Filter; import com.jayway.jsonpath.JsonPath; @@ -10,10 +14,9 @@ import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; import net.minidev.json.JSONArray; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; @@ -27,7 +30,7 @@ public class PushGatewayIT { private GenericContainer prometheusContainer; private Volume sampleAppVolume; - @Before + @BeforeEach public void setUp() throws IOException, URISyntaxException { Network network = Network.newNetwork(); sampleAppVolume = Volume.create("it-pushgateway").copy("pushgateway-test-app.jar"); @@ -53,7 +56,7 @@ public void setUp() throws IOException, URISyntaxException { .withLogConsumer(LogConsumer.withPrefix("prometheus")); } - @After + @AfterEach public void tearDown() throws IOException { prometheusContainer.stop(); pushGatewayContainer.stop(); @@ -177,13 +180,13 @@ public void testProtobuf() throws IOException, InterruptedException { private void assertMetrics() throws IOException, InterruptedException { double value = getValue("my_batch_job_duration_seconds", "job", "pushgateway-test-app"); - Assert.assertEquals(0.5, value, 0.0); + assertThat(value).isCloseTo(0.5, offset(0.0)); value = getValue("file_sizes_bytes_bucket", "job", "pushgateway-test-app", "le", "512"); - Assert.assertEquals(0.0, value, 0.0); + assertThat(value).isCloseTo(0.0, offset(0.0)); value = getValue("file_sizes_bytes_bucket", "job", "pushgateway-test-app", "le", "1024"); - Assert.assertEquals(2.0, value, 0.0); + assertThat(value).isCloseTo(2.0, offset(0.0)); value = getValue("file_sizes_bytes_bucket", "job", "pushgateway-test-app", "le", "+Inf"); - Assert.assertEquals(3.0, value, 0.0); + assertThat(value).isCloseTo(3.0, offset(0.0)); } private double getValue(String name, String... labels) throws IOException, InterruptedException { @@ -195,13 +198,13 @@ private double getValue(String name, String... labels) throws IOException, Inter JSONArray result = JsonPath.parse(scrapeResponseJson) .read("$.data.result" + Filter.filter(criteria) + ".value[1]"); - Assert.assertEquals(1, result.size()); - return Double.valueOf(result.get(0).toString()); + assertThat(result.size()).isOne(); + return Double.parseDouble(result.get(0).toString()); } private void assertNativeHistogram() throws IOException, InterruptedException { double count = getNativeHistogramCount("file_sizes_bytes", "pushgateway-test-app"); - Assert.assertEquals(3, count, 0.0); + assertThat(count).isCloseTo(3, offset(0.0)); } private double getNativeHistogramCount(String name, String job) @@ -211,7 +214,7 @@ private double getNativeHistogramCount(String name, String job) JSONArray result = JsonPath.parse(scrapeResponseJson) .read("$.data.result" + Filter.filter(criteria) + ".value[1]"); - return Double.valueOf(result.get(0).toString()); + return Double.parseDouble(result.get(0).toString()); } private String scrape(String query) throws IOException, InterruptedException { @@ -242,7 +245,7 @@ private String scrape(String query) throws IOException, InterruptedException { Thread.sleep(250); timeRemaining -= 250; } - Assert.fail("timeout while scraping " + url); + fail("timeout while scraping " + url); return null; } @@ -251,7 +254,7 @@ private void awaitTermination(GenericContainer container, long timeout, TimeU long waitTimeMillis = 0; while (container.isRunning()) { if (waitTimeMillis > unit.toMillis(timeout)) { - Assert.fail( + fail( container.getContainerName() + " did not terminate after " + timeout diff --git a/pom.xml b/pom.xml index f55a754c2..75f31709f 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ UTF-8 --module-name-need-to-be-overriden-- + 5.11.2 @@ -87,6 +88,33 @@ + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + test + + + org.mockito + mockito-core + 5.12.0 + test + + + org.assertj + assertj-core + 3.26.3 + test + + + diff --git a/prometheus-metrics-config/pom.xml b/prometheus-metrics-config/pom.xml index 2d1e95c88..94f2904cb 100644 --- a/prometheus-metrics-config/pom.xml +++ b/prometheus-metrics-config/pom.xml @@ -35,14 +35,4 @@ fabian@fstab.de - - - - - junit - junit - 4.13.2 - test - - diff --git a/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesLoaderTests.java b/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesLoaderTests.java index 8d16eadb7..9da800c27 100644 --- a/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesLoaderTests.java +++ b/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesLoaderTests.java @@ -1,25 +1,25 @@ package io.prometheus.metrics.config; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.Properties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link PrometheusPropertiesLoader}. */ -public class PrometheusPropertiesLoaderTests { +class PrometheusPropertiesLoaderTests { @Test public void propertiesShouldBeLoadedFromPropertiesFile() { PrometheusProperties prometheusProperties = PrometheusPropertiesLoader.load(); - Assert.assertEquals( - 11, - prometheusProperties.getDefaultMetricProperties().getHistogramClassicUpperBounds().size()); - Assert.assertEquals( - 4, - prometheusProperties - .getMetricProperties("http_duration_seconds") - .getHistogramClassicUpperBounds() - .size()); - Assert.assertTrue(prometheusProperties.getExporterProperties().getExemplarsOnAllMetricTypes()); + assertThat(prometheusProperties.getDefaultMetricProperties().getHistogramClassicUpperBounds()) + .hasSize(11); + assertThat( + prometheusProperties + .getMetricProperties("http_duration_seconds") + .getHistogramClassicUpperBounds()) + .hasSize(4); + assertThat(prometheusProperties.getExporterProperties().getExemplarsOnAllMetricTypes()) + .isTrue(); } @Test @@ -32,15 +32,14 @@ public void externalPropertiesShouldOverridePropertiesFile() { properties.setProperty("io.prometheus.exporter.exemplarsOnAllMetricTypes", "false"); PrometheusProperties prometheusProperties = PrometheusPropertiesLoader.load(properties); - Assert.assertEquals( - 2, - prometheusProperties.getDefaultMetricProperties().getHistogramClassicUpperBounds().size()); - Assert.assertEquals( - 3, - prometheusProperties - .getMetricProperties("http_duration_seconds") - .getHistogramClassicUpperBounds() - .size()); - Assert.assertFalse(prometheusProperties.getExporterProperties().getExemplarsOnAllMetricTypes()); + assertThat(prometheusProperties.getDefaultMetricProperties().getHistogramClassicUpperBounds()) + .hasSize(2); + assertThat( + prometheusProperties + .getMetricProperties("http_duration_seconds") + .getHistogramClassicUpperBounds()) + .hasSize(3); + assertThat(prometheusProperties.getExporterProperties().getExemplarsOnAllMetricTypes()) + .isFalse(); } } diff --git a/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesTest.java b/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesTest.java index f9ef25a7a..cce7213a6 100644 --- a/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesTest.java +++ b/prometheus-metrics-config/src/test/java/io/prometheus/metrics/config/PrometheusPropertiesTest.java @@ -1,24 +1,20 @@ package io.prometheus.metrics.config; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; import java.io.InputStream; import java.util.Properties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PrometheusPropertiesTest { +class PrometheusPropertiesTest { @Test public void testPrometheusConfig() { PrometheusProperties result = PrometheusProperties.get(); - Assert.assertEquals( - 11, result.getDefaultMetricProperties().getHistogramClassicUpperBounds().size()); - Assert.assertEquals( - 4, - result - .getMetricProperties("http_duration_seconds") - .getHistogramClassicUpperBounds() - .size()); + assertThat(result.getDefaultMetricProperties().getHistogramClassicUpperBounds()).hasSize(11); + assertThat(result.getMetricProperties("http_duration_seconds").getHistogramClassicUpperBounds()) + .hasSize(4); } @Test @@ -30,8 +26,8 @@ public void testEmptyUpperBounds() throws IOException { .getResourceAsStream("emptyUpperBounds.properties")) { properties.load(stream); } - Assert.assertEquals(1, properties.size()); + assertThat(properties).hasSize(1); MetricsProperties.load("io.prometheus.metrics", properties); - Assert.assertEquals(0, properties.size()); + assertThat(properties).isEmpty(); } } diff --git a/prometheus-metrics-core/pom.xml b/prometheus-metrics-core/pom.xml index fd3c9a04f..5afaac18a 100644 --- a/prometheus-metrics-core/pom.xml +++ b/prometheus-metrics-core/pom.xml @@ -66,11 +66,5 @@ 3.6.1 test - - junit - junit - 4.13.2 - test - diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/datapoints/TimerApiTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/datapoints/TimerApiTest.java index 8c015f591..70755b938 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/datapoints/TimerApiTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/datapoints/TimerApiTest.java @@ -1,6 +1,6 @@ package io.prometheus.metrics.core.datapoints; -public class TimerApiTest { +class TimerApiTest { // TODO: Port this from the simpleclient SimpleTimerTest } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/ExemplarSamplerTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/ExemplarSamplerTest.java index 9d51ae17b..1572eb645 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/ExemplarSamplerTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/ExemplarSamplerTest.java @@ -1,16 +1,17 @@ package io.prometheus.metrics.core.exemplars; +import static org.assertj.core.api.Assertions.assertThat; + import io.prometheus.metrics.core.util.Scheduler; import io.prometheus.metrics.model.snapshots.Exemplar; import io.prometheus.metrics.model.snapshots.Exemplars; import io.prometheus.metrics.model.snapshots.Label; import io.prometheus.metrics.tracer.initializer.SpanContextSupplier; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ExemplarSamplerTest { +class ExemplarSamplerTest { private final int tick = 10; // Time step in milliseconds. Make this larger if the test is flaky. private final int sampleInterval = 10 * tick; // do not change this @@ -60,12 +61,12 @@ public void testCustomExemplarsBuckets() throws Exception { private io.prometheus.metrics.tracer.common.SpanContext origContext; - @Before + @BeforeEach public void setUp() { origContext = SpanContextSupplier.getSpanContext(); } - @After + @AfterEach public void tearDown() { SpanContextSupplier.setSpanContext(origContext); } @@ -185,7 +186,7 @@ public void testDefaultExemplarsNoBuckets() throws Exception { private void assertExemplars(ExemplarSampler sampler, double... values) { Exemplars exemplars = sampler.collect(); - Assert.assertEquals(values.length, exemplars.size()); + assertThat(exemplars.size()).isEqualTo(values.length); for (double value : values) { boolean found = false; for (Exemplar exemplar : exemplars) { @@ -194,7 +195,7 @@ private void assertExemplars(ExemplarSampler sampler, double... values) { break; } } - Assert.assertTrue(value + " not found", found); + assertThat(found).as(value + " not found").isTrue(); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/SpanContextSupplierTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/SpanContextSupplierTest.java index cc7005c77..6c89b48a5 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/SpanContextSupplierTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/exemplars/SpanContextSupplierTest.java @@ -1,15 +1,18 @@ package io.prometheus.metrics.core.exemplars; import static io.prometheus.metrics.model.snapshots.Exemplar.TRACE_ID; +import static org.assertj.core.api.Assertions.assertThat; import io.prometheus.metrics.config.ExemplarsProperties; import io.prometheus.metrics.model.snapshots.Exemplar; import io.prometheus.metrics.model.snapshots.Exemplars; import io.prometheus.metrics.tracer.common.SpanContext; import io.prometheus.metrics.tracer.initializer.SpanContextSupplier; -import org.junit.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SpanContextSupplierTest { +class SpanContextSupplierTest { public SpanContext makeSpanContext(String traceId, String spanId) { @@ -47,12 +50,12 @@ public void markCurrentSpanAsExemplar() {} null // histogram upper bounds ); - @Before + @BeforeEach public void setUp() { origSpanContext = SpanContextSupplier.getSpanContext(); } - @After + @AfterEach public void tearDown() { SpanContextSupplier.setSpanContext(origSpanContext); } @@ -71,9 +74,9 @@ public void testConstructorInjection() { SpanContextSupplier.setSpanContext(spanContextB); exemplarSampler.observe(1.0); Exemplars exemplars = exemplarSampler.collect(); - Assert.assertEquals(1, exemplars.size()); + assertThat(exemplars.size()).isOne(); Exemplar exemplar = exemplars.get(0); - Assert.assertEquals("A", exemplar.getLabels().get(TRACE_ID)); + assertThat(exemplar.getLabels().get(TRACE_ID)).isEqualTo("A"); } /** @@ -89,17 +92,17 @@ public void testUpdateSpanContext() throws InterruptedException { SpanContextSupplier.setSpanContext(spanContextB); exemplarSampler.observe(1.0); Exemplars exemplars = exemplarSampler.collect(); - Assert.assertEquals(1, exemplars.size()); + assertThat(exemplars.size()).isOne(); Exemplar exemplar = exemplars.get(0); - Assert.assertEquals("B", exemplar.getLabels().get(TRACE_ID)); + assertThat(exemplar.getLabels().get(TRACE_ID)).isEqualTo("B"); Thread.sleep(15); // more than the minimum retention period defined in config above. SpanContextSupplier.setSpanContext(spanContextA); exemplarSampler.observe(1.0); exemplars = exemplarSampler.collect(); - Assert.assertEquals(1, exemplars.size()); + assertThat(exemplars.size()).isOne(); exemplar = exemplars.get(0); - Assert.assertEquals("A", exemplar.getLabels().get(TRACE_ID)); + assertThat(exemplar.getLabels().get(TRACE_ID)).isEqualTo("A"); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CKMSQuantilesTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CKMSQuantilesTest.java index 326b0a463..19f32f677 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CKMSQuantilesTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CKMSQuantilesTest.java @@ -1,17 +1,17 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.core.metrics.CKMSQuantiles.Quantile; import java.util.*; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CKMSQuantilesTest { +class CKMSQuantilesTest { private final Quantile qMin = new Quantile(0.0, 0.00); private final Quantile q50 = new Quantile(0.5, 0.01); @@ -22,7 +22,7 @@ public class CKMSQuantilesTest { @Test public void testGetOnEmptyValues() { CKMSQuantiles ckms = new CKMSQuantiles(q50, q95, q99); - assertTrue(Double.isNaN(ckms.get(q95.quantile))); + assertThat(Double.isNaN(ckms.get(q95.quantile))).isTrue(); } @Test @@ -95,7 +95,7 @@ public void testGetWithAMillionElements() { ckms.insert(v); } validateResults(ckms); - assertTrue("sample size should be way below 1_000_000", ckms.samples.size() < 1000); + assertThat(ckms.samples).as("sample size should be way below 1_000_000").hasSizeLessThan(1000); } @Test @@ -108,7 +108,7 @@ public void testMin() { } validateResults(ckms); ckms.compress(); - assertEquals(2, ckms.samples.size()); + assertThat(ckms.samples).hasSize(2); } @Test @@ -121,7 +121,7 @@ public void testMax() { } validateResults(ckms); ckms.compress(); - assertEquals(2, ckms.samples.size()); + assertThat(ckms.samples).hasSize(2); } @Test @@ -134,7 +134,7 @@ public void testMinMax() { } validateResults(ckms); ckms.compress(); - assertEquals(2, ckms.samples.size()); + assertThat(ckms.samples).hasSize(2); } @Test @@ -146,7 +146,7 @@ public void testMinAndOthers() { ckms.insert(v); } validateResults(ckms); - assertTrue(ckms.samples.size() < 200); // should be a lot less than input.size() + assertThat(ckms.samples).hasSizeLessThan(200); // should be a lot less than input.size() } @Test @@ -158,7 +158,7 @@ public void testMaxAndOthers() { ckms.insert(v); } validateResults(ckms); - assertTrue(ckms.samples.size() < 200); // should be a lot less than input.size() + assertThat(ckms.samples).hasSizeLessThan(200); // should be a lot less than input.size() } @Test @@ -170,7 +170,7 @@ public void testMinMaxAndOthers() { ckms.insert(v); } validateResults(ckms); - assertTrue(ckms.samples.size() < 200); // should be a lot less than input.size() + assertThat(ckms.samples).hasSizeLessThan(200); // should be a lot less than input.size() } @Test @@ -183,7 +183,7 @@ public void testExactQuantile() { } validateResults(ckms); // With epsilon == 0 we need to keep all inputs in samples. - assertEquals(input.size(), ckms.samples.size()); + assertThat(ckms.samples).hasSameSizeAs(input); } @Test @@ -196,7 +196,7 @@ public void testExactAndOthers() { } validateResults(ckms); // With epsilon == 0 we need to keep all inputs in samples. - assertEquals(input.size(), ckms.samples.size()); + assertThat(ckms.samples).hasSameSizeAs(input); } @Test @@ -209,7 +209,7 @@ public void testExactAndMin() { } validateResults(ckms); // With epsilon == 0 we need to keep all inputs in samples. - assertEquals(input.size(), ckms.samples.size()); + assertThat(ckms.samples).hasSameSizeAs(input); } @Test @@ -260,15 +260,18 @@ public void testGetGaussian() { // ε-approximate quantiles relaxes the requirement // to finding an item with rank between (φ−ε)n and (φ+ε)n. - assertEquals(p10, ckms.get(0.1), errorBoundsNormalDistribution(0.1, 0.001, normalDistribution)); - assertEquals(mean, ckms.get(0.5), errorBoundsNormalDistribution(0.5, 0.01, normalDistribution)); - assertEquals(p90, ckms.get(0.9), errorBoundsNormalDistribution(0.9, 0.001, normalDistribution)); - assertEquals( - p95, ckms.get(0.95), errorBoundsNormalDistribution(0.95, 0.001, normalDistribution)); - assertEquals( - p99, ckms.get(0.99), errorBoundsNormalDistribution(0.99, 0.001, normalDistribution)); - - assertTrue("sample size should be below 1000", ckms.samples.size() < 1000); + assertThat(ckms.get(0.1)) + .isCloseTo(p10, offset(errorBoundsNormalDistribution(0.1, 0.001, normalDistribution))); + assertThat(ckms.get(0.5)) + .isCloseTo(mean, offset(errorBoundsNormalDistribution(0.5, 0.01, normalDistribution))); + assertThat(ckms.get(0.9)) + .isCloseTo(p90, offset(errorBoundsNormalDistribution(0.9, 0.001, normalDistribution))); + assertThat(ckms.get(0.95)) + .isCloseTo(p95, offset(errorBoundsNormalDistribution(0.95, 0.001, normalDistribution))); + assertThat(ckms.get(0.99)) + .isCloseTo(p99, offset(errorBoundsNormalDistribution(0.99, 0.001, normalDistribution))); + + assertThat(ckms.samples).as("sample size should be below 1000").hasSizeLessThan(1000); } double errorBoundsNormalDistribution(double p, double epsilon, NormalDistribution nd) { @@ -285,14 +288,14 @@ public void testIllegalArgumentException() { try { new Quantile(-1, 0); } catch (IllegalArgumentException e) { - assertEquals("Quantile must be between 0 and 1", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Quantile must be between 0 and 1"); } catch (Exception e) { fail("Wrong exception thrown" + e); } try { new Quantile(0.95, 2); } catch (IllegalArgumentException e) { - assertEquals("Epsilon must be between 0 and 1", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Epsilon must be between 0 and 1"); } catch (Exception e) { fail("Wrong exception thrown" + e); } @@ -314,14 +317,17 @@ private void validateSamples(CKMSQuantiles ckms) { for (CKMSQuantiles.Sample sample : ckms.samples) { String msg = "invalid sample " + sample + ": count=" + ckms.n + " r=" + r + " f(r)=" + ckms.f(r); - assertTrue(msg, sample.g + sample.delta <= ckms.f(r)); - assertTrue( - "Samples not ordered. Keep in mind that insertBatch() takes a sorted array as parameter.", - prev <= sample.value); + assertThat(sample.g + sample.delta).as(msg).isLessThanOrEqualTo(ckms.f(r)); + assertThat(prev) + .as( + "Samples not ordered. Keep in mind that insertBatch() takes a sorted array as parameter.") + .isLessThanOrEqualTo(sample.value); prev = sample.value; r += sample.g; } - assertEquals("the sum of all g's must be the total number of observations", r, ckms.n); + assertThat(ckms.n) + .as("the sum of all g's must be the total number of observations") + .isEqualTo(r); } /** @@ -365,7 +371,7 @@ private void validateResults(CKMSQuantiles ckms) { + ckms.n + "=" + (q.quantile * ckms.n); - assertTrue(errorMessage, ok); + assertThat(ok).as(errorMessage).isTrue(); } } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterTest.java index 0c1408c56..087b230d2 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterTest.java @@ -1,16 +1,16 @@ package io.prometheus.metrics.core.metrics; import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.core.exemplars.ExemplarSamplerConfigTestUtil; import io.prometheus.metrics.expositionformats.PrometheusProtobufWriter; import io.prometheus.metrics.expositionformats.generated.com_google_protobuf_3_25_3.Metrics; import io.prometheus.metrics.model.snapshots.CounterSnapshot; import io.prometheus.metrics.model.snapshots.Exemplar; +import io.prometheus.metrics.model.snapshots.Label; import io.prometheus.metrics.model.snapshots.Labels; import io.prometheus.metrics.model.snapshots.Unit; import io.prometheus.metrics.shaded.com_google_protobuf_3_25_3.TextFormat; @@ -18,13 +18,11 @@ import io.prometheus.metrics.tracer.initializer.SpanContextSupplier; import java.util.Arrays; import java.util.Iterator; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class CounterTest { +class CounterTest { private Counter noLabels; private Counter labels; @@ -32,9 +30,7 @@ public class CounterTest { private static final long exemplarMinAgeMillis = 100; private SpanContext origSpanContext; - @Rule public final ExpectedException thrown = none(); - - @Before + @BeforeEach public void setUp() throws NoSuchFieldException, IllegalAccessException { noLabels = Counter.builder().name("nolabels").build(); labels = @@ -46,7 +42,7 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException { ExemplarSamplerConfigTestUtil.setMinRetentionPeriodMillis(labels, exemplarMinAgeMillis); } - @After + @AfterEach public void tearDown() { SpanContextSupplier.setSpanContext(origSpanContext); } @@ -72,38 +68,38 @@ private int getNumberOfLabels(Counter counter) { @Test public void testIncrement() { noLabels.inc(); - assertEquals(1.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(1.0, offset(.001)); noLabels.inc(2); - assertEquals(3.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(3.0, offset(.001)); noLabels.labelValues().inc(4); - assertEquals(7.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(7.0, offset(.001)); noLabels.labelValues().inc(); - assertEquals(8.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(8.0, offset(.001)); } @Test public void testNegativeIncrementFails() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Negative increment -1 is illegal for Counter metrics."); - noLabels.inc(-1); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> noLabels.inc(-1)) + .withMessage("Negative increment -1 is illegal for Counter metrics."); } @Test public void testEmptyCountersHaveNoLabels() { - assertEquals(1, getNumberOfLabels(noLabels)); - assertEquals(0, getNumberOfLabels(labels)); + assertThat(getNumberOfLabels(noLabels)).isOne(); + assertThat(getNumberOfLabels(labels)).isZero(); } @Test public void testLabels() { - assertEquals(0, getNumberOfLabels(labels)); + assertThat(getNumberOfLabels(labels)).isZero(); labels.labelValues("a").inc(); - assertEquals(1, getNumberOfLabels(labels)); - assertEquals(1.0, getValue(labels, "l", "a"), .001); + assertThat(getNumberOfLabels(labels)).isOne(); + assertThat(getValue(labels, "l", "a")).isCloseTo(1.0, offset(.001)); labels.labelValues("b").inc(3); - assertEquals(2, getNumberOfLabels(labels)); - assertEquals(1.0, getValue(labels, "l", "a"), .001); - assertEquals(3.0, getValue(labels, "l", "b"), .001); + assertThat(getNumberOfLabels(labels)).isEqualTo(2); + assertThat(getValue(labels, "l", "a")).isCloseTo(1.0, offset(.001)); + assertThat(getValue(labels, "l", "b")).isCloseTo(3.0, offset(.001)); } @Test @@ -117,9 +113,9 @@ public void testTotalStrippedFromName() { }) { Counter counter = Counter.builder().name(name).unit(Unit.SECONDS).build(); Metrics.MetricFamily protobufData = new PrometheusProtobufWriter().convert(counter.collect()); - assertEquals( - "name: \"my_counter_seconds_total\" type: COUNTER metric { counter { value: 0.0 } }", - TextFormat.printer().shortDebugString(protobufData)); + assertThat(TextFormat.printer().shortDebugString(protobufData)) + .isEqualTo( + "name: \"my_counter_seconds_total\" type: COUNTER metric { counter { value: 0.0 } }"); } } @@ -137,29 +133,45 @@ public void testSnapshotComplete() { counter.labelValues("/", "200").inc(2); counter.labelValues("/", "500").inc(); CounterSnapshot snapshot = counter.collect(); - assertEquals("test_seconds", snapshot.getMetadata().getName()); - assertEquals("seconds", snapshot.getMetadata().getUnit().toString()); - assertEquals("help message", snapshot.getMetadata().getHelp()); - assertEquals(2, snapshot.getDataPoints().size()); + assertThat(snapshot.getMetadata().getName()).isEqualTo("test_seconds"); + assertThat(snapshot.getMetadata().getUnit()).hasToString("seconds"); + assertThat(snapshot.getMetadata().getHelp()).isEqualTo("help message"); + assertThat(snapshot.getDataPoints()).hasSize(2); Iterator iter = snapshot.getDataPoints().iterator(); // data is ordered by labels, so 200 comes before 500 CounterSnapshot.CounterDataPointSnapshot data = iter.next(); - assertEquals( - Labels.of( - "const1name", "const1value", "const2name", "const2value", "path", "/", "status", "200"), - data.getLabels()); - assertEquals(2, data.getValue(), 0.0001); - assertTrue(data.getCreatedTimestampMillis() >= before); - assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis()); + assertThat((Iterable) data.getLabels()) + .isEqualTo( + Labels.of( + "const1name", + "const1value", + "const2name", + "const2value", + "path", + "/", + "status", + "200")); + assertThat(data.getValue()).isCloseTo(2, offset(0.0001)); + assertThat(data.getCreatedTimestampMillis()) + .isGreaterThanOrEqualTo(before) + .isLessThanOrEqualTo(System.currentTimeMillis()); // 500 data = iter.next(); - assertEquals( - Labels.of( - "const1name", "const1value", "const2name", "const2value", "path", "/", "status", "500"), - data.getLabels()); - assertEquals(1, data.getValue(), 0.0001); - assertTrue(data.getCreatedTimestampMillis() >= before); - assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis()); + assertThat((Iterable) data.getLabels()) + .isEqualTo( + Labels.of( + "const1name", + "const1value", + "const2name", + "const2value", + "path", + "/", + "status", + "500")); + assertThat(data.getValue()).isCloseTo(1, offset(0.0001)); + assertThat(data.getCreatedTimestampMillis()) + .isGreaterThanOrEqualTo(before) + .isLessThanOrEqualTo(System.currentTimeMillis()); } @Test @@ -180,8 +192,8 @@ public void testIncWithExemplar() throws Exception { private void assertExemplar(Counter counter, double value, String... labels) { Exemplar exemplar = getData(counter).getExemplar(); - assertEquals(value, exemplar.getValue(), 0.0001); - assertEquals(Labels.of(labels), exemplar.getLabels()); + assertThat(exemplar.getValue()).isCloseTo(value, offset(0.0001)); + assertThat((Iterable) exemplar.getLabels()).isEqualTo(Labels.of(labels)); } @Test @@ -291,26 +303,32 @@ public void testExemplarSamplerDisabled() { .withoutExemplars() .build(); counter.incWithExemplar(3.0, Labels.of("a", "b")); - assertNull(getData(counter).getExemplar()); + assertThat(getData(counter).getExemplar()).isNull(); counter.inc(2.0); - assertNull(getData(counter).getExemplar()); + assertThat(getData(counter).getExemplar()).isNull(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testConstLabelsFirst() { - Counter.builder() - .name("test_total") - .constLabels(Labels.of("const_a", "const_b")) - .labelNames("const.a") - .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + Counter.builder() + .name("test_total") + .constLabels(Labels.of("const_a", "const_b")) + .labelNames("const.a") + .build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testConstLabelsSecond() { - Counter.builder() - .name("test_total") - .labelNames("const.a") - .constLabels(Labels.of("const_a", "const_b")) - .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + Counter.builder() + .name("test_total") + .labelNames("const.a") + .constLabels(Labels.of("const_a", "const_b")) + .build()); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterWithCallbackTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterWithCallbackTest.java index e4af61bde..47c5f5c57 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterWithCallbackTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/CounterWithCallbackTest.java @@ -1,14 +1,16 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.model.snapshots.CounterSnapshot; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CounterWithCallbackTest { +class CounterWithCallbackTest { @Test public void testCounter() { @@ -23,20 +25,22 @@ public void testCounter() { .build(); CounterSnapshot snapshot = counter.collect(); - assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); CounterSnapshot.CounterDataPointSnapshot datapoint = snapshot.getDataPoints().get(0); - assertEquals(value.doubleValue(), datapoint.getValue(), 0.1); - assertEquals(labelValues.size(), datapoint.getLabels().size()); + assertThat(datapoint.getValue()).isCloseTo(value.doubleValue(), offset(0.1)); + assertThat(datapoint.getLabels().size()).isEqualTo(labelValues.size()); value.incrementAndGet(); snapshot = counter.collect(); - assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); datapoint = snapshot.getDataPoints().get(0); - assertEquals(value.doubleValue(), datapoint.getValue(), 0.1); + assertThat(datapoint.getValue()).isCloseTo(value.doubleValue(), offset(0.1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testCounterNoCallback() { - CounterWithCallback.builder().name("counter").labelNames("l1", "l2").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> CounterWithCallback.builder().name("counter").labelNames("l1", "l2").build()); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeTest.java index 0443cc7bf..1e48d63c0 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeTest.java @@ -1,8 +1,8 @@ package io.prometheus.metrics.core.metrics; import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.core.datapoints.Timer; import io.prometheus.metrics.core.exemplars.ExemplarSamplerConfigTestUtil; @@ -11,11 +11,11 @@ import io.prometheus.metrics.model.snapshots.Labels; import io.prometheus.metrics.tracer.common.SpanContext; import io.prometheus.metrics.tracer.initializer.SpanContextSupplier; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class GaugeTest { +class GaugeTest { private static final long exemplarSampleIntervalMillis = 10; private static final long exemplarMinAgeMillis = 100; @@ -24,14 +24,14 @@ public class GaugeTest { private SpanContext origSpanContext; - @Before + @BeforeEach public void setUp() { noLabels = Gauge.builder().name("nolabels").build(); labels = Gauge.builder().name("labels").labelNames("l").build(); origSpanContext = SpanContextSupplier.getSpanContext(); } - @After + @AfterEach public void tearDown() { SpanContextSupplier.setSpanContext(origSpanContext); } @@ -50,33 +50,33 @@ private double getValue(Gauge gauge, String... labels) { @Test public void testIncrement() { noLabels.inc(); - assertEquals(1.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(1.0, offset(.001)); noLabels.inc(2); - assertEquals(3.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(3.0, offset(.001)); noLabels.inc(4); - assertEquals(7.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(7.0, offset(.001)); noLabels.inc(); - assertEquals(8.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(8.0, offset(.001)); } @Test public void testDecrement() { noLabels.dec(); - assertEquals(-1.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(-1.0, offset(.001)); noLabels.dec(2); - assertEquals(-3.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(-3.0, offset(.001)); noLabels.dec(4); - assertEquals(-7.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(-7.0, offset(.001)); noLabels.dec(); - assertEquals(-8.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(-8.0, offset(.001)); } @Test public void testSet() { noLabels.set(42); - assertEquals(42, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(42, offset(.001)); noLabels.set(7); - assertEquals(7.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(7.0, offset(.001)); } @Test @@ -84,21 +84,21 @@ public void testTimer() throws InterruptedException { try (Timer timer = noLabels.startTimer()) { Thread.sleep(12); } - assertEquals( - 0.012, getValue(noLabels), 0.005); // 5ms delta should be enough so this isn't flaky + assertThat(getValue(noLabels)) + .isCloseTo(0.012, offset(0.005)); // 5ms delta should be enough so this isn't flaky } @Test public void noLabelsDefaultZeroValue() { - assertEquals(0.0, getValue(noLabels), .001); + assertThat(getValue(noLabels)).isCloseTo(0.0, offset(.001)); } @Test public void testLabels() { labels.labelValues("a").inc(); labels.labelValues("b").inc(3); - assertEquals(1.0, getValue(labels, "l", "a"), .001); - assertEquals(3.0, getValue(labels, "l", "b"), .001); + assertThat(getValue(labels, "l", "a")).isCloseTo(1.0, offset(.001)); + assertThat(getValue(labels, "l", "b")).isCloseTo(3.0, offset(.001)); } @Test @@ -202,8 +202,8 @@ public void markCurrentSpanAsExemplar() {} public void testExemplarSamplerDisabled() { Gauge gauge = Gauge.builder().name("test").withoutExemplars().build(); gauge.setWithExemplar(3.0, Labels.of("a", "b")); - assertNull(getData(gauge).getExemplar()); + assertThat(getData(gauge).getExemplar()).isNull(); gauge.inc(2.0); - assertNull(getData(gauge).getExemplar()); + assertThat(getData(gauge).getExemplar()).isNull(); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeWithCallbackTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeWithCallbackTest.java index 3a6a4ffac..92a2d605e 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeWithCallbackTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/GaugeWithCallbackTest.java @@ -1,14 +1,16 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.model.snapshots.GaugeSnapshot; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GaugeWithCallbackTest { +class GaugeWithCallbackTest { @Test public void testGauge() { @@ -23,20 +25,21 @@ public void testGauge() { .build(); GaugeSnapshot snapshot = gauge.collect(); - assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); GaugeSnapshot.GaugeDataPointSnapshot datapoint = snapshot.getDataPoints().get(0); - assertEquals(value.doubleValue(), datapoint.getValue(), 0.1); - assertEquals(labelValues.size(), datapoint.getLabels().size()); + assertThat(datapoint.getValue()).isCloseTo(value.doubleValue(), offset(0.1)); + assertThat(datapoint.getLabels().size()).isEqualTo(labelValues.size()); value.incrementAndGet(); snapshot = gauge.collect(); - assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); datapoint = snapshot.getDataPoints().get(0); - assertEquals(value.doubleValue(), datapoint.getValue(), 0.1); + assertThat(datapoint.getValue()).isCloseTo(value.doubleValue(), offset(0.1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testGaugeNoCallback() { - GaugeWithCallback.builder().name("gauge").labelNames("l1", "l2").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> GaugeWithCallback.builder().name("gauge").labelNames("l1", "l2").build()); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/HistogramTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/HistogramTest.java index 0b9f90260..1eb1121ad 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/HistogramTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/HistogramTest.java @@ -1,10 +1,9 @@ package io.prometheus.metrics.core.metrics; import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.core.datapoints.DistributionDataPoint; import io.prometheus.metrics.core.exemplars.ExemplarSamplerConfigTestUtil; @@ -41,11 +40,11 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class HistogramTest { +class HistogramTest { private static final double RESET_DURATION_REACHED = -123.456; // just a random value indicating that we should simulate that the reset duration @@ -53,12 +52,12 @@ public class HistogramTest { private SpanContext origSpanContext; - @Before + @BeforeEach public void setUp() { origSpanContext = SpanContextSupplier.getSpanContext(); } - @After + @AfterEach public void tearDown() { SpanContextSupplier.setSpanContext(origSpanContext); } @@ -93,10 +92,9 @@ private void run() throws NoSuchFieldException, IllegalAccessException { new PrometheusProtobufWriter().convert(histogram.collect()); String expectedWithMetadata = "name: \"test\" type: HISTOGRAM metric { histogram { " + expected + " } }"; - assertEquals( - "test \"" + name + "\" failed", - expectedWithMetadata, - TextFormat.printer().shortDebugString(protobufData)); + assertThat(TextFormat.printer().shortDebugString(protobufData)) + .as("test \"" + name + "\" failed") + .isEqualTo(expectedWithMetadata); } } @@ -829,11 +827,9 @@ public void testNativeBucketIndexToUpperBound() Histogram.builder().name("test").nativeInitialSchema(schemas[i]).build(); Histogram.DataPoint histogramData = histogram.newDataPoint(); double result = (double) method.invoke(histogramData, schemas[i], indexes[i]); - assertEquals( - "index=" + indexes[i] + ", schema=" + schemas[i], - expectedUpperBounds[i], - result, - 0.0000000000001); + assertThat(result) + .as("index=" + indexes[i] + ", schema=" + schemas[i]) + .isCloseTo(expectedUpperBounds[i], offset(0.0000000000001)); } } @@ -867,19 +863,20 @@ public void testFindBucketIndex() (double) nativeBucketIndexToUpperBound.invoke( histogram.getNoLabels(), schema, bucketIndex); - assertTrue( - "Bucket index " - + bucketIndex - + " with schema " - + schema - + " has range [" - + lowerBound - + ", " - + upperBound - + "]. Value " - + value - + " is outside of that range.", - lowerBound < value && upperBound >= value); + assertThat(lowerBound < value && upperBound >= value) + .as( + "Bucket index " + + bucketIndex + + " with schema " + + schema + + " has range [" + + lowerBound + + ", " + + upperBound + + "]. Value " + + value + + " is outside of that range.") + .isTrue(); } } } @@ -891,8 +888,7 @@ public void testDefaults() throws IOException { histogram.observe(0.5); HistogramSnapshot snapshot = histogram.collect(); String expectedProtobuf = - "" - + "name: \"test\" " + "name: \"test\" " + "type: HISTOGRAM " + "metric { " + "histogram { " @@ -925,9 +921,8 @@ public void testDefaults() throws IOException { + "positive_delta: 1 " + "} }"; String expectedTextFormat = - "" - // default classic buckets - + "# TYPE test histogram\n" + // default classic buckets + "# TYPE test histogram\n" + "test_bucket{le=\"0.005\"} 0\n" + "test_bucket{le=\"0.01\"} 0\n" + "test_bucket{le=\"0.025\"} 0\n" @@ -946,13 +941,13 @@ public void testDefaults() throws IOException { // protobuf Metrics.MetricFamily protobufData = new PrometheusProtobufWriter().convert(snapshot); - assertEquals(expectedProtobuf, TextFormat.printer().shortDebugString(protobufData)); + assertThat(TextFormat.printer().shortDebugString(protobufData)).isEqualTo(expectedProtobuf); // text ByteArrayOutputStream out = new ByteArrayOutputStream(); OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(false, true); writer.write(out, MetricSnapshots.of(snapshot)); - assertEquals(expectedTextFormat, out.toString()); + assertThat(out).hasToString(expectedTextFormat); } @Test @@ -1012,14 +1007,14 @@ public void markCurrentSpanAsExemplar() {} HistogramSnapshot snapshot = histogram.collect(); assertExemplarEquals(ex1a, getExemplar(snapshot, 1.0, "path", "/hello")); assertExemplarEquals(ex1b, getExemplar(snapshot, 1.0, "path", "/world")); - assertNull(getExemplar(snapshot, 2.0, "path", "/hello")); - assertNull(getExemplar(snapshot, 2.0, "path", "/world")); - assertNull(getExemplar(snapshot, 3.0, "path", "/hello")); - assertNull(getExemplar(snapshot, 3.0, "path", "/world")); - assertNull(getExemplar(snapshot, 4.0, "path", "/hello")); - assertNull(getExemplar(snapshot, 4.0, "path", "/world")); - assertNull(getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/hello")); - assertNull(getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/world")); + assertThat(getExemplar(snapshot, 2.0, "path", "/hello")).isNull(); + assertThat(getExemplar(snapshot, 2.0, "path", "/world")).isNull(); + assertThat(getExemplar(snapshot, 3.0, "path", "/hello")).isNull(); + assertThat(getExemplar(snapshot, 3.0, "path", "/world")).isNull(); + assertThat(getExemplar(snapshot, 4.0, "path", "/hello")).isNull(); + assertThat(getExemplar(snapshot, 4.0, "path", "/world")).isNull(); + assertThat(getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/hello")).isNull(); + assertThat(getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/world")).isNull(); Thread.sleep(sampleIntervalMillis + 1); histogram.labelValues("/hello").observe(4.5); @@ -1028,12 +1023,12 @@ public void markCurrentSpanAsExemplar() {} snapshot = histogram.collect(); assertExemplarEquals(ex1a, getExemplar(snapshot, 1.0, "path", "/hello")); assertExemplarEquals(ex1b, getExemplar(snapshot, 1.0, "path", "/world")); - assertNull(getExemplar(snapshot, 2.0, "path", "/hello")); - assertNull(getExemplar(snapshot, 2.0, "path", "/world")); - assertNull(getExemplar(snapshot, 3.0, "path", "/hello")); - assertNull(getExemplar(snapshot, 3.0, "path", "/world")); - assertNull(getExemplar(snapshot, 4.0, "path", "/hello")); - assertNull(getExemplar(snapshot, 4.0, "path", "/world")); + assertThat(getExemplar(snapshot, 2.0, "path", "/hello")).isNull(); + assertThat(getExemplar(snapshot, 2.0, "path", "/world")).isNull(); + assertThat(getExemplar(snapshot, 3.0, "path", "/hello")).isNull(); + assertThat(getExemplar(snapshot, 3.0, "path", "/world")).isNull(); + assertThat(getExemplar(snapshot, 4.0, "path", "/hello")).isNull(); + assertThat(getExemplar(snapshot, 4.0, "path", "/world")).isNull(); assertExemplarEquals(ex2a, getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/hello")); assertExemplarEquals(ex2b, getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/world")); @@ -1154,12 +1149,16 @@ private void assertExemplar(Histogram histogram, double value, String... labels) } } Exemplar exemplar = data.getExemplars().get(lowerBound, upperBound); - assertNotNull("No exemplar found in bucket [" + lowerBound + ", " + upperBound + "]", exemplar); - assertEquals(value, exemplar.getValue(), 0.0); - assertEquals("" + exemplar.getLabels(), labels.length / 2, exemplar.getLabels().size()); + assertThat(exemplar) + .as("No exemplar found in bucket [" + lowerBound + ", " + upperBound + "]") + .isNotNull(); + assertThat(exemplar.getValue()).isCloseTo(value, offset(0.0)); + assertThat(exemplar.getLabels().size()) + .as("" + exemplar.getLabels()) + .isEqualTo(labels.length / 2); for (int i = 0; i < labels.length; i += 2) { - assertEquals(labels[i], exemplar.getLabels().getName(i / 2)); - assertEquals(labels[i + 1], exemplar.getLabels().getValue(i / 2)); + assertThat(exemplar.getLabels().getName(i / 2)).isEqualTo(labels[i]); + assertThat(exemplar.getLabels().getValue(i / 2)).isEqualTo(labels[i + 1]); } } @@ -1207,59 +1206,69 @@ public void markCurrentSpanAsExemplar() {} histogram.labelValues("/hello").observe(3.11); histogram.labelValues("/world").observe(3.12); - assertEquals(1, getData(histogram, "path", "/hello").getExemplars().size()); + assertThat(getData(histogram, "path", "/hello").getExemplars().size()).isOne(); assertExemplarEquals( ex1, getData(histogram, "path", "/hello").getExemplars().iterator().next()); - assertEquals(1, getData(histogram, "path", "/world").getExemplars().size()); + assertThat(getData(histogram, "path", "/world").getExemplars().size()).isOne(); assertExemplarEquals( ex2, getData(histogram, "path", "/world").getExemplars().iterator().next()); histogram .labelValues("/world") .observeWithExemplar(3.13, Labels.of("key1", "value1", "key2", "value2")); - assertEquals(1, getData(histogram, "path", "/hello").getExemplars().size()); + assertThat(getData(histogram, "path", "/hello").getExemplars().size()).isOne(); assertExemplarEquals( ex1, getData(histogram, "path", "/hello").getExemplars().iterator().next()); - assertEquals(2, getData(histogram, "path", "/world").getExemplars().size()); + assertThat(getData(histogram, "path", "/world").getExemplars().size()).isEqualTo(2); Exemplars exemplars = getData(histogram, "path", "/world").getExemplars(); List exemplarList = new ArrayList<>(exemplars.size()); for (Exemplar exemplar : exemplars) { exemplarList.add(exemplar); } exemplarList.sort(Comparator.comparingDouble(Exemplar::getValue)); - assertEquals(2, exemplars.size()); + assertThat(exemplars.size()).isEqualTo(2); assertExemplarEquals(ex2, exemplarList.get(0)); assertExemplarEquals(ex3, exemplarList.get(1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalLabelName() { - Histogram.builder().name("test").labelNames("label", "le"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Histogram.builder().name("test").labelNames("label", "le")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalLabelNameConstLabels() { - Histogram.builder().name("test").constLabels(Labels.of("label1", "value1", "le", "0.3")); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + Histogram.builder() + .name("test") + .constLabels(Labels.of("label1", "value1", "le", "0.3"))); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalLabelNamePrefix() { - Histogram.builder().name("test").labelNames("__hello"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Histogram.builder().name("test").labelNames("__hello")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalName() { - Histogram.builder().name("my_namespace/server.durations"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Histogram.builder().name("my_namespace/server.durations")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNoName() { - Histogram.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Histogram.builder().build()); } - @Test(expected = NullPointerException.class) + @Test public void testNullName() { - Histogram.builder().name(null); + assertThatExceptionOfType(NullPointerException.class) + .isThrownBy(() -> Histogram.builder().name(null)); } @Test @@ -1270,7 +1279,8 @@ public void testDuplicateClassicBuckets() { getData(histogram).getClassicBuckets().stream() .map(ClassicHistogramBucket::getUpperBound) .collect(Collectors.toList()); - assertEquals(Arrays.asList(0.0, 3.0, 17.0, 21.0, Double.POSITIVE_INFINITY), upperBounds); + assertThat(upperBounds) + .isEqualTo(Arrays.asList(0.0, 3.0, 17.0, 21.0, Double.POSITIVE_INFINITY)); } @Test @@ -1280,7 +1290,7 @@ public void testUnsortedBuckets() { getData(histogram).getClassicBuckets().stream() .map(ClassicHistogramBucket::getUpperBound) .collect(Collectors.toList()); - assertEquals(Arrays.asList(0.1, 0.2, Double.POSITIVE_INFINITY), upperBounds); + assertThat(upperBounds).isEqualTo(Arrays.asList(0.1, 0.2, Double.POSITIVE_INFINITY)); } @Test @@ -1290,7 +1300,7 @@ public void testEmptyBuckets() { getData(histogram).getClassicBuckets().stream() .map(ClassicHistogramBucket::getUpperBound) .collect(Collectors.toList()); - assertEquals(Collections.singletonList(Double.POSITIVE_INFINITY), upperBounds); + assertThat(upperBounds).isEqualTo(Collections.singletonList(Double.POSITIVE_INFINITY)); } @Test @@ -1304,7 +1314,7 @@ public void testBucketsIncludePositiveInfinity() { getData(histogram).getClassicBuckets().stream() .map(ClassicHistogramBucket::getUpperBound) .collect(Collectors.toList()); - assertEquals(Arrays.asList(0.01, 0.1, 1.0, Double.POSITIVE_INFINITY), upperBounds); + assertThat(upperBounds).isEqualTo(Arrays.asList(0.01, 0.1, 1.0, Double.POSITIVE_INFINITY)); } @Test @@ -1315,9 +1325,10 @@ public void testLinearBuckets() { getData(histogram).getClassicBuckets().stream() .map(ClassicHistogramBucket::getUpperBound) .collect(Collectors.toList()); - assertEquals( - Arrays.asList(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, Double.POSITIVE_INFINITY), - upperBounds); + assertThat(upperBounds) + .isEqualTo( + Arrays.asList( + 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, Double.POSITIVE_INFINITY)); } @Test @@ -1328,20 +1339,22 @@ public void testExponentialBuckets() { getData(histogram).getClassicBuckets().stream() .map(ClassicHistogramBucket::getUpperBound) .collect(Collectors.toList()); - assertEquals(Arrays.asList(2.0, 5.0, 12.5, Double.POSITIVE_INFINITY), upperBounds); + assertThat(upperBounds).isEqualTo(Arrays.asList(2.0, 5.0, 12.5, Double.POSITIVE_INFINITY)); } - @Test(expected = RuntimeException.class) + @Test public void testBucketsIncludeNaN() { - Histogram.builder().name("test").classicUpperBounds(0.01, 0.1, 1.0, Double.NaN); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy( + () -> Histogram.builder().name("test").classicUpperBounds(0.01, 0.1, 1.0, Double.NaN)); } @Test public void testNoLabelsDefaultZeroValue() { Histogram noLabels = Histogram.builder().name("test").build(); - assertEquals(0.0, getBucket(noLabels, 0.005).getCount(), 0.0); - assertEquals(0, getData(noLabels).getCount()); - assertEquals(0.0, getData(noLabels).getSum(), 0.0); + assertThat(getBucket(noLabels, 0.005).getCount()).isZero(); + assertThat(getData(noLabels).getCount()).isZero(); + assertThat(getData(noLabels).getSum()).isCloseTo(0.0, offset(0.0)); } private ClassicHistogramBucket getBucket(Histogram histogram, double le, String... labels) { @@ -1355,18 +1368,18 @@ private ClassicHistogramBucket getBucket(Histogram histogram, double le, String. public void testObserve() { Histogram noLabels = Histogram.builder().name("test").build(); noLabels.observe(2); - assertEquals(1, getData(noLabels).getCount()); - assertEquals(2.0, getData(noLabels).getSum(), .0); - assertEquals(0.0, getBucket(noLabels, 1).getCount(), .0); - assertEquals(1.0, getBucket(noLabels, 2.5).getCount(), .0); + assertThat(getData(noLabels).getCount()).isOne(); + assertThat(getData(noLabels).getSum()).isCloseTo(2.0, offset(.0)); + assertThat(getBucket(noLabels, 1).getCount()).isZero(); + assertThat(getBucket(noLabels, 2.5).getCount()).isOne(); noLabels.observe(4); - assertEquals(2.0, getData(noLabels).getCount(), .0); - assertEquals(6.0, getData(noLabels).getSum(), .0); - assertEquals(0.0, getBucket(noLabels, 1).getCount(), .0); - assertEquals(1.0, getBucket(noLabels, 2.5).getCount(), .0); - assertEquals(1.0, getBucket(noLabels, 5).getCount(), .0); - assertEquals(0.0, getBucket(noLabels, 10).getCount(), .0); - assertEquals(0.0, getBucket(noLabels, Double.POSITIVE_INFINITY).getCount(), .0); + assertThat(getData(noLabels).getCount()).isEqualTo(2); + assertThat(getData(noLabels).getSum()).isCloseTo(6.0, offset(.0)); + assertThat(getBucket(noLabels, 1).getCount()).isZero(); + assertThat(getBucket(noLabels, 2.5).getCount()).isOne(); + assertThat(getBucket(noLabels, 5).getCount()).isOne(); + assertThat(getBucket(noLabels, 10).getCount()).isZero(); + assertThat(getBucket(noLabels, Double.POSITIVE_INFINITY).getCount()).isZero(); } @Test @@ -1384,8 +1397,8 @@ public void testNegativeAmount() { histogram.observe(i); expectedCount++; expectedSum += i; - assertEquals(expectedSum, getData(histogram).getSum(), .001); - assertEquals(expectedCount, getData(histogram).getCount(), .001); + assertThat(getData(histogram).getSum()).isCloseTo(expectedSum, offset(.001)); + assertThat(getData(histogram).getCount()).isEqualTo((long) expectedCount); } List expectedBucketCounts = Arrays.asList(2L, 5L, 5L, 5L, 5L, 0L); // buckets -10, -5, 0, 5, 10, +Inf @@ -1393,22 +1406,22 @@ public void testNegativeAmount() { getData(histogram).getClassicBuckets().stream() .map(ClassicHistogramBucket::getCount) .collect(Collectors.toList()); - assertEquals(expectedBucketCounts, actualBucketCounts); + assertThat(actualBucketCounts).isEqualTo(expectedBucketCounts); } @Test public void testBoundaryConditions() { Histogram histogram = Histogram.builder().name("test").build(); histogram.observe(2.5); - assertEquals(0, getBucket(histogram, 1).getCount()); - assertEquals(1, getBucket(histogram, 2.5).getCount()); + assertThat(getBucket(histogram, 1).getCount()).isZero(); + assertThat(getBucket(histogram, 2.5).getCount()).isOne(); histogram.observe(Double.POSITIVE_INFINITY); - assertEquals(0, getBucket(histogram, 1).getCount()); - assertEquals(1, getBucket(histogram, 2.5).getCount()); - assertEquals(0, getBucket(histogram, 5).getCount()); - assertEquals(0, getBucket(histogram, 10).getCount()); - assertEquals(1, getBucket(histogram, Double.POSITIVE_INFINITY).getCount()); + assertThat(getBucket(histogram, 1).getCount()).isZero(); + assertThat(getBucket(histogram, 2.5).getCount()).isOne(); + assertThat(getBucket(histogram, 5).getCount()).isZero(); + assertThat(getBucket(histogram, 10).getCount()).isZero(); + assertThat(getBucket(histogram, Double.POSITIVE_INFINITY).getCount()).isOne(); } @Test @@ -1426,17 +1439,17 @@ public void testObserveWithLabels() { getData(histogram, "env", "prod", "path", "/hello", "status", "200"); HistogramSnapshot.HistogramDataPointSnapshot data500 = getData(histogram, "env", "prod", "path", "/hello", "status", "500"); - assertEquals(2, data200.getCount()); - assertEquals(0.31, data200.getSum(), 0.0000001); - assertEquals(1, data500.getCount()); - assertEquals(0.19, data500.getSum(), 0.0000001); + assertThat(data200.getCount()).isEqualTo(2); + assertThat(data200.getSum()).isCloseTo(0.31, offset(0.0000001)); + assertThat(data500.getCount()).isOne(); + assertThat(data500.getSum()).isCloseTo(0.19, offset(0.0000001)); histogram.labelValues("/hello", "200").observe(0.13); data200 = getData(histogram, "env", "prod", "path", "/hello", "status", "200"); data500 = getData(histogram, "env", "prod", "path", "/hello", "status", "500"); - assertEquals(3, data200.getCount()); - assertEquals(0.44, data200.getSum(), 0.0000001); - assertEquals(1, data500.getCount()); - assertEquals(0.19, data500.getSum(), 0.0000001); + assertThat(data200.getCount()).isEqualTo(3); + assertThat(data200.getSum()).isCloseTo(0.44, offset(0.0000001)); + assertThat(data500.getCount()).isOne(); + assertThat(data500.getSum()).isCloseTo(0.19, offset(0.0000001)); } @Test @@ -1472,22 +1485,23 @@ public void testObserveMultithreaded() List snapshots = future.get(5, TimeUnit.SECONDS); long count = 0; for (HistogramSnapshot snapshot : snapshots) { - assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); HistogramSnapshot.HistogramDataPointSnapshot data = snapshot.getDataPoints().stream().findFirst().orElseThrow(RuntimeException::new); - assertTrue( - data.getCount() - >= (count + 1000)); // 1000 own observations plus the ones from other threads + assertThat(data.getCount()) + .isGreaterThanOrEqualTo( + (count + 1000)); // 1000 own observations plus the ones from other threads count = data.getCount(); } if (count > maxCount) { maxCount = count; } } - assertEquals(nThreads * 10_000, maxCount); // the last collect() has seen all observations - assertEquals(getBucket(histogram, 2.5, "status", "200").getCount(), nThreads * 10_000); + assertThat(maxCount) + .isEqualTo(nThreads * 10_000); // the last collect() has seen all observations + assertThat(nThreads * 10_000).isEqualTo(getBucket(histogram, 2.5, "status", "200").getCount()); executor.shutdown(); - assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); } private HistogramSnapshot.HistogramDataPointSnapshot getData( @@ -1495,9 +1509,6 @@ private HistogramSnapshot.HistogramDataPointSnapshot getData( return histogram.collect().getDataPoints().stream() .filter(d -> d.getLabels().equals(Labels.of(labels))) .findAny() - .orElseThrow( - () -> - new RuntimeException( - "histogram with labels " + Arrays.toString(labels) + " not found")); + .orElseThrow(() -> new RuntimeException("histogram with labels " + labels + " not found")); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/InfoTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/InfoTest.java index e527a3340..efdf211bb 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/InfoTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/InfoTest.java @@ -1,6 +1,7 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import io.prometheus.metrics.expositionformats.OpenMetricsTextFormatWriter; import io.prometheus.metrics.expositionformats.PrometheusProtobufWriter; @@ -11,9 +12,9 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class InfoTest { +class InfoTest { @Test public void testInfoStrippedFromName() { @@ -26,9 +27,9 @@ public void testInfoStrippedFromName() { Info info = Info.builder().name(name).labelNames(labelName).build(); info.addLabelValues("value"); Metrics.MetricFamily protobufData = new PrometheusProtobufWriter().convert(info.collect()); - assertEquals( - "name: \"jvm_runtime_info\" type: GAUGE metric { label { name: \"my_key\" value: \"value\" } gauge { value: 1.0 } }", - TextFormat.printer().shortDebugString(protobufData)); + assertThat(TextFormat.printer().shortDebugString(protobufData)) + .isEqualTo( + "name: \"jvm_runtime_info\" type: GAUGE metric { label { name: \"my_key\" value: \"value\" } gauge { value: 1.0 } }"); } } } @@ -36,19 +37,19 @@ public void testInfoStrippedFromName() { @Test public void testAddAndRemove() { Info info = Info.builder().name("test_info").labelNames("a", "b").build(); - assertEquals(0, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).isEmpty(); info.addLabelValues("val1", "val2"); - assertEquals(1, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(1); info.addLabelValues("val1", "val2"); // already exist, so no change - assertEquals(1, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(1); info.addLabelValues("val2", "val2"); - assertEquals(2, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(2); info.remove("val1", "val3"); // does not exist, so no change - assertEquals(2, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(2); info.remove("val1", "val2"); - assertEquals(1, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(1); info.remove("val2", "val2"); - assertEquals(0, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).isEmpty(); } @Test @@ -60,9 +61,9 @@ public void testSet() throws IOException { .labelNames("service.version") .build(); info.setLabelValues("1.0.0"); - assertEquals(1, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(1); info.setLabelValues("2.0.0"); - assertEquals(1, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(1); assertTextFormat( "target_info{service_instance_id=\"123\",service_name=\"test\",service_version=\"2.0.0\"} 1\n", info); @@ -75,18 +76,22 @@ public void testConstLabelsOnly() throws IOException { .name("target_info") .constLabels(Labels.of("service.name", "test", "service.instance.id", "123")) .build(); - assertEquals(1, info.collect().getDataPoints().size()); + assertThat(info.collect().getDataPoints()).hasSize(1); assertTextFormat("target_info{service_instance_id=\"123\",service_name=\"test\"} 1\n", info); } - @Test(expected = IllegalArgumentException.class) + @Test public void testConstLabelsDuplicate1() { - Info.builder().constLabels(Labels.of("a_1", "val1")).labelNames("a.1").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> Info.builder().constLabels(Labels.of("a_1", "val1")).labelNames("a.1").build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testConstLabelsDuplicate2() { - Info.builder().labelNames("a_1").constLabels(Labels.of("a.1", "val1")).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> Info.builder().labelNames("a_1").constLabels(Labels.of("a.1", "val1")).build()); } private void assertTextFormat(String expected, Info info) throws IOException { diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SlidingWindowTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SlidingWindowTest.java index 54639e7b6..334724a81 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SlidingWindowTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SlidingWindowTest.java @@ -1,14 +1,14 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SlidingWindowTest { +class SlidingWindowTest { class Observer { @@ -19,19 +19,19 @@ public void observe(double value) { } void assertValues(double... expectedValues) { - List expectedList = new ArrayList<>(); + ArrayList expectedList = new ArrayList<>(); for (double expectedValue : expectedValues) { expectedList.add(expectedValue); } - assertEquals( - "Start time: " - + startTime - + ", current time: " - + currentTimeMillis.get() - + ", elapsed time: " - + (currentTimeMillis.get() - startTime), - expectedList, - values); + assertThat(values) + .as( + "Start time: " + + startTime + + ", current time: " + + currentTimeMillis.get() + + ", elapsed time: " + + (currentTimeMillis.get() - startTime)) + .isEqualTo(expectedList); } } @@ -42,7 +42,7 @@ void assertValues(double... expectedValues) { private final int ageBuckets = 5; private final long timeBetweenRotateMillis = maxAgeSeconds * 1000 / ageBuckets + 2; - @Before + @BeforeEach public void setUp() { startTime = System.currentTimeMillis(); currentTimeMillis.set(startTime); diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StateSetTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StateSetTest.java index ddb2c4e9b..a419e876c 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StateSetTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StateSetTest.java @@ -1,16 +1,14 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import io.prometheus.metrics.model.snapshots.Labels; import io.prometheus.metrics.model.snapshots.StateSetSnapshot; import java.util.Arrays; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class StateSetTest { +class StateSetTest { enum MyFeatureFlag { EXPERIMENTAL_FEATURE_1 { @@ -39,30 +37,30 @@ public void testEnumStateSet() { stateSet.labelValues("dev").setTrue(MyFeatureFlag.EXPERIMENTAL_FEATURE_2); stateSet.labelValues("prod").setFalse(MyFeatureFlag.EXPERIMENTAL_FEATURE_2); StateSetSnapshot snapshot = stateSet.collect(); - assertEquals(2, snapshot.getDataPoints().size()); - assertEquals(2, getData(stateSet, "environment", "dev").size()); - assertEquals("feature1", getData(stateSet, "environment", "dev").getName(0)); - assertFalse(getData(stateSet, "environment", "dev").isTrue(0)); - assertEquals("feature2", getData(stateSet, "environment", "dev").getName(1)); - assertTrue(getData(stateSet, "environment", "dev").isTrue(1)); - assertEquals(2, getData(stateSet, "environment", "prod").size()); - assertEquals("feature1", getData(stateSet, "environment", "prod").getName(0)); - Assert.assertFalse(getData(stateSet, "environment", "prod").isTrue(0)); - assertEquals("feature2", getData(stateSet, "environment", "prod").getName(1)); - Assert.assertFalse(getData(stateSet, "environment", "prod").isTrue(1)); + assertThat(snapshot.getDataPoints()).hasSize(2); + assertThat(getData(stateSet, "environment", "dev").size()).isEqualTo(2); + assertThat(getData(stateSet, "environment", "dev").getName(0)).isEqualTo("feature1"); + assertThat(getData(stateSet, "environment", "dev").isTrue(0)).isFalse(); + assertThat(getData(stateSet, "environment", "dev").getName(1)).isEqualTo("feature2"); + assertThat(getData(stateSet, "environment", "dev").isTrue(1)).isTrue(); + assertThat(getData(stateSet, "environment", "prod").size()).isEqualTo(2); + assertThat(getData(stateSet, "environment", "prod").getName(0)).isEqualTo("feature1"); + assertThat(getData(stateSet, "environment", "prod").isTrue(0)).isFalse(); + assertThat(getData(stateSet, "environment", "prod").getName(1)).isEqualTo("feature2"); + assertThat(getData(stateSet, "environment", "prod").isTrue(1)).isFalse(); } @Test public void testDefaultFalse() { StateSet stateSet = StateSet.builder().name("test").states("state1", "state2", "state3").build(); - assertEquals(3, getData(stateSet).size()); - assertEquals("state1", getData(stateSet).getName(0)); - Assert.assertFalse(getData(stateSet).isTrue(0)); - assertEquals("state2", getData(stateSet).getName(1)); - Assert.assertFalse(getData(stateSet).isTrue(1)); - assertEquals("state3", getData(stateSet).getName(2)); - Assert.assertFalse(getData(stateSet).isTrue(2)); + assertThat(getData(stateSet).size()).isEqualTo(3); + assertThat(getData(stateSet).getName(0)).isEqualTo("state1"); + assertThat(getData(stateSet).isTrue(0)).isFalse(); + assertThat(getData(stateSet).getName(1)).isEqualTo("state2"); + assertThat(getData(stateSet).isTrue(1)).isFalse(); + assertThat(getData(stateSet).getName(2)).isEqualTo("state3"); + assertThat(getData(stateSet).isTrue(2)).isFalse(); } private StateSetSnapshot.StateSetDataPointSnapshot getData(StateSet stateSet, String... labels) { @@ -75,8 +73,9 @@ private StateSetSnapshot.StateSetDataPointSnapshot getData(StateSet stateSet, St "stateset with labels " + Arrays.toString(labels) + " not found")); } - @Test(expected = IllegalStateException.class) + @Test public void testStatesCannotBeEmpty() { - StateSet.builder().name("invalid").build(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> StateSet.builder().name("invalid").build()); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StatefulMetricTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StatefulMetricTest.java index a3ddbcc84..d05cf145a 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StatefulMetricTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StatefulMetricTest.java @@ -1,13 +1,13 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import java.lang.reflect.Field; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class StatefulMetricTest { +class StatefulMetricTest { @Test public void testLabelRemoveWhileCollecting() throws Exception { @@ -30,8 +30,8 @@ public void testLabelRemoveWhileCollecting() throws Exception { counter.remove("c", "d"); counter.remove("e", "f"); } - assertNotNull(entry.getKey()); - assertNotNull(entry.getValue()); + assertThat(entry.getKey()).isNotNull(); + assertThat(entry.getValue()).isNotNull(); } } @@ -41,31 +41,31 @@ public void testClear() { counter.labelValues("a", "b").inc(3.0); counter.labelValues("c", "d").inc(3.0); counter.labelValues("a", "b").inc(); - assertEquals(2, counter.collect().getDataPoints().size()); + assertThat(counter.collect().getDataPoints()).hasSize(2); counter.clear(); - assertEquals(0, counter.collect().getDataPoints().size()); + assertThat(counter.collect().getDataPoints()).isEmpty(); counter.labelValues("a", "b").inc(); - assertEquals(1, counter.collect().getDataPoints().size()); + assertThat(counter.collect().getDataPoints()).hasSize(1); } @Test public void testClearNoLabels() { Counter counter = Counter.builder().name("test").build(); counter.inc(); - assertEquals(1, counter.collect().getDataPoints().size()); - assertEquals(1.0, counter.collect().getDataPoints().get(0).getValue(), 0.0); + assertThat(counter.collect().getDataPoints()).hasSize(1); + assertThat(counter.collect().getDataPoints().get(0).getValue()).isCloseTo(1.0, offset(0.0)); counter.clear(); // No labels is always present, but as no value has been observed after clear() the value should // be 0.0 - assertEquals(1, counter.collect().getDataPoints().size()); - assertEquals(0.0, counter.collect().getDataPoints().get(0).getValue(), 0.0); + assertThat(counter.collect().getDataPoints()).hasSize(1); + assertThat(counter.collect().getDataPoints().get(0).getValue()).isCloseTo(0.0, offset(0.0)); // Making inc() works correctly after clear() counter.inc(); - assertEquals(1, counter.collect().getDataPoints().size()); - assertEquals(1.0, counter.collect().getDataPoints().get(0).getValue(), 0.0); + assertThat(counter.collect().getDataPoints()).hasSize(1); + assertThat(counter.collect().getDataPoints().get(0).getValue()).isCloseTo(1.0, offset(0.0)); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryTest.java index 365ff1824..dbabb1a93 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryTest.java @@ -1,7 +1,9 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.core.datapoints.Timer; import io.prometheus.metrics.model.registry.PrometheusRegistry; @@ -12,10 +14,10 @@ import io.prometheus.metrics.model.snapshots.SummarySnapshot; import io.prometheus.metrics.model.snapshots.Unit; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SummaryTest { +class SummaryTest { private final Label label = new Label("name", "value"); private final Labels labels = Labels.builder().label(label.getName(), label.getValue()).build(); @@ -26,7 +28,7 @@ public class SummaryTest { private Summary withLabelsAndQuantiles; private Summary noLabelsAndQuantiles; - @Before + @BeforeEach public void setUp() { registry = new PrometheusRegistry(); noLabels = @@ -62,27 +64,27 @@ public void setUp() { @Test public void testObserve() { noLabels.observe(2); - assertEquals(1, getCount(noLabels, Labels.EMPTY)); - assertEquals(2.0, getSum(noLabels, Labels.EMPTY), .001); + assertThat(getCount(noLabels, Labels.EMPTY)).isOne(); + assertThat(getSum(noLabels, Labels.EMPTY)).isCloseTo(2.0, offset(.001)); noLabels.observe(3); - assertEquals(2, getCount(noLabels, Labels.EMPTY)); - assertEquals(5.0, getSum(noLabels, Labels.EMPTY), .001); + assertThat(getCount(noLabels, Labels.EMPTY)).isEqualTo(2); + assertThat(getSum(noLabels, Labels.EMPTY)).isCloseTo(5.0, offset(.001)); withLabels.labelValues(label.getValue()).observe(4); - assertEquals(1, getCount(withLabels, labels)); - assertEquals(4.0, getSum(withLabels, labels), .001); + assertThat(getCount(withLabels, labels)).isOne(); + assertThat(getSum(withLabels, labels)).isCloseTo(4.0, offset(.001)); withLabels.labelValues(label.getValue()).observeWithExemplar(6, labels); - assertEquals(2, getCount(withLabels, labels)); - assertEquals(10.0, getSum(withLabels, labels), .001); + assertThat(getCount(withLabels, labels)).isEqualTo(2); + assertThat(getSum(withLabels, labels)).isCloseTo(10.0, offset(.001)); } @Test public void testNegativeAmount() { noLabels.observe(-1); noLabels.observe(-3); - assertEquals(2, getCount(noLabels, Labels.EMPTY)); - assertEquals(-4.0, getSum(noLabels, Labels.EMPTY), .001); + assertThat(getCount(noLabels, Labels.EMPTY)).isEqualTo(2); + assertThat(getSum(noLabels, Labels.EMPTY)).isCloseTo(-4.0, offset(.001)); } @Test @@ -95,17 +97,19 @@ public void testQuantiles() { withLabelsAndQuantiles.labelValues(label.getValue()).observe(i); noLabelsAndQuantiles.observe(i); } - assertEquals( - getQuantile(noLabelsAndQuantiles, 0.5, Labels.EMPTY), 0.5 * nSamples, 0.05 * nSamples); - assertEquals( - getQuantile(noLabelsAndQuantiles, 0.9, Labels.EMPTY), 0.9 * nSamples, 0.01 * nSamples); - assertEquals( - getQuantile(noLabelsAndQuantiles, 0.99, Labels.EMPTY), 0.99 * nSamples, 0.001 * nSamples); - - assertEquals(getQuantile(withLabelsAndQuantiles, 0.5, labels), 0.5 * nSamples, 0.05 * nSamples); - assertEquals(getQuantile(withLabelsAndQuantiles, 0.9, labels), 0.9 * nSamples, 0.01 * nSamples); - assertEquals( - getQuantile(withLabelsAndQuantiles, 0.99, labels), 0.99 * nSamples, 0.001 * nSamples); + assertThat(0.5 * nSamples) + .isCloseTo(getQuantile(noLabelsAndQuantiles, 0.5, Labels.EMPTY), offset(0.05 * nSamples)); + assertThat(0.9 * nSamples) + .isCloseTo(getQuantile(noLabelsAndQuantiles, 0.9, Labels.EMPTY), offset(0.01 * nSamples)); + assertThat(0.99 * nSamples) + .isCloseTo(getQuantile(noLabelsAndQuantiles, 0.99, Labels.EMPTY), offset(0.001 * nSamples)); + + assertThat(0.5 * nSamples) + .isCloseTo(getQuantile(withLabelsAndQuantiles, 0.5, labels), offset(0.05 * nSamples)); + assertThat(0.9 * nSamples) + .isCloseTo(getQuantile(withLabelsAndQuantiles, 0.9, labels), offset(0.01 * nSamples)); + assertThat(0.99 * nSamples) + .isCloseTo(getQuantile(withLabelsAndQuantiles, 0.99, labels), offset(0.001 * nSamples)); } @Test @@ -119,52 +123,56 @@ public void testMaxAge() throws InterruptedException { .help("help") .register(registry); summary.observe(8.0); - assertEquals(8.0, getQuantile(summary, 0.99, Labels.EMPTY), 0.0); // From bucket 1. + assertThat(getQuantile(summary, 0.99, Labels.EMPTY)) + .isCloseTo(8.0, offset(0.0)); // From bucket 1. Thread.sleep(600); - assertEquals(8.0, getQuantile(summary, 0.99, Labels.EMPTY), 0.0); // From bucket 2. + assertThat(getQuantile(summary, 0.99, Labels.EMPTY)) + .isCloseTo(8.0, offset(0.0)); // From bucket 2. Thread.sleep(600); - assertEquals( - Double.NaN, - getQuantile(summary, 0.99, Labels.EMPTY), - 0.0); // Bucket 1 again, now it is empty. + assertThat(getQuantile(summary, 0.99, Labels.EMPTY)) + .isCloseTo(Double.NaN, offset(0.0)); // Bucket 1 again, now it is empty. } @Test public void testTimer() { int result = noLabels.time(() -> 123); - assertEquals(123, result); - assertEquals(1, getCount(noLabels, Labels.EMPTY)); + assertThat(result).isEqualTo(123); + assertThat(getCount(noLabels, Labels.EMPTY)).isOne(); try (Timer timer = noLabels.startTimer()) { timer.observeDuration(); - assertEquals(2, getCount(noLabels, Labels.EMPTY), .001); + assertThat(getCount(noLabels, Labels.EMPTY)).isEqualTo(2); } } @Test public void noLabelsDefaultZeroValue() { - assertEquals(0.0, getCount(noLabels, Labels.EMPTY), .001); - assertEquals(0.0, getSum(noLabels, Labels.EMPTY), .001); + assertThat(getCount(noLabels, Labels.EMPTY)).isZero(); + assertThat(getSum(noLabels, Labels.EMPTY)).isCloseTo(0.0, offset(.001)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBuilderInvalidNumberOfAgeBuckets() { - Summary.builder().name("name").numberOfAgeBuckets(-1).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Summary.builder().name("name").numberOfAgeBuckets(-1).build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBuilderInvalidMaxAge() { - Summary.builder().name("name").maxAgeSeconds(-1).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Summary.builder().name("name").maxAgeSeconds(-1).build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBuilderInvalidQuantile() { - Summary.builder().name("name").quantile(42).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Summary.builder().name("name").quantile(42).build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBuilderInvalidQuantileError() { - Summary.builder().name("name").quantile(0.5, 20).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Summary.builder().name("name").quantile(0.5, 20).build()); } private double getQuantile(Summary summary, double quantile, Labels labels) { @@ -182,9 +190,9 @@ private double getQuantile(Summary summary, double quantile, Labels labels) { private SummarySnapshot.SummaryDataPointSnapshot getDatapoint(Summary summary, Labels labels) { SummarySnapshot snapshot = summary.collect(); List datapoints = snapshot.getDataPoints(); - assertEquals(1, datapoints.size()); + assertThat(datapoints.size()).isOne(); SummarySnapshot.SummaryDataPointSnapshot datapoint = datapoints.get(0); - assertEquals(labels, datapoint.getLabels()); + assertThat((Iterable) datapoint.getLabels()).isEqualTo(labels); return datapoint; } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryWithCallbackTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryWithCallbackTest.java index ba1df05ff..929efc597 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryWithCallbackTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/SummaryWithCallbackTest.java @@ -1,6 +1,8 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.model.snapshots.Quantile; import io.prometheus.metrics.model.snapshots.Quantiles; @@ -8,9 +10,9 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SummaryWithCallbackTest { +class SummaryWithCallbackTest { @Test public void testGauge() { @@ -30,24 +32,26 @@ public void testGauge() { .build(); SummarySnapshot snapshot = gauge.collect(); - assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); SummarySnapshot.SummaryDataPointSnapshot datapoint = snapshot.getDataPoints().get(0); - assertEquals(count.get(), datapoint.getCount()); - assertEquals(sum.doubleValue(), datapoint.getSum(), 0.1); - assertEquals(quantiles, datapoint.getQuantiles()); - assertEquals(labelValues.size(), datapoint.getLabels().size()); + assertThat(datapoint.getCount()).isEqualTo(count.get()); + assertThat(datapoint.getSum()).isCloseTo(sum.doubleValue(), offset(0.1)); + assertThat(datapoint.getQuantiles()).isEqualTo(quantiles); + assertThat(datapoint.getLabels().size()).isEqualTo(labelValues.size()); count.incrementAndGet(); sum.incrementAndGet(); snapshot = gauge.collect(); - assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); datapoint = snapshot.getDataPoints().get(0); - assertEquals(count.get(), datapoint.getCount()); - assertEquals(sum.doubleValue(), datapoint.getSum(), 0.1); + assertThat(datapoint.getCount()).isEqualTo(count.get()); + assertThat(datapoint.getSum()).isCloseTo(sum.doubleValue(), offset(0.1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSummaryNoCallback() { - SummaryWithCallback.builder().name("summary").labelNames("l1", "l2").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> SummaryWithCallback.builder().name("summary").labelNames("l1", "l2").build()); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TestUtil.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TestUtil.java index 6a242a8be..8d9a5bd0f 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TestUtil.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TestUtil.java @@ -1,14 +1,16 @@ package io.prometheus.metrics.core.metrics; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.model.snapshots.Exemplar; +import io.prometheus.metrics.model.snapshots.Label; -public class TestUtil { +class TestUtil { public static void assertExemplarEquals(Exemplar expected, Exemplar actual) { // ignore timestamp - assertEquals(expected.getValue(), actual.getValue(), 0.00001); - assertEquals(expected.getLabels(), actual.getLabels()); + assertThat(actual.getValue()).isCloseTo(expected.getValue(), offset(0.00001)); + assertThat((Iterable) actual.getLabels()).isEqualTo(expected.getLabels()); } } diff --git a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TodoTest.java b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TodoTest.java index be6d17784..417226b94 100644 --- a/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TodoTest.java +++ b/prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/TodoTest.java @@ -1,6 +1,6 @@ package io.prometheus.metrics.core.metrics; -public class TodoTest { +class TodoTest { // if a metric with labels is created but never used it has no data. // The registry's collect() method should skip those metrics to avoid illegal protobuf or text diff --git a/prometheus-metrics-exporter-opentelemetry/pom.xml b/prometheus-metrics-exporter-opentelemetry/pom.xml index 448390bb2..0247be420 100644 --- a/prometheus-metrics-exporter-opentelemetry/pom.xml +++ b/prometheus-metrics-exporter-opentelemetry/pom.xml @@ -51,12 +51,6 @@ - - junit - junit - 4.13.2 - test - org.wiremock wiremock diff --git a/prometheus-metrics-exporter-opentelemetry/src/test/java/io/prometheus/metrics/exporter/opentelemetry/ExemplarTest.java b/prometheus-metrics-exporter-opentelemetry/src/test/java/io/prometheus/metrics/exporter/opentelemetry/ExemplarTest.java index 5af5193f6..def62834f 100644 --- a/prometheus-metrics-exporter-opentelemetry/src/test/java/io/prometheus/metrics/exporter/opentelemetry/ExemplarTest.java +++ b/prometheus-metrics-exporter-opentelemetry/src/test/java/io/prometheus/metrics/exporter/opentelemetry/ExemplarTest.java @@ -5,13 +5,15 @@ import static com.github.tomakehurst.wiremock.client.WireMock.ok; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.awaitility.Awaitility.await; import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockTest; import com.github.tomakehurst.wiremock.matching.MatchResult; import com.github.tomakehurst.wiremock.matching.ValueMatcher; import com.google.protobuf.InvalidProtocolBufferException; @@ -28,12 +30,12 @@ import io.prometheus.metrics.core.metrics.Counter; import io.prometheus.metrics.model.registry.PrometheusRegistry; import org.awaitility.core.ConditionTimeoutException; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ExemplarTest { +@WireMockTest(httpPort = 4317) +class ExemplarTest { private static final String ENDPOINT_PATH = "/v1/metrics"; private static final int TIMEOUT = 3; private static final String INSTRUMENTATION_SCOPE_NAME = "testInstrumentationScope"; @@ -41,9 +43,8 @@ public class ExemplarTest { public static final String TEST_COUNTER_NAME = "test_counter"; private Counter testCounter; private OpenTelemetryExporter openTelemetryExporter; - @Rule public WireMockRule wireMockRule = new WireMockRule(4317); - @Before + @BeforeEach public void setUp() { openTelemetryExporter = OpenTelemetryExporter.builder() @@ -54,7 +55,7 @@ public void setUp() { testCounter = Counter.builder().name(TEST_COUNTER_NAME).withExemplars().register(); - wireMockRule.stubFor( + stubFor( post(ENDPOINT_PATH) .withHeader("Content-Type", containing("application/x-protobuf")) .willReturn( @@ -62,7 +63,7 @@ public void setUp() { .withBody("{\"partialSuccess\":{}}"))); } - @After + @AfterEach public void tearDown() { PrometheusRegistry.defaultRegistry.unregister(testCounter); openTelemetryExporter.close(); @@ -93,7 +94,7 @@ public void sampledExemplarIsForwarded() { }); } - @Test(expected = ConditionTimeoutException.class) + @Test public void notSampledExemplarIsNotForwarded() { try (SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().setSampler(Sampler.alwaysOff()).build()) { @@ -105,17 +106,21 @@ public void notSampledExemplarIsNotForwarded() { } } - await() - .atMost(TIMEOUT, SECONDS) - .ignoreException(com.github.tomakehurst.wiremock.client.VerificationException.class) - .until( - () -> { - verify( - postRequestedFor(urlEqualTo(ENDPOINT_PATH)) - .withHeader("Content-Type", equalTo("application/x-protobuf")) - .andMatching(getExemplarCountMatcher(1))); - return true; - }); + assertThatExceptionOfType(ConditionTimeoutException.class) + .isThrownBy( + () -> + await() + .atMost(TIMEOUT, SECONDS) + .ignoreException( + com.github.tomakehurst.wiremock.client.VerificationException.class) + .until( + () -> { + verify( + postRequestedFor(urlEqualTo(ENDPOINT_PATH)) + .withHeader("Content-Type", equalTo("application/x-protobuf")) + .andMatching(getExemplarCountMatcher(1))); + return true; + })); } private static ValueMatcher getExemplarCountMatcher(int expectedCount) { diff --git a/prometheus-metrics-exporter-pushgateway/pom.xml b/prometheus-metrics-exporter-pushgateway/pom.xml index 8b6e22525..8272ac9d7 100644 --- a/prometheus-metrics-exporter-pushgateway/pom.xml +++ b/prometheus-metrics-exporter-pushgateway/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 @@ -29,12 +30,12 @@ - + brian-brazil Brian Brazil brian.brazil@boxever.com - - + + fstab Fabian Stäber fabian@fstab.de @@ -47,21 +48,9 @@ prometheus-metrics-exporter-common ${project.version} - - junit - junit - 4.13.2 - test - - - org.mock-server - mockserver-netty - 5.15.0 - test - org.mock-server - mockserver-junit-rule-no-dependencies + mockserver-netty-no-dependencies 5.15.0 test diff --git a/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BasicAuthPushGatewayTest.java b/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BasicAuthPushGatewayTest.java index 7fbb32b10..598172eaa 100644 --- a/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BasicAuthPushGatewayTest.java +++ b/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BasicAuthPushGatewayTest.java @@ -6,34 +6,38 @@ import io.prometheus.metrics.core.metrics.Gauge; import io.prometheus.metrics.model.registry.PrometheusRegistry; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockserver.client.MockServerClient; -import org.mockserver.junit.MockServerRule; +import org.mockserver.integration.ClientAndServer; -public class BasicAuthPushGatewayTest { - - @Rule public MockServerRule mockServerRule = new MockServerRule(this); +class BasicAuthPushGatewayTest { private MockServerClient mockServerClient; PrometheusRegistry registry; Gauge gauge; PushGateway pushGateway; - @Before + @BeforeEach public void setUp() { + mockServerClient = ClientAndServer.startClientAndServer(0); registry = new PrometheusRegistry(); gauge = Gauge.builder().name("g").help("help").build(); pushGateway = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .basicAuth("testUser", "testPwd") .registry(registry) .job("j") .build(); } + @AfterEach + void tearDown() { + mockServerClient.stop(); + } + @Test public void testAuthorizedPush() throws IOException { mockServerClient diff --git a/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BearerTokenPushGatewayTest.java b/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BearerTokenPushGatewayTest.java index 144a0f24f..09e6ff5e9 100644 --- a/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BearerTokenPushGatewayTest.java +++ b/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/BearerTokenPushGatewayTest.java @@ -6,34 +6,39 @@ import io.prometheus.metrics.core.metrics.Gauge; import io.prometheus.metrics.model.registry.PrometheusRegistry; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockserver.client.MockServerClient; -import org.mockserver.junit.MockServerRule; +import org.mockserver.integration.ClientAndServer; -public class BearerTokenPushGatewayTest { +class BearerTokenPushGatewayTest { - @Rule public MockServerRule mockServerRule = new MockServerRule(this); private MockServerClient mockServerClient; PrometheusRegistry registry; Gauge gauge; PushGateway pushGateway; - @Before + @BeforeEach public void setUp() { + mockServerClient = ClientAndServer.startClientAndServer(0); registry = new PrometheusRegistry(); gauge = Gauge.builder().name("g").help("help").build(); pushGateway = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .bearerToken("xxx") .registry(registry) .job("j") .build(); } + @AfterEach + void tearDown() { + mockServerClient.stop(); + } + @Test public void testAuthorizedPush() throws IOException { mockServerClient diff --git a/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/PushGatewayTest.java b/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/PushGatewayTest.java index ce88300db..27617913b 100644 --- a/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/PushGatewayTest.java +++ b/prometheus-metrics-exporter-pushgateway/src/test/java/io/prometheus/metrics/exporter/pushgateway/PushGatewayTest.java @@ -1,6 +1,7 @@ package io.prometheus.metrics.exporter.pushgateway; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; @@ -10,35 +11,40 @@ import java.lang.reflect.Field; import java.net.InetAddress; import java.net.URL; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockserver.client.MockServerClient; -import org.mockserver.junit.MockServerRule; +import org.mockserver.integration.ClientAndServer; -public class PushGatewayTest { +class PushGatewayTest { - @Rule public final ExpectedException thrown = none(); - - @Rule public MockServerRule mockServerRule = new MockServerRule(this); private MockServerClient mockServerClient; PrometheusRegistry registry; Gauge gauge; - @Before + @BeforeEach public void setUp() { + mockServerClient = ClientAndServer.startClientAndServer(0); registry = new PrometheusRegistry(); gauge = Gauge.builder().name("g").help("help").build(); } - @Test(expected = RuntimeException.class) + @AfterEach + void tearDown() { + mockServerClient.stop(); + } + + @Test public void testInvalidURLThrowsRuntimeException() { - PushGateway.builder() - .address("::") - .build(); // ":" is interpreted as port number, so parsing fails + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy( + () -> { + PushGateway.builder() + .address("::") + .build(); // ":" is interpreted as port number, so parsing fails + }); } @Test @@ -46,8 +52,8 @@ public void testMultipleSlashesAreStrippedFromURL() throws NoSuchFieldException, IllegalAccessException { final PushGateway pushGateway = PushGateway.builder().address("example.com:1234/context///path//").job("test").build(); - Assert.assertEquals( - "http://example.com:1234/context/path/metrics/job/test", getUrl(pushGateway).toString()); + assertThat(getUrl(pushGateway)) + .hasToString("http://example.com:1234/context/path/metrics/job/test"); } private URL getUrl(PushGateway pushGateway) throws IllegalAccessException, NoSuchFieldException { @@ -63,7 +69,7 @@ public void testPush() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .build(); @@ -77,7 +83,7 @@ public void testPush200Response() throws IOException { .respond(response().withStatusCode(200)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .build(); @@ -85,22 +91,25 @@ public void testPush200Response() throws IOException { } @Test - public void testNon202ResponseThrows() throws IOException { + public void testNon202ResponseThrows() { mockServerClient .when(request().withMethod("PUT").withPath("/metrics/job/j")) .respond(response().withStatusCode(500)); - thrown.expect(IOException.class); - thrown.expectMessage( - "Response code from http://localhost:" - + mockServerRule.getPort() - + "/metrics/job/j was 500"); - PushGateway pg = - PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) - .registry(registry) - .job("j") - .build(); - pg.push(); + assertThatExceptionOfType(IOException.class) + .isThrownBy( + () -> { + PushGateway pg = + PushGateway.builder() + .address("localhost:" + mockServerClient.getPort()) + .registry(registry) + .job("j") + .build(); + pg.push(); + }) + .withMessageContaining( + "Response code from http://localhost:" + + mockServerClient.getPort() + + "/metrics/job/j was 500"); } @Test @@ -110,7 +119,7 @@ public void testPushCollector() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .build(); @@ -124,7 +133,7 @@ public void testPushWithGroupingKey() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .groupingKey("l", "v") @@ -139,7 +148,7 @@ public void testPushWithMultiGroupingKey() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .groupingKey("l", "v") @@ -155,7 +164,7 @@ public void testPushWithEmptyLabelGroupingKey() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .groupingKey("l", "v") @@ -172,7 +181,7 @@ public void testPushWithGroupingKeyWithSlashes() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("a/b") .groupingKey("l", "v") @@ -188,7 +197,7 @@ public void testPushCollectorWithGroupingKey() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .groupingKey("l", "v") @@ -203,7 +212,7 @@ public void testPushAdd() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .job("j") .build(); @@ -216,7 +225,7 @@ public void testPushAddCollector() throws IOException { .when(request().withMethod("POST").withPath("/metrics/job/j")) .respond(response().withStatusCode(202)); PushGateway pg = - PushGateway.builder().address("localhost:" + mockServerRule.getPort()).job("j").build(); + PushGateway.builder().address("localhost:" + mockServerClient.getPort()).job("j").build(); pg.pushAdd(gauge); } @@ -227,7 +236,7 @@ public void testPushAddWithGroupingKey() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .groupingKey("l", "v") .job("j") @@ -242,7 +251,7 @@ public void testPushAddCollectorWithGroupingKey() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .registry(registry) .groupingKey("l", "v") .job("j") @@ -256,7 +265,7 @@ public void testDelete() throws IOException { .when(request().withMethod("DELETE").withPath("/metrics/job/j")) .respond(response().withStatusCode(202)); PushGateway pg = - PushGateway.builder().address("localhost:" + mockServerRule.getPort()).job("j").build(); + PushGateway.builder().address("localhost:" + mockServerClient.getPort()).job("j").build(); pg.delete(); } @@ -267,7 +276,7 @@ public void testDeleteWithGroupingKey() throws IOException { .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .job("j") .groupingKey("l", "v") .build(); @@ -277,13 +286,13 @@ public void testDeleteWithGroupingKey() throws IOException { @Test public void testInstanceIpGroupingKey() throws IOException { String ip = InetAddress.getLocalHost().getHostAddress(); - Assert.assertFalse(ip.isEmpty()); + assertThat(ip).isNotEmpty(); mockServerClient .when(request().withMethod("DELETE").withPath("/metrics/job/j/instance/" + ip + "/l/v")) .respond(response().withStatusCode(202)); PushGateway pg = PushGateway.builder() - .address("localhost:" + mockServerRule.getPort()) + .address("localhost:" + mockServerClient.getPort()) .job("j") .groupingKey("l", "v") .instanceIpGroupingKey() diff --git a/prometheus-metrics-exposition-formats/pom.xml b/prometheus-metrics-exposition-formats/pom.xml index b745e62cc..e7de1e28b 100644 --- a/prometheus-metrics-exposition-formats/pom.xml +++ b/prometheus-metrics-exposition-formats/pom.xml @@ -53,14 +53,6 @@ 1.3.1 - - - - junit - junit - 4.13.2 - test - diff --git a/prometheus-metrics-exposition-formats/src/test/java/io/prometheus/metrics/expositionformats/ExpositionFormatsTest.java b/prometheus-metrics-exposition-formats/src/test/java/io/prometheus/metrics/expositionformats/ExpositionFormatsTest.java index 1ce3f2840..307b88938 100644 --- a/prometheus-metrics-exposition-formats/src/test/java/io/prometheus/metrics/expositionformats/ExpositionFormatsTest.java +++ b/prometheus-metrics-exposition-formats/src/test/java/io/prometheus/metrics/expositionformats/ExpositionFormatsTest.java @@ -1,5 +1,7 @@ package io.prometheus.metrics.expositionformats; +import static org.assertj.core.api.Assertions.assertThat; + import io.prometheus.metrics.expositionformats.generated.com_google_protobuf_3_25_3.Metrics; import io.prometheus.metrics.model.snapshots.*; import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot; @@ -9,10 +11,9 @@ import io.prometheus.metrics.shaded.com_google_protobuf_3_25_3.TextFormat; import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ExpositionFormatsTest { +class ExpositionFormatsTest { private final String exemplar1String = "{env=\"prod\",span_id=\"12345\",trace_id=\"abcde\"} 1.7 1672850685.829"; @@ -80,8 +81,7 @@ public class ExpositionFormatsTest { @Test public void testCounterComplete() throws IOException { String openMetricsText = - "" - + "# TYPE service_time_seconds counter\n" + "# TYPE service_time_seconds counter\n" + "# UNIT service_time_seconds seconds\n" + "# HELP service_time_seconds total time spent serving\n" + "service_time_seconds_total{path=\"/hello\",status=\"200\"} 0.8 " @@ -106,8 +106,7 @@ public void testCounterComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP service_time_seconds_total total time spent serving\n" + "# HELP service_time_seconds_total total time spent serving\n" + "# TYPE service_time_seconds_total counter\n" + "service_time_seconds_total{path=\"/hello\",status=\"200\"} 0.8 " + scrapeTimestamp1s @@ -128,8 +127,7 @@ public void testCounterComplete() throws IOException { + scrapeTimestamp2s + "\n"; String openMetricsTextWithoutCreated = - "" - + "# TYPE service_time_seconds counter\n" + "# TYPE service_time_seconds counter\n" + "# UNIT service_time_seconds seconds\n" + "# HELP service_time_seconds total time spent serving\n" + "service_time_seconds_total{path=\"/hello\",status=\"200\"} 0.8 " @@ -144,8 +142,7 @@ public void testCounterComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusTextWithoutCreated = - "" - + "# HELP service_time_seconds_total total time spent serving\n" + "# HELP service_time_seconds_total total time spent serving\n" + "# TYPE service_time_seconds_total counter\n" + "service_time_seconds_total{path=\"/hello\",status=\"200\"} 0.8 " + scrapeTimestamp1s @@ -154,10 +151,8 @@ public void testCounterComplete() throws IOException { + scrapeTimestamp2s + "\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"service_time_seconds_total\" " + // @formatter:off + "name: \"service_time_seconds_total\" " + "help: \"total time spent serving\" " + "type: COUNTER " + "metric { " @@ -213,11 +208,10 @@ public void testCounterComplete() throws IOException { @Test public void testCounterMinimal() throws IOException { - String openMetricsText = - "" + "# TYPE my_counter counter\n" + "my_counter_total 1.1\n" + "# EOF\n"; - String prometheusText = "" + "# TYPE my_counter_total counter\n" + "my_counter_total 1.1\n"; + String openMetricsText = "# TYPE my_counter counter\n" + "my_counter_total 1.1\n" + "# EOF\n"; + String prometheusText = "# TYPE my_counter_total counter\n" + "my_counter_total 1.1\n"; String prometheusProtobuf = - "" + "name: \"my_counter_total\" type: COUNTER metric { counter { value: 1.1 } }"; + "name: \"my_counter_total\" type: COUNTER metric { counter { value: 1.1 } }"; CounterSnapshot counter = CounterSnapshot.builder() .name("my_counter") @@ -233,21 +227,17 @@ public void testCounterMinimal() throws IOException { @Test public void testCounterWithDots() throws IOException { String openMetricsText = - "" - + "# TYPE my_request_count counter\n" + "# TYPE my_request_count counter\n" + "my_request_count_total{http_path=\"/hello\"} 3.0 # " + exemplarWithDotsString + "\n" + "# EOF\n"; String prometheusText = - "" - + "# TYPE my_request_count_total counter\n" + "# TYPE my_request_count_total counter\n" + "my_request_count_total{http_path=\"/hello\"} 3.0\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"my_request_count_total\" " + // @formatter:off + "name: \"my_request_count_total\" " + "type: COUNTER " + "metric { " + "label { name: \"http_path\" value: \"/hello\" } " @@ -277,8 +267,7 @@ public void testCounterWithDots() throws IOException { @Test public void testGaugeComplete() throws IOException { String openMetricsText = - "" - + "# TYPE disk_usage_ratio gauge\n" + "# TYPE disk_usage_ratio gauge\n" + "# UNIT disk_usage_ratio ratio\n" + "# HELP disk_usage_ratio percentage used\n" + "disk_usage_ratio{device=\"/dev/sda1\"} 0.2 " @@ -289,8 +278,7 @@ public void testGaugeComplete() throws IOException { + "\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE disk_usage_ratio gauge\n" + "# TYPE disk_usage_ratio gauge\n" + "# UNIT disk_usage_ratio ratio\n" + "# HELP disk_usage_ratio percentage used\n" + "disk_usage_ratio{device=\"/dev/sda1\"} 0.2 " @@ -305,8 +293,7 @@ public void testGaugeComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP disk_usage_ratio percentage used\n" + "# HELP disk_usage_ratio percentage used\n" + "# TYPE disk_usage_ratio gauge\n" + "disk_usage_ratio{device=\"/dev/sda1\"} 0.2 " + scrapeTimestamp1s @@ -315,10 +302,8 @@ public void testGaugeComplete() throws IOException { + scrapeTimestamp2s + "\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"disk_usage_ratio\" " + // @formatter:off + "name: \"disk_usage_ratio\" " + "help: \"percentage used\" " + "type: GAUGE " + "metric { " @@ -363,11 +348,11 @@ public void testGaugeComplete() throws IOException { @Test public void testGaugeMinimal() throws IOException { String openMetricsText = - "" + "# TYPE temperature_centigrade gauge\n" + "temperature_centigrade 22.3\n" + "# EOF\n"; + "# TYPE temperature_centigrade gauge\n" + "temperature_centigrade 22.3\n" + "# EOF\n"; String prometheusText = - "" + "# TYPE temperature_centigrade gauge\n" + "temperature_centigrade 22.3\n"; + "# TYPE temperature_centigrade gauge\n" + "temperature_centigrade 22.3\n"; String prometheusProtobuf = - "" + "name: \"temperature_centigrade\" type: GAUGE metric { gauge { value: 22.3 } }"; + "name: \"temperature_centigrade\" type: GAUGE metric { gauge { value: 22.3 } }"; GaugeSnapshot gauge = GaugeSnapshot.builder() .name("temperature_centigrade") @@ -383,15 +368,13 @@ public void testGaugeMinimal() throws IOException { @Test public void testGaugeWithDots() throws IOException { String openMetricsText = - "" - + "# TYPE my_temperature_celsius gauge\n" + "# TYPE my_temperature_celsius gauge\n" + "# UNIT my_temperature_celsius celsius\n" + "# HELP my_temperature_celsius Temperature\n" + "my_temperature_celsius{location_id=\"data-center-1\"} 23.0\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE my_temperature_celsius gauge\n" + "# TYPE my_temperature_celsius gauge\n" + "# UNIT my_temperature_celsius celsius\n" + "# HELP my_temperature_celsius Temperature\n" + "my_temperature_celsius{location_id=\"data-center-1\"} 23.0 # " @@ -399,15 +382,12 @@ public void testGaugeWithDots() throws IOException { + "\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP my_temperature_celsius Temperature\n" + "# HELP my_temperature_celsius Temperature\n" + "# TYPE my_temperature_celsius gauge\n" + "my_temperature_celsius{location_id=\"data-center-1\"} 23.0\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"my_temperature_celsius\" " + // @formatter:off + "name: \"my_temperature_celsius\" " + "help: \"Temperature\" " + "type: GAUGE " + "metric { " @@ -440,8 +420,7 @@ public void testGaugeWithDots() throws IOException { @Test public void testSummaryComplete() throws IOException { String openMetricsText = - "" - + "# TYPE http_request_duration_seconds summary\n" + "# TYPE http_request_duration_seconds summary\n" + "# UNIT http_request_duration_seconds seconds\n" + "# HELP http_request_duration_seconds request duration\n" + "http_request_duration_seconds{status=\"200\",quantile=\"0.5\"} 225.3 " @@ -486,8 +465,7 @@ public void testSummaryComplete() throws IOException { + "\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE http_request_duration_seconds summary\n" + "# TYPE http_request_duration_seconds summary\n" + "# UNIT http_request_duration_seconds seconds\n" + "# HELP http_request_duration_seconds request duration\n" + "http_request_duration_seconds{status=\"200\",quantile=\"0.5\"} 225.3 " @@ -548,8 +526,7 @@ public void testSummaryComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP http_request_duration_seconds request duration\n" + "# HELP http_request_duration_seconds request duration\n" + "# TYPE http_request_duration_seconds summary\n" + "http_request_duration_seconds{status=\"200\",quantile=\"0.5\"} 225.3 " + scrapeTimestamp1s @@ -594,8 +571,7 @@ public void testSummaryComplete() throws IOException { + scrapeTimestamp2s + "\n"; String openMetricsTextWithoutCreated = - "" - + "# TYPE http_request_duration_seconds summary\n" + "# TYPE http_request_duration_seconds summary\n" + "# UNIT http_request_duration_seconds seconds\n" + "# HELP http_request_duration_seconds request duration\n" + "http_request_duration_seconds{status=\"200\",quantile=\"0.5\"} 225.3 " @@ -630,8 +606,7 @@ public void testSummaryComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusTextWithoutCreated = - "" - + "# HELP http_request_duration_seconds request duration\n" + "# HELP http_request_duration_seconds request duration\n" + "# TYPE http_request_duration_seconds summary\n" + "http_request_duration_seconds{status=\"200\",quantile=\"0.5\"} 225.3 " + scrapeTimestamp1s @@ -664,10 +639,8 @@ public void testSummaryComplete() throws IOException { + scrapeTimestamp2s + "\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"http_request_duration_seconds\" " + // @formatter:off + "name: \"http_request_duration_seconds\" " + "help: \"request duration\" " + "type: SUMMARY " + "metric { " @@ -689,7 +662,6 @@ public void testSummaryComplete() throws IOException { + "quantile { quantile: 0.9 value: 240.7 } " + "quantile { quantile: 0.95 value: 245.1 } " + "} " - + "" + "timestamp_ms: 1672850585820 " + "}"; // @formatter:on @@ -741,24 +713,20 @@ public void testSummaryComplete() throws IOException { @Test public void testSummaryWithoutQuantiles() throws IOException { String openMetricsText = - "" - + "# TYPE latency_seconds summary\n" + "# TYPE latency_seconds summary\n" + "# UNIT latency_seconds seconds\n" + "# HELP latency_seconds latency\n" + "latency_seconds_count 3\n" + "latency_seconds_sum 1.2\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP latency_seconds latency\n" + "# HELP latency_seconds latency\n" + "# TYPE latency_seconds summary\n" + "latency_seconds_count 3\n" + "latency_seconds_sum 1.2\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"latency_seconds\" " + // @formatter:off + "name: \"latency_seconds\" " + "help: \"latency\" " + "type: SUMMARY " + "metric { " @@ -785,17 +753,14 @@ public void testSummaryWithoutQuantiles() throws IOException { @Test public void testSummaryNoCountAndSum() throws IOException { String openMetricsText = - "" - + "# TYPE latency_seconds summary\n" + "# TYPE latency_seconds summary\n" + "latency_seconds{quantile=\"0.95\"} 200.0\n" + "# EOF\n"; String prometheusText = - "" + "# TYPE latency_seconds summary\n" + "latency_seconds{quantile=\"0.95\"} 200.0\n"; + "# TYPE latency_seconds summary\n" + "latency_seconds{quantile=\"0.95\"} 200.0\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"latency_seconds\" " + // @formatter:off + "name: \"latency_seconds\" " + "type: SUMMARY " + "metric { " + "summary { " @@ -821,13 +786,11 @@ public void testSummaryNoCountAndSum() throws IOException { @Test public void testSummaryJustCount() throws IOException { String openMetricsText = - "" + "# TYPE latency_seconds summary\n" + "latency_seconds_count 1\n" + "# EOF\n"; - String prometheusText = "" + "# TYPE latency_seconds summary\n" + "latency_seconds_count 1\n"; + "# TYPE latency_seconds summary\n" + "latency_seconds_count 1\n" + "# EOF\n"; + String prometheusText = "# TYPE latency_seconds summary\n" + "latency_seconds_count 1\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"latency_seconds\" " + // @formatter:off + "name: \"latency_seconds\" " + "type: SUMMARY " + "metric { " + "summary { " @@ -850,13 +813,11 @@ public void testSummaryJustCount() throws IOException { @Test public void testSummaryJustSum() throws IOException { String openMetricsText = - "" + "# TYPE latency_seconds summary\n" + "latency_seconds_sum 12.3\n" + "# EOF\n"; - String prometheusText = "" + "# TYPE latency_seconds summary\n" + "latency_seconds_sum 12.3\n"; + "# TYPE latency_seconds summary\n" + "latency_seconds_sum 12.3\n" + "# EOF\n"; + String prometheusText = "# TYPE latency_seconds summary\n" + "latency_seconds_sum 12.3\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"latency_seconds\" " + // @formatter:off + "name: \"latency_seconds\" " + "type: SUMMARY " + "metric { " + "summary { " @@ -897,21 +858,17 @@ public void testSummaryEmptyData() throws IOException { @Test public void testSummaryEmptyAndNonEmpty() throws IOException { String openMetricsText = - "" - + "# TYPE latency_seconds summary\n" + "# TYPE latency_seconds summary\n" + "latency_seconds_count{path=\"/v2\"} 2\n" + "latency_seconds_sum{path=\"/v2\"} 10.7\n" + "# EOF\n"; String prometheusText = - "" - + "# TYPE latency_seconds summary\n" + "# TYPE latency_seconds summary\n" + "latency_seconds_count{path=\"/v2\"} 2\n" + "latency_seconds_sum{path=\"/v2\"} 10.7\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"latency_seconds\" " + // @formatter:off + "name: \"latency_seconds\" " + "type: SUMMARY " + "metric { " + "label { name: \"path\" value: \"/v2\" } " @@ -943,16 +900,14 @@ public void testSummaryEmptyAndNonEmpty() throws IOException { @Test public void testSummaryWithDots() throws IOException { String openMetricsText = - "" - + "# TYPE my_request_duration_seconds summary\n" + "# TYPE my_request_duration_seconds summary\n" + "# UNIT my_request_duration_seconds seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "my_request_duration_seconds_count{http_path=\"/hello\"} 1\n" + "my_request_duration_seconds_sum{http_path=\"/hello\"} 0.03\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE my_request_duration_seconds summary\n" + "# TYPE my_request_duration_seconds summary\n" + "# UNIT my_request_duration_seconds seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "my_request_duration_seconds_count{http_path=\"/hello\"} 1 # " @@ -961,16 +916,13 @@ public void testSummaryWithDots() throws IOException { + "my_request_duration_seconds_sum{http_path=\"/hello\"} 0.03\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP my_request_duration_seconds Request duration in seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "# TYPE my_request_duration_seconds summary\n" + "my_request_duration_seconds_count{http_path=\"/hello\"} 1\n" + "my_request_duration_seconds_sum{http_path=\"/hello\"} 0.03\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"my_request_duration_seconds\" " + // @formatter:off + "name: \"my_request_duration_seconds\" " + "help: \"Request duration in seconds\" " + "type: SUMMARY " + "metric { " @@ -1002,8 +954,7 @@ public void testSummaryWithDots() throws IOException { @Test public void testClassicHistogramComplete() throws Exception { String openMetricsText = - "" - + "# TYPE response_size_bytes histogram\n" + "# TYPE response_size_bytes histogram\n" + "# UNIT response_size_bytes bytes\n" + "# HELP response_size_bytes help\n" + "response_size_bytes_bucket{status=\"200\",le=\"2.2\"} 2 " @@ -1053,8 +1004,7 @@ public void testClassicHistogramComplete() throws Exception { + "\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE response_size_bytes histogram\n" + "# TYPE response_size_bytes histogram\n" + "# UNIT response_size_bytes bytes\n" + "# HELP response_size_bytes help\n" + "response_size_bytes_bucket{status=\"200\",le=\"2.2\"} 2 " @@ -1108,8 +1058,7 @@ public void testClassicHistogramComplete() throws Exception { + "\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP response_size_bytes help\n" + "# HELP response_size_bytes help\n" + "# TYPE response_size_bytes histogram\n" + "response_size_bytes_bucket{status=\"200\",le=\"2.2\"} 2 " + scrapeTimestamp1s @@ -1151,8 +1100,7 @@ public void testClassicHistogramComplete() throws Exception { + scrapeTimestamp2s + "\n"; String openMetricsTextWithoutCreated = - "" - + "# TYPE response_size_bytes histogram\n" + "# TYPE response_size_bytes histogram\n" + "# UNIT response_size_bytes bytes\n" + "# HELP response_size_bytes help\n" + "response_size_bytes_bucket{status=\"200\",le=\"2.2\"} 2 " @@ -1192,8 +1140,7 @@ public void testClassicHistogramComplete() throws Exception { + "\n" + "# EOF\n"; String prometheusTextWithoutCreated = - "" - + "# HELP response_size_bytes help\n" + "# HELP response_size_bytes help\n" + "# TYPE response_size_bytes histogram\n" + "response_size_bytes_bucket{status=\"200\",le=\"2.2\"} 2 " + scrapeTimestamp1s @@ -1223,10 +1170,8 @@ public void testClassicHistogramComplete() throws Exception { + scrapeTimestamp2s + "\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"response_size_bytes\" " + // @formatter:off + "name: \"response_size_bytes\" " + "help: \"help\" " + "type: HISTOGRAM " + "metric { " @@ -1317,20 +1262,16 @@ public void testClassicHistogramMinimal() throws Exception { // In OpenMetrics a histogram can have a _count if and only if it has a _sum. // In Prometheus format, a histogram can have a _count without a _sum. String openMetricsText = - "" - + "# TYPE request_latency_seconds histogram\n" + "# TYPE request_latency_seconds histogram\n" + "request_latency_seconds_bucket{le=\"+Inf\"} 2\n" + "# EOF\n"; String prometheusText = - "" - + "# TYPE request_latency_seconds histogram\n" + "# TYPE request_latency_seconds histogram\n" + "request_latency_seconds_bucket{le=\"+Inf\"} 2\n" + "request_latency_seconds_count 2\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"request_latency_seconds\" " + // @formatter:off + "name: \"request_latency_seconds\" " + "type: HISTOGRAM " + "metric { " + "histogram { " @@ -1363,23 +1304,19 @@ public void testClassicHistogramMinimal() throws Exception { @Test public void testClassicHistogramCountAndSum() throws Exception { String openMetricsText = - "" - + "# TYPE request_latency_seconds histogram\n" + "# TYPE request_latency_seconds histogram\n" + "request_latency_seconds_bucket{le=\"+Inf\"} 2\n" + "request_latency_seconds_count 2\n" + "request_latency_seconds_sum 3.2\n" + "# EOF\n"; String prometheusText = - "" - + "# TYPE request_latency_seconds histogram\n" + "# TYPE request_latency_seconds histogram\n" + "request_latency_seconds_bucket{le=\"+Inf\"} 2\n" + "request_latency_seconds_count 2\n" + "request_latency_seconds_sum 3.2\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"request_latency_seconds\" " + // @formatter:off + "name: \"request_latency_seconds\" " + "type: HISTOGRAM " + "metric { " + "histogram { " @@ -1414,8 +1351,7 @@ public void testClassicHistogramCountAndSum() throws Exception { @Test public void testClassicGaugeHistogramComplete() throws IOException { String openMetricsText = - "" - + "# TYPE cache_size_bytes gaugehistogram\n" + "# TYPE cache_size_bytes gaugehistogram\n" + "# UNIT cache_size_bytes bytes\n" + "# HELP cache_size_bytes number of bytes in the cache\n" + "cache_size_bytes_bucket{db=\"items\",le=\"2.0\"} 3 " @@ -1462,8 +1398,7 @@ public void testClassicGaugeHistogramComplete() throws IOException { + "\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE cache_size_bytes gaugehistogram\n" + "# TYPE cache_size_bytes gaugehistogram\n" + "# UNIT cache_size_bytes bytes\n" + "# HELP cache_size_bytes number of bytes in the cache\n" + "cache_size_bytes_bucket{db=\"items\",le=\"2.0\"} 3 " @@ -1514,8 +1449,7 @@ public void testClassicGaugeHistogramComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP cache_size_bytes number of bytes in the cache\n" + "# HELP cache_size_bytes number of bytes in the cache\n" + "# TYPE cache_size_bytes histogram\n" + "cache_size_bytes_bucket{db=\"items\",le=\"2.0\"} 3 " + scrapeTimestamp1s @@ -1558,8 +1492,7 @@ public void testClassicGaugeHistogramComplete() throws IOException { + scrapeTimestamp2s + "\n"; String openMetricsTextWithoutCreated = - "" - + "# TYPE cache_size_bytes gaugehistogram\n" + "# TYPE cache_size_bytes gaugehistogram\n" + "# UNIT cache_size_bytes bytes\n" + "# HELP cache_size_bytes number of bytes in the cache\n" + "cache_size_bytes_bucket{db=\"items\",le=\"2.0\"} 3 " @@ -1596,8 +1529,7 @@ public void testClassicGaugeHistogramComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusTextWithoutCreated = - "" - + "# HELP cache_size_bytes number of bytes in the cache\n" + "# HELP cache_size_bytes number of bytes in the cache\n" + "# TYPE cache_size_bytes histogram\n" + "cache_size_bytes_bucket{db=\"items\",le=\"2.0\"} 3 " + scrapeTimestamp1s @@ -1628,10 +1560,8 @@ public void testClassicGaugeHistogramComplete() throws IOException { + scrapeTimestamp2s + "\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"cache_size_bytes\" " + // @formatter:off + "name: \"cache_size_bytes\" " + "help: \"number of bytes in the cache\" " + "type: GAUGE_HISTOGRAM " + "metric { " @@ -1719,21 +1649,17 @@ public void testClassicGaugeHistogramMinimal() throws IOException { // In OpenMetrics a histogram can have a _count if and only if it has a _sum. // In Prometheus format, a histogram can have a _count without a _sum. String openMetricsText = - "" - + "# TYPE queue_size_bytes gaugehistogram\n" + "# TYPE queue_size_bytes gaugehistogram\n" + "queue_size_bytes_bucket{le=\"+Inf\"} 130\n" + "# EOF\n"; String prometheusText = - "" - + "# TYPE queue_size_bytes histogram\n" + "# TYPE queue_size_bytes histogram\n" + "queue_size_bytes_bucket{le=\"+Inf\"} 130\n" + "# TYPE queue_size_bytes_gcount gauge\n" + "queue_size_bytes_gcount 130\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"queue_size_bytes\" " + // @formatter:off + "name: \"queue_size_bytes\" " + "type: GAUGE_HISTOGRAM " + "metric { " + "histogram { " @@ -1767,25 +1693,21 @@ public void testClassicGaugeHistogramMinimal() throws IOException { @Test public void testClassicGaugeHistogramCountAndSum() throws IOException { String openMetricsText = - "" - + "# TYPE queue_size_bytes gaugehistogram\n" + "# TYPE queue_size_bytes gaugehistogram\n" + "queue_size_bytes_bucket{le=\"+Inf\"} 130\n" + "queue_size_bytes_gcount 130\n" + "queue_size_bytes_gsum 27000.0\n" + "# EOF\n"; String prometheusText = - "" - + "# TYPE queue_size_bytes histogram\n" + "# TYPE queue_size_bytes histogram\n" + "queue_size_bytes_bucket{le=\"+Inf\"} 130\n" + "# TYPE queue_size_bytes_gcount gauge\n" + "queue_size_bytes_gcount 130\n" + "# TYPE queue_size_bytes_gsum gauge\n" + "queue_size_bytes_gsum 27000.0\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"queue_size_bytes\" " + // @formatter:off + "name: \"queue_size_bytes\" " + "type: GAUGE_HISTOGRAM " + "metric { " + "histogram { " @@ -1821,8 +1743,7 @@ public void testClassicGaugeHistogramCountAndSum() throws IOException { @Test public void testClassicHistogramWithDots() throws IOException { String openMetricsText = - "" - + "# TYPE my_request_duration_seconds histogram\n" + "# TYPE my_request_duration_seconds histogram\n" + "# UNIT my_request_duration_seconds seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "my_request_duration_seconds_bucket{http_path=\"/hello\",le=\"+Inf\"} 130 # " @@ -1832,8 +1753,7 @@ public void testClassicHistogramWithDots() throws IOException { + "my_request_duration_seconds_sum{http_path=\"/hello\"} 0.01\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE my_request_duration_seconds histogram\n" + "# TYPE my_request_duration_seconds histogram\n" + "# UNIT my_request_duration_seconds seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "my_request_duration_seconds_bucket{http_path=\"/hello\",le=\"+Inf\"} 130 # " @@ -1845,17 +1765,14 @@ public void testClassicHistogramWithDots() throws IOException { + "my_request_duration_seconds_sum{http_path=\"/hello\"} 0.01\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP my_request_duration_seconds Request duration in seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "# TYPE my_request_duration_seconds histogram\n" + "my_request_duration_seconds_bucket{http_path=\"/hello\",le=\"+Inf\"} 130\n" + "my_request_duration_seconds_count{http_path=\"/hello\"} 130\n" + "my_request_duration_seconds_sum{http_path=\"/hello\"} 0.01\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"my_request_duration_seconds\" " + // @formatter:off + "name: \"my_request_duration_seconds\" " + "help: \"Request duration in seconds\" " + "type: HISTOGRAM " + "metric { " @@ -1896,8 +1813,7 @@ public void testClassicHistogramWithDots() throws IOException { @Test public void testNativeHistogramComplete() throws IOException { String openMetricsText = - "" - + "# TYPE response_size_bytes histogram\n" + "# TYPE response_size_bytes histogram\n" + "# UNIT response_size_bytes bytes\n" + "# HELP response_size_bytes help\n" + "response_size_bytes_bucket{status=\"200\",le=\"+Inf\"} 2 " @@ -1934,8 +1850,7 @@ public void testNativeHistogramComplete() throws IOException { + "\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE response_size_bytes histogram\n" + "# TYPE response_size_bytes histogram\n" + "# UNIT response_size_bytes bytes\n" + "# HELP response_size_bytes help\n" + "response_size_bytes_bucket{status=\"200\",le=\"+Inf\"} 2 " @@ -1976,8 +1891,7 @@ public void testNativeHistogramComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP response_size_bytes help\n" + "# HELP response_size_bytes help\n" + "# TYPE response_size_bytes histogram\n" + "response_size_bytes_bucket{status=\"200\",le=\"+Inf\"} 2 " + scrapeTimestamp1s @@ -2010,8 +1924,7 @@ public void testNativeHistogramComplete() throws IOException { + scrapeTimestamp2s + "\n"; String openMetricsTextWithoutCreated = - "" - + "# TYPE response_size_bytes histogram\n" + "# TYPE response_size_bytes histogram\n" + "# UNIT response_size_bytes bytes\n" + "# HELP response_size_bytes help\n" + "response_size_bytes_bucket{status=\"200\",le=\"+Inf\"} 2 " @@ -2038,8 +1951,7 @@ public void testNativeHistogramComplete() throws IOException { + "\n" + "# EOF\n"; String prometheusTextWithoutCreated = - "" - + "# HELP response_size_bytes help\n" + "# HELP response_size_bytes help\n" + "# TYPE response_size_bytes histogram\n" + "response_size_bytes_bucket{status=\"200\",le=\"+Inf\"} 2 " + scrapeTimestamp1s @@ -2060,10 +1972,8 @@ public void testNativeHistogramComplete() throws IOException { + scrapeTimestamp2s + "\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"response_size_bytes\" " + // @formatter:off + "name: \"response_size_bytes\" " + "help: \"help\" " + "type: HISTOGRAM " + "metric { " @@ -2214,20 +2124,16 @@ public void testNativeHistogramComplete() throws IOException { @Test public void testNativeHistogramMinimal() throws IOException { String openMetricsText = - "" - + "# TYPE latency_seconds histogram\n" + "# TYPE latency_seconds histogram\n" + "latency_seconds_bucket{le=\"+Inf\"} 0\n" + "# EOF\n"; String prometheusText = - "" - + "# TYPE latency_seconds histogram\n" + "# TYPE latency_seconds histogram\n" + "latency_seconds_bucket{le=\"+Inf\"} 0\n" + "latency_seconds_count 0\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"latency_seconds\" " + // @formatter:off + "name: \"latency_seconds\" " + "type: HISTOGRAM " + "metric { " + "histogram { " @@ -2252,8 +2158,7 @@ public void testNativeHistogramMinimal() throws IOException { @Test public void testNativeHistogramWithDots() throws IOException { String openMetricsText = - "" - + "# TYPE my_request_duration_seconds histogram\n" + "# TYPE my_request_duration_seconds histogram\n" + "# UNIT my_request_duration_seconds seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "my_request_duration_seconds_bucket{http_path=\"/hello\",le=\"+Inf\"} 4 # " @@ -2263,8 +2168,7 @@ public void testNativeHistogramWithDots() throws IOException { + "my_request_duration_seconds_sum{http_path=\"/hello\"} 3.2\n" + "# EOF\n"; String openMetricsTextWithExemplarsOnAllTimeSeries = - "" - + "# TYPE my_request_duration_seconds histogram\n" + "# TYPE my_request_duration_seconds histogram\n" + "# UNIT my_request_duration_seconds seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "my_request_duration_seconds_bucket{http_path=\"/hello\",le=\"+Inf\"} 4 # " @@ -2276,17 +2180,14 @@ public void testNativeHistogramWithDots() throws IOException { + "my_request_duration_seconds_sum{http_path=\"/hello\"} 3.2\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP my_request_duration_seconds Request duration in seconds\n" + "# HELP my_request_duration_seconds Request duration in seconds\n" + "# TYPE my_request_duration_seconds histogram\n" + "my_request_duration_seconds_bucket{http_path=\"/hello\",le=\"+Inf\"} 4\n" + "my_request_duration_seconds_count{http_path=\"/hello\"} 4\n" + "my_request_duration_seconds_sum{http_path=\"/hello\"} 3.2\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"my_request_duration_seconds\" " + // @formatter:off + "name: \"my_request_duration_seconds\" " + "help: \"Request duration in seconds\" " + "type: HISTOGRAM " + "metric { " @@ -2334,14 +2235,12 @@ public void testNativeHistogramWithDots() throws IOException { @Test public void testInfo() throws IOException { String openMetrics = - "" - + "# TYPE version info\n" + "# TYPE version info\n" + "# HELP version version information\n" + "version_info{version=\"1.2.3\"} 1\n" + "# EOF\n"; String prometheus = - "" - + "# HELP version_info version information\n" + "# HELP version_info version information\n" + "# TYPE version_info gauge\n" + "version_info{version=\"1.2.3\"} 1\n"; InfoSnapshot info = @@ -2362,25 +2261,20 @@ public void testInfo() throws IOException { @Test public void testInfoWithDots() throws IOException { String openMetricsText = - "" - + "# TYPE jvm_status info\n" + "# TYPE jvm_status info\n" + "# HELP jvm_status JVM status info\n" + "jvm_status_info{jvm_version=\"1.2.3\"} 1\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP jvm_status_info JVM status info\n" + "# HELP jvm_status_info JVM status info\n" + "# TYPE jvm_status_info gauge\n" + "jvm_status_info{jvm_version=\"1.2.3\"} 1\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"jvm_status_info\" " + // @formatter:off + "name: \"jvm_status_info\" " + "help: \"JVM status info\" " + "type: GAUGE " + "metric { " - + "" + "label { name: \"jvm_version\" value: \"1.2.3\" } " + "gauge { value: 1.0 } " + "}"; @@ -2402,8 +2296,7 @@ public void testInfoWithDots() throws IOException { @Test public void testStateSetComplete() throws IOException { String openMetrics = - "" - + "# TYPE state stateset\n" + "# TYPE state stateset\n" + "# HELP state complete state set example\n" + "state{env=\"dev\",state=\"state1\"} 1 " + scrapeTimestamp1s @@ -2419,8 +2312,7 @@ public void testStateSetComplete() throws IOException { + "\n" + "# EOF\n"; String prometheus = - "" - + "# HELP state complete state set example\n" + "# HELP state complete state set example\n" + "# TYPE state gauge\n" + "state{env=\"dev\",state=\"state1\"} 1 " + scrapeTimestamp1s @@ -2462,13 +2354,12 @@ public void testStateSetComplete() throws IOException { @Test public void testStateSetMinimal() throws IOException { String openMetrics = - "" - + "# TYPE state stateset\n" + "# TYPE state stateset\n" + "state{state=\"a\"} 1\n" + "state{state=\"bb\"} 0\n" + "# EOF\n"; String prometheus = - "" + "# TYPE state gauge\n" + "state{state=\"a\"} 1\n" + "state{state=\"bb\"} 0\n"; + "# TYPE state gauge\n" + "state{state=\"a\"} 1\n" + "state{state=\"bb\"} 0\n"; StateSetSnapshot stateSet = StateSetSnapshot.builder() .name("state") @@ -2487,23 +2378,19 @@ public void testStateSetMinimal() throws IOException { @Test public void testStateSetWithDots() throws IOException { String openMetricsText = - "" - + "# TYPE my_application_state stateset\n" + "# TYPE my_application_state stateset\n" + "# HELP my_application_state My application state\n" + "my_application_state{data_center=\"us east\",my_application_state=\"feature.enabled\"} 1\n" + "my_application_state{data_center=\"us east\",my_application_state=\"is.alpha.version\"} 0\n" + "# EOF\n"; String prometheusText = - "" - + "# HELP my_application_state My application state\n" + "# HELP my_application_state My application state\n" + "# TYPE my_application_state gauge\n" + "my_application_state{data_center=\"us east\",my_application_state=\"feature.enabled\"} 1\n" + "my_application_state{data_center=\"us east\",my_application_state=\"is.alpha.version\"} 0\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"my_application_state\" " + // @formatter:off + "name: \"my_application_state\" " + "help: \"My application state\" " + "type: GAUGE " + "metric { " @@ -2535,8 +2422,7 @@ public void testStateSetWithDots() throws IOException { @Test public void testUnknownComplete() throws IOException { String openMetrics = - "" - + "# TYPE my_special_thing_bytes unknown\n" + "# TYPE my_special_thing_bytes unknown\n" + "# UNIT my_special_thing_bytes bytes\n" + "# HELP my_special_thing_bytes help message\n" + "my_special_thing_bytes{env=\"dev\"} 0.2 " @@ -2547,8 +2433,7 @@ public void testUnknownComplete() throws IOException { + "\n" + "# EOF\n"; String openMetricsWithExemplarsOnAllTimeSeries = - "" - + "# TYPE my_special_thing_bytes unknown\n" + "# TYPE my_special_thing_bytes unknown\n" + "# UNIT my_special_thing_bytes bytes\n" + "# HELP my_special_thing_bytes help message\n" + "my_special_thing_bytes{env=\"dev\"} 0.2 " @@ -2563,8 +2448,7 @@ public void testUnknownComplete() throws IOException { + "\n" + "# EOF\n"; String prometheus = - "" - + "# HELP my_special_thing_bytes help message\n" + "# HELP my_special_thing_bytes help message\n" + "# TYPE my_special_thing_bytes untyped\n" + "my_special_thing_bytes{env=\"dev\"} 0.2 " + scrapeTimestamp1s @@ -2602,8 +2486,8 @@ public void testUnknownComplete() throws IOException { @Test public void testUnknownMinimal() throws IOException { - String openMetrics = "" + "# TYPE other unknown\n" + "other 22.3\n" + "# EOF\n"; - String prometheus = "" + "# TYPE other untyped\n" + "other 22.3\n"; + String openMetrics = "# TYPE other unknown\n" + "other 22.3\n" + "# EOF\n"; + String prometheus = "# TYPE other untyped\n" + "other 22.3\n"; UnknownSnapshot unknown = UnknownSnapshot.builder() .name("other") @@ -2618,15 +2502,13 @@ public void testUnknownMinimal() throws IOException { @Test public void testUnknownWithDots() throws IOException { String openMetrics = - "" - + "# TYPE some_unknown_metric_bytes unknown\n" + "# TYPE some_unknown_metric_bytes unknown\n" + "# UNIT some_unknown_metric_bytes bytes\n" + "# HELP some_unknown_metric_bytes help message\n" + "some_unknown_metric_bytes{test_env=\"7\"} 0.7\n" + "# EOF\n"; String openMetricsWithExemplarsOnAllTimeSeries = - "" - + "# TYPE some_unknown_metric_bytes unknown\n" + "# TYPE some_unknown_metric_bytes unknown\n" + "# UNIT some_unknown_metric_bytes bytes\n" + "# HELP some_unknown_metric_bytes help message\n" + "some_unknown_metric_bytes{test_env=\"7\"} 0.7 # " @@ -2634,15 +2516,12 @@ public void testUnknownWithDots() throws IOException { + "\n" + "# EOF\n"; String prometheus = - "" - + "# HELP some_unknown_metric_bytes help message\n" + "# HELP some_unknown_metric_bytes help message\n" + "# TYPE some_unknown_metric_bytes untyped\n" + "some_unknown_metric_bytes{test_env=\"7\"} 0.7\n"; String prometheusProtobuf = - "" - + - // @formatter:off - "name: \"some_unknown_metric_bytes\" " + // @formatter:off + "name: \"some_unknown_metric_bytes\" " + "help: \"help message\" " + "type: UNTYPED " + "metric { " @@ -2672,14 +2551,12 @@ public void testUnknownWithDots() throws IOException { @Test public void testHelpEscape() throws IOException { String openMetrics = - "" - + "# TYPE test counter\n" + "# TYPE test counter\n" + "# HELP test Some text and \\n some \\\" escaping\n" + "test_total 1.0\n" + "# EOF\n"; String prometheus = - "" - + "# HELP test_total Some text and \\n some \" escaping\n" + "# HELP test_total Some text and \\n some \" escaping\n" + "# TYPE test_total counter\n" + "test_total 1.0\n"; CounterSnapshot counter = @@ -2697,14 +2574,11 @@ public void testHelpEscape() throws IOException { @Test public void testLabelValueEscape() throws IOException { String openMetrics = - "" - + "# TYPE test counter\n" + "# TYPE test counter\n" + "test_total{a=\"x\",b=\"escaping\\\" example \\n \"} 1.0\n" + "# EOF\n"; String prometheus = - "" - + "# TYPE test_total counter\n" - + "test_total{a=\"x\",b=\"escaping\\\" example \\n \"} 1.0\n"; + "# TYPE test_total counter\n" + "test_total{a=\"x\",b=\"escaping\\\" example \\n \"} 1.0\n"; CounterSnapshot counter = CounterSnapshot.builder() .name("test") @@ -2723,7 +2597,7 @@ private void assertOpenMetricsText(String expected, MetricSnapshot snapshot) thr ByteArrayOutputStream out = new ByteArrayOutputStream(); OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(true, false); writer.write(out, MetricSnapshots.of(snapshot)); - Assert.assertEquals(expected, out.toString()); + assertThat(out).hasToString(expected); } private void assertOpenMetricsTextWithExemplarsOnAllTimeSeries( @@ -2731,7 +2605,7 @@ private void assertOpenMetricsTextWithExemplarsOnAllTimeSeries( ByteArrayOutputStream out = new ByteArrayOutputStream(); OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(true, true); writer.write(out, MetricSnapshots.of(snapshot)); - Assert.assertEquals(expected, out.toString()); + assertThat(out).hasToString(expected); } private void assertOpenMetricsTextWithoutCreated(String expected, MetricSnapshot snapshot) @@ -2739,14 +2613,14 @@ private void assertOpenMetricsTextWithoutCreated(String expected, MetricSnapshot ByteArrayOutputStream out = new ByteArrayOutputStream(); OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(false, false); writer.write(out, MetricSnapshots.of(snapshot)); - Assert.assertEquals(expected, out.toString()); + assertThat(out).hasToString(expected); } private void assertPrometheusText(String expected, MetricSnapshot snapshot) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrometheusTextFormatWriter writer = new PrometheusTextFormatWriter(true); writer.write(out, MetricSnapshots.of(snapshot)); - Assert.assertEquals(expected, out.toString()); + assertThat(out).hasToString(expected); } private void assertPrometheusTextWithoutCreated(String expected, MetricSnapshot snapshot) @@ -2754,13 +2628,13 @@ private void assertPrometheusTextWithoutCreated(String expected, MetricSnapshot ByteArrayOutputStream out = new ByteArrayOutputStream(); PrometheusTextFormatWriter writer = new PrometheusTextFormatWriter(false); writer.write(out, MetricSnapshots.of(snapshot)); - Assert.assertEquals(expected, out.toString()); + assertThat(out).hasToString(expected); } private void assertPrometheusProtobuf(String expected, MetricSnapshot snapshot) { PrometheusProtobufWriter writer = new PrometheusProtobufWriter(); Metrics.MetricFamily protobufData = writer.convert(snapshot); String actual = TextFormat.printer().shortDebugString(protobufData); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } } diff --git a/prometheus-metrics-instrumentation-caffeine/pom.xml b/prometheus-metrics-instrumentation-caffeine/pom.xml index a1b560251..a12f26918 100644 --- a/prometheus-metrics-instrumentation-caffeine/pom.xml +++ b/prometheus-metrics-instrumentation-caffeine/pom.xml @@ -54,28 +54,8 @@ 3.1.8 provided - - - - junit - junit - 4.13.2 - test - - - - org.mockito - mockito-core - 5.12.0 - test - - - org.assertj - assertj-core - 3.26.3 - test - + io.prometheus prometheus-metrics-exposition-formats diff --git a/prometheus-metrics-instrumentation-caffeine/src/test/java/io/prometheus/metrics/instrumentation/caffeine/CacheMetricsCollectorTest.java b/prometheus-metrics-instrumentation-caffeine/src/test/java/io/prometheus/metrics/instrumentation/caffeine/CacheMetricsCollectorTest.java index acbfe3e1e..f74d5d041 100644 --- a/prometheus-metrics-instrumentation-caffeine/src/test/java/io/prometheus/metrics/instrumentation/caffeine/CacheMetricsCollectorTest.java +++ b/prometheus-metrics-instrumentation-caffeine/src/test/java/io/prometheus/metrics/instrumentation/caffeine/CacheMetricsCollectorTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.caffeine; -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -20,26 +20,15 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; -import java.util.concurrent.Executor; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CacheMetricsCollectorTest { +class CacheMetricsCollectorTest { @Test public void cacheExposesMetricsForHitMissAndEviction() { + // Run cleanup in same thread, to remove async behavior with evictions final Cache cache = - Caffeine.newBuilder() - .maximumSize(2) - .recordStats() - .executor( - new Executor() { - @Override - public void execute(Runnable command) { - // Run cleanup in same thread, to remove async behavior with evictions - command.run(); - } - }) - .build(); + Caffeine.newBuilder().maximumSize(2).recordStats().executor(Runnable::run).build(); final CacheMetricsCollector collector = new CacheMetricsCollector(); collector.addCache("users", cache); @@ -83,7 +72,7 @@ public void execute(Runnable command) { + "caffeine_cache_requests_total{cache=\"users\"} 3.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(registry)); + assertThat(convertToOpenMetricsFormat(registry)).isEqualTo(expected); } @SuppressWarnings("unchecked") @@ -122,7 +111,7 @@ public void loadingCacheExposesMetricsForLoadsAndExceptions() throws Exception { (SummarySnapshot.SummaryDataPointSnapshot) getDataPointSnapshot(registry, "caffeine_cache_load_duration_seconds", "loadingusers"); - assertEquals(3, loadDuration.getCount()); + assertThat(loadDuration.getCount()).isEqualTo(3); assertThat(loadDuration.getSum()).isGreaterThan(0); } @@ -131,7 +120,7 @@ private void assertCounterMetric( final CounterSnapshot.CounterDataPointSnapshot dataPointSnapshot = (CounterSnapshot.CounterDataPointSnapshot) getDataPointSnapshot(registry, name, cacheName); - assertEquals(value, dataPointSnapshot.getValue(), 0); + assertThat(dataPointSnapshot.getValue()).isCloseTo(value, offset(0.0)); } private DataPointSnapshot getDataPointSnapshot( diff --git a/prometheus-metrics-instrumentation-dropwizard5/pom.xml b/prometheus-metrics-instrumentation-dropwizard5/pom.xml index 085e6de74..8de53d0f0 100644 --- a/prometheus-metrics-instrumentation-dropwizard5/pom.xml +++ b/prometheus-metrics-instrumentation-dropwizard5/pom.xml @@ -54,26 +54,7 @@ 5.0.0 provided - - - junit - junit - 4.13.2 - test - - - org.assertj - assertj-core - 3.25.3 - test - - - org.mockito - mockito-core - 5.12.0 - test - - + io.prometheus prometheus-metrics-exporter-httpserver diff --git a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExportsTest.java b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExportsTest.java index 0473329ce..11402fa7e 100644 --- a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExportsTest.java +++ b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExportsTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.dropwizard5; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import io.dropwizard.metrics5.*; import io.prometheus.metrics.expositionformats.OpenMetricsTextFormatWriter; @@ -13,16 +13,15 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class DropwizardExportsTest { +class DropwizardExportsTest { private PrometheusRegistry registry = new PrometheusRegistry(); private MetricRegistry metricRegistry; - @Before + @BeforeEach public void setUp() { metricRegistry = new MetricRegistry(); DropwizardExports.builder().dropwizardRegistry(metricRegistry).register(registry); @@ -37,11 +36,12 @@ public void testCounter() { + "foo_bar_total 1.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat()); + assertThat(convertToOpenMetricsFormat()).isEqualTo(expected); } @Test public void testGauge() { + // don't convert to lambda, as we need to test the type Gauge integerGauge = new Gauge() { @Override @@ -102,41 +102,29 @@ public Boolean getValue() { + "long_gauge 1234.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat()); + assertThat(convertToOpenMetricsFormat()).isEqualTo(expected); } @Test public void testInvalidGaugeType() { - Gauge invalidGauge = - new Gauge() { - @Override - public String getValue() { - return "foobar"; - } - }; + Gauge invalidGauge = () -> "foobar"; metricRegistry.register("invalid_gauge", invalidGauge); String expected = "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat()); + assertThat(convertToOpenMetricsFormat()).isEqualTo(expected); } @Test public void testGaugeReturningNullValue() { - Gauge invalidGauge = - new Gauge() { - @Override - public String getValue() { - return null; - } - }; + Gauge invalidGauge = () -> null; metricRegistry.register("invalid_gauge", invalidGauge); String expected = "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat()); + assertThat(convertToOpenMetricsFormat()).isEqualTo(expected); } @Test - public void testHistogram() throws IOException { + public void testHistogram() { // just test the standard mapper final MetricRegistry metricRegistry = new MetricRegistry(); PrometheusRegistry pmRegistry = new PrometheusRegistry(); @@ -181,31 +169,31 @@ public void testHistogram() throws IOException { // The following asserts the values, but allows an error of 1.0 for quantile values. MetricSnapshots snapshots = pmRegistry.scrape(name -> name.equals("hist")); - Assert.assertEquals(1, snapshots.size()); + assertThat(snapshots.size()).isOne(); SummarySnapshot snapshot = (SummarySnapshot) snapshots.get(0); - Assert.assertEquals("hist", snapshot.getMetadata().getName()); - Assert.assertEquals( - "Generated from Dropwizard metric import (metric=hist, type=io.dropwizard.metrics5.Histogram)", - snapshot.getMetadata().getHelp()); - Assert.assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getMetadata().getName()).isEqualTo("hist"); + assertThat(snapshot.getMetadata().getHelp()) + .isEqualTo( + "Generated from Dropwizard metric import (metric=hist, type=io.dropwizard.metrics5.Histogram)"); + assertThat(snapshot.getDataPoints().size()).isOne(); SummarySnapshot.SummaryDataPointSnapshot dataPoint = snapshot.getDataPoints().get(0); - Assert.assertTrue(dataPoint.hasCount()); - Assert.assertEquals(100, dataPoint.getCount()); - Assert.assertFalse(dataPoint.hasSum()); + assertThat(dataPoint.hasCount()).isTrue(); + assertThat(dataPoint.getCount()).isEqualTo(100); + assertThat(dataPoint.hasSum()).isFalse(); Quantiles quantiles = dataPoint.getQuantiles(); - Assert.assertEquals(6, quantiles.size()); - Assert.assertEquals(0.5, quantiles.get(0).getQuantile(), 0.0); - Assert.assertEquals(49.0, quantiles.get(0).getValue(), 1.0); - Assert.assertEquals(0.75, quantiles.get(1).getQuantile(), 0.0); - Assert.assertEquals(74.0, quantiles.get(1).getValue(), 1.0); - Assert.assertEquals(0.95, quantiles.get(2).getQuantile(), 0.0); - Assert.assertEquals(94.0, quantiles.get(2).getValue(), 1.0); - Assert.assertEquals(0.98, quantiles.get(3).getQuantile(), 0.0); - Assert.assertEquals(97.0, quantiles.get(3).getValue(), 1.0); - Assert.assertEquals(0.99, quantiles.get(4).getQuantile(), 0.0); - Assert.assertEquals(98.0, quantiles.get(4).getValue(), 1.0); - Assert.assertEquals(0.999, quantiles.get(5).getQuantile(), 0.0); - Assert.assertEquals(99.0, quantiles.get(5).getValue(), 1.0); + assertThat(quantiles.size()).isEqualTo(6); + assertThat(quantiles.get(0).getQuantile()).isCloseTo(0.5, offset(0.0)); + assertThat(quantiles.get(0).getValue()).isCloseTo(49.0, offset(1.0)); + assertThat(quantiles.get(1).getQuantile()).isCloseTo(0.75, offset(0.0)); + assertThat(quantiles.get(1).getValue()).isCloseTo(74.0, offset(1.0)); + assertThat(quantiles.get(2).getQuantile()).isCloseTo(0.95, offset(0.0)); + assertThat(quantiles.get(2).getValue()).isCloseTo(94.0, offset(1.0)); + assertThat(quantiles.get(3).getQuantile()).isCloseTo(0.98, offset(0.0)); + assertThat(quantiles.get(3).getValue()).isCloseTo(97.0, offset(1.0)); + assertThat(quantiles.get(4).getQuantile()).isCloseTo(0.99, offset(0.0)); + assertThat(quantiles.get(4).getValue()).isCloseTo(98.0, offset(1.0)); + assertThat(quantiles.get(5).getQuantile()).isCloseTo(0.999, offset(0.0)); + assertThat(quantiles.get(5).getValue()).isCloseTo(99.0, offset(1.0)); } @Test @@ -219,7 +207,7 @@ public void testMeter() { + "# HELP meter Generated from Dropwizard metric import (metric=meter_total, type=io.dropwizard.metrics5.Meter)\n" + "meter_total 2.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat()); + assertThat(convertToOpenMetricsFormat()).isEqualTo(expected); } @Test @@ -237,15 +225,15 @@ public void testTimer() throws InterruptedException { (SummarySnapshot.SummaryDataPointSnapshot) exports.collect().stream().flatMap(i -> i.getDataPoints().stream()).findFirst().get(); // We slept for 1Ms so we ensure that all timers are above 1ms: - assertTrue(dataPointSnapshot.getQuantiles().size() > 1); + assertThat(dataPointSnapshot.getQuantiles().size()).isGreaterThan(1); dataPointSnapshot .getQuantiles() .forEach( i -> { System.out.println(i.getQuantile() + " : " + i.getValue()); - assertTrue(i.getValue() > timeSpentMillis / 1000d); + assertThat(i.getValue()).isGreaterThan(timeSpentMillis / 1000d); }); - assertEquals(1, dataPointSnapshot.getCount()); + assertThat(dataPointSnapshot.getCount()).isOne(); } @Test @@ -286,7 +274,7 @@ public void testThatMetricHelpUsesOriginalDropwizardName() { + "my_application_namedTimer1{quantile=\"0.999\"} 0.0\n" + "my_application_namedTimer1_count 0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat()); + assertThat(convertToOpenMetricsFormat()).isEqualTo(expected); } private static class ExampleDoubleGauge implements Gauge { diff --git a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/CustomLabelMapperTest.java b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/CustomLabelMapperTest.java index 5d1950111..ac0b0a328 100644 --- a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/CustomLabelMapperTest.java +++ b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/CustomLabelMapperTest.java @@ -1,6 +1,7 @@ package io.prometheus.metrics.instrumentation.dropwizard5.labels; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import io.dropwizard.metrics5.MetricFilter; import io.dropwizard.metrics5.MetricRegistry; @@ -11,21 +12,21 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class CustomLabelMapperTest { +class CustomLabelMapperTest { private MetricRegistry metricRegistry; - @Before + @BeforeEach public void setUp() { metricRegistry = new MetricRegistry(); } - @Test(expected = IllegalArgumentException.class) + @Test public void test_WHEN_EmptyConfig_THEN_Fail() { - final CustomLabelMapper converter = - new CustomLabelMapper(Collections.emptyList()); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new CustomLabelMapper(Collections.emptyList())); } @Test @@ -48,7 +49,7 @@ public void test_WHEN_NoMatches_THEN_ShouldReturnDefaultSample() { + "app_okhttpclient_client_HttpClient_service_total 1.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(dropwizardExports.collect())); + assertThat(convertToOpenMetricsFormat(dropwizardExports.collect())).isEqualTo(expected); } @Test @@ -76,12 +77,12 @@ public void test_WHEN_OneMatch_THEN_ShouldReturnConverted() { + "# HELP app_okhttpclient_client_HttpClient Generated from Dropwizard metric import (metric=app.okhttpclient.client.HttpClient.greatService.total, type=io.dropwizard.metrics5.Counter)\n" + "app_okhttpclient_client_HttpClient_total{service=\"greatService\"} 1.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(dropwizardExports.collect())); + assertThat(convertToOpenMetricsFormat(dropwizardExports.collect())).isEqualTo(expected); } @Test public void test_WHEN_MoreMatches_THEN_ShouldReturnFirstOne() { - final Map labels = new HashMap(); + final Map labels = new HashMap<>(); labels.put("service", "${0}"); final MapperConfig mapperConfig = new MapperConfig( @@ -105,12 +106,12 @@ public void test_WHEN_MoreMatches_THEN_ShouldReturnFirstOne() { + "# HELP app_okhttpclient_client_HttpClient Generated from Dropwizard metric import (metric=app.okhttpclient.client.HttpClient.greatService.total, type=io.dropwizard.metrics5.Counter)\n" + "app_okhttpclient_client_HttpClient_total{service=\"greatService\"} 1.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(dropwizardExports.collect())); + assertThat(convertToOpenMetricsFormat(dropwizardExports.collect())).isEqualTo(expected); } @Test public void test_WHEN_MoreMatchesReverseOrder_THEN_ShouldReturnFirstOne() { - final Map labels = new LinkedHashMap(); + final Map labels = new LinkedHashMap<>(); labels.put("service", "${0}"); labels.put("status", "${1}"); final MapperConfig mapperConfig = @@ -140,12 +141,12 @@ public void test_WHEN_MoreMatchesReverseOrder_THEN_ShouldReturnFirstOne() { + "# HELP app_okhttpclient_client_HttpClient Generated from Dropwizard metric import (metric=app.okhttpclient.client.HttpClient.greatService.400, type=io.dropwizard.metrics5.Counter)\n" + "app_okhttpclient_client_HttpClient_total{service=\"greatService\",status=\"400\"} 1.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(dropwizardExports.collect())); + assertThat(convertToOpenMetricsFormat(dropwizardExports.collect())).isEqualTo(expected); } @Test public void test_WHEN_MoreToFormatInLabelsAndName_THEN_ShouldReturnCorrectSample() { - final Map labels = new LinkedHashMap(); + final Map labels = new LinkedHashMap<>(); labels.put("service", "${0}_${1}"); labels.put("status", "s_${1}"); final MapperConfig mapperConfig = @@ -171,12 +172,12 @@ public void test_WHEN_MoreToFormatInLabelsAndName_THEN_ShouldReturnCorrectSample + "# HELP app_okhttpclient_client_HttpClient_greatService Generated from Dropwizard metric import (metric=app.okhttpclient.client.HttpClient.greatService.400, type=io.dropwizard.metrics5.Counter)\n" + "app_okhttpclient_client_HttpClient_greatService_total{service=\"greatService_400\",status=\"s_400\"} 1.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(dropwizardExports.collect())); + assertThat(convertToOpenMetricsFormat(dropwizardExports.collect())).isEqualTo(expected); } @Test public void test_WHEN_AdditionalLabels_THEN_ShouldReturnCorrectSample() { - final Map labels = new LinkedHashMap(); + final Map labels = new LinkedHashMap<>(); labels.put("service", "${0}"); labels.put("status", "s_${1}"); labels.put("client", "sampleClient"); @@ -198,7 +199,7 @@ public void test_WHEN_AdditionalLabels_THEN_ShouldReturnCorrectSample() { + "# HELP app_okhttpclient_client_HttpClient_greatService Generated from Dropwizard metric import (metric=app.okhttpclient.client.HttpClient.greatService.400, type=io.dropwizard.metrics5.Counter)\n" + "app_okhttpclient_client_HttpClient_greatService_total{client=\"sampleClient\",service=\"greatService\",status=\"s_400\"} 1.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(dropwizardExports.collect())); + assertThat(convertToOpenMetricsFormat(dropwizardExports.collect())).isEqualTo(expected); } private String convertToOpenMetricsFormat(MetricSnapshots snapshots) { diff --git a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/GraphiteNamePatternTest.java b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/GraphiteNamePatternTest.java index 9e8316d0b..ed27d7f22 100644 --- a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/GraphiteNamePatternTest.java +++ b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/GraphiteNamePatternTest.java @@ -1,18 +1,20 @@ package io.prometheus.metrics.instrumentation.dropwizard5.labels; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.assertj.core.api.Assertions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GraphiteNamePatternTest { +class GraphiteNamePatternTest { - @Test(expected = IllegalArgumentException.class) + @Test public void createNew_WHEN_InvalidPattern_THEN_ShouldThrowException() { - final List invalidPatterns = + List invalidPatterns = Arrays.asList( "", "a", @@ -29,15 +31,10 @@ public void createNew_WHEN_InvalidPattern_THEN_ShouldThrowException() { "org.com*pany.*", "org.test.contr.oller.gather.status..400", "org.test.controller.gather.status..400"); - final GraphiteNamePattern graphiteNamePattern = new GraphiteNamePattern(""); for (String pattern : invalidPatterns) { - try { - new GraphiteNamePattern(pattern); - - Assertions.failBecauseExceptionWasNotThrown(IllegalArgumentException.class); - } catch (IllegalArgumentException e) { - Assertions.assertThat(e).hasMessageContaining(pattern); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new GraphiteNamePattern(pattern)) + .withMessageContaining(pattern); } } diff --git a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfigTest.java b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfigTest.java index 7bf7b6520..a17963e0d 100644 --- a/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfigTest.java +++ b/prometheus-metrics-instrumentation-dropwizard5/src/test/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfigTest.java @@ -1,48 +1,50 @@ package io.prometheus.metrics.instrumentation.dropwizard5.labels; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MapperConfigTest { +class MapperConfigTest { @Test public void setMatch_WHEN_ExpressionMatchesPattern_AllGood() { final MapperConfig mapperConfig = new MapperConfig(); mapperConfig.setMatch("com.company.meter.*"); - assertEquals("com.company.meter.*", mapperConfig.getMatch()); + assertThat(mapperConfig.getMatch()).isEqualTo("com.company.meter.*"); } - @Test(expected = IllegalArgumentException.class) + @Test public void setMatch_WHEN_ExpressionDoesnNotMatchPattern_ThrowException() { - final MapperConfig mapperConfig = new MapperConfig(); - mapperConfig.setMatch("com.company.meter.**.yay"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new MapperConfig().setMatch("com.company.meter.**.yay")); } @Test public void setLabels_WHEN_ExpressionMatchesPattern_AllGood() { final MapperConfig mapperConfig = new MapperConfig(); - final Map labels = new HashMap(); + final Map labels = new HashMap<>(); labels.put("valid", "${0}"); mapperConfig.setLabels(labels); - assertEquals(labels, mapperConfig.getLabels()); + assertThat(mapperConfig.getLabels()).isEqualTo(labels); } - @Test(expected = IllegalArgumentException.class) + @Test public void setLabels_WHEN_ExpressionDoesnNotMatchPattern_ThrowException() { final MapperConfig mapperConfig = new MapperConfig(); - final Map labels = new HashMap(); + final Map labels = new HashMap<>(); labels.put("valid", "${0}"); labels.put("not valid", "${0}"); - mapperConfig.setLabels(labels); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> mapperConfig.setLabels(labels)); } @Test public void toString_WHEN_EmptyConfig_AllGood() { final MapperConfig mapperConfig = new MapperConfig(); - assertEquals("MapperConfig{match=null, name=null, labels={}}", mapperConfig.toString()); + assertThat(mapperConfig).hasToString("MapperConfig{match=null, name=null, labels={}}"); } @Test @@ -51,8 +53,7 @@ public void toString_WHEN_FullyConfigured_AllGood() { mapperConfig.setMatch("com.company.meter.*.foo"); mapperConfig.setName("foo"); mapperConfig.setLabels(Collections.singletonMap("type", "${0}")); - assertEquals( - "MapperConfig{match=com.company.meter.*.foo, name=foo, labels={type=${0}}}", - mapperConfig.toString()); + assertThat(mapperConfig) + .hasToString("MapperConfig{match=com.company.meter.*.foo, name=foo, labels={type=${0}}}"); } } diff --git a/prometheus-metrics-instrumentation-guava/pom.xml b/prometheus-metrics-instrumentation-guava/pom.xml index a4103e051..a93bc7960 100644 --- a/prometheus-metrics-instrumentation-guava/pom.xml +++ b/prometheus-metrics-instrumentation-guava/pom.xml @@ -54,28 +54,6 @@ 33.2.1-jre provided - - - - junit - junit - 4.13.2 - test - - - - org.mockito - mockito-core - 5.12.0 - test - - - org.assertj - assertj-core - 3.26.3 - test - - io.prometheus prometheus-metrics-exposition-formats diff --git a/prometheus-metrics-instrumentation-guava/src/test/java/io/prometheus/metrics/instrumentation/guava/CacheMetricsCollectorTest.java b/prometheus-metrics-instrumentation-guava/src/test/java/io/prometheus/metrics/instrumentation/guava/CacheMetricsCollectorTest.java index 96de845a8..3931520ff 100644 --- a/prometheus-metrics-instrumentation-guava/src/test/java/io/prometheus/metrics/instrumentation/guava/CacheMetricsCollectorTest.java +++ b/prometheus-metrics-instrumentation-guava/src/test/java/io/prometheus/metrics/instrumentation/guava/CacheMetricsCollectorTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.guava; -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -20,9 +20,9 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CacheMetricsCollectorTest { +class CacheMetricsCollectorTest { @Test public void cacheExposesMetricsForHitMissAndEviction() { @@ -68,7 +68,7 @@ public void cacheExposesMetricsForHitMissAndEviction() { + "guava_cache_size{cache=\"users\"} 2.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(registry)); + assertThat(convertToOpenMetricsFormat(registry)).isEqualTo(expected); } @SuppressWarnings("unchecked") @@ -107,7 +107,7 @@ public void loadingCacheExposesMetricsForLoadsAndExceptions() throws Exception { (SummarySnapshot.SummaryDataPointSnapshot) getDataPointSnapshot(registry, "guava_cache_load_duration_seconds", "loadingusers"); - assertEquals(3, loadDuration.getCount()); + assertThat(loadDuration.getCount()).isEqualTo(3); assertThat(loadDuration.getSum()).isGreaterThan(0); } @@ -116,7 +116,7 @@ private void assertCounterMetric( final CounterSnapshot.CounterDataPointSnapshot dataPointSnapshot = (CounterSnapshot.CounterDataPointSnapshot) getDataPointSnapshot(registry, name, cacheName); - assertEquals(value, dataPointSnapshot.getValue(), 0); + assertThat(dataPointSnapshot.getValue()).isCloseTo(value, offset(0.0)); } private DataPointSnapshot getDataPointSnapshot( diff --git a/prometheus-metrics-instrumentation-jvm/pom.xml b/prometheus-metrics-instrumentation-jvm/pom.xml index c847500db..c0a847509 100644 --- a/prometheus-metrics-instrumentation-jvm/pom.xml +++ b/prometheus-metrics-instrumentation-jvm/pom.xml @@ -49,18 +49,6 @@ - - junit - junit - 4.13.2 - test - - - org.mockito - mockito-core - 5.12.0 - test - io.prometheus prometheus-metrics-exporter-httpserver diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ExampleExporterForManualTesting.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ExampleExporterForManualTesting.java index b3d1c8169..0bea87baf 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ExampleExporterForManualTesting.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ExampleExporterForManualTesting.java @@ -3,7 +3,7 @@ import io.prometheus.metrics.exporter.httpserver.HTTPServer; import java.io.IOException; -public class ExampleExporterForManualTesting { +class ExampleExporterForManualTesting { public static void main(String[] args) throws IOException, InterruptedException { diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmBufferPoolMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmBufferPoolMetricsTest.java index cad2e8eb5..5d4523351 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmBufferPoolMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmBufferPoolMetricsTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -12,16 +12,16 @@ import java.io.IOException; import java.lang.management.BufferPoolMXBean; import java.util.Arrays; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JvmBufferPoolMetricsTest { +class JvmBufferPoolMetricsTest { private final BufferPoolMXBean directBuffer = Mockito.mock(BufferPoolMXBean.class); private final BufferPoolMXBean mappedBuffer = Mockito.mock(BufferPoolMXBean.class); - @Before + @BeforeEach public void setUp() { when(directBuffer.getName()).thenReturn("direct"); when(directBuffer.getCount()).thenReturn(2L); @@ -42,8 +42,7 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_buffer_pool_capacity_bytes gauge\n" + "# TYPE jvm_buffer_pool_capacity_bytes gauge\n" + "# UNIT jvm_buffer_pool_capacity_bytes bytes\n" + "# HELP jvm_buffer_pool_capacity_bytes Bytes capacity of a given JVM buffer pool.\n" + "jvm_buffer_pool_capacity_bytes{pool=\"direct\"} 3456.0\n" @@ -59,7 +58,7 @@ public void testGoodCase() throws IOException { + "jvm_buffer_pool_used_bytes{pool=\"mapped\"} 2345.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetricsTest.java index 0d8d77b51..6070aebba 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetricsTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -11,15 +11,15 @@ import io.prometheus.metrics.model.snapshots.MetricSnapshots; import java.io.IOException; import java.lang.management.ClassLoadingMXBean; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JvmClassLoadingMetricsTest { +class JvmClassLoadingMetricsTest { private final ClassLoadingMXBean mockClassLoadingBean = Mockito.mock(ClassLoadingMXBean.class); - @Before + @BeforeEach public void setUp() { when(mockClassLoadingBean.getLoadedClassCount()).thenReturn(1000); when(mockClassLoadingBean.getTotalLoadedClassCount()).thenReturn(2000L); @@ -33,8 +33,7 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_classes_currently_loaded gauge\n" + "# TYPE jvm_classes_currently_loaded gauge\n" + "# HELP jvm_classes_currently_loaded The number of classes that are currently loaded in the JVM\n" + "jvm_classes_currently_loaded 1000.0\n" + "# TYPE jvm_classes_loaded counter\n" @@ -45,7 +44,7 @@ public void testGoodCase() throws IOException { + "jvm_classes_unloaded_total 500.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmCompilationMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmCompilationMetricsTest.java index e966d0c11..caddb89ea 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmCompilationMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmCompilationMetricsTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; @@ -11,15 +11,15 @@ import io.prometheus.metrics.model.snapshots.MetricSnapshots; import java.io.IOException; import java.lang.management.CompilationMXBean; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JvmCompilationMetricsTest { +class JvmCompilationMetricsTest { private final CompilationMXBean mockCompilationBean = Mockito.mock(CompilationMXBean.class); - @Before + @BeforeEach public void setUp() { when(mockCompilationBean.getTotalCompilationTime()).thenReturn(10000L); when(mockCompilationBean.isCompilationTimeMonitoringSupported()).thenReturn(true); @@ -32,14 +32,13 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_compilation_time_seconds counter\n" + "# TYPE jvm_compilation_time_seconds counter\n" + "# UNIT jvm_compilation_time_seconds seconds\n" + "# HELP jvm_compilation_time_seconds The total time in seconds taken for HotSpot class compilation\n" + "jvm_compilation_time_seconds_total 10.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test @@ -54,6 +53,6 @@ public void testIgnoredMetricNotScraped() { MetricSnapshots snapshots = registry.scrape(filter); verify(mockCompilationBean, times(0)).getTotalCompilationTime(); - assertEquals(0, snapshots.size()); + assertThat(snapshots.size()).isZero(); } } diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmGarbageCollectorMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmGarbageCollectorMetricsTest.java index 5bbf3a427..3a09b4ef0 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmGarbageCollectorMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmGarbageCollectorMetricsTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -13,16 +13,16 @@ import java.lang.management.GarbageCollectorMXBean; import java.util.Arrays; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JvmGarbageCollectorMetricsTest { +class JvmGarbageCollectorMetricsTest { private final GarbageCollectorMXBean mockGcBean1 = Mockito.mock(GarbageCollectorMXBean.class); private final GarbageCollectorMXBean mockGcBean2 = Mockito.mock(GarbageCollectorMXBean.class); - @Before + @BeforeEach public void setUp() { when(mockGcBean1.getName()).thenReturn("MyGC1"); when(mockGcBean1.getCollectionCount()).thenReturn(100L); @@ -41,8 +41,7 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_gc_collection_seconds summary\n" + "# TYPE jvm_gc_collection_seconds summary\n" + "# UNIT jvm_gc_collection_seconds seconds\n" + "# HELP jvm_gc_collection_seconds Time spent in a given JVM garbage collector in seconds.\n" + "jvm_gc_collection_seconds_count{gc=\"MyGC1\"} 100\n" @@ -51,7 +50,7 @@ public void testGoodCase() throws IOException { + "jvm_gc_collection_seconds_sum{gc=\"MyGC2\"} 20.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test @@ -67,6 +66,6 @@ public void testIgnoredMetricNotScraped() { verify(mockGcBean1, times(0)).getCollectionTime(); verify(mockGcBean1, times(0)).getCollectionCount(); - assertEquals(0, snapshots.size()); + assertThat(snapshots.size()).isZero(); } } diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetricsTest.java index 94bdbbee3..a10bb1b7b 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetricsTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -14,11 +14,11 @@ import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.util.Arrays; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JvmMemoryMetricsTest { +class JvmMemoryMetricsTest { private final MemoryMXBean mockMemoryBean = Mockito.mock(MemoryMXBean.class); private final MemoryPoolMXBean mockPoolsBeanEdenSpace = Mockito.mock(MemoryPoolMXBean.class); @@ -30,7 +30,7 @@ public class JvmMemoryMetricsTest { private final MemoryUsage memoryUsagePoolCollectionEdenSpace = Mockito.mock(MemoryUsage.class); private final MemoryUsage memoryUsagePoolCollectionOldGen = Mockito.mock(MemoryUsage.class); - @Before + @BeforeEach public void setUp() { when(mockMemoryBean.getHeapMemoryUsage()).thenReturn(memoryUsageHeap); when(mockMemoryBean.getNonHeapMemoryUsage()).thenReturn(memoryUsageNonHeap); @@ -88,8 +88,7 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_memory_committed_bytes gauge\n" + "# TYPE jvm_memory_committed_bytes gauge\n" + "# UNIT jvm_memory_committed_bytes bytes\n" + "# HELP jvm_memory_committed_bytes Committed (bytes) of a given JVM memory area.\n" + "jvm_memory_committed_bytes{area=\"heap\"} 4.0\n" @@ -154,7 +153,7 @@ public void testGoodCase() throws IOException { + "jvm_memory_used_bytes{area=\"nonheap\"} 6.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetricsTest.java index 9a75e9e15..d9714e30c 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetricsTest.java @@ -1,7 +1,8 @@ package io.prometheus.metrics.instrumentation.jvm; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.data.Offset.offset; import io.prometheus.metrics.core.metrics.Counter; import io.prometheus.metrics.instrumentation.jvm.JvmMemoryPoolAllocationMetrics.AllocationCountingNotificationListener; @@ -9,9 +10,9 @@ import io.prometheus.metrics.model.snapshots.CounterSnapshot; import io.prometheus.metrics.model.snapshots.MetricSnapshot; import io.prometheus.metrics.model.snapshots.MetricSnapshots; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JvmMemoryPoolAllocationMetricsTest { +class JvmMemoryPoolAllocationMetricsTest { @Test public void testListenerLogic() { @@ -22,31 +23,31 @@ public void testListenerLogic() { // Increase by 123 listener.handleMemoryPool("TestPool", 0, 123); - assertEquals(123, getCountByPool("test", "TestPool", registry.scrape()), 0.0); + assertThat(getCountByPool("test", "TestPool", registry.scrape())).isCloseTo(123, offset(0.0)); // No increase listener.handleMemoryPool("TestPool", 123, 123); - assertEquals(123, getCountByPool("test", "TestPool", registry.scrape()), 0.0); + assertThat(getCountByPool("test", "TestPool", registry.scrape())).isCloseTo(123, offset(0.0)); // No increase, then decrease to 0 listener.handleMemoryPool("TestPool", 123, 0); - assertEquals(123, getCountByPool("test", "TestPool", registry.scrape()), 0.0); + assertThat(getCountByPool("test", "TestPool", registry.scrape())).isCloseTo(123, offset(0.0)); // No increase, then increase by 7 listener.handleMemoryPool("TestPool", 0, 7); - assertEquals(130, getCountByPool("test", "TestPool", registry.scrape()), 0.0); + assertThat(getCountByPool("test", "TestPool", registry.scrape())).isCloseTo(130, offset(0.0)); // Increase by 10, then decrease to 10 listener.handleMemoryPool("TestPool", 17, 10); - assertEquals(140, getCountByPool("test", "TestPool", registry.scrape()), 0.0); + assertThat(getCountByPool("test", "TestPool", registry.scrape())).isCloseTo(140, offset(0.0)); // Increase by 7, then increase by 3 listener.handleMemoryPool("TestPool", 17, 20); - assertEquals(150, getCountByPool("test", "TestPool", registry.scrape()), 0.0); + assertThat(getCountByPool("test", "TestPool", registry.scrape())).isCloseTo(150, offset(0.0)); // Decrease to 17, then increase by 3 listener.handleMemoryPool("TestPool", 17, 20); - assertEquals(153, getCountByPool("test", "TestPool", registry.scrape()), 0.0); + assertThat(getCountByPool("test", "TestPool", registry.scrape())).isCloseTo(153, offset(0.0)); } private double getCountByPool(String metricName, String poolName, MetricSnapshots snapshots) { diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMetricsTest.java index f0df40538..ab8b0d61d 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmMetricsTest.java @@ -1,19 +1,18 @@ package io.prometheus.metrics.instrumentation.jvm; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import io.prometheus.metrics.model.registry.PrometheusRegistry; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JvmMetricsTest { +class JvmMetricsTest { @Test public void testRegisterIdempotent() { PrometheusRegistry registry = new PrometheusRegistry(); - assertEquals(0, registry.scrape().size()); + assertThat(registry.scrape().size()).isZero(); JvmMetrics.builder().register(registry); - assertTrue(registry.scrape().size() > 0); + assertThat(registry.scrape().size()).isGreaterThan(0); JvmMetrics.builder().register(registry); } } diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetricsTest.java index e5a90e38d..3bc424985 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetricsTest.java @@ -1,17 +1,17 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import io.prometheus.metrics.config.PrometheusProperties; import io.prometheus.metrics.model.registry.PrometheusRegistry; import io.prometheus.metrics.model.snapshots.MetricSnapshots; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JvmNativeMemoryMetricsTest { +class JvmNativeMemoryMetricsTest { @Test public void testNativeMemoryTrackingFail() throws IOException { @@ -27,7 +27,7 @@ public void testNativeMemoryTrackingFail() throws IOException { String expected = "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test @@ -44,7 +44,7 @@ public void testNativeMemoryTrackingEmpty() throws IOException { String expected = "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test @@ -62,7 +62,7 @@ public void testNativeMemoryTrackingDisabled() throws IOException { String expected = "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test @@ -172,8 +172,7 @@ public void testNativeMemoryTrackingEnabled() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_native_memory_committed_bytes gauge\n" + "# TYPE jvm_native_memory_committed_bytes gauge\n" + "# UNIT jvm_native_memory_committed_bytes bytes\n" + "# HELP jvm_native_memory_committed_bytes Committed bytes of a given JVM. Committed memory represents the amount of memory the JVM is using right now.\n" + "jvm_native_memory_committed_bytes{pool=\"Arena Chunk\"} 503216.0\n" @@ -225,6 +224,6 @@ public void testNativeMemoryTrackingEnabled() throws IOException { + "jvm_native_memory_reserved_bytes{pool=\"Tracing\"} 33097.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } } diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmRuntimeInfoMetricTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmRuntimeInfoMetricTest.java index 1dcaff2d9..35057bd51 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmRuntimeInfoMetricTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmRuntimeInfoMetricTest.java @@ -1,14 +1,14 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import io.prometheus.metrics.model.registry.PrometheusRegistry; import io.prometheus.metrics.model.snapshots.MetricSnapshots; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JvmRuntimeInfoMetricTest { +class JvmRuntimeInfoMetricTest { @Test public void testGoodCase() throws IOException { @@ -21,12 +21,11 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_runtime info\n" + "# TYPE jvm_runtime info\n" + "# HELP jvm_runtime JVM runtime info\n" + "jvm_runtime_info{runtime=\"OpenJDK Runtime Environment\",vendor=\"Oracle Corporation\",version=\"1.8.0_382-b05\"} 1\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } } diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetricsTest.java index 3aaa5b94b..effd79117 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetricsTest.java @@ -1,8 +1,8 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -18,18 +18,18 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JvmThreadsMetricsTest { +class JvmThreadsMetricsTest { private final ThreadMXBean mockThreadsBean = Mockito.mock(ThreadMXBean.class); private final ThreadInfo mockThreadInfoBlocked = Mockito.mock(ThreadInfo.class); private final ThreadInfo mockThreadInfoRunnable1 = Mockito.mock(ThreadInfo.class); private final ThreadInfo mockThreadInfoRunnable2 = Mockito.mock(ThreadInfo.class); - @Before + @BeforeEach public void setUp() { when(mockThreadsBean.getThreadCount()).thenReturn(300); when(mockThreadsBean.getDaemonThreadCount()).thenReturn(200); @@ -55,8 +55,7 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE jvm_threads_current gauge\n" + "# TYPE jvm_threads_current gauge\n" + "# HELP jvm_threads_current Current thread count of a JVM\n" + "jvm_threads_current 300.0\n" + "# TYPE jvm_threads_daemon gauge\n" @@ -85,7 +84,7 @@ public void testGoodCase() throws IOException { + "jvm_threads_state{state=\"WAITING\"} 0.0\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test @@ -134,9 +133,9 @@ public void testInvalidThreadIds() { Map actual = getCountByState(registry.scrape()); - assertEquals(expected.size(), actual.size()); + assertThat(actual).hasSameSizeAs(expected); for (String threadState : expected.keySet()) { - assertEquals(expected.get(threadState), actual.get(threadState), 0.0); + assertThat(actual.get(threadState)).isCloseTo(expected.get(threadState), offset(0.0)); } } finally { for (int i = 0; i < numberOfInvalidThreadIds; i++) { @@ -152,7 +151,7 @@ private Map getCountByState(MetricSnapshots snapshots) { for (GaugeSnapshot.GaugeDataPointSnapshot data : ((GaugeSnapshot) snapshot).getDataPoints()) { String state = data.getLabels().get("state"); - assertNotNull(state); + assertThat(state).isNotNull(); result.put(state, data.getValue()); } } diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetricsTest.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetricsTest.java index 6dafa1fb3..2a447a5ec 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetricsTest.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetricsTest.java @@ -1,7 +1,7 @@ package io.prometheus.metrics.instrumentation.jvm; import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; @@ -15,11 +15,11 @@ import java.io.IOException; import java.lang.management.RuntimeMXBean; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class ProcessMetricsTest { +class ProcessMetricsTest { private final com.sun.management.UnixOperatingSystemMXBean sunOsBean = Mockito.mock(com.sun.management.UnixOperatingSystemMXBean.class); @@ -29,7 +29,7 @@ public class ProcessMetricsTest { private final ProcessMetrics.Grepper windowsGrepper = Mockito.mock(ProcessMetrics.Grepper.class); private final RuntimeMXBean runtimeBean = Mockito.mock(RuntimeMXBean.class); - @Before + @BeforeEach public void setUp() throws IOException { when(sunOsBean.getProcessCpuTime()).thenReturn(TimeUnit.MILLISECONDS.toNanos(72)); when(sunOsBean.getOpenFileDescriptorCount()).thenReturn(127L); @@ -52,8 +52,7 @@ public void testGoodCase() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE process_cpu_seconds counter\n" + "# TYPE process_cpu_seconds counter\n" + "# UNIT process_cpu_seconds seconds\n" + "# HELP process_cpu_seconds Total user and system CPU time spent in seconds.\n" + "process_cpu_seconds_total 0.072\n" @@ -66,30 +65,27 @@ public void testGoodCase() throws IOException { // To allow running this test in non-linux environments if (ProcessMetrics.PROC_SELF_STATUS.canRead()) { expected += - "" - + "# TYPE process_resident_memory_bytes gauge\n" + "# TYPE process_resident_memory_bytes gauge\n" + "# UNIT process_resident_memory_bytes bytes\n" + "# HELP process_resident_memory_bytes Resident memory size in bytes.\n" + "process_resident_memory_bytes 1036288.0\n"; } expected += - "" - + "# TYPE process_start_time_seconds gauge\n" + "# TYPE process_start_time_seconds gauge\n" + "# UNIT process_start_time_seconds seconds\n" + "# HELP process_start_time_seconds Start time of the process since unix epoch in seconds.\n" + "process_start_time_seconds 37.1\n"; // To allow running this test in non-linux environments if (ProcessMetrics.PROC_SELF_STATUS.canRead()) { expected += - "" - + "# TYPE process_virtual_memory_bytes gauge\n" + "# TYPE process_virtual_memory_bytes gauge\n" + "# UNIT process_virtual_memory_bytes bytes\n" + "# HELP process_virtual_memory_bytes Virtual memory size in bytes.\n" + "process_virtual_memory_bytes 6180864.0\n"; } expected += "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test @@ -103,14 +99,13 @@ public void testMinimal() throws IOException { MetricSnapshots snapshots = registry.scrape(); String expected = - "" - + "# TYPE process_start_time_seconds gauge\n" + "# TYPE process_start_time_seconds gauge\n" + "# UNIT process_start_time_seconds seconds\n" + "# HELP process_start_time_seconds Start time of the process since unix epoch in seconds.\n" + "process_start_time_seconds 37.1\n" + "# EOF\n"; - assertEquals(expected, convertToOpenMetricsFormat(snapshots)); + assertThat(convertToOpenMetricsFormat(snapshots)).isEqualTo(expected); } @Test diff --git a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/TestUtil.java b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/TestUtil.java index a86517368..70a093f4b 100644 --- a/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/TestUtil.java +++ b/prometheus-metrics-instrumentation-jvm/src/test/java/io/prometheus/metrics/instrumentation/jvm/TestUtil.java @@ -6,7 +6,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -public class TestUtil { +class TestUtil { static String convertToOpenMetricsFormat(MetricSnapshots snapshots) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); diff --git a/prometheus-metrics-model/pom.xml b/prometheus-metrics-model/pom.xml index 8d3051dfe..82bbf96cf 100644 --- a/prometheus-metrics-model/pom.xml +++ b/prometheus-metrics-model/pom.xml @@ -35,14 +35,4 @@ fabian@fstab.de - - - - - junit - junit - 4.13.2 - test - - diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MetricNameFilterTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MetricNameFilterTest.java index 6c7917bda..0dc9cdee1 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MetricNameFilterTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MetricNameFilterTest.java @@ -1,21 +1,16 @@ package io.prometheus.metrics.model.registry; +import static org.assertj.core.api.Assertions.assertThat; + import io.prometheus.metrics.model.snapshots.CounterSnapshot; import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot; import io.prometheus.metrics.model.snapshots.Labels; import io.prometheus.metrics.model.snapshots.MetricSnapshots; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class MetricNameFilterTest { +import org.junit.jupiter.api.Test; - private PrometheusRegistry registry; +class MetricNameFilterTest { - @Before - public void setUp() { - registry = new PrometheusRegistry(); - } + private final PrometheusRegistry registry = new PrometheusRegistry(); @Test public void testCounter() { @@ -44,28 +39,28 @@ public void testCounter() { .build()); MetricNameFilter filter = MetricNameFilter.builder().build(); - Assert.assertEquals(2, registry.scrape(filter).size()); + assertThat(registry.scrape(filter).size()).isEqualTo(2); filter = MetricNameFilter.builder().nameMustStartWith("counter1").build(); MetricSnapshots snapshots = registry.scrape(filter); - Assert.assertEquals(1, snapshots.size()); - Assert.assertEquals("counter1", snapshots.get(0).getMetadata().getName()); + assertThat(snapshots.size()).isOne(); + assertThat(snapshots.get(0).getMetadata().getName()).isEqualTo("counter1"); filter = MetricNameFilter.builder().nameMustNotStartWith("counter1").build(); snapshots = registry.scrape(filter); - Assert.assertEquals(1, snapshots.size()); - Assert.assertEquals("counter2", snapshots.get(0).getMetadata().getName()); + assertThat(snapshots.size()).isOne(); + assertThat(snapshots.get(0).getMetadata().getName()).isEqualTo("counter2"); filter = MetricNameFilter.builder().nameMustBeEqualTo("counter2_total", "counter1_total").build(); snapshots = registry.scrape(filter); - Assert.assertEquals(2, snapshots.size()); + assertThat(snapshots.size()).isEqualTo(2); filter = MetricNameFilter.builder() .nameMustBeEqualTo("counter1_total") .nameMustNotBeEqualTo("counter1_total") .build(); - Assert.assertEquals(0, registry.scrape(filter).size()); + assertThat(registry.scrape(filter).size()).isZero(); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MultiCollectorNameFilterTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MultiCollectorNameFilterTest.java index b302f4508..b8810316f 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MultiCollectorNameFilterTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/MultiCollectorNameFilterTest.java @@ -1,100 +1,89 @@ package io.prometheus.metrics.model.registry; +import static org.assertj.core.api.Assertions.assertThat; + import io.prometheus.metrics.model.snapshots.CounterSnapshot; import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot; import io.prometheus.metrics.model.snapshots.GaugeSnapshot; import io.prometheus.metrics.model.snapshots.GaugeSnapshot.GaugeDataPointSnapshot; import io.prometheus.metrics.model.snapshots.MetricSnapshots; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.function.Predicate; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class MultiCollectorNameFilterTest { - - private final boolean[] collectCalled = {false}; - private PrometheusRegistry registry; - private Predicate includedNames = null; - private List prometheusNames = new ArrayList<>(); - - @Before - public void setUp() { - registry = new PrometheusRegistry(); - collectCalled[0] = false; - includedNames = null; - prometheusNames = Collections.emptyList(); - - registry.register( - new MultiCollector() { - @Override - public MetricSnapshots collect() { - collectCalled[0] = true; - return MetricSnapshots.builder() - .metricSnapshot( - CounterSnapshot.builder() - .name("counter_1") - .dataPoint(CounterDataPointSnapshot.builder().value(1.0).build()) - .build()) - .metricSnapshot( - GaugeSnapshot.builder() - .name("gauge_2") - .dataPoint(GaugeDataPointSnapshot.builder().value(1.0).build()) - .build()) - .build(); - } - - @Override - public List getPrometheusNames() { - return prometheusNames; - } - }); +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; + +class MultiCollectorNameFilterTest { + + private static class Registry extends PrometheusRegistry { + private final AtomicBoolean collectCalled = new AtomicBoolean(); + + public Registry(List prometheusNames) { + register( + new MultiCollector() { + @Override + public MetricSnapshots collect() { + collectCalled.set(true); + return MetricSnapshots.builder() + .metricSnapshot( + CounterSnapshot.builder() + .name("counter_1") + .dataPoint(CounterDataPointSnapshot.builder().value(1.0).build()) + .build()) + .metricSnapshot( + GaugeSnapshot.builder() + .name("gauge_2") + .dataPoint(GaugeDataPointSnapshot.builder().value(1.0).build()) + .build()) + .build(); + } + + @Override + public List getPrometheusNames() { + return prometheusNames; + } + }); + } + + public boolean collectCalled() { + return collectCalled.get(); + } } @Test public void testPartialFilter() { - - includedNames = name -> name.equals("counter_1"); - - MetricSnapshots snapshots = registry.scrape(includedNames); - Assert.assertTrue(collectCalled[0]); - Assert.assertEquals(1, snapshots.size()); - Assert.assertEquals("counter_1", snapshots.get(0).getMetadata().getName()); + Registry registry = new Registry(Collections.emptyList()); + MetricSnapshots snapshots = registry.scrape(name -> name.equals("counter_1")); + assertThat(registry.collectCalled()).isTrue(); + assertThat(snapshots.size()).isOne(); + assertThat(snapshots.get(0).getMetadata().getName()).isEqualTo("counter_1"); } @Test public void testPartialFilterWithPrometheusNames() { + Registry registry = new Registry(Arrays.asList("counter_1", "gauge_2")); - includedNames = name -> name.equals("counter_1"); - prometheusNames = Arrays.asList("counter_1", "gauge_2"); - - MetricSnapshots snapshots = registry.scrape(includedNames); - Assert.assertTrue(collectCalled[0]); - Assert.assertEquals(1, snapshots.size()); - Assert.assertEquals("counter_1", snapshots.get(0).getMetadata().getName()); + MetricSnapshots snapshots = registry.scrape(name -> name.equals("counter_1")); + assertThat(registry.collectCalled()).isTrue(); + assertThat(snapshots.size()).isOne(); + assertThat(snapshots.get(0).getMetadata().getName()).isEqualTo("counter_1"); } @Test public void testCompleteFilter_CollectCalled() { - - includedNames = name -> !name.equals("counter_1") && !name.equals("gauge_2"); - - MetricSnapshots snapshots = registry.scrape(includedNames); - Assert.assertTrue(collectCalled[0]); - Assert.assertEquals(0, snapshots.size()); + Registry registry = new Registry(Collections.emptyList()); + MetricSnapshots snapshots = + registry.scrape(name -> !name.equals("counter_1") && !name.equals("gauge_2")); + assertThat(registry.collectCalled()).isTrue(); + assertThat(snapshots.size()).isZero(); } @Test public void testCompleteFilter_CollectNotCalled() { - - includedNames = name -> !name.equals("counter_1") && !name.equals("gauge_2"); - prometheusNames = Arrays.asList("counter_1", "gauge_2"); - - MetricSnapshots snapshots = registry.scrape(includedNames); - Assert.assertFalse(collectCalled[0]); - Assert.assertEquals(0, snapshots.size()); + Registry registry = new Registry(Arrays.asList("counter_1", "gauge_2")); + MetricSnapshots snapshots = + registry.scrape(name -> !name.equals("counter_1") && !name.equals("gauge_2")); + assertThat(registry.collectCalled()).isFalse(); + assertThat(snapshots.size()).isZero(); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java index c5dd287d7..55e8b0be4 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java @@ -1,15 +1,18 @@ package io.prometheus.metrics.model.registry; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.fail; + import io.prometheus.metrics.model.snapshots.CounterSnapshot; import io.prometheus.metrics.model.snapshots.GaugeSnapshot; import io.prometheus.metrics.model.snapshots.MetricSnapshot; import io.prometheus.metrics.model.snapshots.MetricSnapshots; import java.util.Arrays; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PrometheusRegistryTest { +class PrometheusRegistryTest { Collector noName = () -> GaugeSnapshot.builder().name("no_name_gauge").build(); @@ -90,18 +93,19 @@ public void registerNoName() { try { registry.scrape(); } catch (IllegalStateException e) { - Assert.assertTrue( - e.getMessage().contains("duplicate") && e.getMessage().contains("no_name_gauge")); + assertThat(e.getMessage().contains("duplicate") && e.getMessage().contains("no_name_gauge")) + .isTrue(); return; } - Assert.fail("Expected duplicate name exception"); + fail("Expected duplicate name exception"); } - @Test(expected = IllegalStateException.class) + @Test public void registerDuplicateName() { PrometheusRegistry registry = new PrometheusRegistry(); registry.register(counterA1); - registry.register(counterA2); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> registry.register(counterA2)); } @Test @@ -111,22 +115,23 @@ public void registerOk() { registry.register(counterB); registry.register(gaugeA); MetricSnapshots snapshots = registry.scrape(); - Assert.assertEquals(3, snapshots.size()); + assertThat(snapshots.size()).isEqualTo(3); registry.unregister(counterB); snapshots = registry.scrape(); - Assert.assertEquals(2, snapshots.size()); + assertThat(snapshots.size()).isEqualTo(2); registry.register(counterB); snapshots = registry.scrape(); - Assert.assertEquals(3, snapshots.size()); + assertThat(snapshots.size()).isEqualTo(3); } - @Test(expected = IllegalStateException.class) + @Test public void registerDuplicateMultiCollector() { PrometheusRegistry registry = new PrometheusRegistry(); registry.register(multiCollector); - registry.register(multiCollector); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> registry.register(multiCollector)); } @Test @@ -134,10 +139,10 @@ public void registerOkMultiCollector() { PrometheusRegistry registry = new PrometheusRegistry(); registry.register(multiCollector); MetricSnapshots snapshots = registry.scrape(); - Assert.assertEquals(2, snapshots.size()); + assertThat(snapshots.size()).isEqualTo(2); registry.unregister(multiCollector); snapshots = registry.scrape(); - Assert.assertEquals(0, snapshots.size()); + assertThat(snapshots.size()).isZero(); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ClassicHistogramBucketsTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ClassicHistogramBucketsTest.java index 082981431..278a8fafc 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ClassicHistogramBucketsTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ClassicHistogramBucketsTest.java @@ -1,10 +1,13 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; + import java.util.Iterator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ClassicHistogramBucketsTest { +class ClassicHistogramBucketsTest { @Test public void testGoodCase() { @@ -15,7 +18,7 @@ public void testGoodCase() { .bucket(1024, 3) .bucket(Double.POSITIVE_INFINITY, 8) .build(); - Assert.assertEquals(4, buckets.size()); + assertThat(buckets.size()).isEqualTo(4); } @Test @@ -26,64 +29,80 @@ public void testSort() { .bucket(2, 0) .bucket(Double.POSITIVE_INFINITY, 3) .build(); - Assert.assertEquals(3, buckets.size()); - Assert.assertEquals(2, buckets.getUpperBound(0), 0.0); - Assert.assertEquals(7, buckets.getUpperBound(1), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, buckets.getUpperBound(2), 0.0); - Assert.assertEquals(0, buckets.getCount(0)); - Assert.assertEquals(2, buckets.getCount(1)); - Assert.assertEquals(3, buckets.getCount(2)); + assertThat(buckets.size()).isEqualTo(3); + assertThat(buckets.getUpperBound(0)).isCloseTo(2, offset(0.0)); + assertThat(buckets.getUpperBound(1)).isCloseTo(7, offset(0.0)); + assertThat(buckets.getUpperBound(2)).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(buckets.getCount(0)).isZero(); + assertThat(buckets.getCount(1)).isEqualTo(2); + assertThat(buckets.getCount(2)).isEqualTo(3); } @Test public void testMinimalBuckets() { ClassicHistogramBuckets buckets = ClassicHistogramBuckets.builder().bucket(Double.POSITIVE_INFINITY, 0).build(); - Assert.assertEquals(1, buckets.size()); + assertThat(buckets.size()).isOne(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInfBucketMissing() { - ClassicHistogramBuckets.builder().bucket(Double.NEGATIVE_INFINITY, 0).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> ClassicHistogramBuckets.builder().bucket(Double.NEGATIVE_INFINITY, 0).build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNegativeCount() { - ClassicHistogramBuckets.builder().bucket(0.0, 10).bucket(Double.POSITIVE_INFINITY, -1).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + ClassicHistogramBuckets.builder() + .bucket(0.0, 10) + .bucket(Double.POSITIVE_INFINITY, -1) + .build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNaNBoundary() { - ClassicHistogramBuckets.builder() - .bucket(0.0, 1) - .bucket(Double.NaN, 2) - .bucket(Double.POSITIVE_INFINITY, 0) - .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + ClassicHistogramBuckets.builder() + .bucket(0.0, 1) + .bucket(Double.NaN, 2) + .bucket(Double.POSITIVE_INFINITY, 0) + .build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDuplicateBoundary() { - ClassicHistogramBuckets.builder() - .bucket(1.0, 1) - .bucket(2.0, 2) - .bucket(1.0, 2) - .bucket(Double.POSITIVE_INFINITY, 0) - .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + ClassicHistogramBuckets.builder() + .bucket(1.0, 1) + .bucket(2.0, 2) + .bucket(1.0, 2) + .bucket(Double.POSITIVE_INFINITY, 0) + .build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testEmptyBuckets() { - ClassicHistogramBuckets.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> ClassicHistogramBuckets.builder().build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDifferentLength() { double[] upperBounds = new double[] {0.7, 1.3, Double.POSITIVE_INFINITY}; long[] counts = new long[] {13, 178, 1024, 3000}; - ClassicHistogramBuckets.of(upperBounds, counts); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> ClassicHistogramBuckets.of(upperBounds, counts)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testImmutable() { ClassicHistogramBuckets buckets = ClassicHistogramBuckets.builder() @@ -93,6 +112,6 @@ public void testImmutable() { .build(); Iterator iterator = buckets.iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/CounterSnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/CounterSnapshotTest.java index 96e8df4c9..e381e5903 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/CounterSnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/CounterSnapshotTest.java @@ -1,12 +1,15 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; + import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot; import java.util.Iterator; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CounterSnapshotTest { +class CounterSnapshotTest { @Test public void testCompleteGoodCase() { @@ -47,22 +50,22 @@ public void testCompleteGoodCase() { .build(); SnapshotTestUtil.assertMetadata( snapshot, "http_server_requests_seconds", "total time spent serving requests", "seconds"); - Assert.assertEquals(2, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(2); CounterDataPointSnapshot data = snapshot .getDataPoints() .get(0); // data is sorted by labels, so the first one should be path="/hello" - Assert.assertEquals(Labels.of("path", "/hello"), data.getLabels()); - Assert.assertEquals(2.0, data.getValue(), 0.0); - Assert.assertEquals(4.0, data.getExemplar().getValue(), 0.0); - Assert.assertEquals(createdTimestamp2, data.getCreatedTimestampMillis()); - Assert.assertFalse(data.hasScrapeTimestamp()); + assertThat((Iterable) data.getLabels()).isEqualTo(Labels.of("path", "/hello")); + assertThat(data.getValue()).isCloseTo(2.0, offset(0.0)); + assertThat(data.getExemplar().getValue()).isCloseTo(4.0, offset(0.0)); + assertThat(data.getCreatedTimestampMillis()).isEqualTo(createdTimestamp2); + assertThat(data.hasScrapeTimestamp()).isFalse(); data = snapshot.getDataPoints().get(1); - Assert.assertEquals(Labels.of("path", "/world"), data.getLabels()); - Assert.assertEquals(1.0, data.getValue(), 0.0); - Assert.assertEquals(3.0, data.getExemplar().getValue(), 0.0); - Assert.assertEquals(createdTimestamp1, data.getCreatedTimestampMillis()); - Assert.assertFalse(data.hasScrapeTimestamp()); + assertThat((Iterable) data.getLabels()).isEqualTo(Labels.of("path", "/world")); + assertThat(data.getValue()).isCloseTo(1.0, offset(0.0)); + assertThat(data.getExemplar().getValue()).isCloseTo(3.0, offset(0.0)); + assertThat(data.getCreatedTimestampMillis()).isEqualTo(createdTimestamp1); + assertThat(data.hasScrapeTimestamp()).isFalse(); } @Test @@ -73,32 +76,34 @@ public void testMinimalGoodCase() { .dataPoint(CounterDataPointSnapshot.builder().value(1.0).build()) .build(); SnapshotTestUtil.assertMetadata(snapshot, "events", null, null); - Assert.assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(1); CounterDataPointSnapshot data = snapshot.getDataPoints().get(0); - Assert.assertEquals(Labels.EMPTY, data.getLabels()); - Assert.assertEquals(1.0, data.getValue(), 0.0); - Assert.assertNull(data.getExemplar()); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); + assertThat((Iterable) data.getLabels()).isEmpty(); + assertThat(data.getValue()).isCloseTo(1.0, offset(0.0)); + assertThat(data.getExemplar()).isNull(); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); } @Test public void testEmptyCounter() { CounterSnapshot snapshot = CounterSnapshot.builder().name("events").build(); - Assert.assertEquals(0, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).isEmpty(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testTotalSuffixPresent() { - CounterSnapshot.builder().name("test_total").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CounterSnapshot.builder().name("test_total").build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testValueMissing() { - CounterDataPointSnapshot.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CounterDataPointSnapshot.builder().build()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testDataImmutable() { CounterSnapshot snapshot = CounterSnapshot.builder() @@ -110,6 +115,6 @@ public void testDataImmutable() { .build(); Iterator iterator = snapshot.getDataPoints().iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarTest.java index 1a94b12f1..ebc875d5f 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarTest.java @@ -1,9 +1,13 @@ package io.prometheus.metrics.model.snapshots; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; -public class ExemplarTest { +import org.assertj.core.api.IterableAssert; +import org.junit.jupiter.api.Test; + +class ExemplarTest { @Test public void testGoodCaseComplete() { @@ -16,47 +20,52 @@ public void testGoodCaseComplete() { .timestampMillis(timestamp) .labels(Labels.of("path", "/", "error", "none")) .build(); - Assert.assertEquals(2.2, exemplar.getValue(), 0.0); - Assert.assertEquals( - Labels.of( - Exemplar.TRACE_ID, - "abc123abc123", - Exemplar.SPAN_ID, - "def456def456", - "path", - "/", - "error", - "none"), - exemplar.getLabels()); - Assert.assertTrue(exemplar.hasTimestamp()); - Assert.assertEquals(timestamp, exemplar.getTimestampMillis()); + assertThat(exemplar.getValue()).isCloseTo(2.2, offset(0.0)); + assertLabels(exemplar.getLabels()) + .isEqualTo( + Labels.of( + Exemplar.TRACE_ID, + "abc123abc123", + Exemplar.SPAN_ID, + "def456def456", + "path", + "/", + "error", + "none")); + assertThat(exemplar.hasTimestamp()).isTrue(); + assertThat(exemplar.getTimestampMillis()).isEqualTo(timestamp); } - @Test(expected = IllegalStateException.class) + @Test public void testValueMissing() { - Exemplar.builder().build(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> Exemplar.builder().build()); } @Test public void testMinimal() { Exemplar exemplar = Exemplar.builder().value(0.0).build(); - Assert.assertEquals(0.0, exemplar.getValue(), 0.0); - Assert.assertEquals(Labels.EMPTY, exemplar.getLabels()); - Assert.assertFalse(exemplar.hasTimestamp()); + assertThat(exemplar.getValue()).isCloseTo(0.0, offset(0.0)); + assertLabels(exemplar.getLabels()).isEqualTo(Labels.EMPTY); + assertThat(exemplar.hasTimestamp()).isFalse(); } @Test public void testLabelsMergeTraceId() { Exemplar exemplar = Exemplar.builder().value(0.0).labels(Labels.of("a", "b")).traceId("abc").build(); - Assert.assertEquals(Labels.of("a", "b", "trace_id", "abc"), exemplar.getLabels()); + assertLabels(exemplar.getLabels()).isEqualTo(Labels.of("a", "b", "trace_id", "abc")); + } + + private static IterableAssert assertLabels(Labels labels) { + return assertThat((Iterable) labels); } @Test public void testLabelsMergeSpanId() { Exemplar exemplar = Exemplar.builder().value(0.0).labels(Labels.of("a", "b")).spanId("abc").build(); - Assert.assertEquals(Labels.of("a", "b", "span_id", "abc"), exemplar.getLabels()); + assertLabels(exemplar.getLabels()).isEqualTo(Labels.of("a", "b", "span_id", "abc")); } @Test @@ -68,13 +77,13 @@ public void testLabelsMergeTraceIdAndSpanId() { .spanId("abc") .traceId("def") .build(); - Assert.assertEquals( - Labels.of("span_id", "abc", "a", "b", "trace_id", "def"), exemplar.getLabels()); + assertLabels(exemplar.getLabels()) + .isEqualTo(Labels.of("span_id", "abc", "a", "b", "trace_id", "def")); } @Test public void testLabelsMergeNone() { Exemplar exemplar = Exemplar.builder().value(0.0).labels(Labels.of("a", "b")).build(); - Assert.assertEquals(Labels.of("a", "b"), exemplar.getLabels()); + assertLabels(exemplar.getLabels()).isEqualTo(Labels.of("a", "b")); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarsTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarsTest.java index 93a1c1efa..74a3fbe8a 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarsTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/ExemplarsTest.java @@ -1,10 +1,13 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; + import java.util.Iterator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ExemplarsTest { +class ExemplarsTest { @Test public void testUpperBound() { @@ -13,19 +16,19 @@ public void testUpperBound() { Exemplar.builder().value(1.0).build(), Exemplar.builder().value(3.0).build(), Exemplar.builder().value(2.0).build()); - Assert.assertEquals(3, exemplars.size()); - Assert.assertEquals(1.0, exemplars.get(0).getValue(), 0.0); - Assert.assertEquals(3.0, exemplars.get(1).getValue(), 0.0); - Assert.assertEquals(2.0, exemplars.get(2).getValue(), 0.0); - Assert.assertEquals(1.0, exemplars.get(0.0, Double.POSITIVE_INFINITY).getValue(), 0.0); - Assert.assertEquals(1.0, exemplars.get(0.0, 1.0).getValue(), 0.0); - Assert.assertEquals(3.0, exemplars.get(1.0, 4.0).getValue(), 0.0); - Assert.assertEquals(3.0, exemplars.get(2.0, 3.0).getValue(), 0.0); - Assert.assertEquals(2.0, exemplars.get(1.0, 2.1).getValue(), 0.0); - Assert.assertNull(exemplars.get(2.0, 2.1)); + assertThat(exemplars.size()).isEqualTo(3); + assertThat(exemplars.get(0).getValue()).isCloseTo(1.0, offset(0.0)); + assertThat(exemplars.get(1).getValue()).isCloseTo(3.0, offset(0.0)); + assertThat(exemplars.get(2).getValue()).isCloseTo(2.0, offset(0.0)); + assertThat(exemplars.get(0.0, Double.POSITIVE_INFINITY).getValue()).isCloseTo(1.0, offset(0.0)); + assertThat(exemplars.get(0.0, 1.0).getValue()).isCloseTo(1.0, offset(0.0)); + assertThat(exemplars.get(1.0, 4.0).getValue()).isCloseTo(3.0, offset(0.0)); + assertThat(exemplars.get(2.0, 3.0).getValue()).isCloseTo(3.0, offset(0.0)); + assertThat(exemplars.get(1.0, 2.1).getValue()).isCloseTo(2.0, offset(0.0)); + assertThat(exemplars.get(2.0, 2.1)).isNull(); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testImmutable() { Exemplars exemplars = Exemplars.of( @@ -34,7 +37,7 @@ public void testImmutable() { Exemplar.builder().value(2.0).build()); Iterator iterator = exemplars.iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } @Test @@ -47,8 +50,8 @@ public void testGet() { Exemplar.builder().timestampMillis(System.currentTimeMillis()).value(1.0).build(); Exemplars exemplars = Exemplars.of(oldest, newest, middle); Exemplar result = exemplars.get(1.1, 1.9); // newest is not within these bounds - Assert.assertSame(result, middle); + assertThat(middle).isSameAs(result); result = exemplars.get(0.9, Double.POSITIVE_INFINITY); - Assert.assertSame(result, newest); + assertThat(newest).isSameAs(result); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/GaugeSnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/GaugeSnapshotTest.java index fe7f386ba..1fd55d67e 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/GaugeSnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/GaugeSnapshotTest.java @@ -1,12 +1,15 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; + import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot; import io.prometheus.metrics.model.snapshots.GaugeSnapshot.GaugeDataPointSnapshot; import java.util.Iterator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GaugeSnapshotTest { +class GaugeSnapshotTest { @Test public void testCompleteGoodCase() { @@ -42,22 +45,22 @@ public void testCompleteGoodCase() { .build()) .build(); SnapshotTestUtil.assertMetadata(snapshot, "cache_size_bytes", "cache size in Bytes", "bytes"); - Assert.assertEquals(2, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(2); GaugeDataPointSnapshot data = snapshot .getDataPoints() .get(0); // data is sorted by labels, so the first one should be path="/hello" - Assert.assertEquals(Labels.of("env", "dev"), data.getLabels()); - Assert.assertEquals(128.0, data.getValue(), 0.0); - Assert.assertEquals(128.0, data.getExemplar().getValue(), 0.0); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); + assertThat((Iterable) data.getLabels()).isEqualTo(Labels.of("env", "dev")); + assertThat(data.getValue()).isCloseTo(128.0, offset(0.0)); + assertThat(data.getExemplar().getValue()).isCloseTo(128.0, offset(0.0)); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); data = snapshot.getDataPoints().get(1); - Assert.assertEquals(Labels.of("env", "prod"), data.getLabels()); - Assert.assertEquals(1024.0, data.getValue(), 0.0); - Assert.assertEquals(1024.0, data.getExemplar().getValue(), 0.0); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); + assertThat((Iterable) data.getLabels()).isEqualTo(Labels.of("env", "prod")); + assertThat(data.getValue()).isCloseTo(1024.0, offset(0.0)); + assertThat(data.getExemplar().getValue()).isCloseTo(1024.0, offset(0.0)); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); } @Test @@ -68,37 +71,40 @@ public void testMinimalGoodCase() { .dataPoint(GaugeDataPointSnapshot.builder().value(23.0).build()) .build(); SnapshotTestUtil.assertMetadata(snapshot, "temperature", null, null); - Assert.assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isOne(); GaugeDataPointSnapshot data = snapshot.getDataPoints().get(0); - Assert.assertEquals(Labels.EMPTY, data.getLabels()); - Assert.assertEquals(23.0, data.getValue(), 0.0); - Assert.assertNull(data.getExemplar()); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); + assertThat((Iterable) data.getLabels()).isEmpty(); + assertThat(data.getValue()).isCloseTo(23.0, offset(0.0)); + assertThat(data.getExemplar()).isNull(); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); } @Test public void testEmptyGauge() { GaugeSnapshot snapshot = GaugeSnapshot.builder().name("temperature").build(); - Assert.assertEquals(0, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isZero(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testTotalSuffixPresent() { - CounterSnapshot.builder().name("test_total").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CounterSnapshot.builder().name("test_total").build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testTotalSuffixPresentDot() { - CounterSnapshot.builder().name("test.total").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CounterSnapshot.builder().name("test.total").build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testValueMissing() { - CounterDataPointSnapshot.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CounterDataPointSnapshot.builder().build()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testDataImmutable() { GaugeSnapshot snapshot = GaugeSnapshot.builder() @@ -110,6 +116,6 @@ public void testDataImmutable() { .build(); Iterator iterator = snapshot.getDataPoints().iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/HistogramSnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/HistogramSnapshotTest.java index e8e53e219..2f8aeb730 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/HistogramSnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/HistogramSnapshotTest.java @@ -1,12 +1,15 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; + import io.prometheus.metrics.model.snapshots.HistogramSnapshot.HistogramDataPointSnapshot; import java.util.Iterator; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HistogramSnapshotTest { +class HistogramSnapshotTest { @Test public void testGoodCaseComplete() { @@ -82,94 +85,94 @@ public void testGoodCaseComplete() { SnapshotTestUtil.assertMetadata( snapshot, "request_size_bytes", "request sizes in bytes", "bytes"); - Assert.assertEquals(2, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(2); HistogramDataPointSnapshot data = snapshot .getDataPoints() .get(0); // data is sorted by labels, so the first one should be path="/" - Assert.assertTrue(data.hasSum()); - Assert.assertTrue(data.hasCount()); - Assert.assertTrue(data.hasCreatedTimestamp()); - Assert.assertTrue(data.hasScrapeTimestamp()); - Assert.assertEquals(22, data.getCount()); - Assert.assertEquals(27000.0, data.getSum(), 0.0); - Assert.assertEquals(Labels.of("path", "/"), data.getLabels()); - Assert.assertEquals( - exemplar1.getValue(), data.getExemplars().get(128.0, 1024.0).getValue(), 0.0); - Assert.assertEquals(createdTimestamp, data.getCreatedTimestampMillis()); - Assert.assertEquals(scrapeTimestamp, data.getScrapeTimestampMillis()); + assertThat(data.hasSum()).isTrue(); + assertThat(data.hasCount()).isTrue(); + assertThat(data.hasCreatedTimestamp()).isTrue(); + assertThat(data.hasScrapeTimestamp()).isTrue(); + assertThat(data.getCount()).isEqualTo(22); + assertThat(data.getSum()).isCloseTo(27000.0, offset(0.0)); + assertThat((Iterable) data.getLabels()).isEqualTo(Labels.of("path", "/")); + assertThat(data.getExemplars().get(128.0, 1024.0).getValue()) + .isCloseTo(exemplar1.getValue(), offset(0.0)); + assertThat(data.getCreatedTimestampMillis()).isEqualTo(createdTimestamp); + assertThat(data.getScrapeTimestampMillis()).isEqualTo(scrapeTimestamp); // classic histogram 1 int i = 0; for (ClassicHistogramBucket bucket : data.getClassicBuckets()) { switch (i++) { case 0: - Assert.assertEquals(128.0, bucket.getUpperBound(), 0.0); - Assert.assertEquals(7, bucket.getCount()); + assertThat(bucket.getUpperBound()).isCloseTo(128.0, offset(0.0)); + assertThat(bucket.getCount()).isEqualTo(7); break; case 1: - Assert.assertEquals(1024.0, bucket.getUpperBound(), 0.0); - Assert.assertEquals(15, bucket.getCount()); + assertThat(bucket.getUpperBound()).isCloseTo(1024.0, offset(0.0)); + assertThat(bucket.getCount()).isEqualTo(15); break; case 2: - Assert.assertEquals(Double.POSITIVE_INFINITY, bucket.getUpperBound(), 0.0); - Assert.assertEquals(0, bucket.getCount()); + assertThat(bucket.getUpperBound()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(bucket.getCount()).isZero(); break; } } - Assert.assertEquals("expecting 3 classic histogram buckets", 3, i); + assertThat(i).as("expecting 3 classic histogram buckets").isEqualTo(3); // native histogram 1 - Assert.assertEquals(5, data.getNativeSchema()); - Assert.assertEquals(2, data.getNativeZeroCount()); - Assert.assertEquals(0.0000001, data.getNativeZeroThreshold(), 0.0000001); - Assert.assertEquals(3, data.getNativeBucketsForPositiveValues().size()); + assertThat(data.getNativeSchema()).isEqualTo(5); + assertThat(data.getNativeZeroCount()).isEqualTo(2); + assertThat(data.getNativeZeroThreshold()).isCloseTo(0.0000001, offset(0.0000001)); + assertThat(data.getNativeBucketsForPositiveValues().size()).isEqualTo(3); i = 0; for (NativeHistogramBucket bucket : data.getNativeBucketsForPositiveValues()) { switch (i++) { case 0: - Assert.assertEquals(1, bucket.getBucketIndex()); - Assert.assertEquals(12, bucket.getCount()); + assertThat(bucket.getBucketIndex()).isOne(); + assertThat(bucket.getCount()).isEqualTo(12); break; case 1: - Assert.assertEquals(2, bucket.getBucketIndex()); - Assert.assertEquals(3, bucket.getCount()); + assertThat(bucket.getBucketIndex()).isEqualTo(2); + assertThat(bucket.getCount()).isEqualTo(3); break; case 2: - Assert.assertEquals(4, bucket.getBucketIndex()); - Assert.assertEquals(2, bucket.getCount()); + assertThat(bucket.getBucketIndex()).isEqualTo(4); + assertThat(bucket.getCount()).isEqualTo(2); break; } } - Assert.assertEquals("expecting 3 native buckets for positive values", 3, i); + assertThat(i).as("expecting 3 native buckets for positive values").isEqualTo(3); i = 0; - Assert.assertEquals(2, data.getNativeBucketsForNegativeValues().size()); + assertThat(data.getNativeBucketsForNegativeValues().size()).isEqualTo(2); for (NativeHistogramBucket bucket : data.getNativeBucketsForNegativeValues()) { switch (i++) { case 0: - Assert.assertEquals(-1, bucket.getBucketIndex()); - Assert.assertEquals(1, bucket.getCount()); + assertThat(bucket.getBucketIndex()).isEqualTo(-1); + assertThat(bucket.getCount()).isOne(); break; case 1: - Assert.assertEquals(0, bucket.getBucketIndex()); - Assert.assertEquals(2, bucket.getCount()); + assertThat(bucket.getBucketIndex()).isZero(); + assertThat(bucket.getCount()).isEqualTo(2); break; } } - Assert.assertEquals("expecting 2 native buckets for positive values", 2, i); + assertThat(i).as("expecting 2 native buckets for positive values").isEqualTo(2); // classic histogram 2 (it's ok that this is incomplete, because we covered it with the other // tests) data = snapshot.getDataPoints().get(1); - Assert.assertEquals(6, data.getCount()); + assertThat(data.getCount()).isEqualTo(6); // native histogram 2 (it's ok that this is incomplete, because we covered it with the other // tests) - Assert.assertEquals(5, data.getNativeSchema()); - Assert.assertEquals(0, data.getNativeZeroCount()); - Assert.assertEquals(0, data.getNativeZeroThreshold(), 0); + assertThat(data.getNativeSchema()).isEqualTo(5); + assertThat(data.getNativeZeroCount()).isZero(); + assertThat(data.getNativeZeroThreshold()).isZero(); } @Test public void testEmptyHistogram() { HistogramSnapshot snapshot = HistogramSnapshot.builder().name("empty_histogram").build(); - Assert.assertEquals(0, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).isEmpty(); } @Test @@ -185,8 +188,8 @@ public void testMinimalClassicHistogram() { .build()) .build(); HistogramDataPointSnapshot data = snapshot.getDataPoints().get(0); - Assert.assertFalse(data.hasSum()); - Assert.assertEquals(1, snapshot.getDataPoints().get(0).getClassicBuckets().size()); + assertThat(data.hasSum()).isFalse(); + assertThat(snapshot.getDataPoints().get(0).getClassicBuckets().size()).isOne(); } @Test @@ -196,17 +199,17 @@ public void testMinimalNativeHistogram() { .name("hist") .dataPoint(HistogramDataPointSnapshot.builder().nativeSchema(5).build()) .build(); - Assert.assertEquals("hist", snapshot.getMetadata().getName()); - Assert.assertFalse(snapshot.getMetadata().hasUnit()); - Assert.assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getMetadata().getName()).isEqualTo("hist"); + assertThat(snapshot.getMetadata().hasUnit()).isFalse(); + assertThat(snapshot.getDataPoints().size()).isOne(); HistogramDataPointSnapshot data = snapshot.getDataPoints().get(0); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); - Assert.assertTrue(data.hasCount()); - Assert.assertEquals(0, data.getCount()); - Assert.assertFalse(data.hasSum()); - Assert.assertEquals(0, data.getNativeBucketsForNegativeValues().size()); - Assert.assertEquals(0, data.getNativeBucketsForPositiveValues().size()); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); + assertThat(data.hasCount()).isTrue(); + assertThat(data.getCount()).isZero(); + assertThat(data.hasSum()).isFalse(); + assertThat(data.getNativeBucketsForNegativeValues().size()).isZero(); + assertThat(data.getNativeBucketsForPositiveValues().size()).isZero(); } @Test @@ -225,25 +228,26 @@ public void testClassicCount() { .build()) .build(); HistogramDataPointSnapshot data = snapshot.getDataPoints().get(0); - Assert.assertFalse(data.hasSum()); - Assert.assertTrue(data.hasCount()); - Assert.assertEquals(5, data.getCount()); + assertThat(data.hasSum()).isFalse(); + assertThat(data.hasCount()).isTrue(); + assertThat(data.getCount()).isEqualTo(5); } - @Test(expected = IllegalArgumentException.class) + @Test public void testEmptyData() { // This will fail because one of nativeSchema and classicHistogramBuckets is required - HistogramDataPointSnapshot.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> HistogramDataPointSnapshot.builder().build()); } @Test public void testEmptyNativeData() { HistogramDataPointSnapshot data = HistogramDataPointSnapshot.builder().nativeSchema(5).build(); - Assert.assertEquals(0, data.getNativeBucketsForNegativeValues().size()); - Assert.assertEquals(0, data.getNativeBucketsForPositiveValues().size()); + assertThat(data.getNativeBucketsForNegativeValues().size()).isZero(); + assertThat(data.getNativeBucketsForPositiveValues().size()).isZero(); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testDataImmutable() { HistogramSnapshot snapshot = HistogramSnapshot.builder() @@ -265,13 +269,16 @@ public void testDataImmutable() { .build(); Iterator iterator = snapshot.getDataPoints().iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } - @Test(expected = IllegalArgumentException.class) + @Test public void testEmptyClassicBuckets() { - new HistogramDataPointSnapshot( - ClassicHistogramBuckets.EMPTY, Double.NaN, Labels.EMPTY, Exemplars.EMPTY, 0L); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + new HistogramDataPointSnapshot( + ClassicHistogramBuckets.EMPTY, Double.NaN, Labels.EMPTY, Exemplars.EMPTY, 0L)); } @Test diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/InfoSnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/InfoSnapshotTest.java index 78e26d100..423b57da7 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/InfoSnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/InfoSnapshotTest.java @@ -1,10 +1,12 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import java.util.Iterator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class InfoSnapshotTest { +class InfoSnapshotTest { @Test public void testCompleteGoodCase() { @@ -17,19 +19,19 @@ public void testCompleteGoodCase() { .labels(Labels.of("instance_id", "127.0.0.1:9100", "service_name", "gateway")) .build()) .build(); - Assert.assertEquals("target", snapshot.getMetadata().getName()); - Assert.assertEquals("Target info", snapshot.getMetadata().getHelp()); - Assert.assertFalse(snapshot.getMetadata().hasUnit()); - Assert.assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getMetadata().getName()).isEqualTo("target"); + assertThat(snapshot.getMetadata().getHelp()).isEqualTo("Target info"); + assertThat(snapshot.getMetadata().hasUnit()).isFalse(); + assertThat(snapshot.getDataPoints().size()).isOne(); } @Test public void testEmptyInfo() { InfoSnapshot snapshot = InfoSnapshot.builder().name("target").build(); - Assert.assertEquals(0, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).isEmpty(); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testDataImmutable() { InfoSnapshot snapshot = InfoSnapshot.builder() @@ -47,16 +49,18 @@ public void testDataImmutable() { .build(); Iterator iterator = snapshot.getDataPoints().iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNameMustNotIncludeSuffix() { - InfoSnapshot.builder().name("jvm_info").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> InfoSnapshot.builder().name("jvm_info").build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNameMustNotIncludeSuffixDot() { - InfoSnapshot.builder().name("jvm.info").build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> InfoSnapshot.builder().name("jvm.info").build()); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/LabelsTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/LabelsTest.java index e7ae37723..4d68b82a8 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/LabelsTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/LabelsTest.java @@ -1,18 +1,19 @@ package io.prometheus.metrics.model.snapshots; -import static org.junit.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import org.junit.Assert; -import org.junit.Test; +import org.assertj.core.api.IterableAssert; +import org.junit.jupiter.api.Test; -public class LabelsTest { +class LabelsTest { private > void assertLessThan(T a, T b) { - Assert.assertTrue(a.compareTo(b) < 0); + assertThat(a).isLessThan(b); } private > void assertGreaterThan(T a, T b) { - Assert.assertTrue(a.compareTo(b) > 0); + assertThat(a).isGreaterThan(b); } @Test @@ -21,8 +22,12 @@ public void testCompareDifferentLabelNames() { Labels labels2 = Labels.of("env", "prod", "status1", "200"); assertGreaterThan(labels1, labels2); assertLessThan(labels2, labels1); - assertNotEquals(labels1, labels2); - assertNotEquals(labels2, labels1); + assertLabels(labels2).isNotEqualTo(labels1); + assertLabels(labels1).isNotEqualTo(labels2); + } + + private static IterableAssert assertLabels(Labels labels) { + return assertThat((Iterable) labels); } @Test @@ -32,8 +37,8 @@ public void testCompareSameLabelNames() { Labels labels2 = Labels.of("env", "prod", "status", "500"); assertLessThan(labels1, labels2); assertGreaterThan(labels2, labels1); - assertNotEquals(labels1, labels2); - assertNotEquals(labels2, labels1); + assertLabels(labels2).isNotEqualTo(labels1); + assertLabels(labels1).isNotEqualTo(labels2); } @Test @@ -42,8 +47,8 @@ public void testCompareDifferentNumberOfLabels() { Labels labels2 = Labels.of("env", "prod", "status", "200", "x_code", "none"); assertLessThan(labels1, labels2); assertGreaterThan(labels2, labels1); - assertNotEquals(labels1, labels2); - assertNotEquals(labels2, labels1); + assertLabels(labels2).isNotEqualTo(labels1); + assertLabels(labels1).isNotEqualTo(labels2); } @Test @@ -57,51 +62,54 @@ public void testComparePrometheusNames() { public void testEqualsHashcodeDots() { Labels labels1 = Labels.of("my_a", "val"); Labels labels2 = Labels.of("my.a", "val"); - Assert.assertEquals(labels1, labels2); - Assert.assertEquals(labels1.hashCode(), labels2.hashCode()); + assertLabels(labels2).isEqualTo(labels1).hasSameHashCodeAs(labels1); } + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testCompareEquals() { Labels labels1 = Labels.of("env", "prod", "status", "200"); Labels labels2 = Labels.of("env", "prod", "status", "200"); - Assert.assertEquals(0, labels1.compareTo(labels2)); - Assert.assertEquals(0, labels2.compareTo(labels1)); - Assert.assertEquals(labels1, labels2); - Assert.assertEquals(labels2, labels1); + assertThat((Comparable) labels1).isEqualByComparingTo(labels2); + assertThat((Comparable) labels2).isEqualByComparingTo(labels1); + assertLabels(labels2).isEqualTo(labels1); + assertLabels(labels1).isEqualTo(labels2); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalLabelName() { - Labels.of("my_service/status", "200"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Labels.of("my_service/status", "200")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testReservedLabelName() { - Labels.of("__name__", "requests_total"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Labels.of("__name__", "requests_total")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDuplicateLabelName() { - Labels.of("name1", "value1", "name2", "value2", "name1", "value3"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Labels.of("name1", "value1", "name2", "value2", "name1", "value3")); } @Test public void testMakePrometheusNames() { String[] names = new String[] {}; String[] prometheusNames = Labels.makePrometheusNames(names); - Assert.assertSame(names, prometheusNames); + assertThat(prometheusNames).isSameAs(names); names = new String[] {"no_dots", "at_all"}; prometheusNames = Labels.makePrometheusNames(names); - Assert.assertSame(names, prometheusNames); + assertThat(prometheusNames).isSameAs(names); names = new String[] {"dots", "here.it.is"}; prometheusNames = Labels.makePrometheusNames(names); - Assert.assertNotSame(names, prometheusNames); - Assert.assertSame(names[0], prometheusNames[0]); - Assert.assertEquals("here.it.is", names[1]); - Assert.assertEquals("here_it_is", prometheusNames[1]); + assertThat(prometheusNames).isNotSameAs(names); + assertThat(prometheusNames[0]).isSameAs(names[0]); + assertThat(names[1]).isEqualTo("here.it.is"); + assertThat(prometheusNames[1]).isEqualTo("here_it_is"); } @Test @@ -109,20 +117,22 @@ public void testMerge() { Labels labels1 = Labels.of("key.1", "value 1", "key.3", "value 3"); Labels labels2 = Labels.of("key_2", "value 2"); Labels merged = labels2.merge(labels1); - Assert.assertEquals("key.1", merged.getName(0)); - Assert.assertEquals("key_2", merged.getName(1)); - Assert.assertEquals("key.3", merged.getName(2)); + assertThat(merged.getName(0)).isEqualTo("key.1"); + assertThat(merged.getName(1)).isEqualTo("key_2"); + assertThat(merged.getName(2)).isEqualTo("key.3"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testMergeDuplicateName() { Labels labels1 = Labels.of("key_one", "v1"); Labels labels2 = Labels.of("key.one", "v2"); - labels2.merge(labels1); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> labels2.merge(labels1)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDuplicateName() { - Labels.of("key_one", "v1", "key.one", "v2"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> Labels.of("key_one", "v1", "key.one", "v2")); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricMetadataTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricMetadataTest.java index 9a3a980bc..fab885488 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricMetadataTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricMetadataTest.java @@ -1,26 +1,33 @@ package io.prometheus.metrics.model.snapshots; import static io.prometheus.metrics.model.snapshots.PrometheusNaming.sanitizeMetricName; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MetricMetadataTest { +class MetricMetadataTest { - @Test(expected = IllegalArgumentException.class) + @Test public void testEmptyName() { - new MetricMetadata(""); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new MetricMetadata("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNullName() { - new MetricMetadata(null); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new MetricMetadata(null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalName() { - new MetricMetadata( - "my_namespace/http_server_duration"); // let's see when we decide to allow slashes :) + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + new MetricMetadata( + "my_namespace/http_server_duration")); // let's see when we decide to allow + // slashes :) } @Test @@ -30,38 +37,40 @@ public void testSanitizationIllegalCharacters() { sanitizeMetricName("my_namespace/http.server.duration", Unit.SECONDS), "help string", Unit.SECONDS); - Assert.assertEquals("my_namespace_http.server.duration_seconds", metadata.getName()); - Assert.assertEquals("my_namespace_http_server_duration_seconds", metadata.getPrometheusName()); - Assert.assertEquals("help string", metadata.getHelp()); - Assert.assertEquals("seconds", metadata.getUnit().toString()); + assertThat(metadata.getName()).isEqualTo("my_namespace_http.server.duration_seconds"); + assertThat(metadata.getPrometheusName()).isEqualTo("my_namespace_http_server_duration_seconds"); + assertThat(metadata.getHelp()).isEqualTo("help string"); + assertThat(metadata.getUnit().toString()).isEqualTo("seconds"); } @Test public void testSanitizationCounter() { MetricMetadata metadata = new MetricMetadata(sanitizeMetricName("my_events_total")); - Assert.assertEquals("my_events", metadata.getName()); + assertThat(metadata.getName()).isEqualTo("my_events"); } @Test public void testSanitizationInfo() { MetricMetadata metadata = new MetricMetadata(sanitizeMetricName("target_info")); - Assert.assertEquals("target", metadata.getName()); + assertThat(metadata.getName()).isEqualTo("target"); } @Test public void testSanitizationWeirdCornerCase() { MetricMetadata metadata = new MetricMetadata(sanitizeMetricName("_total_created")); - Assert.assertEquals("total", metadata.getName()); + assertThat(metadata.getName()).isEqualTo("total"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSanitizeEmptyString() { - sanitizeMetricName(""); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> sanitizeMetricName("")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testUnitSuffixRequired() { - new MetricMetadata("my_counter", "help", Unit.SECONDS); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new MetricMetadata("my_counter", "help", Unit.SECONDS)); } @Test @@ -71,6 +80,6 @@ public void testUnitSuffixAdded() { @Test public void testUnitNotDuplicated() { - Assert.assertEquals("my_counter_bytes", sanitizeMetricName("my_counter_bytes", Unit.BYTES)); + assertThat(sanitizeMetricName("my_counter_bytes", Unit.BYTES)).isEqualTo("my_counter_bytes"); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotTest.java index e387d7155..fc0c24bfc 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotTest.java @@ -1,40 +1,46 @@ package io.prometheus.metrics.model.snapshots; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -public class MetricSnapshotTest { +import org.junit.jupiter.api.Test; - @Test(expected = IllegalArgumentException.class) +class MetricSnapshotTest { + + @Test public void testDuplicateLabels() { - CounterSnapshot.builder() - .name("events") - .dataPoint( - CounterSnapshot.CounterDataPointSnapshot.builder() - .labels(Labels.of("path", "/hello", "status", "200")) - .value(1.0) - .build()) - .dataPoint( - CounterSnapshot.CounterDataPointSnapshot.builder() - .labels(Labels.of("path", "/world", "status", "200")) - .value(2.0) - .build()) - .dataPoint( - CounterSnapshot.CounterDataPointSnapshot.builder() - .labels(Labels.of("status", "200", "path", "/hello")) - .value(3.0) - .build()) - .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + CounterSnapshot.builder() + .name("events") + .dataPoint( + CounterSnapshot.CounterDataPointSnapshot.builder() + .labels(Labels.of("path", "/hello", "status", "200")) + .value(1.0) + .build()) + .dataPoint( + CounterSnapshot.CounterDataPointSnapshot.builder() + .labels(Labels.of("path", "/world", "status", "200")) + .value(2.0) + .build()) + .dataPoint( + CounterSnapshot.CounterDataPointSnapshot.builder() + .labels(Labels.of("status", "200", "path", "/hello")) + .value(3.0) + .build()) + .build()); } @Test public void testNoData() { MetricSnapshot snapshot = CounterSnapshot.builder().name("test").build(); - Assert.assertEquals(0, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints().size()).isEqualTo(0); } - @Test(expected = NullPointerException.class) + @Test public void testNullData() { - new CounterSnapshot(new MetricMetadata("test"), null); + assertThatExceptionOfType(NullPointerException.class) + .isThrownBy(() -> new CounterSnapshot(new MetricMetadata("test"), null)); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotsTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotsTest.java index b85fe629f..ed2f66fec 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotsTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/MetricSnapshotsTest.java @@ -1,15 +1,17 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import java.util.Iterator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MetricSnapshotsTest { +class MetricSnapshotsTest { @Test public void testEmpty() { MetricSnapshots snapshots = MetricSnapshots.builder().build(); - Assert.assertFalse(snapshots.stream().findAny().isPresent()); + assertThat(snapshots.stream().findAny().isPresent()).isFalse(); } @Test @@ -30,13 +32,13 @@ public void testSort() { .dataPoint(CounterSnapshot.CounterDataPointSnapshot.builder().value(1.0).build()) .build(); MetricSnapshots snapshots = new MetricSnapshots(c2, c3, c1); - Assert.assertEquals(3, snapshots.size()); - Assert.assertEquals("counter1", snapshots.get(0).getMetadata().getName()); - Assert.assertEquals("counter2", snapshots.get(1).getMetadata().getName()); - Assert.assertEquals("counter3", snapshots.get(2).getMetadata().getName()); + assertThat(snapshots.size()).isEqualTo(3); + assertThat(snapshots.get(0).getMetadata().getName()).isEqualTo("counter1"); + assertThat(snapshots.get(1).getMetadata().getName()).isEqualTo("counter2"); + assertThat(snapshots.get(2).getMetadata().getName()).isEqualTo("counter3"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDuplicateName() { // Q: What if you have a counter named "foo" and a gauge named "foo"? // A: Great question. You might think this is a valid scenario, because the counter will produce @@ -55,7 +57,8 @@ public void testDuplicateName() { .name("my_metric") .dataPoint(GaugeSnapshot.GaugeDataPointSnapshot.builder().value(1.0).build()) .build(); - new MetricSnapshots(c, g); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new MetricSnapshots(c, g)); } @Test @@ -66,12 +69,12 @@ public void testBuilder() { .dataPoint(CounterSnapshot.CounterDataPointSnapshot.builder().value(1.0).build()) .build(); MetricSnapshots.Builder builder = MetricSnapshots.builder(); - Assert.assertFalse(builder.containsMetricName("my_metric")); + assertThat(builder.containsMetricName("my_metric")).isFalse(); builder.metricSnapshot(counter); - Assert.assertTrue(builder.containsMetricName("my_metric")); + assertThat(builder.containsMetricName("my_metric")).isTrue(); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testImmutable() { CounterSnapshot c1 = CounterSnapshot.builder() @@ -91,6 +94,6 @@ public void testImmutable() { MetricSnapshots snapshots = new MetricSnapshots(c2, c3, c1); Iterator iterator = snapshots.iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/NativeHistogramBucketsTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/NativeHistogramBucketsTest.java index 1aa7a1023..32c7f3eb3 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/NativeHistogramBucketsTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/NativeHistogramBucketsTest.java @@ -1,54 +1,57 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import java.util.Iterator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NativeHistogramBucketsTest { +class NativeHistogramBucketsTest { @Test public void testGoodCase() { NativeHistogramBuckets buckets = NativeHistogramBuckets.builder().bucket(-10, 12).bucket(120, 17).build(); - Assert.assertEquals(2, buckets.size()); - Assert.assertEquals(-10, buckets.getBucketIndex(0)); - Assert.assertEquals(12, buckets.getCount(0)); - Assert.assertEquals(120, buckets.getBucketIndex(1)); - Assert.assertEquals(17, buckets.getCount(1)); + assertThat(buckets.size()).isEqualTo(2); + assertThat(buckets.getBucketIndex(0)).isEqualTo(-10); + assertThat(buckets.getCount(0)).isEqualTo(12); + assertThat(buckets.getBucketIndex(1)).isEqualTo(120); + assertThat(buckets.getCount(1)).isEqualTo(17); } @Test public void testEmpty() { NativeHistogramBuckets buckets = NativeHistogramBuckets.builder().build(); - Assert.assertEquals(0, buckets.size()); + assertThat(buckets.size()).isZero(); } @Test public void testSort() { NativeHistogramBuckets buckets = NativeHistogramBuckets.builder().bucket(7, 4).bucket(2, 0).bucket(5, 3).build(); - Assert.assertEquals(3, buckets.size()); - Assert.assertEquals(2, buckets.getBucketIndex(0)); - Assert.assertEquals(5, buckets.getBucketIndex(1)); - Assert.assertEquals(7, buckets.getBucketIndex(2)); - Assert.assertEquals(0, buckets.getCount(0)); - Assert.assertEquals(3, buckets.getCount(1)); - Assert.assertEquals(4, buckets.getCount(2)); + assertThat(buckets.size()).isEqualTo(3); + assertThat(buckets.getBucketIndex(0)).isEqualTo(2); + assertThat(buckets.getBucketIndex(1)).isEqualTo(5); + assertThat(buckets.getBucketIndex(2)).isEqualTo(7); + assertThat(buckets.getCount(0)).isZero(); + assertThat(buckets.getCount(1)).isEqualTo(3); + assertThat(buckets.getCount(2)).isEqualTo(4); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDifferentLength() { int[] bucketIndexes = new int[] {0, 1, 2}; long[] cumulativeCounts = new long[] {13, 178, 1024, 3000}; - NativeHistogramBuckets.of(bucketIndexes, cumulativeCounts); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> NativeHistogramBuckets.of(bucketIndexes, cumulativeCounts)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testImmutable() { NativeHistogramBuckets buckets = NativeHistogramBuckets.builder().bucket(1, 1).bucket(2, 1).build(); Iterator iterator = buckets.iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/PrometheusNamingTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/PrometheusNamingTest.java index 62f2fc2c8..fad55e0ac 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/PrometheusNamingTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/PrometheusNamingTest.java @@ -1,95 +1,99 @@ package io.prometheus.metrics.model.snapshots; import static io.prometheus.metrics.model.snapshots.PrometheusNaming.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PrometheusNamingTest { +class PrometheusNamingTest { @Test public void testSanitizeMetricName() { - Assert.assertEquals("_abc_def", prometheusName(sanitizeMetricName("0abc.def"))); - Assert.assertEquals("___ab__c0", prometheusName(sanitizeMetricName("___ab.:c0"))); - Assert.assertEquals("my_prefix_my_metric", sanitizeMetricName("my_prefix/my_metric")); - Assert.assertEquals("my_counter", prometheusName(sanitizeMetricName("my_counter_total"))); - Assert.assertEquals("jvm", sanitizeMetricName("jvm.info")); - Assert.assertEquals("jvm", sanitizeMetricName("jvm_info")); - Assert.assertEquals("jvm", sanitizeMetricName("jvm.info")); - Assert.assertEquals("a.b", sanitizeMetricName("a.b")); - Assert.assertEquals("total", sanitizeMetricName("_total")); - Assert.assertEquals("total", sanitizeMetricName("total")); + assertThat(prometheusName(sanitizeMetricName("0abc.def"))).isEqualTo("_abc_def"); + assertThat(prometheusName(sanitizeMetricName("___ab.:c0"))).isEqualTo("___ab__c0"); + assertThat(sanitizeMetricName("my_prefix/my_metric")).isEqualTo("my_prefix_my_metric"); + assertThat(prometheusName(sanitizeMetricName("my_counter_total"))).isEqualTo("my_counter"); + assertThat(sanitizeMetricName("jvm.info")).isEqualTo("jvm"); + assertThat(sanitizeMetricName("jvm_info")).isEqualTo("jvm"); + assertThat(sanitizeMetricName("jvm.info")).isEqualTo("jvm"); + assertThat(sanitizeMetricName("a.b")).isEqualTo("a.b"); + assertThat(sanitizeMetricName("_total")).isEqualTo("total"); + assertThat(sanitizeMetricName("total")).isEqualTo("total"); } @Test public void testSanitizeMetricNameWithUnit() { - Assert.assertEquals( - "_abc_def_" + Unit.RATIO, prometheusName(sanitizeMetricName("0abc.def", Unit.RATIO))); - Assert.assertEquals( - "___ab__c0_" + Unit.RATIO, prometheusName(sanitizeMetricName("___ab.:c0", Unit.RATIO))); - Assert.assertEquals( - "my_prefix_my_metric_" + Unit.RATIO, sanitizeMetricName("my_prefix/my_metric", Unit.RATIO)); - Assert.assertEquals( - "my_counter_" + Unit.RATIO, - prometheusName(sanitizeMetricName("my_counter_total", Unit.RATIO))); - Assert.assertEquals("jvm_" + Unit.RATIO, sanitizeMetricName("jvm.info", Unit.RATIO)); - Assert.assertEquals("jvm_" + Unit.RATIO, sanitizeMetricName("jvm_info", Unit.RATIO)); - Assert.assertEquals("jvm_" + Unit.RATIO, sanitizeMetricName("jvm.info", Unit.RATIO)); - Assert.assertEquals("a.b_" + Unit.RATIO, sanitizeMetricName("a.b", Unit.RATIO)); - Assert.assertEquals("total_" + Unit.RATIO, sanitizeMetricName("_total", Unit.RATIO)); - Assert.assertEquals("total_" + Unit.RATIO, sanitizeMetricName("total", Unit.RATIO)); + assertThat(prometheusName(sanitizeMetricName("0abc.def", Unit.RATIO))) + .isEqualTo("_abc_def_" + Unit.RATIO); + assertThat(prometheusName(sanitizeMetricName("___ab.:c0", Unit.RATIO))) + .isEqualTo("___ab__c0_" + Unit.RATIO); + assertThat(sanitizeMetricName("my_prefix/my_metric", Unit.RATIO)) + .isEqualTo("my_prefix_my_metric_" + Unit.RATIO); + assertThat(prometheusName(sanitizeMetricName("my_counter_total", Unit.RATIO))) + .isEqualTo("my_counter_" + Unit.RATIO); + assertThat(sanitizeMetricName("jvm.info", Unit.RATIO)).isEqualTo("jvm_" + Unit.RATIO); + assertThat(sanitizeMetricName("jvm_info", Unit.RATIO)).isEqualTo("jvm_" + Unit.RATIO); + assertThat(sanitizeMetricName("jvm.info", Unit.RATIO)).isEqualTo("jvm_" + Unit.RATIO); + assertThat(sanitizeMetricName("a.b", Unit.RATIO)).isEqualTo("a.b_" + Unit.RATIO); + assertThat(sanitizeMetricName("_total", Unit.RATIO)).isEqualTo("total_" + Unit.RATIO); + assertThat(sanitizeMetricName("total", Unit.RATIO)).isEqualTo("total_" + Unit.RATIO); } @Test public void testSanitizeLabelName() { - Assert.assertEquals("_abc_def", prometheusName(sanitizeLabelName("0abc.def"))); - Assert.assertEquals("_abc", prometheusName(sanitizeLabelName("_abc"))); - Assert.assertEquals("_abc", prometheusName(sanitizeLabelName("__abc"))); - Assert.assertEquals("_abc", prometheusName(sanitizeLabelName("___abc"))); - Assert.assertEquals("_abc", prometheusName(sanitizeLabelName("_.abc"))); - Assert.assertEquals("abc.def", sanitizeLabelName("abc.def")); - Assert.assertEquals("abc.def2", sanitizeLabelName("abc.def2")); + assertThat(prometheusName(sanitizeLabelName("0abc.def"))).isEqualTo("_abc_def"); + assertThat(prometheusName(sanitizeLabelName("_abc"))).isEqualTo("_abc"); + assertThat(prometheusName(sanitizeLabelName("__abc"))).isEqualTo("_abc"); + assertThat(prometheusName(sanitizeLabelName("___abc"))).isEqualTo("_abc"); + assertThat(prometheusName(sanitizeLabelName("_.abc"))).isEqualTo("_abc"); + assertThat(sanitizeLabelName("abc.def")).isEqualTo("abc.def"); + assertThat(sanitizeLabelName("abc.def2")).isEqualTo("abc.def2"); } @Test public void testValidateUnitName() { - Assert.assertNotNull(validateUnitName("secondstotal")); - Assert.assertNotNull(validateUnitName("total")); - Assert.assertNotNull(validateUnitName("seconds_total")); - Assert.assertNotNull(validateUnitName("_total")); - Assert.assertNotNull(validateUnitName("")); + assertThat(validateUnitName("secondstotal")).isNotNull(); + assertThat(validateUnitName("total")).isNotNull(); + assertThat(validateUnitName("seconds_total")).isNotNull(); + assertThat(validateUnitName("_total")).isNotNull(); + assertThat(validateUnitName("")).isNotNull(); - Assert.assertNull(validateUnitName("seconds")); - Assert.assertNull(validateUnitName("2")); + assertThat(validateUnitName("seconds")).isNull(); + assertThat(validateUnitName("2")).isNull(); } @Test public void testSanitizeUnitName() { - Assert.assertEquals("seconds", sanitizeUnitName("seconds")); - Assert.assertEquals("seconds", sanitizeUnitName("seconds_total")); - Assert.assertEquals("seconds", sanitizeUnitName("seconds_total_total")); - Assert.assertEquals("m_s", sanitizeUnitName("m/s")); - Assert.assertEquals("seconds", sanitizeUnitName("secondstotal")); - Assert.assertEquals("2", sanitizeUnitName("2")); + assertThat(sanitizeUnitName("seconds")).isEqualTo("seconds"); + assertThat(sanitizeUnitName("seconds_total")).isEqualTo("seconds"); + assertThat(sanitizeUnitName("seconds_total_total")).isEqualTo("seconds"); + assertThat(sanitizeUnitName("m/s")).isEqualTo("m_s"); + assertThat(sanitizeUnitName("secondstotal")).isEqualTo("seconds"); + assertThat(sanitizeUnitName("2")).isEqualTo("2"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInvalidUnitName1() { - sanitizeUnitName("total"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> sanitizeUnitName("total")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInvalidUnitName2() { - sanitizeUnitName("_total"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> sanitizeUnitName("_total")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInvalidUnitName3() { - sanitizeUnitName("%"); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> sanitizeUnitName("%")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testEmptyUnitName() { - sanitizeUnitName(""); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> sanitizeUnitName("")); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/QuantilesTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/QuantilesTest.java index 0d66d5632..4179cf630 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/QuantilesTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/QuantilesTest.java @@ -1,40 +1,50 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; + import java.util.Iterator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class QuantilesTest { +class QuantilesTest { @Test public void testSort() { Quantiles quantiles = Quantiles.builder().quantile(0.99, 0.23).quantile(0.5, 0.2).quantile(0.95, 0.22).build(); - Assert.assertEquals(3, quantiles.size()); - Assert.assertEquals(0.5, quantiles.get(0).getQuantile(), 0); - Assert.assertEquals(0.2, quantiles.get(0).getValue(), 0); - Assert.assertEquals(0.95, quantiles.get(1).getQuantile(), 0); - Assert.assertEquals(0.22, quantiles.get(1).getValue(), 0); - Assert.assertEquals(0.99, quantiles.get(2).getQuantile(), 0); - Assert.assertEquals(0.23, quantiles.get(2).getValue(), 0); + assertThat(quantiles.size()).isEqualTo(3); + assertThat(quantiles.get(0).getQuantile()).isCloseTo(0.5, offset(0.0)); + assertThat(quantiles.get(0).getValue()).isCloseTo(0.2, offset(0.0)); + assertThat(quantiles.get(1).getQuantile()).isCloseTo(0.95, offset(0.0)); + assertThat(quantiles.get(1).getValue()).isCloseTo(0.22, offset(0.0)); + assertThat(quantiles.get(2).getQuantile()).isCloseTo(0.99, offset(0.0)); + assertThat(quantiles.get(2).getValue()).isCloseTo(0.23, offset(0.0)); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testImmutable() { Quantiles quantiles = Quantiles.builder().quantile(0.99, 0.23).quantile(0.5, 0.2).quantile(0.95, 0.22).build(); Iterator iterator = quantiles.iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } @Test public void testEmpty() { - Assert.assertEquals(0, Quantiles.EMPTY.size()); + assertThat(Quantiles.EMPTY.size()).isZero(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDuplicate() { - Quantiles.builder().quantile(0.95, 0.23).quantile(0.5, 0.2).quantile(0.95, 0.22).build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + Quantiles.builder() + .quantile(0.95, 0.23) + .quantile(0.5, 0.2) + .quantile(0.95, 0.22) + .build()); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SnapshotTestUtil.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SnapshotTestUtil.java index 1a531b5fd..d8e8d33e4 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SnapshotTestUtil.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SnapshotTestUtil.java @@ -1,17 +1,17 @@ package io.prometheus.metrics.model.snapshots; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; -public class SnapshotTestUtil { +class SnapshotTestUtil { public static void assertMetadata( MetricSnapshot snapshot, String name, String help, String unit) { - Assert.assertEquals(name, snapshot.getMetadata().getName()); - Assert.assertEquals(help, snapshot.getMetadata().getHelp()); + assertThat(snapshot.getMetadata().getName()).isEqualTo(name); + assertThat(snapshot.getMetadata().getHelp()).isEqualTo(help); if (unit != null) { - Assert.assertEquals(unit, snapshot.getMetadata().getUnit().toString()); + assertThat(snapshot.getMetadata().getUnit()).hasToString(unit); } else { - Assert.assertNull(snapshot.getMetadata().getUnit()); + assertThat(snapshot.getMetadata().getUnit()).isNull(); } } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/StateSetSnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/StateSetSnapshotTest.java index ccc159b30..cb3c70f8d 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/StateSetSnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/StateSetSnapshotTest.java @@ -1,11 +1,13 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import java.util.Iterator; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class StateSetSnapshotTest { +class StateSetSnapshotTest { @Test public void testCompleteGoodCase() { @@ -29,20 +31,21 @@ public void testCompleteGoodCase() { .build()) .build(); SnapshotTestUtil.assertMetadata(snapshot, "my_feature_flags", "Feature Flags", null); - Assert.assertEquals(2, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(2); StateSetSnapshot.StateSetDataPointSnapshot data = snapshot .getDataPoints() .get(1); // data is sorted by labels, so the second one should be entity="controller" - Assert.assertEquals(Labels.of("entity", "controller"), data.getLabels()); - Assert.assertEquals(2, data.size()); - Assert.assertEquals("feature1", data.getName(0)); - Assert.assertTrue(data.isTrue(0)); - Assert.assertEquals("feature2", data.getName(1)); - Assert.assertFalse(data.isTrue(1)); - Assert.assertTrue(data.hasScrapeTimestamp()); - Assert.assertEquals(scrapeTimestamp, data.getScrapeTimestampMillis()); - Assert.assertFalse(data.hasCreatedTimestamp()); + assertThat((Iterable) data.getLabels()) + .isEqualTo(Labels.of("entity", "controller")); + assertThat(data.size()).isEqualTo(2); + assertThat(data.getName(0)).isEqualTo("feature1"); + assertThat(data.isTrue(0)).isTrue(); + assertThat(data.getName(1)).isEqualTo("feature2"); + assertThat(data.isTrue(1)).isFalse(); + assertThat(data.hasScrapeTimestamp()).isTrue(); + assertThat(data.getScrapeTimestampMillis()).isEqualTo(scrapeTimestamp); + assertThat(data.hasCreatedTimestamp()).isFalse(); } @Test @@ -54,21 +57,22 @@ public void testStateSetDataSorted() { .state("c", true) .state("a", false) .build(); - Assert.assertEquals(4, data.size()); - Assert.assertEquals("a", data.getName(0)); - Assert.assertFalse(data.isTrue(0)); - Assert.assertEquals("b", data.getName(1)); - Assert.assertTrue(data.isTrue(1)); - Assert.assertEquals("c", data.getName(2)); - Assert.assertTrue(data.isTrue(2)); - Assert.assertEquals("d", data.getName(3)); - Assert.assertFalse(data.isTrue(3)); + assertThat(data.size()).isEqualTo(4); + assertThat(data.getName(0)).isEqualTo("a"); + assertThat(data.isTrue(0)).isFalse(); + assertThat(data.getName(1)).isEqualTo("b"); + assertThat(data.isTrue(1)).isTrue(); + assertThat(data.getName(2)).isEqualTo("c"); + assertThat(data.isTrue(2)).isTrue(); + assertThat(data.getName(3)).isEqualTo("d"); + assertThat(data.isTrue(3)).isFalse(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testMustHaveState() { // Must have at least one state. - StateSetSnapshot.StateSetDataPointSnapshot.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> StateSetSnapshot.StateSetDataPointSnapshot.builder().build()); } @Test @@ -79,16 +83,16 @@ public void testMinimal() { .dataPoint( StateSetSnapshot.StateSetDataPointSnapshot.builder().state("flag", true).build()) .build(); - Assert.assertEquals(1, snapshot.dataPoints.size()); + assertThat(snapshot.dataPoints.size()).isOne(); } @Test public void testEmpty() { StateSetSnapshot snapshot = StateSetSnapshot.builder().name("my_flag").build(); - Assert.assertEquals(0, snapshot.dataPoints.size()); + assertThat(snapshot.dataPoints).isEmpty(); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testDataImmutable() { StateSetSnapshot.StateSetDataPointSnapshot data = StateSetSnapshot.StateSetDataPointSnapshot.builder() @@ -98,19 +102,22 @@ public void testDataImmutable() { .build(); Iterator iterator = data.iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDuplicateState() { - StateSetSnapshot.StateSetDataPointSnapshot.builder() - .state("a", true) - .state("b", true) - .state("a", true) - .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + StateSetSnapshot.StateSetDataPointSnapshot.builder() + .state("a", true) + .state("b", true) + .state("a", true) + .build()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testStateSetImmutable() { StateSetSnapshot snapshot = StateSetSnapshot.builder() @@ -129,17 +136,24 @@ public void testStateSetImmutable() { Iterator iterator = snapshot.getDataPoints().iterator(); iterator.next(); - iterator.remove(); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(iterator::remove); } - @Test(expected = IllegalArgumentException.class) + @Test public void testLabelsUnique() { - StateSetSnapshot.builder() - .name("flags") - .dataPoint( - StateSetSnapshot.StateSetDataPointSnapshot.builder().state("feature", true).build()) - .dataPoint( - StateSetSnapshot.StateSetDataPointSnapshot.builder().state("feature", true).build()) - .build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> + StateSetSnapshot.builder() + .name("flags") + .dataPoint( + StateSetSnapshot.StateSetDataPointSnapshot.builder() + .state("feature", true) + .build()) + .dataPoint( + StateSetSnapshot.StateSetDataPointSnapshot.builder() + .state("feature", true) + .build()) + .build()); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SummarySnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SummarySnapshotTest.java index 4a4a2a355..a57b5f4e0 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SummarySnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/SummarySnapshotTest.java @@ -1,10 +1,12 @@ package io.prometheus.metrics.model.snapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; + import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SummarySnapshotTest { +class SummarySnapshotTest { @Test public void testCompleteGoodCase() { @@ -55,28 +57,28 @@ public void testCompleteGoodCase() { .build()) .build(); SnapshotTestUtil.assertMetadata(snapshot, "latency_seconds", "latency in seconds", "seconds"); - Assert.assertEquals(2, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(2); SummarySnapshot.SummaryDataPointSnapshot data = snapshot.getDataPoints().get(0); - Assert.assertEquals(Labels.of("endpoint", "/"), data.getLabels()); - Assert.assertTrue(data.hasCount()); - Assert.assertEquals(1093, data.getCount()); - Assert.assertTrue(data.hasSum()); - Assert.assertEquals(218.6, data.getSum(), 0); - Assert.assertTrue(data.hasCreatedTimestamp()); - Assert.assertEquals(createdTimestamp, data.getCreatedTimestampMillis()); - Assert.assertTrue(data.hasScrapeTimestamp()); - Assert.assertEquals(scrapeTimestamp, data.getScrapeTimestampMillis()); + assertThat((Iterable) data.getLabels()).isEqualTo(Labels.of("endpoint", "/")); + assertThat(data.hasCount()).isTrue(); + assertThat(data.getCount()).isEqualTo(1093); + assertThat(data.hasSum()).isTrue(); + assertThat(data.getSum()).isCloseTo(218.6, offset(0.0)); + assertThat(data.hasCreatedTimestamp()).isTrue(); + assertThat(data.getCreatedTimestampMillis()).isEqualTo(createdTimestamp); + assertThat(data.hasScrapeTimestamp()).isTrue(); + assertThat(data.getScrapeTimestampMillis()).isEqualTo(scrapeTimestamp); Quantiles quantiles = data.getQuantiles(); - Assert.assertEquals(3, quantiles.size()); + assertThat(quantiles.size()).isEqualTo(3); // quantiles are tested in QuantilesTest already, skipping here. - Assert.assertEquals(2, data.getExemplars().size()); + assertThat(data.getExemplars().size()).isEqualTo(2); // exemplars are tested in ExemplarsTest already, skipping here. data = snapshot.getDataPoints().get(1); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); - Assert.assertTrue(data.hasCount()); - Assert.assertTrue(data.hasSum()); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); + assertThat(data.hasCount()).isTrue(); + assertThat(data.hasSum()).isTrue(); } @Test @@ -87,25 +89,26 @@ public void testMinimal() { .dataPoint( SummarySnapshot.SummaryDataPointSnapshot.builder().count(10).sum(12.0).build()) .build(); - Assert.assertEquals(1, snapshot.getDataPoints().size()); - Assert.assertEquals(Labels.EMPTY, snapshot.getDataPoints().get(0).getLabels()); + assertThat(snapshot.getDataPoints()).hasSize(1); + assertThat((Iterable) snapshot.getDataPoints().get(0).getLabels()) + .isEqualTo(Labels.EMPTY); } @Test public void testEmptySnapshot() { SummarySnapshot snapshot = SummarySnapshot.builder().name("empty_summary").build(); - Assert.assertEquals(0, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).isEmpty(); } @Test public void testEmptyData() { SummarySnapshot.SummaryDataPointSnapshot data = SummarySnapshot.SummaryDataPointSnapshot.builder().build(); - Assert.assertEquals(0, data.getQuantiles().size()); - Assert.assertFalse(data.hasCount()); - Assert.assertFalse(data.hasSum()); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); - Assert.assertEquals(0, data.getExemplars().size()); + assertThat(data.getQuantiles().size()).isZero(); + assertThat(data.hasCount()).isFalse(); + assertThat(data.hasSum()).isFalse(); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); + assertThat(data.getExemplars().size()).isZero(); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnitTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnitTest.java index 1f70f6520..4585e7281 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnitTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnitTest.java @@ -1,13 +1,15 @@ package io.prometheus.metrics.model.snapshots; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -public class UnitTest { +import org.junit.jupiter.api.Test; - @Test(expected = IllegalArgumentException.class) +class UnitTest { + + @Test public void testEmpty() { - new Unit(" "); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Unit(" ")); } @Test @@ -15,7 +17,7 @@ public void testEquals1() { Unit unit1 = Unit.BYTES; Unit unit2 = new Unit("bytes"); - Assert.assertEquals(unit2, unit1); + assertThat(unit1).isEqualTo(unit2); } @Test @@ -23,7 +25,7 @@ public void testEquals2() { Unit unit1 = new Unit("bytes "); Unit unit2 = new Unit("bytes"); - Assert.assertEquals(unit2, unit1); + assertThat(unit1).isEqualTo(unit2); } @Test @@ -31,7 +33,7 @@ public void testEquals3() { Unit unit1 = new Unit(" bytes"); Unit unit2 = new Unit("bytes"); - Assert.assertEquals(unit2, unit1); + assertThat(unit1).isEqualTo(unit2); } @Test @@ -39,6 +41,6 @@ public void testEquals4() { Unit unit1 = new Unit(" bytes "); Unit unit2 = new Unit("bytes"); - Assert.assertEquals(unit2, unit1); + assertThat(unit1).isEqualTo(unit2); } } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnknownSnapshotTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnknownSnapshotTest.java index cdb81c9dc..a8c266b07 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnknownSnapshotTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/snapshots/UnknownSnapshotTest.java @@ -1,9 +1,12 @@ package io.prometheus.metrics.model.snapshots; -import org.junit.Assert; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.data.Offset.offset; -public class UnknownSnapshotTest { +import org.junit.jupiter.api.Test; + +class UnknownSnapshotTest { @Test public void testCompleteGoodCase() { @@ -33,13 +36,13 @@ public void testCompleteGoodCase() { .build(); SnapshotTestUtil.assertMetadata( snapshot, "my_unknown_seconds", "something in seconds", "seconds"); - Assert.assertEquals(2, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(2); UnknownSnapshot.UnknownDataPointSnapshot data = snapshot.getDataPoints().get(1); // env="prod" - Assert.assertEquals(Labels.of("env", "prod"), data.getLabels()); - Assert.assertEquals(0.3, data.getValue(), 0.0); - Assert.assertEquals(0.12, data.getExemplar().getValue(), 0.0); - Assert.assertFalse(data.hasCreatedTimestamp()); - Assert.assertFalse(data.hasScrapeTimestamp()); + assertThat((Iterable) data.getLabels()).isEqualTo(Labels.of("env", "prod")); + assertThat(data.getValue()).isCloseTo(0.3, offset(0.0)); + assertThat(data.getExemplar().getValue()).isCloseTo(0.12, offset(0.0)); + assertThat(data.hasCreatedTimestamp()).isFalse(); + assertThat(data.hasScrapeTimestamp()).isFalse(); } @Test @@ -49,23 +52,25 @@ public void testMinimal() { .name("test") .dataPoint(UnknownSnapshot.UnknownDataPointSnapshot.builder().value(1.0).build()) .build(); - Assert.assertEquals(1, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).hasSize(1); } @Test public void testEmpty() { UnknownSnapshot snapshot = UnknownSnapshot.builder().name("test").build(); - Assert.assertEquals(0, snapshot.getDataPoints().size()); + assertThat(snapshot.getDataPoints()).isEmpty(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testNameMissing() { - UnknownSnapshot.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> UnknownSnapshot.builder().build()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testValueMissing() { - UnknownSnapshot.UnknownDataPointSnapshot.builder().build(); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> UnknownSnapshot.UnknownDataPointSnapshot.builder().build()); } @Test @@ -75,13 +80,13 @@ public void testUnknownDataPointSnapshot() { UnknownSnapshot.UnknownDataPointSnapshot data = new UnknownSnapshot.UnknownDataPointSnapshot(1.0, labels, exemplar); - Assert.assertEquals(1.0, data.getValue(), 0.1); - Assert.assertEquals(labels, data.getLabels()); - Assert.assertEquals(exemplar, data.getExemplar()); + assertThat(data.getValue()).isCloseTo(1.0, offset(0.1)); + assertThat((Iterable) data.getLabels()).isEqualTo(labels); + assertThat(data.getExemplar()).isEqualTo(exemplar); data = new UnknownSnapshot.UnknownDataPointSnapshot(1.0, labels, exemplar, 0L); - Assert.assertEquals(1.0, data.getValue(), 0.1); - Assert.assertEquals(labels, data.getLabels()); - Assert.assertEquals(exemplar, data.getExemplar()); + assertThat(data.getValue()).isCloseTo(1.0, offset(0.1)); + assertThat((Iterable) data.getLabels()).isEqualTo(labels); + assertThat(data.getExemplar()).isEqualTo(exemplar); } } diff --git a/prometheus-metrics-simpleclient-bridge/pom.xml b/prometheus-metrics-simpleclient-bridge/pom.xml index ba88815f7..0cc2e8cfc 100644 --- a/prometheus-metrics-simpleclient-bridge/pom.xml +++ b/prometheus-metrics-simpleclient-bridge/pom.xml @@ -55,12 +55,6 @@ - - junit - junit - 4.13.2 - test - io.prometheus prometheus-metrics-exposition-formats diff --git a/prometheus-metrics-simpleclient-bridge/src/test/java/io/prometheus/metrics/simpleclient/bridge/SimpleclientCollectorTest.java b/prometheus-metrics-simpleclient-bridge/src/test/java/io/prometheus/metrics/simpleclient/bridge/SimpleclientCollectorTest.java index 83e28d982..a678bed93 100644 --- a/prometheus-metrics-simpleclient-bridge/src/test/java/io/prometheus/metrics/simpleclient/bridge/SimpleclientCollectorTest.java +++ b/prometheus-metrics-simpleclient-bridge/src/test/java/io/prometheus/metrics/simpleclient/bridge/SimpleclientCollectorTest.java @@ -1,5 +1,7 @@ package io.prometheus.metrics.simpleclient.bridge; +import static org.assertj.core.api.Assertions.assertThat; + import io.prometheus.client.Collector; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.Counter; @@ -18,16 +20,15 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SimpleclientCollectorTest { +class SimpleclientCollectorTest { private CollectorRegistry origRegistry; private PrometheusRegistry newRegistry; - @Before + @BeforeEach public void setUp() { origRegistry = new CollectorRegistry(); newRegistry = new PrometheusRegistry(); @@ -46,14 +47,14 @@ public void testCounterComplete() throws IOException, InterruptedException { Thread.sleep(3); // make timestamps a bit different counter.labels("/hello", "500").incWithExemplar(2.4, "trace_id", "23446", "span_id", "bcdef"); - Assert.assertEquals(fixTimestamps(sort(origOpenMetrics())), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixTimestamps(sort(origOpenMetrics()))); } @Test public void testCounterMinimal() throws IOException { Counter.build().name("events").help("total number of events").register(origRegistry); - Assert.assertEquals(fixTimestamps(sort(origOpenMetrics())), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixTimestamps(sort(origOpenMetrics()))); } @Test @@ -69,7 +70,7 @@ public void testGaugeComplete() throws IOException, InterruptedException { Thread.sleep(3); gauge.labels("/dev/sda2").set(0.7); - Assert.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(sort(origOpenMetrics())); } @Test @@ -82,7 +83,7 @@ public void testGaugeMinimal() throws IOException, InterruptedException { .register(origRegistry); gauge.set(22.3); - Assert.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(sort(origOpenMetrics())); } @Test @@ -102,14 +103,14 @@ public void testHistogramComplete() throws IOException, InterruptedException { Thread.sleep(3); // make timestamps a bit different histogram.labels("500").observeWithExemplar(10000, "trace_id", "11", "span_id", "12"); - Assert.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixCounts(fixTimestamps(sort(origOpenMetrics())))); } @Test public void testHistogramMinimal() throws IOException, InterruptedException { Histogram.build().name("request_latency").help("request latency").register(origRegistry); - Assert.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixCounts(fixTimestamps(sort(origOpenMetrics())))); } @Test @@ -133,7 +134,7 @@ public void testSummaryComplete() throws IOException, InterruptedException { summary.labels("/", "500").observe(0.31); summary.labels("/", "500").observe(0.32); - Assert.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixCounts(fixTimestamps(sort(origOpenMetrics())))); } @Test @@ -141,7 +142,7 @@ public void testSummaryMinimal() throws IOException, InterruptedException { Summary summary = Summary.build().name("request_size").help("request size").register(origRegistry); - Assert.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixCounts(fixTimestamps(sort(origOpenMetrics())))); } @Test @@ -156,7 +157,7 @@ public void testInfoComplete() throws IOException, InterruptedException { Thread.sleep(3); info.labels("dev").info("major_version", "13", "minor_version", "1"); - Assert.assertEquals(fixBoolean(sort(origOpenMetrics())), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixBoolean(sort(origOpenMetrics()))); } @Test @@ -164,7 +165,7 @@ public void testInfoMinimal() throws IOException, InterruptedException { Info info = Info.build().name("jvm").help("JVM info").register(origRegistry); info.info("version", "17"); - Assert.assertEquals(fixBoolean(sort(origOpenMetrics())), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixBoolean(sort(origOpenMetrics()))); } @Test @@ -187,7 +188,7 @@ public List collect() { }; origRegistry.register(stateSet); - Assert.assertEquals(fixBoolean(sort(origOpenMetrics())), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(fixBoolean(sort(origOpenMetrics()))); } @Test @@ -220,7 +221,7 @@ public List collect() { }; origRegistry.register(unknown); - Assert.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics())); + assertThat(sort(newOpenMetrics())).isEqualTo(sort(origOpenMetrics())); } private String fixBoolean(String s) { diff --git a/simpleclient-archive/simpleclient_graphite_bridge/pom.xml b/simpleclient-archive/simpleclient_graphite_bridge/pom.xml index e9f432cc1..babc6814b 100644 --- a/simpleclient-archive/simpleclient_graphite_bridge/pom.xml +++ b/simpleclient-archive/simpleclient_graphite_bridge/pom.xml @@ -39,12 +39,5 @@ simpleclient ${project.version} - - - junit - junit - 4.13.2 - test - diff --git a/simpleclient-archive/simpleclient_graphite_bridge/src/test/java/io/prometheus/client/bridge/GraphiteTest.java b/simpleclient-archive/simpleclient_graphite_bridge/src/test/java/io/prometheus/client/bridge/GraphiteTest.java index d0f00bc49..15eb7c60c 100644 --- a/simpleclient-archive/simpleclient_graphite_bridge/src/test/java/io/prometheus/client/bridge/GraphiteTest.java +++ b/simpleclient-archive/simpleclient_graphite_bridge/src/test/java/io/prometheus/client/bridge/GraphiteTest.java @@ -14,7 +14,7 @@ import java.net.ServerSocket; import java.net.Socket; -public class GraphiteTest { +class GraphiteTest { @Test public void testPush() throws Exception { // Create a metric. diff --git a/simpleclient-archive/simpleclient_hibernate/pom.xml b/simpleclient-archive/simpleclient_hibernate/pom.xml index ca99206a4..605d06989 100644 --- a/simpleclient-archive/simpleclient_hibernate/pom.xml +++ b/simpleclient-archive/simpleclient_hibernate/pom.xml @@ -33,7 +33,7 @@ - + io.prometheus simpleclient @@ -47,20 +47,5 @@ 6.1.0.Final provided - - - - junit - junit - 4.13.2 - test - - - org.mockito - mockito-core - 4.6.1 - test - - diff --git a/simpleclient-archive/simpleclient_hibernate/src/main/java/io/prometheus/client/hibernate/HibernateStatisticsCollector.java b/simpleclient-archive/simpleclient_hibernate/src/main/java/io/prometheus/client/hibernate/HibernateStatisticsCollector.java index 32f07f8f9..6ab9e2c42 100644 --- a/simpleclient-archive/simpleclient_hibernate/src/main/java/io/prometheus/client/hibernate/HibernateStatisticsCollector.java +++ b/simpleclient-archive/simpleclient_hibernate/src/main/java/io/prometheus/client/hibernate/HibernateStatisticsCollector.java @@ -40,7 +40,7 @@ * * @author Christian Kaltepoth */ -public class HibernateStatisticsCollector extends Collector { +class HibernaTestatisticsCollector extends Collector { private static final List LABEL_NAMES = Collections.singletonList("unit"); diff --git a/simpleclient-archive/simpleclient_hibernate/src/test/java/io/prometheus/client/hibernate/HibernateStatisticsCollectorTest.java b/simpleclient-archive/simpleclient_hibernate/src/test/java/io/prometheus/client/hibernate/HibernateStatisticsCollectorTest.java index b148ee108..b990988d4 100644 --- a/simpleclient-archive/simpleclient_hibernate/src/test/java/io/prometheus/client/hibernate/HibernateStatisticsCollectorTest.java +++ b/simpleclient-archive/simpleclient_hibernate/src/test/java/io/prometheus/client/hibernate/HibernateStatisticsCollectorTest.java @@ -16,7 +16,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -public class HibernateStatisticsCollectorTest { +class HibernateStatisticsCollectorTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -240,4 +240,4 @@ private Double getSampleForQuery(String metric, String factory, String query) { ); } -} \ No newline at end of file +} diff --git a/simpleclient-archive/simpleclient_httpserver/pom.xml b/simpleclient-archive/simpleclient_httpserver/pom.xml index d34088965..1635375c0 100644 --- a/simpleclient-archive/simpleclient_httpserver/pom.xml +++ b/simpleclient-archive/simpleclient_httpserver/pom.xml @@ -44,18 +44,6 @@ ${project.version} - - junit - junit - 4.13.2 - test - - - org.assertj - assertj-core - 3.23.1 - test - javax.xml.bind jaxb-api diff --git a/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestDaemonFlags.java b/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestDaemonFlags.java index aaddd5e22..466ede1d0 100644 --- a/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestDaemonFlags.java +++ b/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestDaemonFlags.java @@ -9,7 +9,7 @@ import static org.assertj.core.api.Java6Assertions.assertThat; -public class TestDaemonFlags { +class TestDaemonFlags { @Test public void testDefaultIsNotDaemon() throws IOException, ExecutionException, InterruptedException { diff --git a/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestHTTPServer.java b/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestHTTPServer.java index 2b18f4e82..7e012ca97 100644 --- a/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestHTTPServer.java +++ b/simpleclient-archive/simpleclient_httpserver/src/test/java/io/prometheus/client/exporter/TestHTTPServer.java @@ -35,7 +35,7 @@ import static org.assertj.core.api.Java6Assertions.assertThat; -public class TestHTTPServer { +class TestHTTPServer { CollectorRegistry registry; diff --git a/simpleclient-archive/simpleclient_jetty/pom.xml b/simpleclient-archive/simpleclient_jetty/pom.xml index 24aa35902..2d263c7d2 100644 --- a/simpleclient-archive/simpleclient_jetty/pom.xml +++ b/simpleclient-archive/simpleclient_jetty/pom.xml @@ -51,12 +51,6 @@ ${jetty.version} - - junit - junit - 4.13.2 - test - org.hamcrest hamcrest-all diff --git a/simpleclient-archive/simpleclient_jetty/src/test/java/io/prometheus/client/jetty/JettyStatisticsCollectorTest.java b/simpleclient-archive/simpleclient_jetty/src/test/java/io/prometheus/client/jetty/JettyStatisticsCollectorTest.java index dcf6b8c7c..1686bcd2b 100644 --- a/simpleclient-archive/simpleclient_jetty/src/test/java/io/prometheus/client/jetty/JettyStatisticsCollectorTest.java +++ b/simpleclient-archive/simpleclient_jetty/src/test/java/io/prometheus/client/jetty/JettyStatisticsCollectorTest.java @@ -19,7 +19,7 @@ import org.junit.Before; import org.junit.Test; -public class JettyStatisticsCollectorTest { +class JettyStatisticsCollectorTest { private final Server server = new Server(); private final ServerConnector connector = new ServerConnector(server); diff --git a/simpleclient-archive/simpleclient_jetty_jdk8/pom.xml b/simpleclient-archive/simpleclient_jetty_jdk8/pom.xml index c696d7236..f75003907 100644 --- a/simpleclient-archive/simpleclient_jetty_jdk8/pom.xml +++ b/simpleclient-archive/simpleclient_jetty_jdk8/pom.xml @@ -47,12 +47,6 @@ 11.0.9 - - junit - junit - 4.13.2 - test - org.hamcrest hamcrest-all diff --git a/simpleclient-archive/simpleclient_jetty_jdk8/src/test/java/io/prometheus/client/jetty/QueuedThreadPoolStatisticsCollectorTest.java b/simpleclient-archive/simpleclient_jetty_jdk8/src/test/java/io/prometheus/client/jetty/QueuedThreadPoolStatisticsCollectorTest.java index 326a1c45c..23101a42c 100644 --- a/simpleclient-archive/simpleclient_jetty_jdk8/src/test/java/io/prometheus/client/jetty/QueuedThreadPoolStatisticsCollectorTest.java +++ b/simpleclient-archive/simpleclient_jetty_jdk8/src/test/java/io/prometheus/client/jetty/QueuedThreadPoolStatisticsCollectorTest.java @@ -14,7 +14,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -public class QueuedThreadPoolStatisticsCollectorTest { +class QueuedThreadPoolStatisticsCollectorTest { private static final String[] LABEL_NAMES = {"unit"}; diff --git a/simpleclient-archive/simpleclient_log4j/pom.xml b/simpleclient-archive/simpleclient_log4j/pom.xml index bfe2be75a..3651fe107 100644 --- a/simpleclient-archive/simpleclient_log4j/pom.xml +++ b/simpleclient-archive/simpleclient_log4j/pom.xml @@ -50,19 +50,5 @@ 2.17.2 provided - - - junit - junit - 4.13.2 - test - - - - org.mockito - mockito-core - 4.6.1 - test - diff --git a/simpleclient-archive/simpleclient_log4j/src/test/java/io/prometheus/client/log4j/InstrumentedAppenderTest.java b/simpleclient-archive/simpleclient_log4j/src/test/java/io/prometheus/client/log4j/InstrumentedAppenderTest.java index 39c50029c..7a6b2d282 100644 --- a/simpleclient-archive/simpleclient_log4j/src/test/java/io/prometheus/client/log4j/InstrumentedAppenderTest.java +++ b/simpleclient-archive/simpleclient_log4j/src/test/java/io/prometheus/client/log4j/InstrumentedAppenderTest.java @@ -11,7 +11,7 @@ import org.junit.Before; import org.junit.Test; -public class InstrumentedAppenderTest { +class InstrumentedAppenderTest { private InstrumentedAppender appender; private LoggingEvent event; diff --git a/simpleclient-archive/simpleclient_log4j2/pom.xml b/simpleclient-archive/simpleclient_log4j2/pom.xml index c8afc9da1..909ecb220 100644 --- a/simpleclient-archive/simpleclient_log4j2/pom.xml +++ b/simpleclient-archive/simpleclient_log4j2/pom.xml @@ -44,19 +44,5 @@ 2.17.2 provided - - - junit - junit - 4.13.2 - test - - - - org.mockito - mockito-core - 4.6.1 - test - diff --git a/simpleclient-archive/simpleclient_log4j2/src/test/java/io/prometheus/client/log4j2/InstrumentedAppenderTest.java b/simpleclient-archive/simpleclient_log4j2/src/test/java/io/prometheus/client/log4j2/InstrumentedAppenderTest.java index 08b91e6ce..74b4882a5 100644 --- a/simpleclient-archive/simpleclient_log4j2/src/test/java/io/prometheus/client/log4j2/InstrumentedAppenderTest.java +++ b/simpleclient-archive/simpleclient_log4j2/src/test/java/io/prometheus/client/log4j2/InstrumentedAppenderTest.java @@ -12,7 +12,7 @@ import static org.apache.logging.log4j.Level.*; -public class InstrumentedAppenderTest { +class InstrumentedAppenderTest { private InstrumentedAppender appender; private LogEvent event; diff --git a/simpleclient-archive/simpleclient_logback/pom.xml b/simpleclient-archive/simpleclient_logback/pom.xml index 96f4fb34d..195aa19a8 100644 --- a/simpleclient-archive/simpleclient_logback/pom.xml +++ b/simpleclient-archive/simpleclient_logback/pom.xml @@ -43,20 +43,5 @@ logback-classic 1.2.11 - - - - junit - junit - 4.13.2 - test - - - - org.mockito - mockito-core - 4.6.1 - test - diff --git a/simpleclient-archive/simpleclient_logback/src/test/java/io/prometheus/client/logback/InstrumentedAppenderTest.java b/simpleclient-archive/simpleclient_logback/src/test/java/io/prometheus/client/logback/InstrumentedAppenderTest.java index af3bd1610..2534825b5 100644 --- a/simpleclient-archive/simpleclient_logback/src/test/java/io/prometheus/client/logback/InstrumentedAppenderTest.java +++ b/simpleclient-archive/simpleclient_logback/src/test/java/io/prometheus/client/logback/InstrumentedAppenderTest.java @@ -11,7 +11,7 @@ import org.junit.Before; import org.junit.Test; -public class InstrumentedAppenderTest { +class InstrumentedAppenderTest { private CollectorRegistry registry; private InstrumentedAppender appender; private InstrumentedAppender defaultAppender; diff --git a/simpleclient-archive/simpleclient_servlet/pom.xml b/simpleclient-archive/simpleclient_servlet/pom.xml index 7f6b843de..402ab351c 100644 --- a/simpleclient-archive/simpleclient_servlet/pom.xml +++ b/simpleclient-archive/simpleclient_servlet/pom.xml @@ -59,30 +59,12 @@ provided - - junit - junit - 4.13.2 - test - - - org.assertj - assertj-core - 3.23.1 - test - org.eclipse.jetty jetty-servlet 8.2.0.v20160908 test - - org.mockito - mockito-core - 4.6.1 - test - diff --git a/simpleclient-archive/simpleclient_servlet_common/pom.xml b/simpleclient-archive/simpleclient_servlet_common/pom.xml index 31d477e71..dd8f9fb6d 100644 --- a/simpleclient-archive/simpleclient_servlet_common/pom.xml +++ b/simpleclient-archive/simpleclient_servlet_common/pom.xml @@ -47,18 +47,5 @@ simpleclient_common ${project.version} - - - junit - junit - 4.13.2 - test - - - org.assertj - assertj-core - 3.23.1 - test - diff --git a/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/exporter/ExporterTest.java b/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/exporter/ExporterTest.java index 3143a55d8..85e3054a2 100644 --- a/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/exporter/ExporterTest.java +++ b/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/exporter/ExporterTest.java @@ -15,7 +15,7 @@ import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.fail; -public class ExporterTest { +class ExporterTest { private HttpServletRequestAdapter mockHttpServletRequest() { return mockHttpServletRequest(null, false); diff --git a/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/filter/FilterTest.java b/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/filter/FilterTest.java index 583b6f1c9..fd845fa20 100644 --- a/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/filter/FilterTest.java +++ b/simpleclient-archive/simpleclient_servlet_common/src/test/java/io/prometheus/client/servlet/common/filter/FilterTest.java @@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class FilterTest { +class FilterTest { public static final String GET = "GET"; public static final String POST = "POST"; diff --git a/simpleclient-archive/simpleclient_servlet_jakarta/pom.xml b/simpleclient-archive/simpleclient_servlet_jakarta/pom.xml index 186dd0526..336a18a19 100644 --- a/simpleclient-archive/simpleclient_servlet_jakarta/pom.xml +++ b/simpleclient-archive/simpleclient_servlet_jakarta/pom.xml @@ -59,29 +59,11 @@ provided - - junit - junit - 4.13.2 - test - - - org.assertj - assertj-core - 3.23.1 - test - org.eclipse.jetty jetty-servlet 11.0.9 test - - org.mockito - mockito-core - 4.6.1 - test - diff --git a/simpleclient-archive/simpleclient_spring_web/pom.xml b/simpleclient-archive/simpleclient_spring_web/pom.xml index 7591085fa..38440f814 100644 --- a/simpleclient-archive/simpleclient_spring_web/pom.xml +++ b/simpleclient-archive/simpleclient_spring_web/pom.xml @@ -85,12 +85,6 @@ - - junit - junit - 4.13.2 - test - org.springframework spring-test diff --git a/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerAppTest.java b/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerAppTest.java index 5de999178..c787338e3 100644 --- a/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerAppTest.java +++ b/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerAppTest.java @@ -8,7 +8,7 @@ @ContextConfiguration @EnablePrometheusTiming -public class MethodTimerAppTest { +class MethodTimerAppTest { @Controller public static class MyController { @@ -23,4 +23,4 @@ public void waitJustAGoshDarnSecond() throws Exception { public static class MyConfig { } -} \ No newline at end of file +} diff --git a/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerTest.java b/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerTest.java index 2a1957f38..77fa5943d 100644 --- a/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerTest.java +++ b/simpleclient-archive/simpleclient_spring_web/src/test/java/io/prometheus/client/spring/web/MethodTimerTest.java @@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class MethodTimerTest { +class MethodTimerTest { private interface Timeable { void timeMe() throws Exception; } diff --git a/simpleclient-archive/simpleclient_vertx/pom.xml b/simpleclient-archive/simpleclient_vertx/pom.xml index 2a91f20c8..5b8180d25 100644 --- a/simpleclient-archive/simpleclient_vertx/pom.xml +++ b/simpleclient-archive/simpleclient_vertx/pom.xml @@ -53,18 +53,5 @@ 3.9.13 provided - - - junit - junit - 4.13.2 - test - - - org.assertj - assertj-core - 3.23.1 - test - diff --git a/simpleclient-archive/simpleclient_vertx/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java b/simpleclient-archive/simpleclient_vertx/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java index d4d51a5fc..02b7ec42a 100644 --- a/simpleclient-archive/simpleclient_vertx/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java +++ b/simpleclient-archive/simpleclient_vertx/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java @@ -17,7 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class MetricsHandlerTest { +class MetricsHandlerTest { private static Vertx vertx; private static Integer port; diff --git a/simpleclient-archive/simpleclient_vertx4/pom.xml b/simpleclient-archive/simpleclient_vertx4/pom.xml index 5e365bd2a..2374cad9f 100644 --- a/simpleclient-archive/simpleclient_vertx4/pom.xml +++ b/simpleclient-archive/simpleclient_vertx4/pom.xml @@ -53,18 +53,5 @@ 4.3.1 provided - - - junit - junit - 4.13.2 - test - - - org.assertj - assertj-core - 3.23.1 - test - diff --git a/simpleclient-archive/simpleclient_vertx4/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java b/simpleclient-archive/simpleclient_vertx4/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java index 6e71b55c6..889877e2c 100644 --- a/simpleclient-archive/simpleclient_vertx4/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java +++ b/simpleclient-archive/simpleclient_vertx4/src/test/java/io/prometheus/client/vertx/MetricsHandlerTest.java @@ -17,7 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class MetricsHandlerTest { +class MetricsHandlerTest { private static Vertx vertx; private static Integer port;