From 1960decdb9c8eef9e6d472cec9dec40b45f1f39f Mon Sep 17 00:00:00 2001
From: Greg Eales <0x006ea1e5@gmail.com>
Date: Tue, 12 Dec 2023 12:08:56 +0000
Subject: [PATCH] #907 JUnit5 migration
---
.../ManualCompleteMetricsTest.java | 2 +-
integration-tests/it-common/pom.xml | 5 +
.../prometheus/client/it/common/Volume.java | 6 +-
.../it-exporter/it-exporter-test/pom.xml | 12 +-
.../metrics/it/exporter/test/ExporterIT.java | 476 ++++++++++--------
integration-tests/pom.xml | 2 +
pom.xml | 52 +-
prometheus-metrics-config/pom.xml | 5 +-
.../config/PrometheusPropertiesTest.java | 18 +-
prometheus-metrics-core/pom.xml | 5 +-
.../metrics/core/datapoints/TimerApiTest.java | 2 +-
.../core/exemplars/ExemplarSamplerTest.java | 36 +-
.../core/metrics/CKMSQuantilesTest.java | 50 +-
.../metrics/core/metrics/CounterTest.java | 144 +++---
.../core/metrics/CounterWithCallbackTest.java | 2 +-
.../metrics/core/metrics/GaugeTest.java | 40 +-
.../core/metrics/GaugeWithCallbackTest.java | 2 +-
.../metrics/core/metrics/HistogramTest.java | 268 +++++-----
.../metrics/core/metrics/InfoTest.java | 63 +--
.../core/metrics/SlidingWindowTest.java | 18 +-
.../metrics/core/metrics/StateSetTest.java | 52 +-
.../core/metrics/StatefulMetricTest.java | 12 +-
.../metrics/core/metrics/SummaryTest.java | 2 +-
.../core/metrics/SummaryWithCallbackTest.java | 2 +-
.../metrics/core/metrics/TestUtil.java | 6 +-
.../metrics/core/metrics/TodoTest.java | 2 +-
.../pom.xml | 9 +-
.../exporter/opentelemetry/ExemplarTest.java | 66 ++-
prometheus-metrics-exposition-formats/pom.xml | 5 +-
.../ExpositionFormatsTest.java | 84 ++--
.../pom.xml | 5 +-
.../instrumentation/jvm/ProcessMetrics.java | 16 +-
.../jvm/JvmBufferPoolMetricsTest.java | 18 +-
.../jvm/JvmClassLoadingMetricsTest.java | 18 +-
.../jvm/JvmCompilationMetricsTest.java | 22 +-
.../jvm/JvmGarbageCollectorMetricsTest.java | 20 +-
.../jvm/JvmMemoryMetricsTest.java | 18 +-
.../JvmMemoryPoolAllocationMetricsTest.java | 12 +-
.../jvm/JvmRuntimeInfoMetricTest.java | 10 +-
.../jvm/JvmThreadsMetricsTest.java | 26 +-
.../jvm/ProcessMetricsTest.java | 27 +-
prometheus-metrics-model/pom.xml | 5 +-
.../model/registry/MetricNameFilterTest.java | 36 +-
.../MultiCollectorNameFilterTest.java | 40 +-
.../registry/PrometheusRegistryTest.java | 26 +-
.../ClassicHistogramBucketsTest.java | 106 ++--
.../model/snapshots/CounterSnapshotTest.java | 68 +--
.../metrics/model/snapshots/ExemplarTest.java | 46 +-
.../model/snapshots/ExemplarsTest.java | 34 +-
.../model/snapshots/GaugeSnapshotTest.java | 74 +--
.../snapshots/HistogramSnapshotTest.java | 156 +++---
.../model/snapshots/InfoSnapshotTest.java | 50 +-
.../metrics/model/snapshots/LabelsTest.java | 92 ++--
.../model/snapshots/MetricMetadataTest.java | 56 ++-
.../model/snapshots/MetricSnapshotTest.java | 25 +-
.../model/snapshots/MetricSnapshotsTest.java | 40 +-
.../snapshots/NativeHistogramBucketsTest.java | 52 +-
.../model/snapshots/PrometheusNamingTest.java | 40 +-
.../model/snapshots/QuantilesTest.java | 50 +-
.../model/snapshots/SnapshotTestUtil.java | 11 +-
.../model/snapshots/StateSetSnapshotTest.java | 118 ++---
.../model/snapshots/SummarySnapshotTest.java | 65 ++-
.../metrics/model/snapshots/UnitTest.java | 27 +-
.../model/snapshots/UnknownSnapshotTest.java | 42 +-
.../pom.xml | 5 +-
.../bridge/SimpleclientCollectorTest.java | 60 +--
.../client/spring/web/MethodTimerAppTest.java | 4 +-
67 files changed, 1524 insertions(+), 1444 deletions(-)
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 72e8dd107..06c514987 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 results.
diff --git a/integration-tests/it-common/pom.xml b/integration-tests/it-common/pom.xml
index 04198dc37..1864f8dca 100644
--- a/integration-tests/it-common/pom.xml
+++ b/integration-tests/it-common/pom.xml
@@ -30,6 +30,11 @@
testcontainers
test
+
+ org.junit.jupiter
+ junit-jupiter-api
+ test
+
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 6c32ba74b..0d52ba9fa 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,6 @@
package io.prometheus.client.it.common;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
import java.io.File;
import java.io.IOException;
@@ -24,7 +24,7 @@ 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());
+ Assertions.assertEquals("target", targetDir.getFileName().toString(), "failed to locate target/ directory");
return new Volume(Files.createTempDirectory(targetDir, prefix + "-"));
}
@@ -56,7 +56,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
}
});
} else {
- Assert.fail(src + ": No such file or directory");
+ Assertions.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 7300b9318..04bff8cc7 100644
--- a/integration-tests/it-exporter/it-exporter-test/pom.xml
+++ b/integration-tests/it-exporter/it-exporter-test/pom.xml
@@ -37,10 +37,16 @@
prometheus-metrics-exposition-formats
${project.version}
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ test
+
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-params
test
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 2f7baf908..1a8fe2fc1 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
@@ -4,11 +4,10 @@
import io.prometheus.client.it.common.Volume;
import io.prometheus.metrics.expositionformats.generated.com_google_protobuf_3_21_7.Metrics;
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.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.GenericContainer;
@@ -25,270 +24,309 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
-@RunWith(Parameterized.class)
-public 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",
- };
- }
+class ExporterIT {
+ private static class SampleApp implements AutoCloseable{
+ public SampleApp(String appName) throws IOException, URISyntaxException {
+ this.sampleAppVolume = Volume.create("it-exporter")
+ .copy("../../it-" + appName + "/target/" + appName + ".jar");
+ this.sampleAppContainer = new GenericContainer<>("openjdk:17")
+ .withFileSystemBind(sampleAppVolume.getHostPath(), "/app", BindMode.READ_ONLY)
+ .withWorkingDirectory("/app")
+ .withLogConsumer(LogConsumer.withPrefix(appName))
+ .withExposedPorts(9400);
+ }
+ private final GenericContainer> sampleAppContainer;
+ private final Volume sampleAppVolume;
- public ExporterIT(String sampleApp) throws IOException, URISyntaxException {
- this.sampleApp = sampleApp;
- this.sampleAppVolume = Volume.create("it-exporter")
- .copy("../../it-" + sampleApp + "/target/" + sampleApp + ".jar");
- this.sampleAppContainer = new GenericContainer<>("openjdk:17")
- .withFileSystemBind(sampleAppVolume.getHostPath(), "/app", BindMode.READ_ONLY)
- .withWorkingDirectory("/app")
- .withLogConsumer(LogConsumer.withPrefix(sampleApp))
- .withExposedPorts(9400);
+ @Override
+ public void close() throws Exception {
+ sampleAppContainer.stop();
+ sampleAppVolume.remove();
+ }
}
- @After
- public void tearDown() throws IOException {
- sampleAppContainer.stop();
- sampleAppVolume.remove();
+ private static Stream provideSampleAppNames() {
+ return Stream.of(
+ Arguments.of("exporter-httpserver-sample"),
+ Arguments.of("exporter-servlet-tomcat-sample"),
+ Arguments.of("exporter-servlet-jetty-sample")
+ );
}
- @Test
- public void testOpenMetricsTextFormat() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", "", "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8");
- Assert.assertEquals(200, response.status);
- 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"));
- 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"));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testOpenMetricsTextFormat(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET", "", sampleApp.sampleAppContainer.getMappedPort(9400), "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8");
+ Assertions.assertEquals(200, response.status);
+ assertContentType("application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type"));
+ Assertions.assertNull(response.getHeader("Content-Encoding"));
+ Assertions.assertNull(response.getHeader("Transfer-Encoding"));
+ Assertions.assertEquals(Integer.toString(response.body.length), response.getHeader("Content-Length"));
+ String bodyString = new String(response.body);
+ Assertions.assertTrue(bodyString.contains("integration_test_info{test_name=\"" + appName + "\"} 1"));
+ Assertions.assertTrue(bodyString.contains("temperature_celsius{location=\"inside\"} 23.0"));
+ Assertions.assertTrue(bodyString.contains("temperature_celsius{location=\"outside\"} 27.0"));
+ Assertions.assertTrue(bodyString.contains("uptime_seconds_total 17.0"));
+ // OpenMetrics text format has a UNIT.
+ Assertions.assertTrue(bodyString.contains("# UNIT uptime_seconds seconds"));
+ }
}
- @Test
- public void testPrometheusTextFormat() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", "");
- Assert.assertEquals(200, response.status);
- 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"));
- 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"));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testPrometheusTextFormat(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET", "", sampleApp.sampleAppContainer.getMappedPort(9400));
+ Assertions.assertEquals(200, response.status);
+ assertContentType("text/plain; version=0.0.4; charset=utf-8", response.getHeader("Content-Type"));
+ Assertions.assertNull(response.getHeader("Content-Encoding"));
+ Assertions.assertNull(response.getHeader("Transfer-Encoding"));
+ Assertions.assertEquals(Integer.toString(response.body.length), response.getHeader("Content-Length"));
+ String bodyString = new String(response.body);
+ Assertions.assertTrue(bodyString.contains("integration_test_info{test_name=\"" + appName + "\"} 1"));
+ Assertions.assertTrue(bodyString.contains("temperature_celsius{location=\"inside\"} 23.0"));
+ Assertions.assertTrue(bodyString.contains("temperature_celsius{location=\"outside\"} 27.0"));
+ Assertions.assertTrue(bodyString.contains("uptime_seconds_total 17.0"));
+ // Prometheus text format does not have a UNIT.
+ Assertions.assertFalse(bodyString.contains("# UNIT uptime_seconds seconds"));
+ }
}
- @Test
- public void testPrometheusProtobufFormat() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", "", "Accept", "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited");
- Assert.assertEquals(200, response.status);
- 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"));
- List metrics = new ArrayList<>();
- InputStream in = new ByteArrayInputStream(response.body);
- while (in.available() > 0) {
- metrics.add(Metrics.MetricFamily.parseDelimitedFrom(in));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testPrometheusProtobufFormat(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET", "", sampleApp.sampleAppContainer.getMappedPort(9400), "Accept", "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited");
+ Assertions.assertEquals(200, response.status);
+ assertContentType("application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited", response.getHeader("Content-Type"));
+ Assertions.assertNull(response.getHeader("Content-Encoding"));
+ Assertions.assertNull(response.getHeader("Transfer-Encoding"));
+ Assertions.assertEquals(Integer.toString(response.body.length), response.getHeader("Content-Length"));
+ List metrics = new ArrayList<>();
+ InputStream in = new ByteArrayInputStream(response.body);
+ while (in.available() > 0) {
+ metrics.add(Metrics.MetricFamily.parseDelimitedFrom(in));
+ }
+ Assertions.assertEquals(3, metrics.size());
+ // metrics are sorted by name
+ Assertions.assertEquals("integration_test_info", metrics.get(0).getName());
+ Assertions.assertEquals("temperature_celsius", metrics.get(1).getName());
+ Assertions.assertEquals("uptime_seconds_total", metrics.get(2).getName());
}
- Assert.assertEquals(3, metrics.size());
- // 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());
}
- @Test
- public void testCompression() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", "",
- "Accept", "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"));
- 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"));
- } else {
- // If no content length is set, transfer-encoding chunked must be used.
- Assert.assertEquals("chunked", response.getHeader("Transfer-Encoding"));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testCompression(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET",
+ "", sampleApp.sampleAppContainer.getMappedPort(9400), "Accept",
+ "application/openmetrics-text; version=1.0.0; charset=utf-8", "Accept-Encoding", "gzip");
+ Assertions.assertEquals(200, response.status);
+ Assertions.assertEquals("gzip", response.getHeader("Content-Encoding"));
+ if (response.getHeader("Content-Length") != null) {
+ // The servlet container might set a content length as the body is very small.
+ Assertions.assertEquals(Integer.toString(response.body.length), response.getHeader("Content-Length"));
+ Assertions.assertNull(response.getHeader("Transfer-Encoding"));
+ } else {
+ // If no content length is set, transfer-encoding chunked must be used.
+ Assertions.assertEquals("chunked", response.getHeader("Transfer-Encoding"));
+ }
+ assertContentType("application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type"));
+ String body = new String(IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8);
+ Assertions.assertTrue(body.contains("uptime_seconds_total 17.0"));
}
- assertContentType("application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type"));
- String body = new String(IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8);
- Assert.assertTrue(body.contains("uptime_seconds_total 17.0"));
}
- @Test
- public void testErrorHandling() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "error")
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testErrorHandling(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".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."));
+ Response response = scrape("GET", "", sampleApp.sampleAppContainer.getMappedPort(9400));
+ Assertions.assertEquals(500, response.status);
+ Assertions.assertTrue(new String(response.body, UTF_8).contains("Simulating an error."));
+ }
}
- @Test
- public void testHeadRequest() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response fullResponse = scrape("GET", "");
- int size = fullResponse.body.length;
- Assert.assertTrue(size > 0);
- Response headResponse = scrape("HEAD", "");
- Assert.assertEquals(200, headResponse.status);
- Assert.assertEquals(Integer.toString(size), headResponse.getHeader("Content-Length"));
- Assert.assertEquals(0, headResponse.body.length);
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testHeadRequest(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response fullResponse = scrape("GET", "", sampleApp.sampleAppContainer.getMappedPort(9400));
+ int size = fullResponse.body.length;
+ Assertions.assertTrue(size > 0);
+ Response headResponse = scrape("HEAD", "", sampleApp.sampleAppContainer.getMappedPort(9400));
+ Assertions.assertEquals(200, headResponse.status);
+ Assertions.assertEquals(Integer.toString(size), headResponse.getHeader("Content-Length"));
+ Assertions.assertEquals(0, headResponse.body.length);
+ }
}
- @Test
- public void testDebug() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", "debug=openmetrics");
- Assert.assertEquals(200, response.status);
- 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"));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testDebug(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET", "debug=openmetrics", sampleApp.sampleAppContainer.getMappedPort(9400));
+ Assertions.assertEquals(200, response.status);
+ assertContentType("text/plain; charset=utf-8", response.getHeader("Content-Type"));
+ String bodyString = new String(response.body, UTF_8);
+ Assertions.assertTrue(bodyString.contains("uptime_seconds_total 17.0"));
+ Assertions.assertTrue(bodyString.contains("# UNIT uptime_seconds seconds"));
+ }
}
- @Test
- public void testNameFilter() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", nameParam("integration_test_info") + "&" + nameParam("uptime_seconds_total"),
- "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8");
- Assert.assertEquals(200, response.status);
- 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"));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testNameFilter(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET",
+ nameParam("integration_test_info") + "&" + nameParam("uptime_seconds_total"), sampleApp.sampleAppContainer.getMappedPort(9400), "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8");
+ Assertions.assertEquals(200, response.status);
+ assertContentType("application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type"));
+ String bodyString = new String(response.body, UTF_8);
+ Assertions.assertTrue(bodyString.contains("integration_test_info{test_name=\"" + appName + "\"} 1"));
+ Assertions.assertTrue(bodyString.contains("uptime_seconds_total 17.0"));
+ Assertions.assertFalse(bodyString.contains("temperature_celsius"));
+ }
}
- @Test
- public void testEmptyResponseOpenMetrics() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", nameParam("none_existing"),
- "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8");
- Assert.assertEquals(200, response.status);
- 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));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testEmptyResponseOpenMetrics(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET",
+ nameParam("none_existing"), sampleApp.sampleAppContainer.getMappedPort(9400), "Accept", "application/openmetrics-text; version=1.0.0; charset=utf-8");
+ Assertions.assertEquals(200, response.status);
+ assertContentType("application/openmetrics-text; version=1.0.0; charset=utf-8", response.getHeader("Content-Type"));
+ Assertions.assertEquals(Integer.toString(response.body.length), response.getHeader("Content-Length"));
+ Assertions.assertEquals("# EOF\n", new String(response.body, UTF_8));
+ }
}
- @Test
- public void testEmptyResponseText() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", nameParam("none_existing"));
- Assert.assertEquals(200, response.status);
- 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"));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testEmptyResponseText(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET", nameParam("none_existing"), sampleApp.sampleAppContainer.getMappedPort(9400));
+ Assertions.assertEquals(200, response.status);
+ 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
+ Assertions.assertEquals("0", response.getHeader("Content-Length"));
+ }
+ Assertions.assertEquals(0, response.body.length);
}
- Assert.assertEquals(0, response.body.length);
}
- @Test
- public void testEmptyResponseProtobuf() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", nameParam("none_existing"),
- "Accept", "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited");
- Assert.assertEquals(200, response.status);
- assertContentType("application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited", response.getHeader("Content-Type"));
- Assert.assertEquals(0, response.body.length);
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testEmptyResponseProtobuf(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET",
+ nameParam("none_existing"), sampleApp.sampleAppContainer.getMappedPort(9400), "Accept", "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited");
+ Assertions.assertEquals(200, response.status);
+ assertContentType("application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited", response.getHeader("Content-Type"));
+ Assertions.assertEquals(0, response.body.length);
+ }
}
- @Test
- public void testEmptyResponseGzipOpenMetrics() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", nameParam("none_existing"),
- "Accept", "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"));
- String body = new String(IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8);
- Assert.assertEquals("# EOF\n", body);
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testEmptyResponseGzipOpenMetrics(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET",
+ nameParam("none_existing"), sampleApp.sampleAppContainer.getMappedPort(9400), "Accept",
+ "application/openmetrics-text; version=1.0.0; charset=utf-8", "Accept-Encoding", "gzip");
+ Assertions.assertEquals(200, response.status);
+ Assertions.assertEquals("gzip", response.getHeader("Content-Encoding"));
+ String body = new String(IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8);
+ Assertions.assertEquals("# EOF\n", body);
+ }
}
- @Test
- public void testEmptyResponseGzipText() throws IOException {
- sampleAppContainer
- .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"));
- String body = new String(IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8);
- Assert.assertEquals(0, body.length());
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testEmptyResponseGzipText(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET",
+ nameParam("none_existing"), sampleApp.sampleAppContainer.getMappedPort(9400), "Accept-Encoding", "gzip");
+ Assertions.assertEquals(200, response.status);
+ Assertions.assertEquals("gzip", response.getHeader("Content-Encoding"));
+ String body = new String(IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(response.body))), UTF_8);
+ Assertions.assertEquals(0, body.length());
+ }
}
private String nameParam(String name) throws UnsupportedEncodingException {
return URLEncoder.encode("name[]", UTF_8.name()) + "=" + URLEncoder.encode(name, UTF_8.name());
}
- @Test
- public void testDebugUnknown() throws IOException {
- sampleAppContainer
- .withCommand("java", "-jar", "/app/" + sampleApp + ".jar", "9400", "success")
- .start();
- Response response = scrape("GET", "debug=unknown");
- Assert.assertEquals(500, response.status);
- assertContentType("text/plain; charset=utf-8", response.getHeader("Content-Type"));
+ @ParameterizedTest
+ @MethodSource("provideSampleAppNames")
+ void testDebugUnknown(String appName) throws Exception {
+ try(SampleApp sampleApp = new SampleApp(appName)) {
+ sampleApp.sampleAppContainer
+ .withCommand("java", "-jar", "/app/" + appName + ".jar", "9400", "success")
+ .start();
+ Response response = scrape("GET", "debug=unknown", sampleApp.sampleAppContainer.getMappedPort(9400));
+ Assertions.assertEquals(500, response.status);
+ 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);
+ Assertions.assertEquals(expected, actual);
}
}
- private Response scrape(String method, String queryString, String... requestHeaders) throws IOException {
+ private Response scrape(String method, String queryString, Integer mappedPort, String... requestHeaders) throws IOException {
long timeoutMillis = TimeUnit.SECONDS.toMillis(5);
- URL url = new URL("http://localhost:" + sampleAppContainer.getMappedPort(9400) + "/metrics?" + queryString);
+ URL url = new URL("http://localhost:" + mappedPort + "/metrics?" + queryString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(method);
for (int i = 0; i < requestHeaders.length; i += 2) {
@@ -314,7 +352,7 @@ private Response scrape(String method, String queryString, String... requestHead
if (exception != null) {
exception.printStackTrace();
}
- Assert.fail("timeout while getting metrics from " + url);
+ Assertions.fail("timeout while getting metrics from " + url);
return null; // will not happen
}
diff --git a/integration-tests/pom.xml b/integration-tests/pom.xml
index d76fae256..8365bca5c 100644
--- a/integration-tests/pom.xml
+++ b/integration-tests/pom.xml
@@ -36,6 +36,7 @@
org.apache.maven.plugins
maven-failsafe-plugin
+ 3.2.2
integration-test
@@ -50,6 +51,7 @@
+
diff --git a/pom.xml b/pom.xml
index dd91272fd..ae69951c0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -80,75 +80,87 @@
+
+
+
+ org.junit
+ junit-bom
+ 5.10.1
+ pom
+ import
+
+
+
+
-
+
maven-install-plugin
- 2.4
+ 3.1.1
maven-resources-plugin
- 2.6
+ 3.3.1
maven-compiler-plugin
- 3.1
+ 3.11.0
maven-surefire-plugin
- 2.12.4
+ 3.2.2
maven-jar-plugin
- 2.4
+ 3.3.0
maven-deploy-plugin
- 2.7
+ 3.1.1
maven-clean-plugin
- 2.5
+ 3.3.1
maven-site-plugin
- 3.3
+ 3.12.1
maven-shade-plugin
- 3.2.4
+ 3.5.0
maven-failsafe-plugin
- 2.22.2
+ 3.2.2
maven-release-plugin
- 2.5.3
+ 3.0.1
maven-dependency-plugin
- 3.1.2
+ 3.6.0
maven-javadoc-plugin
- 3.3.0
+ 3.5.0
maven-gpg-plugin
- 3.0.1
+ 3.1.0
maven-source-plugin
- 3.2.1
+ 3.3.0
maven-enforcer-plugin
- 1.4.1
+ 3.3.0
@@ -191,7 +203,7 @@
org.apache.felix
maven-bundle-plugin
- 2.4.0
+ 3.5.0
true
@@ -225,7 +237,7 @@
org.codehaus.mojo
versions-maven-plugin
- 2.10.0
+ 2.16.0
file://${project.basedir}/version-rules.xml
@@ -238,7 +250,7 @@
maven-project-info-reports-plugin
- 2.9
+ 3.1.1
maven-javadoc-plugin
diff --git a/prometheus-metrics-config/pom.xml b/prometheus-metrics-config/pom.xml
index 2247a8e8f..8b0f4a9bc 100644
--- a/prometheus-metrics-config/pom.xml
+++ b/prometheus-metrics-config/pom.xml
@@ -39,9 +39,8 @@
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-engine
test
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 45fec1be0..620e40e75 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,29 +1,29 @@
package io.prometheus.metrics.config;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
-public class PrometheusPropertiesTest {
+class PrometheusPropertiesTest {
@Test
- public void testPrometheusConfig() {
+ void testPrometheusConfig() {
PrometheusProperties result = PrometheusProperties.get();
- Assert.assertEquals(11, result.getDefaultMetricProperties().getHistogramClassicUpperBounds().size());
- Assert.assertEquals(4, result.getMetricProperties("http_duration_seconds").getHistogramClassicUpperBounds().size());
+ Assertions.assertEquals(11, result.getDefaultMetricProperties().getHistogramClassicUpperBounds().size());
+ Assertions.assertEquals(4, result.getMetricProperties("http_duration_seconds").getHistogramClassicUpperBounds().size());
}
@Test
- public void testEmptyUpperBounds() throws IOException {
+ void testEmptyUpperBounds() throws IOException {
Properties properties = new Properties();
try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("emptyUpperBounds.properties")) {
properties.load(stream);
}
- Assert.assertEquals(1, properties.size());
+ Assertions.assertEquals(1, properties.size());
MetricsProperties.load("io.prometheus.metrics", properties);
- Assert.assertEquals(0, properties.size());
+ Assertions.assertEquals(0, properties.size());
}
}
diff --git a/prometheus-metrics-core/pom.xml b/prometheus-metrics-core/pom.xml
index 7773301d0..2bd56471d 100644
--- a/prometheus-metrics-core/pom.xml
+++ b/prometheus-metrics-core/pom.xml
@@ -67,9 +67,8 @@
test
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-engine
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 4ae0cd0bb..d74d27193 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 24882065e..00f9b6a5f 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
@@ -5,12 +5,12 @@
import io.prometheus.metrics.model.snapshots.Exemplars;
import io.prometheus.metrics.model.snapshots.Label;
import io.prometheus.metrics.core.util.Scheduler;
-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.Assertions;
+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
@@ -56,24 +56,24 @@ public void markCurrentSpanAsExemplar() {
}
@Test
- public void testCustomExemplarsBuckets() throws Exception {
+ void testCustomExemplarsBuckets() throws Exception {
// TODO
}
private io.prometheus.metrics.tracer.common.SpanContext origContext;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
origContext = SpanContextSupplier.getSpanContext();
}
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
SpanContextSupplier.setSpanContext(origContext);
}
@Test
- public void testIsSampled() throws Exception {
+ void testIsSampled() throws Exception {
SpanContext context = new SpanContext();
context.isSampled = false;
SpanContextSupplier.setSpanContext(context);
@@ -84,7 +84,7 @@ public void testIsSampled() throws Exception {
}
@Test
- public void testDefaultConfigHasFourExemplars() throws Exception {
+ void testDefaultConfigHasFourExemplars() throws Exception {
SpanContext context = new SpanContext();
SpanContextSupplier.setSpanContext(context);
ExemplarSampler sampler = new ExemplarSampler(makeConfig());
@@ -103,7 +103,7 @@ public void testDefaultConfigHasFourExemplars() throws Exception {
}
@Test
- public void testEmptyBuckets() throws Exception {
+ void testEmptyBuckets() throws Exception {
SpanContext context = new SpanContext();
SpanContextSupplier.setSpanContext(context);
ExemplarSampler sampler = new ExemplarSampler(makeConfig(Double.POSITIVE_INFINITY));
@@ -116,7 +116,7 @@ public void testEmptyBuckets() throws Exception {
}
@Test
- public void testDefaultExemplarsBuckets() throws Exception {
+ void testDefaultExemplarsBuckets() throws Exception {
SpanContext context = new SpanContext();
SpanContextSupplier.setSpanContext(context);
ExemplarSampler sampler = new ExemplarSampler(makeConfig(0.2, 0.4, 0.6, 0.8, 1.0, Double.POSITIVE_INFINITY));
@@ -144,12 +144,12 @@ public void testDefaultExemplarsBuckets() throws Exception {
}
@Test
- public void testCustomExemplarsNoBuckets() throws Exception {
+ void testCustomExemplarsNoBuckets() throws Exception {
// TODO
}
@Test
- public void testDefaultExemplarsNoBuckets() throws Exception {
+ void testDefaultExemplarsNoBuckets() throws Exception {
SpanContext context = new SpanContext();
SpanContextSupplier.setSpanContext(context);
ExemplarSampler sampler = new ExemplarSampler(makeConfig());
@@ -193,7 +193,7 @@ public void testDefaultExemplarsNoBuckets() throws Exception {
private void assertExemplars(ExemplarSampler sampler, double... values) {
Exemplars exemplars = sampler.collect();
- Assert.assertEquals(values.length, exemplars.size());
+ Assertions.assertEquals(values.length, exemplars.size());
for (double value : values) {
boolean found = false;
for (Exemplar exemplar : exemplars) {
@@ -202,7 +202,7 @@ private void assertExemplars(ExemplarSampler sampler, double... values) {
break;
}
}
- Assert.assertTrue(value + " not found", found);
+ Assertions.assertTrue(found, value + " not found");
}
}
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 ef90f85cf..3b38d6d5b 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
@@ -4,13 +4,13 @@
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;
import java.util.*;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-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);
@@ -19,13 +19,13 @@ public class CKMSQuantilesTest {
private final Quantile qMax = new Quantile(1.0, 0.00);
@Test
- public void testGetOnEmptyValues() {
+ void testGetOnEmptyValues() {
CKMSQuantiles ckms = new CKMSQuantiles(q50, q95, q99);
assertTrue(Double.isNaN(ckms.get(q95.quantile)));
}
@Test
- public void testGet() {
+ void testGet() {
Random random = new Random(0);
CKMSQuantiles ckms = new CKMSQuantiles(q50, q95, q99);
List input = shuffledValues(100, random);
@@ -36,7 +36,7 @@ public void testGet() {
}
@Test
- public void testBatchInsert() {
+ void testBatchInsert() {
Random random = new Random(1);
testInsertBatch(1, 1, 100, random);
testInsertBatch(1, 10, 100, random);
@@ -76,7 +76,7 @@ private void testInsertBatch(int batchSize, int compressInterval, int totalNumbe
}
@Test
- public void testGetWithAMillionElements() {
+ void testGetWithAMillionElements() {
Random random = new Random(2);
List input = shuffledValues(1000*1000, random);
CKMSQuantiles ckms = new CKMSQuantiles(q50, q95, q99);
@@ -84,11 +84,11 @@ public void testGetWithAMillionElements() {
ckms.insert(v);
}
validateResults(ckms);
- assertTrue("sample size should be way below 1_000_000", ckms.samples.size() < 1000);
+ assertTrue(ckms.samples.size() < 1000, "sample size should be way below 1_000_000");
}
@Test
- public void testMin() {
+ void testMin() {
Random random = new Random(3);
List input = shuffledValues(1000, random);
CKMSQuantiles ckms = new CKMSQuantiles(qMin);
@@ -101,7 +101,7 @@ public void testMin() {
}
@Test
- public void testMax() {
+ void testMax() {
Random random = new Random(4);
List input = shuffledValues(1000, random);
CKMSQuantiles ckms = new CKMSQuantiles(qMax);
@@ -114,7 +114,7 @@ public void testMax() {
}
@Test
- public void testMinMax() {
+ void testMinMax() {
Random random = new Random(5);
List input = shuffledValues(1000, random);
CKMSQuantiles ckms = new CKMSQuantiles(qMin, qMax);
@@ -127,7 +127,7 @@ public void testMinMax() {
}
@Test
- public void testMinAndOthers() {
+ void testMinAndOthers() {
Random random = new Random(6);
List input = shuffledValues(1000, random);
CKMSQuantiles ckms = new CKMSQuantiles(q95, qMin);
@@ -139,7 +139,7 @@ public void testMinAndOthers() {
}
@Test
- public void testMaxAndOthers() {
+ void testMaxAndOthers() {
Random random = new Random(7);
List input = shuffledValues(10000, random);
CKMSQuantiles ckms = new CKMSQuantiles(q50, q95, qMax);
@@ -151,7 +151,7 @@ public void testMaxAndOthers() {
}
@Test
- public void testMinMaxAndOthers() {
+ void testMinMaxAndOthers() {
Random random = new Random(8);
List input = shuffledValues(10000, random);
CKMSQuantiles ckms = new CKMSQuantiles(qMin, q50, q95, q99, qMax);
@@ -163,7 +163,7 @@ public void testMinMaxAndOthers() {
}
@Test
- public void testExactQuantile() {
+ void testExactQuantile() {
Random random = new Random(9);
List input = shuffledValues(10000, random);
CKMSQuantiles ckms = new CKMSQuantiles(new Quantile(0.95, 0));
@@ -176,7 +176,7 @@ public void testExactQuantile() {
}
@Test
- public void testExactAndOthers() {
+ void testExactAndOthers() {
Random random = new Random(10);
List input = shuffledValues(10000, random);
CKMSQuantiles ckms = new CKMSQuantiles(q50, new Quantile(0.95, 0), q99);
@@ -189,7 +189,7 @@ public void testExactAndOthers() {
}
@Test
- public void testExactAndMin() {
+ void testExactAndMin() {
Random random = new Random(11);
List input = shuffledValues(10000, random);
CKMSQuantiles ckms = new CKMSQuantiles(qMin, q50, new Quantile(0.95, 0));
@@ -202,7 +202,7 @@ public void testExactAndMin() {
}
@Test
- public void testMaxEpsilon() {
+ void testMaxEpsilon() {
Random random = new Random(12);
List input = shuffledValues(10000, random);
// epsilon == 1 basically gives you random results, but it should still not throw an exception.
@@ -214,7 +214,7 @@ public void testMaxEpsilon() {
}
@Test
- public void testGetGaussian() {
+ void testGetGaussian() {
RandomGenerator rand = new JDKRandomGenerator();
rand.setSeed(0);
@@ -253,7 +253,7 @@ public void testGetGaussian() {
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);
+ assertTrue(ckms.samples.size() < 1000, "sample size should be below 1000");
}
double errorBoundsNormalDistribution(double p, double epsilon, NormalDistribution nd) {
@@ -266,7 +266,7 @@ public void testGetGaussian() {
}
@Test
- public void testIllegalArgumentException() {
+ void testIllegalArgumentException() {
try {
new Quantile(-1, 0);
} catch (IllegalArgumentException e) {
@@ -300,12 +300,12 @@ private void validateSamples(CKMSQuantiles ckms) {
int r = 0; // sum of all g's left of the current sample
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);
+ assertTrue(sample.g + sample.delta <= ckms.f(r), msg);
+ assertTrue(prev <= sample.value, "Samples not ordered. Keep in mind that insertBatch() takes a sorted array as parameter.");
prev = sample.value;
r += sample.g;
}
- assertEquals("the sum of all g's must be the total number of observations", r, ckms.n);
+ assertEquals(r, ckms.n, "the sum of all g's must be the total number of observations");
}
/**
@@ -334,7 +334,7 @@ private void validateResults(CKMSQuantiles ckms) {
}
}
String errorMessage = q + ": " + actual + " not in [" + lowerBound + ", " + upperBound + "], n=" + ckms.n + ", " + q.quantile + "*" + ckms.n + "=" + (q.quantile*ckms.n);
- assertTrue(errorMessage, ok);
+ assertTrue(ok, errorMessage);
}
}
}
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 7311c84f6..1beb74f27 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,29 +1,26 @@
package io.prometheus.metrics.core.metrics;
-import io.prometheus.metrics.shaded.com_google_protobuf_3_21_7.TextFormat;
+import io.prometheus.metrics.core.exemplars.ExemplarSamplerConfigTestUtil;
import io.prometheus.metrics.expositionformats.PrometheusProtobufWriter;
import io.prometheus.metrics.expositionformats.generated.com_google_protobuf_3_21_7.Metrics;
-import io.prometheus.metrics.core.exemplars.ExemplarSamplerConfigTestUtil;
-import io.prometheus.metrics.tracer.common.SpanContext;
-import io.prometheus.metrics.tracer.initializer.SpanContextSupplier;
import io.prometheus.metrics.model.snapshots.CounterSnapshot;
import io.prometheus.metrics.model.snapshots.Exemplar;
import io.prometheus.metrics.model.snapshots.Labels;
import io.prometheus.metrics.model.snapshots.Unit;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import io.prometheus.metrics.shaded.com_google_protobuf_3_21_7.TextFormat;
+import io.prometheus.metrics.tracer.common.SpanContext;
+import io.prometheus.metrics.tracer.initializer.SpanContextSupplier;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.rules.ExpectedException.none;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-public class CounterTest {
+class CounterTest {
Counter noLabels;
Counter labels;
@@ -31,11 +28,8 @@ public class CounterTest {
private static final long exemplarMinAgeMillis = 100;
SpanContext origSpanContext;
- @Rule
- public final ExpectedException thrown = none();
-
- @Before
- public void setUp() throws NoSuchFieldException, IllegalAccessException {
+ @BeforeEach
+ void setUp() throws NoSuchFieldException, IllegalAccessException {
noLabels = Counter.builder().name("nolabels").build();
labels = Counter.builder().name("labels")
.help("help")
@@ -49,8 +43,8 @@ public void setUp() throws NoSuchFieldException, IllegalAccessException {
ExemplarSamplerConfigTestUtil.setMinRetentionPeriodMillis(labels, exemplarMinAgeMillis);
}
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
SpanContextSupplier.setSpanContext(origSpanContext);
}
@@ -71,44 +65,42 @@ private int getNumberOfLabels(Counter counter) {
}
@Test
- public void testIncrement() {
+ void testIncrement() {
noLabels.inc();
- assertEquals(1.0, getValue(noLabels), .001);
+ Assertions.assertEquals(1.0, getValue(noLabels), .001);
noLabels.inc(2);
- assertEquals(3.0, getValue(noLabels), .001);
+ Assertions.assertEquals(3.0, getValue(noLabels), .001);
noLabels.labelValues().inc(4);
- assertEquals(7.0, getValue(noLabels), .001);
+ Assertions.assertEquals(7.0, getValue(noLabels), .001);
noLabels.labelValues().inc();
- assertEquals(8.0, getValue(noLabels), .001);
+ Assertions.assertEquals(8.0, getValue(noLabels), .001);
}
@Test
- public void testNegativeIncrementFails() {
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Negative increment -1 is illegal for Counter metrics.");
- noLabels.inc(-1);
+ void testNegativeIncrementFails() {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> noLabels.inc(-1), "Negative increment -1 is illegal for Counter metrics.");
}
@Test
- public void testEmptyCountersHaveNoLabels() {
- assertEquals(1, getNumberOfLabels(noLabels));
- assertEquals(0, getNumberOfLabels(labels));
+ void testEmptyCountersHaveNoLabels() {
+ Assertions.assertEquals(1, getNumberOfLabels(noLabels));
+ Assertions.assertEquals(0, getNumberOfLabels(labels));
}
@Test
- public void testLabels() {
- assertEquals(0, getNumberOfLabels(labels));
+ void testLabels() {
+ Assertions.assertEquals(0, getNumberOfLabels(labels));
labels.labelValues("a").inc();
- assertEquals(1, getNumberOfLabels(labels));
- assertEquals(1.0, getValue(labels, "l", "a"), .001);
+ Assertions.assertEquals(1, getNumberOfLabels(labels));
+ Assertions.assertEquals(1.0, getValue(labels, "l", "a"), .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);
+ Assertions.assertEquals(2, getNumberOfLabels(labels));
+ Assertions.assertEquals(1.0, getValue(labels, "l", "a"), .001);
+ Assertions.assertEquals(3.0, getValue(labels, "l", "b"), .001);
}
@Test
- public void testTotalStrippedFromName() {
+ void testTotalStrippedFromName() {
for (String name : new String[]{
"my_counter_total", "my.counter.total",
"my_counter_seconds_total", "my.counter.seconds.total",
@@ -119,12 +111,12 @@ public void testTotalStrippedFromName() {
.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));
+ Assertions.assertEquals("name: \"my_counter_seconds_total\" type: COUNTER metric { counter { value: 0.0 } }", TextFormat.printer().shortDebugString(protobufData));
}
}
@Test
- public void testSnapshotComplete() {
+ void testSnapshotComplete() {
long before = System.currentTimeMillis();
Counter counter = Counter.builder()
.name("test_seconds_total")
@@ -136,27 +128,27 @@ public void testSnapshotComplete() {
counter.labelValues("/", "200").inc(2);
counter.labelValues("/", "500").inc();
CounterSnapshot snapshot = (CounterSnapshot) counter.collect();
- Assert.assertEquals("test_seconds", snapshot.getMetadata().getName());
- Assert.assertEquals("seconds", snapshot.getMetadata().getUnit().toString());
- Assert.assertEquals("help message", snapshot.getMetadata().getHelp());
- Assert.assertEquals(2, snapshot.getDataPoints().size());
+ Assertions.assertEquals("test_seconds", snapshot.getMetadata().getName());
+ Assertions.assertEquals("seconds", snapshot.getMetadata().getUnit().toString());
+ Assertions.assertEquals("help message", snapshot.getMetadata().getHelp());
+ Assertions.assertEquals(2, snapshot.getDataPoints().size());
Iterator iter = snapshot.getDataPoints().iterator();
// data is ordered by labels, so 200 comes before 500
CounterSnapshot.CounterDataPointSnapshot data = iter.next();
- Assert.assertEquals(Labels.of("const1name", "const1value", "const2name", "const2value", "path", "/", "status", "200"), data.getLabels());
- Assert.assertEquals(2, data.getValue(), 0.0001);
- Assert.assertTrue(data.getCreatedTimestampMillis() >= before);
- Assert.assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
+ Assertions.assertEquals(Labels.of("const1name", "const1value", "const2name", "const2value", "path", "/", "status", "200"), data.getLabels());
+ Assertions.assertEquals(2, data.getValue(), 0.0001);
+ Assertions.assertTrue(data.getCreatedTimestampMillis() >= before);
+ Assertions.assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
// 500
data = iter.next();
- Assert.assertEquals(Labels.of("const1name", "const1value", "const2name", "const2value", "path", "/", "status", "500"), data.getLabels());
- Assert.assertEquals(1, data.getValue(), 0.0001);
- Assert.assertTrue(data.getCreatedTimestampMillis() >= before);
- Assert.assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
+ Assertions.assertEquals(Labels.of("const1name", "const1value", "const2name", "const2value", "path", "/", "status", "500"), data.getLabels());
+ Assertions.assertEquals(1, data.getValue(), 0.0001);
+ Assertions.assertTrue(data.getCreatedTimestampMillis() >= before);
+ Assertions.assertTrue(data.getCreatedTimestampMillis() <= System.currentTimeMillis());
}
@Test
- public void testIncWithExemplar() throws Exception {
+ void testIncWithExemplar() throws Exception {
noLabels.incWithExemplar(Labels.of("key", "value"));
assertExemplar(noLabels, 1.0, "key", "value");
@@ -173,12 +165,12 @@ public void testIncWithExemplar() throws Exception {
private void assertExemplar(Counter counter, double value, String... labels) {
Exemplar exemplar = getData(counter).getExemplar();
- Assert.assertEquals(value, exemplar.getValue(), 0.0001);
- assertEquals(Labels.of(labels), exemplar.getLabels());
+ Assertions.assertEquals(value, exemplar.getValue(), 0.0001);
+ Assertions.assertEquals(Labels.of(labels), exemplar.getLabels());
}
@Test
- public void testExemplarSampler() throws Exception {
+ void testExemplarSampler() throws Exception {
final Exemplar exemplar1 = Exemplar.builder()
.value(2.0)
.traceId("abc")
@@ -286,33 +278,35 @@ public void markCurrentSpanAsExemplar() {
}
@Test
- public void testExemplarSamplerDisabled() {
+ void testExemplarSamplerDisabled() {
Counter counter = Counter.builder()
//.withExemplarSampler((inc, prev) -> {throw new RuntimeException("unexpected call to exemplar sampler");})
.name("count_total")
.withoutExemplars()
.build();
counter.incWithExemplar(3.0, Labels.of("a", "b"));
- Assert.assertNull(getData(counter).getExemplar());
+ Assertions.assertNull(getData(counter).getExemplar());
counter.inc(2.0);
- Assert.assertNull(getData(counter).getExemplar());
+ Assertions.assertNull(getData(counter).getExemplar());
}
- @Test(expected = IllegalArgumentException.class)
- public void testConstLabelsFirst() {
- Counter.builder()
- .name("test_total")
- .constLabels(Labels.of("const_a", "const_b"))
- .labelNames("const.a")
- .build();
+ @Test
+ void testConstLabelsFirst() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Counter.builder()
+ .name("test_total")
+ .constLabels(Labels.of("const_a", "const_b"))
+ .labelNames("const.a")
+ .build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testConstLabelsSecond() {
- Counter.builder()
- .name("test_total")
- .labelNames("const.a")
- .constLabels(Labels.of("const_a", "const_b"))
- .build();
+ @Test
+ void testConstLabelsSecond() {
+ assertThrows(IllegalArgumentException.class,
+ () -> 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 f7c18666d..d64962731 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,6 +1,6 @@
package io.prometheus.metrics.core.metrics;
-public class CounterWithCallbackTest {
+class CounterWithCallbackTest {
// TODO :). Anyway, callbacks are implicitly covered by the JVM metrics tests as well.
}
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 002a44545..c4609be6a 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
@@ -7,15 +7,15 @@
import io.prometheus.metrics.model.snapshots.GaugeSnapshot;
import io.prometheus.metrics.model.snapshots.Labels;
import io.prometheus.metrics.core.datapoints.Timer;
-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.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-public class GaugeTest {
+class GaugeTest {
private static final long exemplarSampleIntervalMillis = 10;
private static final long exemplarMinAgeMillis = 100;
@@ -24,15 +24,15 @@ public class GaugeTest {
private SpanContext origSpanContext;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
noLabels = Gauge.builder().name("nolabels").build();
labels = Gauge.builder().name("labels").labelNames("l").build();
origSpanContext = SpanContextSupplier.getSpanContext();
}
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
SpanContextSupplier.setSpanContext(origSpanContext);
}
@@ -48,7 +48,7 @@ private double getValue(Gauge gauge, String... labels) {
}
@Test
- public void testIncrement() {
+ void testIncrement() {
noLabels.inc();
assertEquals(1.0, getValue(noLabels), .001);
noLabels.inc(2);
@@ -60,7 +60,7 @@ public void testIncrement() {
}
@Test
- public void testDecrement() {
+ void testDecrement() {
noLabels.dec();
assertEquals(-1.0, getValue(noLabels), .001);
noLabels.dec(2);
@@ -72,7 +72,7 @@ public void testDecrement() {
}
@Test
- public void testSet() {
+ void testSet() {
noLabels.set(42);
assertEquals(42, getValue(noLabels), .001);
noLabels.set(7);
@@ -80,7 +80,7 @@ public void testSet() {
}
@Test
- public void testTimer() throws InterruptedException {
+ void testTimer() throws InterruptedException {
try (Timer timer = noLabels.startTimer()) {
Thread.sleep(12);
}
@@ -88,12 +88,12 @@ public void testTimer() throws InterruptedException {
}
@Test
- public void noLabelsDefaultZeroValue() {
+ void noLabelsDefaultZeroValue() {
assertEquals(0.0, getValue(noLabels), .001);
}
@Test
- public void testLabels() {
+ void testLabels() {
labels.labelValues("a").inc();
labels.labelValues("b").inc(3);
assertEquals(1.0, getValue(labels, "l", "a"), .001);
@@ -101,7 +101,7 @@ public void testLabels() {
}
@Test
- public void testExemplarSampler() throws Exception {
+ void testExemplarSampler() throws Exception {
final Exemplar exemplar1 = Exemplar.builder()
.value(2.0)
.traceId("abc")
@@ -209,14 +209,14 @@ public void markCurrentSpanAsExemplar() {
}
@Test
- public void testExemplarSamplerDisabled() {
+ void testExemplarSamplerDisabled() {
Gauge gauge = Gauge.builder()
.name("test")
.withoutExemplars()
.build();
gauge.setWithExemplar(3.0, Labels.of("a", "b"));
- Assert.assertNull(getData(gauge).getExemplar());
+ Assertions.assertNull(getData(gauge).getExemplar());
gauge.inc(2.0);
- Assert.assertNull(getData(gauge).getExemplar());
+ Assertions.assertNull(getData(gauge).getExemplar());
}
}
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 f8f54aa69..f195d07c5 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,6 +1,6 @@
package io.prometheus.metrics.core.metrics;
-public class GaugeWithCallbackTest {
+class GaugeWithCallbackTest {
// TODO :). Anyway, callbacks are implicitly covered by the JVM metrics tests as well.
}
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 2e0df7b01..709e830fd 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
@@ -14,10 +14,10 @@
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
import io.prometheus.metrics.tracer.common.SpanContext;
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.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -42,22 +42,21 @@
import java.util.stream.Collectors;
import static io.prometheus.metrics.core.metrics.TestUtil.assertExemplarEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-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 has been reached
private SpanContext origSpanContext;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
origSpanContext = SpanContextSupplier.getSpanContext();
}
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
SpanContextSupplier.setSpanContext(origSpanContext);
}
@@ -90,7 +89,7 @@ private void run() throws NoSuchFieldException, IllegalAccessException {
}
Metrics.MetricFamily protobufData = new PrometheusProtobufWriter().convert(histogram.collect());
String expectedWithMetadata = "name: \"test\" type: HISTOGRAM metric { histogram { " + expected + " } }";
- assertEquals("test \"" + name + "\" failed", expectedWithMetadata, TextFormat.printer().shortDebugString(protobufData));
+ Assertions.assertEquals(expectedWithMetadata, TextFormat.printer().shortDebugString(protobufData), "test \"" + name + "\" failed");
}
}
@@ -98,7 +97,7 @@ private void run() throws NoSuchFieldException, IllegalAccessException {
* Test cases copied from histogram_test.go in client_golang.
*/
@Test
- public void testGolangTests() throws NoSuchFieldException, IllegalAccessException {
+ void testGolangTests() throws NoSuchFieldException, IllegalAccessException {
GolangTestCase[] testCases = new GolangTestCase[]{
new GolangTestCase("'no sparse buckets' from client_golang",
"sample_count: 3 " +
@@ -587,7 +586,7 @@ public void testGolangTests() throws NoSuchFieldException, IllegalAccessExceptio
* Additional tests that are not part of client_golang's test suite.
*/
@Test
- public void testAdditional() throws NoSuchFieldException, IllegalAccessException {
+ void testAdditional() throws NoSuchFieldException, IllegalAccessException {
GolangTestCase[] testCases = new GolangTestCase[]{
new GolangTestCase("observed values are exactly at bucket boundaries",
"sample_count: 3 " +
@@ -617,7 +616,7 @@ public void testAdditional() throws NoSuchFieldException, IllegalAccessException
* This test is ported from client_golang's TestGetLe().
*/
@Test
- public void testNativeBucketIndexToUpperBound() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ void testNativeBucketIndexToUpperBound() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
int[] indexes = new int[]{-1, 0, 1, 512, 513, -1, 0, 1, 1024, 1025, -1, 0, 1, 4096, 4097};
int[] schemas = new int[]{-1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2};
double[] expectedUpperBounds = new double[]{0.25, 1, 4, Double.MAX_VALUE, Double.POSITIVE_INFINITY,
@@ -632,7 +631,7 @@ public void testNativeBucketIndexToUpperBound() throws NoSuchMethodException, In
.build();
Histogram.DataPoint histogramData = histogram.newDataPoint();
double result = (double) method.invoke(histogramData, schemas[i], indexes[i]);
- Assert.assertEquals("index=" + indexes[i] + ", schema=" + schemas[i], expectedUpperBounds[i], result, 0.0000000000001);
+ Assertions.assertEquals(expectedUpperBounds[i], result, 0.0000000000001, "index=" + indexes[i] + ", schema=" + schemas[i]);
}
}
@@ -640,7 +639,7 @@ public void testNativeBucketIndexToUpperBound() throws NoSuchMethodException, In
* Test if lowerBound < value <= upperBound is true for the bucket index returned by findBucketIndex()
*/
@Test
- public void testFindBucketIndex() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ void testFindBucketIndex() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Random rand = new Random();
Method findBucketIndex = Histogram.DataPoint.class.getDeclaredMethod("findBucketIndex", double.class);
Method nativeBucketIndexToUpperBound = Histogram.DataPoint.class.getDeclaredMethod("nativeBucketIndexToUpperBound", int.class, int.class);
@@ -658,14 +657,14 @@ public void testFindBucketIndex() throws NoSuchMethodException, InvocationTarget
int bucketIndex = (int) findBucketIndex.invoke(histogram.getNoLabels(), value);
double lowerBound = (double) nativeBucketIndexToUpperBound.invoke(histogram.getNoLabels(), schema, bucketIndex - 1);
double upperBound = (double) nativeBucketIndexToUpperBound.invoke(histogram.getNoLabels(), schema, bucketIndex);
- Assert.assertTrue("Bucket index " + bucketIndex + " with schema " + schema + " has range [" + lowerBound + ", " + upperBound + "]. Value " + value + " is outside of that range.", lowerBound < value && upperBound >= value);
+ Assertions.assertTrue(lowerBound < value && upperBound >= value, "Bucket index " + bucketIndex + " with schema " + schema + " has range [" + lowerBound + ", " + upperBound + "]. Value " + value + " is outside of that range.");
}
}
}
}
@Test
- public void testDefaults() throws IOException {
+ void testDefaults() throws IOException {
Histogram histogram = Histogram.builder().name("test").build();
histogram.observe(0.5);
HistogramSnapshot snapshot = histogram.collect();
@@ -718,17 +717,17 @@ public void testDefaults() throws IOException {
// protobuf
Metrics.MetricFamily protobufData = new PrometheusProtobufWriter().convert(snapshot);
- Assert.assertEquals(expectedProtobuf, TextFormat.printer().shortDebugString(protobufData));
+ Assertions.assertEquals(expectedProtobuf, TextFormat.printer().shortDebugString(protobufData));
// text
ByteArrayOutputStream out = new ByteArrayOutputStream();
OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(false, true);
writer.write(out, MetricSnapshots.of(snapshot));
- Assert.assertEquals(expectedTextFormat, out.toString());
+ Assertions.assertEquals(expectedTextFormat, out.toString());
}
@Test
- public void testExemplarsClassicHistogram() throws Exception {
+ void testExemplarsClassicHistogram() throws Exception {
SpanContext spanContext = new SpanContext() {
int callCount = 0;
@@ -820,14 +819,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"));
+ Assertions.assertNull(getExemplar(snapshot, 2.0, "path", "/hello"));
+ Assertions.assertNull(getExemplar(snapshot, 2.0, "path", "/world"));
+ Assertions.assertNull(getExemplar(snapshot, 3.0, "path", "/hello"));
+ Assertions.assertNull(getExemplar(snapshot, 3.0, "path", "/world"));
+ Assertions.assertNull(getExemplar(snapshot, 4.0, "path", "/hello"));
+ Assertions.assertNull(getExemplar(snapshot, 4.0, "path", "/world"));
+ Assertions.assertNull(getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/hello"));
+ Assertions.assertNull(getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/world"));
Thread.sleep(sampleIntervalMillis + 1);
histogram.labelValues("/hello").observe(4.5);
@@ -836,12 +835,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"));
+ Assertions.assertNull(getExemplar(snapshot, 2.0, "path", "/hello"));
+ Assertions.assertNull(getExemplar(snapshot, 2.0, "path", "/world"));
+ Assertions.assertNull(getExemplar(snapshot, 3.0, "path", "/hello"));
+ Assertions.assertNull(getExemplar(snapshot, 3.0, "path", "/world"));
+ Assertions.assertNull(getExemplar(snapshot, 4.0, "path", "/hello"));
+ Assertions.assertNull(getExemplar(snapshot, 4.0, "path", "/world"));
assertExemplarEquals(ex2a, getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/hello"));
assertExemplarEquals(ex2b, getExemplar(snapshot, Double.POSITIVE_INFINITY, "path", "/world"));
@@ -895,7 +894,7 @@ private Exemplar getExemplar(HistogramSnapshot snapshot, double le, String... la
}
@Test
- public void testCustomExemplarsClassicHistogram() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
+ void testCustomExemplarsClassicHistogram() throws InterruptedException, NoSuchFieldException, IllegalAccessException {
// TODO: This was copied from the old simpleclient, can probably be refactored.
@@ -950,18 +949,18 @@ private void assertExemplar(Histogram histogram, double value, String... labels)
}
}
Exemplar exemplar = data.getExemplars().get(lowerBound, upperBound);
- Assert.assertNotNull("No exemplar found in bucket [" + lowerBound + ", " + upperBound + "]", exemplar);
- Assert.assertEquals(value, exemplar.getValue(), 0.0);
- Assert.assertEquals("" + exemplar.getLabels(), labels.length / 2, exemplar.getLabels().size());
+ Assertions.assertNotNull(exemplar, "No exemplar found in bucket [" + lowerBound + ", " + upperBound + "]");
+ Assertions.assertEquals(value, exemplar.getValue(), 0.0);
+ Assertions.assertEquals(labels.length / 2, exemplar.getLabels().size(), "" + exemplar.getLabels());
for (int i = 0; i < labels.length; i += 2) {
- Assert.assertEquals(labels[i], exemplar.getLabels().getName(i / 2));
- Assert.assertEquals(labels[i + 1], exemplar.getLabels().getValue(i / 2));
+ Assertions.assertEquals(labels[i], exemplar.getLabels().getName(i / 2));
+ Assertions.assertEquals(labels[i + 1], exemplar.getLabels().getValue(i / 2));
}
}
@Test
- public void testExemplarsNativeHistogram() throws NoSuchFieldException, IllegalAccessException {
+ void testExemplarsNativeHistogram() throws NoSuchFieldException, IllegalAccessException {
SpanContext spanContext = new SpanContext() {
int callCount = 0;
@@ -1015,65 +1014,67 @@ public void markCurrentSpanAsExemplar() {
histogram.labelValues("/hello").observe(3.11);
histogram.labelValues("/world").observe(3.12);
- assertEquals(1, getData(histogram, "path", "/hello").getExemplars().size());
+ Assertions.assertEquals(1, getData(histogram, "path", "/hello").getExemplars().size());
assertExemplarEquals(ex1, getData(histogram, "path", "/hello").getExemplars().iterator().next());
- assertEquals(1, getData(histogram, "path", "/world").getExemplars().size());
+ Assertions.assertEquals(1, getData(histogram, "path", "/world").getExemplars().size());
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());
+ Assertions.assertEquals(1, getData(histogram, "path", "/hello").getExemplars().size());
assertExemplarEquals(ex1, getData(histogram, "path", "/hello").getExemplars().iterator().next());
- assertEquals(2, getData(histogram, "path", "/world").getExemplars().size());
+ Assertions.assertEquals(2, getData(histogram, "path", "/world").getExemplars().size());
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());
+ Assertions.assertEquals(2, exemplars.size());
assertExemplarEquals(ex2, exemplarList.get(0));
assertExemplarEquals(ex3, exemplarList.get(1));
}
- @Test(expected = IllegalArgumentException.class)
- public void testIllegalLabelName() {
- Histogram.builder()
- .name("test")
- .labelNames("label", "le");
+ @Test
+ void testIllegalLabelName() {
+ Assertions.assertThrows(IllegalArgumentException.class,
+ () -> Histogram.builder()
+ .name("test")
+ .labelNames("label", "le"));
}
- @Test(expected = IllegalArgumentException.class)
- public void testIllegalLabelNameConstLabels() {
- Histogram.builder()
- .name("test")
- .constLabels(Labels.of("label1", "value1", "le", "0.3"));
+ @Test
+ void testIllegalLabelNameConstLabels() {
+ Assertions.assertThrows(IllegalArgumentException.class,
+ () -> Histogram.builder()
+ .name("test")
+ .constLabels(Labels.of("label1", "value1", "le", "0.3")));
}
- @Test(expected = IllegalArgumentException.class)
- public void testIllegalLabelNamePrefix() {
- Histogram.builder()
- .name("test")
- .labelNames("__hello");
+ @Test
+ void testIllegalLabelNamePrefix() {
+ Assertions.assertThrows(IllegalArgumentException.class,
+ () -> Histogram.builder()
+ .name("test")
+ .labelNames("__hello"));
}
- @Test(expected = IllegalArgumentException.class)
- public void testIllegalName() {
- Histogram.builder().name("my_namespace/server.durations");
+ @Test
+ void testIllegalName() {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> Histogram.builder().name("my_namespace/server.durations"));
}
- @Test(expected = IllegalArgumentException.class)
- public void testNoName() {
- Histogram.builder().build();
+ @Test
+ void testNoName() {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> Histogram.builder().build());
}
- @Test(expected = NullPointerException.class)
- public void testNullName() {
- Histogram.builder()
- .name(null);
+ @Test
+ void testNullName() {
+ Assertions.assertThrows(NullPointerException.class, () -> Histogram.builder().name(null));
}
@Test
- public void testDuplicateClassicBuckets() {
+ void testDuplicateClassicBuckets() {
Histogram histogram = Histogram.builder()
.name("test")
.classicUpperBounds(0, 3, 17, 3, 21)
@@ -1081,11 +1082,11 @@ public void testDuplicateClassicBuckets() {
List upperBounds = getData(histogram).getClassicBuckets().stream()
.map(ClassicHistogramBucket::getUpperBound)
.collect(Collectors.toList());
- Assert.assertEquals(Arrays.asList(0.0, 3.0, 17.0, 21.0, Double.POSITIVE_INFINITY), upperBounds);
+ Assertions.assertEquals(Arrays.asList(0.0, 3.0, 17.0, 21.0, Double.POSITIVE_INFINITY), upperBounds);
}
@Test
- public void testUnsortedBuckets() {
+ void testUnsortedBuckets() {
Histogram histogram = Histogram.builder()
.name("test")
.classicUpperBounds(0.2, 0.1)
@@ -1093,11 +1094,11 @@ public void testUnsortedBuckets() {
List upperBounds = getData(histogram).getClassicBuckets().stream()
.map(ClassicHistogramBucket::getUpperBound)
.collect(Collectors.toList());
- Assert.assertEquals(Arrays.asList(0.1, 0.2, Double.POSITIVE_INFINITY), upperBounds);
+ Assertions.assertEquals(Arrays.asList(0.1, 0.2, Double.POSITIVE_INFINITY), upperBounds);
}
@Test
- public void testEmptyBuckets() {
+ void testEmptyBuckets() {
Histogram histogram = Histogram.builder()
.name("test")
.classicUpperBounds()
@@ -1105,11 +1106,11 @@ public void testEmptyBuckets() {
List upperBounds = getData(histogram).getClassicBuckets().stream()
.map(ClassicHistogramBucket::getUpperBound)
.collect(Collectors.toList());
- Assert.assertEquals(Collections.singletonList(Double.POSITIVE_INFINITY), upperBounds);
+ Assertions.assertEquals(Collections.singletonList(Double.POSITIVE_INFINITY), upperBounds);
}
@Test
- public void testBucketsIncludePositiveInfinity() {
+ void testBucketsIncludePositiveInfinity() {
Histogram histogram = Histogram.builder()
.name("test")
.classicUpperBounds(0.01, 0.1, 1.0, Double.POSITIVE_INFINITY)
@@ -1117,11 +1118,11 @@ public void testBucketsIncludePositiveInfinity() {
List upperBounds = getData(histogram).getClassicBuckets().stream()
.map(ClassicHistogramBucket::getUpperBound)
.collect(Collectors.toList());
- Assert.assertEquals(Arrays.asList(0.01, 0.1, 1.0, Double.POSITIVE_INFINITY), upperBounds);
+ Assertions.assertEquals(Arrays.asList(0.01, 0.1, 1.0, Double.POSITIVE_INFINITY), upperBounds);
}
@Test
- public void testLinearBuckets() {
+ void testLinearBuckets() {
Histogram histogram = Histogram.builder()
.name("test")
.classicLinearUpperBounds(0.1, 0.1, 10)
@@ -1129,11 +1130,11 @@ public void testLinearBuckets() {
List upperBounds = getData(histogram).getClassicBuckets().stream()
.map(ClassicHistogramBucket::getUpperBound)
.collect(Collectors.toList());
- Assert.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);
+ Assertions.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);
}
@Test
- public void testExponentialBuckets() {
+ void testExponentialBuckets() {
Histogram histogram = Histogram.builder()
.classicExponentialUpperBounds(2, 2.5, 3)
.name("test")
@@ -1141,22 +1142,23 @@ public void testExponentialBuckets() {
List upperBounds = getData(histogram).getClassicBuckets().stream()
.map(ClassicHistogramBucket::getUpperBound)
.collect(Collectors.toList());
- assertEquals(Arrays.asList(2.0, 5.0, 12.5, Double.POSITIVE_INFINITY), upperBounds);
+ Assertions.assertEquals(Arrays.asList(2.0, 5.0, 12.5, Double.POSITIVE_INFINITY), upperBounds);
}
- @Test(expected = RuntimeException.class)
- public void testBucketsIncludeNaN() {
- Histogram.builder()
- .name("test")
- .classicUpperBounds(0.01, 0.1, 1.0, Double.NaN);
+ @Test
+ void testBucketsIncludeNaN() {
+ Assertions.assertThrows(IllegalArgumentException.class,
+ () -> Histogram.builder()
+ .name("test")
+ .classicUpperBounds(0.01, 0.1, 1.0, Double.NaN));
}
@Test
- public void testNoLabelsDefaultZeroValue() {
+ 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);
+ Assertions.assertEquals(0.0, getBucket(noLabels, 0.005).getCount(), 0.0);
+ Assertions.assertEquals(0, getData(noLabels).getCount());
+ Assertions.assertEquals(0.0, getData(noLabels).getSum(), 0.0);
}
private ClassicHistogramBucket getBucket(Histogram histogram, double le, String... labels) {
@@ -1167,28 +1169,28 @@ private ClassicHistogramBucket getBucket(Histogram histogram, double le, String.
}
@Test
- public void testObserve() {
+ 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);
+ Assertions.assertEquals(1, getData(noLabels).getCount());
+ Assertions.assertEquals(2.0, getData(noLabels).getSum(), .0);
+ Assertions.assertEquals(0.0, getBucket(noLabels, 1).getCount(), .0);
+ Assertions.assertEquals(1.0, getBucket(noLabels, 2.5).getCount(), .0);
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);
+ Assertions.assertEquals(2.0, getData(noLabels).getCount(), .0);
+ Assertions.assertEquals(6.0, getData(noLabels).getSum(), .0);
+ Assertions.assertEquals(0.0, getBucket(noLabels, 1).getCount(), .0);
+ Assertions.assertEquals(1.0, getBucket(noLabels, 2.5).getCount(), .0);
+ Assertions.assertEquals(1.0, getBucket(noLabels, 5).getCount(), .0);
+ Assertions.assertEquals(0.0, getBucket(noLabels, 10).getCount(), .0);
+ Assertions.assertEquals(0.0, getBucket(noLabels, Double.POSITIVE_INFINITY).getCount(), .0);
}
@Test
// See https://github.com/prometheus/client_java/issues/646
- public void testNegativeAmount() {
+ void testNegativeAmount() {
Histogram histogram = Histogram.builder()
.name("histogram")
.help("test histogram for negative values")
@@ -1200,35 +1202,35 @@ public void testNegativeAmount() {
histogram.observe(i);
expectedCount++;
expectedSum += i;
- assertEquals(expectedSum, getData(histogram).getSum(), .001);
- assertEquals(expectedCount, getData(histogram).getCount(), .001);
+ Assertions.assertEquals(expectedSum, getData(histogram).getSum(), .001);
+ Assertions.assertEquals(expectedCount, getData(histogram).getCount(), .001);
}
List expectedBucketCounts = Arrays.asList(2L, 5L, 5L, 5L, 5L, 0L); // buckets -10, -5, 0, 5, 10, +Inf
List actualBucketCounts = getData(histogram).getClassicBuckets().stream()
.map(ClassicHistogramBucket::getCount)
.collect(Collectors.toList());
- assertEquals(expectedBucketCounts, actualBucketCounts);
+ Assertions.assertEquals(expectedBucketCounts, actualBucketCounts);
}
@Test
- public void testBoundaryConditions() {
+ 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());
+ Assertions.assertEquals(0, getBucket(histogram, 1).getCount());
+ Assertions.assertEquals(1, getBucket(histogram, 2.5).getCount());
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());
+ Assertions.assertEquals(0, getBucket(histogram, 1).getCount());
+ Assertions.assertEquals(1, getBucket(histogram, 2.5).getCount());
+ Assertions.assertEquals(0, getBucket(histogram, 5).getCount());
+ Assertions.assertEquals(0, getBucket(histogram, 10).getCount());
+ Assertions.assertEquals(1, getBucket(histogram, Double.POSITIVE_INFINITY).getCount());
}
@Test
- public void testObserveWithLabels() {
+ void testObserveWithLabels() {
Histogram histogram = Histogram.builder()
.name("test")
.constLabels(Labels.of("env", "prod"))
@@ -1239,21 +1241,21 @@ public void testObserveWithLabels() {
histogram.labelValues("/hello", "500").observe(0.19);
HistogramSnapshot.HistogramDataPointSnapshot data200 = 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);
+ Assertions.assertEquals(2, data200.getCount());
+ Assertions.assertEquals(0.31, data200.getSum(), 0.0000001);
+ Assertions.assertEquals(1, data500.getCount());
+ Assertions.assertEquals(0.19, data500.getSum(), 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);
+ Assertions.assertEquals(3, data200.getCount());
+ Assertions.assertEquals(0.44, data200.getSum(), 0.0000001);
+ Assertions.assertEquals(1, data500.getCount());
+ Assertions.assertEquals(0.19, data500.getSum(), 0.0000001);
}
@Test
- public void testObserveMultithreaded() throws InterruptedException, ExecutionException, TimeoutException {
+ void testObserveMultithreaded() throws InterruptedException, ExecutionException, TimeoutException {
// Hard to test concurrency, but let's run a couple of observations in parallel and assert none gets lost.
Histogram histogram = Histogram.builder()
.name("test")
@@ -1284,19 +1286,19 @@ public void testObserveMultithreaded() throws InterruptedException, ExecutionExc
List snapshots = future.get(5, TimeUnit.SECONDS);
long count = 0;
for (HistogramSnapshot snapshot : snapshots) {
- Assert.assertEquals(1, snapshot.getDataPoints().size());
+ Assertions.assertEquals(1, snapshot.getDataPoints().size());
HistogramSnapshot.HistogramDataPointSnapshot data = snapshot.getDataPoints().stream().findFirst().orElseThrow(RuntimeException::new);
- Assert.assertTrue(data.getCount() >= (count + 1000)); // 1000 own observations plus the ones from other threads
+ Assertions.assertTrue(data.getCount() >= (count + 1000)); // 1000 own observations plus the ones from other threads
count = data.getCount();
}
if (count > maxCount) {
maxCount = count;
}
}
- Assert.assertEquals(nThreads * 10_000, maxCount); // the last collect() has seen all observations
- Assert.assertEquals(getBucket(histogram, 2.5, "status", "200").getCount(), nThreads * 10_000);
+ Assertions.assertEquals(nThreads * 10_000, maxCount); // the last collect() has seen all observations
+ Assertions.assertEquals(getBucket(histogram, 2.5, "status", "200").getCount(), nThreads * 10_000);
executor.shutdown();
- Assert.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ Assertions.assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
}
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 f88c98d7c..77a84408e 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
@@ -6,19 +6,20 @@
import io.prometheus.metrics.shaded.com_google_protobuf_3_21_7.TextFormat;
import io.prometheus.metrics.expositionformats.PrometheusProtobufWriter;
import io.prometheus.metrics.expositionformats.generated.com_google_protobuf_3_21_7.Metrics;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-public class InfoTest {
+class InfoTest {
@Test
- public void testInfoStrippedFromName() {
+ void testInfoStrippedFromName() {
for (String name : new String[]{
"jvm.runtime", "jvm_runtime",
"jvm.runtime.info", "jvm_runtime_info"}) {
@@ -35,64 +36,66 @@ public void testInfoStrippedFromName() {
}
@Test
- public void testAddAndRemove() throws IOException {
+ void testAddAndRemove() throws IOException {
Info info = Info.builder()
.name("test_info")
.labelNames("a", "b")
.build();
- Assert.assertEquals(0, info.collect().getDataPoints().size());
+ Assertions.assertEquals(0, info.collect().getDataPoints().size());
info.addLabelValues("val1", "val2");
- Assert.assertEquals(1, info.collect().getDataPoints().size());
+ Assertions.assertEquals(1, info.collect().getDataPoints().size());
info.addLabelValues("val1", "val2"); // already exist, so no change
- Assert.assertEquals(1, info.collect().getDataPoints().size());
+ Assertions.assertEquals(1, info.collect().getDataPoints().size());
info.addLabelValues("val2", "val2");
- Assert.assertEquals(2, info.collect().getDataPoints().size());
+ Assertions.assertEquals(2, info.collect().getDataPoints().size());
info.remove("val1", "val3"); // does not exist, so no change
- Assert.assertEquals(2, info.collect().getDataPoints().size());
+ Assertions.assertEquals(2, info.collect().getDataPoints().size());
info.remove("val1", "val2");
- Assert.assertEquals(1, info.collect().getDataPoints().size());
+ Assertions.assertEquals(1, info.collect().getDataPoints().size());
info.remove("val2", "val2");
- Assert.assertEquals(0, info.collect().getDataPoints().size());
+ Assertions.assertEquals(0, info.collect().getDataPoints().size());
}
@Test
- public void testSet() throws IOException {
+ void testSet() throws IOException {
Info info = Info.builder()
.name("target_info")
.constLabels(Labels.of("service.name", "test", "service.instance.id", "123"))
.labelNames("service.version")
.build();
info.setLabelValues("1.0.0");
- Assert.assertEquals(1, info.collect().getDataPoints().size());
+ Assertions.assertEquals(1, info.collect().getDataPoints().size());
info.setLabelValues("2.0.0");
- Assert.assertEquals(1, info.collect().getDataPoints().size());
+ Assertions.assertEquals(1, info.collect().getDataPoints().size());
assertTextFormat("target_info{service_instance_id=\"123\",service_name=\"test\",service_version=\"2.0.0\"} 1\n", info);
}
@Test
- public void testConstLabelsOnly() throws IOException {
+ void testConstLabelsOnly() throws IOException {
Info info = Info.builder()
.name("target_info")
.constLabels(Labels.of("service.name", "test", "service.instance.id", "123"))
.build();
- Assert.assertEquals(1, info.collect().getDataPoints().size());
+ Assertions.assertEquals(1, info.collect().getDataPoints().size());
assertTextFormat("target_info{service_instance_id=\"123\",service_name=\"test\"} 1\n", info);
}
- @Test(expected = IllegalArgumentException.class)
- public void testConstLabelsDuplicate1() {
- Info.builder()
- .constLabels(Labels.of("a_1", "val1"))
- .labelNames("a.1")
- .build();
+ @Test
+ void testConstLabelsDuplicate1() {
+ assertThrows(IllegalArgumentException.class,
+ () -> Info.builder()
+ .constLabels(Labels.of("a_1", "val1"))
+ .labelNames("a.1")
+ .build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testConstLabelsDuplicate2() {
- Info.builder()
- .labelNames("a_1")
- .constLabels(Labels.of("a.1", "val1"))
- .build();
+ @Test
+ void testConstLabelsDuplicate2() {
+ assertThrows(IllegalArgumentException.class,
+ () -> 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 3b57220f8..4eea8ca6f 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 org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
-public class SlidingWindowTest {
+class SlidingWindowTest {
static class Observer {
@@ -23,7 +23,7 @@ void assertValues(double... expectedValues) {
for (double expectedValue : expectedValues) {
expectedList.add(expectedValue);
}
- Assert.assertEquals(expectedList, values);
+ Assertions.assertEquals(expectedList, values);
}
}
@@ -33,15 +33,15 @@ void assertValues(double... expectedValues) {
private final int ageBuckets = 5;
private final long timeBetweenRotateMillis = maxAgeSeconds * 1000 / ageBuckets + 2;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
currentTimeMillis.set(System.currentTimeMillis());
ringBuffer = new SlidingWindow<>(Observer.class, Observer::new, Observer::observe, maxAgeSeconds, ageBuckets);
ringBuffer.currentTimeMillis = currentTimeMillis::get;
}
@Test
- public void testRotate() {
+ void testRotate() {
for (int i=0; i new RuntimeException("stateset with labels " + labels + " not found"));
}
- @Test(expected = IllegalStateException.class)
- public void testStatesCannotBeEmpty() {
- StateSet.builder().name("invalid").build();
+ @Test
+ void testStatesCannotBeEmpty() {
+ Assertions.assertThrows(IllegalStateException.class, () -> 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 0baddd5fd..edbb8b8e8 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,15 +1,15 @@
package io.prometheus.metrics.core.metrics;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.Map;
-public class StatefulMetricTest {
+class StatefulMetricTest {
@Test
- public void testLabelRemoveWhileCollecting() throws Exception {
+ void testLabelRemoveWhileCollecting() throws Exception {
Counter counter = Counter.builder().name("test").labelNames("label1", "label2").build();
Field data = counter.getClass().getSuperclass().getDeclaredField("data");
data.setAccessible(true);
@@ -29,8 +29,8 @@ public void testLabelRemoveWhileCollecting() throws Exception {
counter.remove("c", "d");
counter.remove("e", "f");
}
- Assert.assertNotNull(entry.getKey());
- Assert.assertNotNull(entry.getValue());
+ Assertions.assertNotNull(entry.getKey());
+ Assertions.assertNotNull(entry.getValue());
}
}
}
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 d5bc791a8..e9b8598c1 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,5 +1,5 @@
package io.prometheus.metrics.core.metrics;
-public class SummaryTest {
+class SummaryTest {
// TODO, port the SummaryTest from simpleclient over.
}
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 cbd9ef53f..3bd8884d4 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,6 @@
package io.prometheus.metrics.core.metrics;
-public class SummaryWithCallbackTest {
+class SummaryWithCallbackTest {
// TODO :). Anyway, callbacks are implicitly covered by the JVM metrics tests as well.
}
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 489bcac33..ec9e133bb 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,13 +1,13 @@
package io.prometheus.metrics.core.metrics;
import io.prometheus.metrics.model.snapshots.Exemplar;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
public class TestUtil {
public static void assertExemplarEquals(Exemplar expected, Exemplar actual) {
// ignore timestamp
- Assert.assertEquals(expected.getValue(), actual.getValue(), 0.00001);
- Assert.assertEquals(expected.getLabels(), actual.getLabels());
+ Assertions.assertEquals(expected.getValue(), actual.getValue(), 0.00001);
+ Assertions.assertEquals(expected.getLabels(), actual.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 996e199db..427d04396 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 format.
diff --git a/prometheus-metrics-exporter-opentelemetry/pom.xml b/prometheus-metrics-exporter-opentelemetry/pom.xml
index b99ee75cf..d0cf05be9 100644
--- a/prometheus-metrics-exporter-opentelemetry/pom.xml
+++ b/prometheus-metrics-exporter-opentelemetry/pom.xml
@@ -51,9 +51,8 @@
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-engine
test
@@ -69,9 +68,9 @@
test
- io.opentelemetry
+ io.opentelemetry.proto
opentelemetry-proto
- 1.7.1-alpha
+ 1.0.0-alpha
test
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 2482d6857..97a8392fc 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
@@ -1,7 +1,7 @@
package io.prometheus.metrics.exporter.opentelemetry;
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;
@@ -9,31 +9,23 @@
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;
-import io.opentelemetry.proto.metrics.v1.InstrumentationLibraryMetrics;
-import io.opentelemetry.proto.metrics.v1.Metric;
-import io.opentelemetry.proto.metrics.v1.NumberDataPoint;
-import io.opentelemetry.proto.metrics.v1.ResourceMetrics;
+import io.opentelemetry.proto.metrics.v1.*;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.samplers.Sampler;
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;
-import static com.github.tomakehurst.wiremock.client.WireMock.containing;
-import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
-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.urlEqualTo;
-import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-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,11 +33,9 @@ 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
- public void setUp() {
+ @BeforeEach
+ void setUp() {
openTelemetryExporter = OpenTelemetryExporter.builder()
.endpoint("http://localhost:4317")
.protocol("http/protobuf")
@@ -57,21 +47,21 @@ public void setUp() {
.withExemplars()
.register();
- wireMockRule.stubFor(post(ENDPOINT_PATH)
+ stubFor(post(ENDPOINT_PATH)
.withHeader("Content-Type", containing("application/x-protobuf"))
.willReturn(ok()
.withHeader("Content-Type", "application/json")
.withBody("{\"partialSuccess\":{}}")));
}
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
PrometheusRegistry.defaultRegistry.unregister(testCounter);
openTelemetryExporter.close();
}
@Test
- public void sampledExemplarIsForwarded() {
+ void sampledExemplarIsForwarded() {
try (SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
.setSampler(Sampler.alwaysOn())
.build()) {
@@ -96,8 +86,8 @@ public void sampledExemplarIsForwarded() {
}
- @Test(expected = ConditionTimeoutException.class)
- public void notSampledExemplarIsNotForwarded() {
+ @Test
+ void notSampledExemplarIsNotForwarded() {
try (SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
.setSampler(Sampler.alwaysOff())
.build()) {
@@ -109,16 +99,16 @@ public void notSampledExemplarIsNotForwarded() {
testCounter.inc(2);
}
}
-
- 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;
- });
-
+ assertThrows(ConditionTimeoutException.class,
+ () -> 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) {
@@ -126,7 +116,7 @@ private static ValueMatcher getExemplarCountMatcher(int expectedCount)
try {
ExportMetricsServiceRequest exportMetricsServiceRequest = ExportMetricsServiceRequest.parseFrom(request.getBody());
for (ResourceMetrics resourceMetrics : exportMetricsServiceRequest.getResourceMetricsList()) {
- for (InstrumentationLibraryMetrics instrumentationLibraryMetrics : resourceMetrics.getInstrumentationLibraryMetricsList()) {
+ for (ScopeMetrics instrumentationLibraryMetrics : resourceMetrics.getScopeMetricsList()) {
for (Metric metric : instrumentationLibraryMetrics.getMetricsList()) {
for (NumberDataPoint numberDataPoint : metric.getSum().getDataPointsList()) {
if (numberDataPoint.getExemplarsCount() == expectedCount) {
diff --git a/prometheus-metrics-exposition-formats/pom.xml b/prometheus-metrics-exposition-formats/pom.xml
index c1f0fdf77..86f291bc2 100644
--- a/prometheus-metrics-exposition-formats/pom.xml
+++ b/prometheus-metrics-exposition-formats/pom.xml
@@ -55,9 +55,8 @@
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-engine
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 7451e7c10..4b5cb58e6 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
@@ -22,13 +22,13 @@
import io.prometheus.metrics.model.snapshots.Unit;
import io.prometheus.metrics.model.snapshots.UnknownSnapshot;
import io.prometheus.metrics.model.snapshots.UnknownSnapshot.UnknownDataPointSnapshot;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-public class ExpositionFormatsTest {
+class ExpositionFormatsTest {
private final String exemplar1String = "{env=\"prod\",span_id=\"12345\",trace_id=\"abcde\"} 1.7 1672850685.829";
private final String exemplar2String = "{env=\"dev\",span_id=\"23456\",trace_id=\"bcdef\"} 2.4 1672850685.830";
@@ -85,7 +85,7 @@ public class ExpositionFormatsTest {
.build();
@Test
- public void testCounterComplete() throws IOException {
+ void testCounterComplete() throws IOException {
String openMetricsText = "" +
"# TYPE service_time_seconds counter\n" +
"# UNIT service_time_seconds seconds\n" +
@@ -174,7 +174,7 @@ public void testCounterComplete() throws IOException {
}
@Test
- public void testCounterMinimal() throws IOException {
+ void testCounterMinimal() throws IOException {
String openMetricsText = "" +
"# TYPE my_counter counter\n" +
"my_counter_total 1.1\n" +
@@ -196,7 +196,7 @@ public void testCounterMinimal() throws IOException {
}
@Test
- public void testCounterWithDots() throws IOException {
+ void testCounterWithDots() throws IOException {
String openMetricsText = "" +
"# TYPE my_request_count counter\n" +
"my_request_count_total{http_path=\"/hello\"} 3.0 # " + exemplarWithDotsString + "\n" +
@@ -232,7 +232,7 @@ public void testCounterWithDots() throws IOException {
}
@Test
- public void testGaugeComplete() throws IOException {
+ void testGaugeComplete() throws IOException {
String openMetricsText = "" +
"# TYPE disk_usage_ratio gauge\n" +
"# UNIT disk_usage_ratio ratio\n" +
@@ -289,7 +289,7 @@ public void testGaugeComplete() throws IOException {
}
@Test
- public void testGaugeMinimal() throws IOException {
+ void testGaugeMinimal() throws IOException {
String openMetricsText = "" +
"# TYPE temperature_centigrade gauge\n" +
"temperature_centigrade 22.3\n" +
@@ -313,7 +313,7 @@ public void testGaugeMinimal() throws IOException {
}
@Test
- public void testGaugeWithDots() throws IOException {
+ void testGaugeWithDots() throws IOException {
String openMetricsText = "" +
"# TYPE my_temperature_celsius gauge\n" +
"# UNIT my_temperature_celsius celsius\n" +
@@ -355,7 +355,7 @@ public void testGaugeWithDots() throws IOException {
}
@Test
- public void testSummaryComplete() throws IOException {
+ void testSummaryComplete() throws IOException {
String openMetricsText = "" +
"# TYPE http_request_duration_seconds summary\n" +
"# UNIT http_request_duration_seconds seconds\n" +
@@ -488,7 +488,7 @@ public void testSummaryComplete() throws IOException {
}
@Test
- public void testSummaryWithoutQuantiles() throws IOException {
+ void testSummaryWithoutQuantiles() throws IOException {
String openMetricsText = "" +
"# TYPE latency_seconds summary\n" +
"# UNIT latency_seconds seconds\n" +
@@ -530,7 +530,7 @@ public void testSummaryWithoutQuantiles() throws IOException {
}
@Test
- public void testSummaryNoCountAndSum() throws IOException {
+ void testSummaryNoCountAndSum() throws IOException {
String openMetricsText = "" +
"# TYPE latency_seconds summary\n" +
"latency_seconds{quantile=\"0.95\"} 200.0\n" +
@@ -562,7 +562,7 @@ public void testSummaryNoCountAndSum() throws IOException {
}
@Test
- public void testSummaryJustCount() throws IOException {
+ void testSummaryJustCount() throws IOException {
String openMetricsText = "" +
"# TYPE latency_seconds summary\n" +
"latency_seconds_count 1\n" +
@@ -594,7 +594,7 @@ public void testSummaryJustCount() throws IOException {
}
@Test
- public void testSummaryJustSum() throws IOException {
+ void testSummaryJustSum() throws IOException {
String openMetricsText = "" +
"# TYPE latency_seconds summary\n" +
"latency_seconds_sum 12.3\n" +
@@ -626,7 +626,7 @@ public void testSummaryJustSum() throws IOException {
}
@Test
- public void testSummaryEmptyData() throws IOException {
+ void testSummaryEmptyData() throws IOException {
// SummaryData can be present but empty (no count, no sum, no quantiles).
// This should be treated like no data is present.
SummarySnapshot summary = SummarySnapshot.builder()
@@ -643,7 +643,7 @@ public void testSummaryEmptyData() throws IOException {
}
@Test
- public void testSummaryEmptyAndNonEmpty() throws IOException {
+ void testSummaryEmptyAndNonEmpty() throws IOException {
String openMetricsText = "" +
"# TYPE latency_seconds summary\n" +
"latency_seconds_count{path=\"/v2\"} 2\n" +
@@ -687,7 +687,7 @@ public void testSummaryEmptyAndNonEmpty() throws IOException {
}
@Test
- public void testSummaryWithDots() throws IOException {
+ void testSummaryWithDots() throws IOException {
String openMetricsText = "" +
"# TYPE my_request_duration_seconds summary\n" +
"# UNIT my_request_duration_seconds seconds\n" +
@@ -730,7 +730,7 @@ public void testSummaryWithDots() throws IOException {
}
@Test
- public void testClassicHistogramComplete() throws Exception {
+ void testClassicHistogramComplete() throws Exception {
String openMetricsText = "" +
"# TYPE response_size_bytes histogram\n" +
"# UNIT response_size_bytes bytes\n" +
@@ -867,7 +867,7 @@ public void testClassicHistogramComplete() throws Exception {
}
@Test
- public void testClassicHistogramMinimal() throws Exception {
+ 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 = "" +
@@ -908,7 +908,7 @@ public void testClassicHistogramMinimal() throws Exception {
}
@Test
- public void testClassicHistogramCountAndSum() throws Exception {
+ void testClassicHistogramCountAndSum() throws Exception {
String openMetricsText = "" +
"# TYPE request_latency_seconds histogram\n" +
"request_latency_seconds_bucket{le=\"+Inf\"} 2\n" +
@@ -952,7 +952,7 @@ public void testClassicHistogramCountAndSum() throws Exception {
}
@Test
- public void testClassicGaugeHistogramComplete() throws IOException {
+ void testClassicGaugeHistogramComplete() throws IOException {
String openMetricsText = "" +
"# TYPE cache_size_bytes gaugehistogram\n" +
"# UNIT cache_size_bytes bytes\n" +
@@ -1091,7 +1091,7 @@ public void testClassicGaugeHistogramComplete() throws IOException {
}
@Test
- public void testClassicGaugeHistogramMinimal() throws IOException {
+ 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 = "" +
@@ -1134,7 +1134,7 @@ public void testClassicGaugeHistogramMinimal() throws IOException {
}
@Test
- public void testClassicGaugeHistogramCountAndSum() throws IOException {
+ void testClassicGaugeHistogramCountAndSum() throws IOException {
String openMetricsText = "" +
"# TYPE queue_size_bytes gaugehistogram\n" +
"queue_size_bytes_bucket{le=\"+Inf\"} 130\n" +
@@ -1181,7 +1181,7 @@ public void testClassicGaugeHistogramCountAndSum() throws IOException {
}
@Test
- public void testClassicHistogramWithDots() throws IOException {
+ void testClassicHistogramWithDots() throws IOException {
String openMetricsText = "" +
"# TYPE my_request_duration_seconds histogram\n" +
"# UNIT my_request_duration_seconds seconds\n" +
@@ -1232,7 +1232,7 @@ public void testClassicHistogramWithDots() throws IOException {
}
@Test
- public void testNativeHistogramComplete() throws IOException {
+ void testNativeHistogramComplete() throws IOException {
String openMetricsText = "" +
"# TYPE response_size_bytes histogram\n" +
"# UNIT response_size_bytes bytes\n" +
@@ -1395,7 +1395,7 @@ public void testNativeHistogramComplete() throws IOException {
}
@Test
- public void testNativeHistogramMinimal() throws IOException {
+ void testNativeHistogramMinimal() throws IOException {
String openMetricsText = "" +
"# TYPE latency_seconds histogram\n" +
"latency_seconds_bucket{le=\"+Inf\"} 0\n" +
@@ -1429,7 +1429,7 @@ public void testNativeHistogramMinimal() throws IOException {
}
@Test
- public void testNativeHistogramWithDots() throws IOException {
+ void testNativeHistogramWithDots() throws IOException {
String openMetricsText = "" +
"# TYPE my_request_duration_seconds histogram\n" +
"# UNIT my_request_duration_seconds seconds\n" +
@@ -1489,7 +1489,7 @@ public void testNativeHistogramWithDots() throws IOException {
// TODO: Gauge Native Histogram
@Test
- public void testInfo() throws IOException {
+ void testInfo() throws IOException {
String openMetrics = "" +
"# TYPE version info\n" +
"# HELP version version information\n" +
@@ -1513,7 +1513,7 @@ public void testInfo() throws IOException {
}
@Test
- public void testInfoWithDots() throws IOException {
+ void testInfoWithDots() throws IOException {
String openMetricsText = "" +
"# TYPE jvm_status info\n" +
"# HELP jvm_status JVM status info\n" +
@@ -1546,7 +1546,7 @@ public void testInfoWithDots() throws IOException {
}
@Test
- public void testStateSetComplete() throws IOException {
+ void testStateSetComplete() throws IOException {
String openMetrics = "" +
"# TYPE state stateset\n" +
"# HELP state complete state set example\n" +
@@ -1585,7 +1585,7 @@ public void testStateSetComplete() throws IOException {
}
@Test
- public void testStateSetMinimal() throws IOException {
+ void testStateSetMinimal() throws IOException {
String openMetrics = "" +
"# TYPE state stateset\n" +
"state{state=\"a\"} 1\n" +
@@ -1609,7 +1609,7 @@ public void testStateSetMinimal() throws IOException {
}
@Test
- public void testStateSetWithDots() throws IOException {
+ void testStateSetWithDots() throws IOException {
String openMetricsText = "" +
"# TYPE my_application_state stateset\n" +
"# HELP my_application_state My application state\n" +
@@ -1651,7 +1651,7 @@ public void testStateSetWithDots() throws IOException {
}
@Test
- public void testUnknownComplete() throws IOException {
+ void testUnknownComplete() throws IOException {
String openMetrics = "" +
"# TYPE my_special_thing_bytes unknown\n" +
"# UNIT my_special_thing_bytes bytes\n" +
@@ -1688,7 +1688,7 @@ public void testUnknownComplete() throws IOException {
}
@Test
- public void testUnknownMinimal() throws IOException {
+ void testUnknownMinimal() throws IOException {
String openMetrics = "" +
"# TYPE other unknown\n" +
"other 22.3\n" +
@@ -1709,7 +1709,7 @@ public void testUnknownMinimal() throws IOException {
}
@Test
- public void testUnknownWithDots() throws IOException {
+ void testUnknownWithDots() throws IOException {
String openMetrics = "" +
"# TYPE some_unknown_metric unknown\n" +
"# UNIT some_unknown_metric bytes\n" +
@@ -1746,7 +1746,7 @@ public void testUnknownWithDots() throws IOException {
}
@Test
- public void testHelpEscape() throws IOException {
+ void testHelpEscape() throws IOException {
String openMetrics = "" +
"# TYPE test counter\n" +
"# HELP test Some text and \\n some \\\" escaping\n" +
@@ -1768,7 +1768,7 @@ public void testHelpEscape() throws IOException {
}
@Test
- public void testLabelValueEscape() throws IOException {
+ void testLabelValueEscape() throws IOException {
String openMetrics = "" +
"# TYPE test counter\n" +
"test_total{a=\"x\",b=\"escaping\\\" example \\n \"} 1.0\n" +
@@ -1792,34 +1792,34 @@ private void assertOpenMetricsText(String expected, MetricSnapshot snapshot) thr
ByteArrayOutputStream out = new ByteArrayOutputStream();
OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(true, true);
writer.write(out, MetricSnapshots.of(snapshot));
- Assert.assertEquals(expected, out.toString());
+ Assertions.assertEquals(expected, out.toString());
}
private void assertOpenMetricsTextWithoutCreated(String expected, MetricSnapshot snapshot) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(false, true);
writer.write(out, MetricSnapshots.of(snapshot));
- Assert.assertEquals(expected, out.toString());
+ Assertions.assertEquals(expected, out.toString());
}
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());
+ Assertions.assertEquals(expected, out.toString());
}
private void assertPrometheusTextWithoutCreated(String expected, MetricSnapshot snapshot) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrometheusTextFormatWriter writer = new PrometheusTextFormatWriter(false);
writer.write(out, MetricSnapshots.of(snapshot));
- Assert.assertEquals(expected, out.toString());
+ Assertions.assertEquals(expected, out.toString());
}
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);
+ Assertions.assertEquals(expected, actual);
}
}
diff --git a/prometheus-metrics-instrumentation-jvm/pom.xml b/prometheus-metrics-instrumentation-jvm/pom.xml
index f55dd9c6f..0f42782d0 100644
--- a/prometheus-metrics-instrumentation-jvm/pom.xml
+++ b/prometheus-metrics-instrumentation-jvm/pom.xml
@@ -50,9 +50,8 @@
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-engine
test
diff --git a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java
index bca58942a..77e5d0196 100644
--- a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java
+++ b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java
@@ -73,12 +73,12 @@ public class ProcessMetrics {
private final Grepper grepper;
private final boolean linux;
- private ProcessMetrics(OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean, Grepper grepper, PrometheusProperties config) {
+ private ProcessMetrics(OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean, Grepper grepper, PrometheusProperties config, boolean linux) {
this.osBean = osBean;
this.runtimeBean = runtimeBean;
this.grepper = grepper;
this.config = config;
- this.linux = PROC_SELF_STATUS.canRead();
+ this.linux = linux;
}
private void register(PrometheusRegistry registry) {
@@ -242,6 +242,7 @@ public static class Builder {
private OperatingSystemMXBean osBean;
private RuntimeMXBean runtimeBean;
private Grepper grepper;
+ private Boolean linux;
private Builder(PrometheusProperties config) {
this.config = config;
@@ -271,6 +272,14 @@ Builder grepper(Grepper grepper) {
return this;
}
+ /**
+ * Package private. For testing only.
+ */
+ Builder linux(boolean linux) {
+ this.linux = linux;
+ return this;
+ }
+
public void register() {
register(PrometheusRegistry.defaultRegistry);
}
@@ -279,7 +288,8 @@ public void register(PrometheusRegistry registry) {
OperatingSystemMXBean osBean = this.osBean != null ? this.osBean : ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runtimeMXBean = this.runtimeBean != null ? this.runtimeBean : ManagementFactory.getRuntimeMXBean();
Grepper grepper = this.grepper != null ? this.grepper : new FileGrepper();
- new ProcessMetrics(osBean, runtimeMXBean, grepper, config).register(registry);
+ boolean linux = this.linux != null ? this.linux : PROC_SELF_STATUS.canRead();
+ new ProcessMetrics(osBean, runtimeMXBean, grepper, config, linux).register(registry);
}
}
}
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 b8aafa0ea..1df4fa1e9 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
@@ -3,9 +3,9 @@
import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
@@ -17,13 +17,13 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-public class JvmBufferPoolMetricsTest {
+class JvmBufferPoolMetricsTest {
private final BufferPoolMXBean directBuffer = Mockito.mock(BufferPoolMXBean.class);
private final BufferPoolMXBean mappedBuffer = Mockito.mock(BufferPoolMXBean.class);
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
when(directBuffer.getName()).thenReturn("direct");
when(directBuffer.getCount()).thenReturn(2L);
when(directBuffer.getMemoryUsed()).thenReturn(1234L);
@@ -35,7 +35,7 @@ public void setUp() {
}
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
JvmBufferPoolMetrics.builder()
.bufferPoolBeans(Arrays.asList(mappedBuffer, directBuffer))
@@ -59,11 +59,11 @@ public void testGoodCase() throws IOException {
"jvm_buffer_pool_used_bytes{pool=\"mapped\"} 2345.0\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testIgnoredMetricNotScraped() {
+ void testIgnoredMetricNotScraped() {
MetricNameFilter filter = MetricNameFilter.builder()
.nameMustNotBeEqualTo("jvm_buffer_pool_used_bytes")
.build();
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 16413b839..f5e9f6bc7 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
@@ -3,9 +3,9 @@
import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
@@ -16,19 +16,19 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-public class JvmClassLoadingMetricsTest {
+class JvmClassLoadingMetricsTest {
private ClassLoadingMXBean mockClassLoadingBean = Mockito.mock(ClassLoadingMXBean.class);
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
when(mockClassLoadingBean.getLoadedClassCount()).thenReturn(1000);
when(mockClassLoadingBean.getTotalLoadedClassCount()).thenReturn(2000L);
when(mockClassLoadingBean.getUnloadedClassCount()).thenReturn(500L);
}
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
JvmClassLoadingMetrics.builder()
.classLoadingBean(mockClassLoadingBean)
@@ -47,11 +47,11 @@ public void testGoodCase() throws IOException {
"jvm_classes_unloaded_total 500.0\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testIgnoredMetricNotScraped() {
+ void testIgnoredMetricNotScraped() {
MetricNameFilter filter = MetricNameFilter.builder()
.nameMustNotBeEqualTo("jvm_classes_currently_loaded")
.build();
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 75ecc8370..9e659130b 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
@@ -3,9 +3,9 @@
import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
@@ -16,18 +16,18 @@
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
-public class JvmCompilationMetricsTest {
+class JvmCompilationMetricsTest {
private CompilationMXBean mockCompilationBean = Mockito.mock(CompilationMXBean.class);
- @Before
- public void setUp() {
- when(mockCompilationBean.getTotalCompilationTime()).thenReturn(10000l);
+ @BeforeEach
+ void setUp() {
+ when(mockCompilationBean.getTotalCompilationTime()).thenReturn(10000L);
when(mockCompilationBean.isCompilationTimeMonitoringSupported()).thenReturn(true);
}
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
JvmCompilationMetrics.builder()
.compilationBean(mockCompilationBean)
@@ -41,11 +41,11 @@ public void testGoodCase() throws IOException {
"jvm_compilation_time_seconds_total 10.0\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testIgnoredMetricNotScraped() {
+ void testIgnoredMetricNotScraped() {
MetricNameFilter filter = MetricNameFilter.builder()
.nameMustNotBeEqualTo("jvm_compilation_time_seconds_total")
.build();
@@ -57,6 +57,6 @@ public void testIgnoredMetricNotScraped() {
MetricSnapshots snapshots = registry.scrape(filter);
verify(mockCompilationBean, times(0)).getTotalCompilationTime();
- Assert.assertEquals(0, snapshots.size());
+ Assertions.assertEquals(0, snapshots.size());
}
}
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 d7dad1787..10a5058f4 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
@@ -3,9 +3,9 @@
import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
@@ -19,13 +19,13 @@
import static org.mockito.Mockito.when;
-public class JvmGarbageCollectorMetricsTest {
+class JvmGarbageCollectorMetricsTest {
private GarbageCollectorMXBean mockGcBean1 = Mockito.mock(GarbageCollectorMXBean.class);
private GarbageCollectorMXBean mockGcBean2 = Mockito.mock(GarbageCollectorMXBean.class);
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
when(mockGcBean1.getName()).thenReturn("MyGC1");
when(mockGcBean1.getCollectionCount()).thenReturn(100L);
when(mockGcBean1.getCollectionTime()).thenReturn(TimeUnit.SECONDS.toMillis(10));
@@ -35,7 +35,7 @@ public void setUp() {
}
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
JvmGarbageCollectorMetrics.builder()
.garbageCollectorBeans(Arrays.asList(mockGcBean1, mockGcBean2))
@@ -52,11 +52,11 @@ public void testGoodCase() throws IOException {
"jvm_gc_collection_seconds_sum{gc=\"MyGC2\"} 20.0\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testIgnoredMetricNotScraped() {
+ void testIgnoredMetricNotScraped() {
MetricNameFilter filter = MetricNameFilter.builder()
.nameMustNotBeEqualTo("jvm_gc_collection_seconds")
.build();
@@ -69,6 +69,6 @@ public void testIgnoredMetricNotScraped() {
verify(mockGcBean1, times(0)).getCollectionTime();
verify(mockGcBean1, times(0)).getCollectionCount();
- Assert.assertEquals(0, snapshots.size());
+ Assertions.assertEquals(0, snapshots.size());
}
}
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 b70bb0bba..67f4e1aaf 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
@@ -3,9 +3,9 @@
import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
@@ -19,7 +19,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-public class JvmMemoryMetricsTest {
+class JvmMemoryMetricsTest {
private MemoryMXBean mockMemoryBean = Mockito.mock(MemoryMXBean.class);
private MemoryPoolMXBean mockPoolsBeanEdenSpace = Mockito.mock(MemoryPoolMXBean.class);
@@ -31,8 +31,8 @@ public class JvmMemoryMetricsTest {
private MemoryUsage memoryUsagePoolCollectionEdenSpace = Mockito.mock(MemoryUsage.class);
private MemoryUsage memoryUsagePoolCollectionOldGen = Mockito.mock(MemoryUsage.class);
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
when(mockMemoryBean.getHeapMemoryUsage()).thenReturn(memoryUsageHeap);
when(mockMemoryBean.getNonHeapMemoryUsage()).thenReturn(memoryUsageNonHeap);
@@ -79,7 +79,7 @@ public void setUp() {
}
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
JvmMemoryMetrics.builder()
.withMemoryBean(mockMemoryBean)
@@ -153,11 +153,11 @@ public void testGoodCase() throws IOException {
"jvm_memory_used_bytes{area=\"nonheap\"} 6.0\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testIgnoredMetricNotScraped() {
+ void testIgnoredMetricNotScraped() {
MetricNameFilter filter = MetricNameFilter.builder()
.nameMustNotBeEqualTo("jvm_memory_pool_used_bytes")
.build();
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 945ac5e27..75839b5d7 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
@@ -6,15 +6,15 @@
import io.prometheus.metrics.model.snapshots.CounterSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-public class JvmMemoryPoolAllocationMetricsTest {
+class JvmMemoryPoolAllocationMetricsTest {
@Test
- public void testListenerLogic() {
+ void testListenerLogic() {
PrometheusRegistry registry = new PrometheusRegistry();
Counter counter = Counter.builder().name("test").labelNames("pool").register(registry);
AllocationCountingNotificationListener listener = new AllocationCountingNotificationListener(counter);
@@ -58,7 +58,7 @@ private double getCountByPool(String metricName, String poolName, MetricSnapshot
}
}
}
- Assert.fail("pool " + poolName + " not found.");
+ Assertions.fail("pool " + poolName + " not found.");
return 0.0;
}
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 0c4dd786a..a9639703b 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
@@ -2,17 +2,17 @@
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static io.prometheus.metrics.instrumentation.jvm.TestUtil.convertToOpenMetricsFormat;
-public class JvmRuntimeInfoMetricTest {
+class JvmRuntimeInfoMetricTest {
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
JvmRuntimeInfoMetric.builder()
.version("1.8.0_382-b05")
@@ -27,6 +27,6 @@ public void testGoodCase() throws IOException {
"jvm_runtime_info{runtime=\"OpenJDK Runtime Environment\",vendor=\"Oracle Corporation\",version=\"1.8.0_382-b05\"} 1\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
}
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 7be7892a9..1516afbc9 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
@@ -5,9 +5,9 @@
import io.prometheus.metrics.model.snapshots.GaugeSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
@@ -22,15 +22,15 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-public class JvmThreadsMetricsTest {
+class JvmThreadsMetricsTest {
private ThreadMXBean mockThreadsBean = Mockito.mock(ThreadMXBean.class);
private ThreadInfo mockThreadInfoBlocked = Mockito.mock(ThreadInfo.class);
private ThreadInfo mockThreadInfoRunnable1 = Mockito.mock(ThreadInfo.class);
private ThreadInfo mockThreadInfoRunnable2 = Mockito.mock(ThreadInfo.class);
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
when(mockThreadsBean.getThreadCount()).thenReturn(300);
when(mockThreadsBean.getDaemonThreadCount()).thenReturn(200);
when(mockThreadsBean.getPeakThreadCount()).thenReturn(301);
@@ -47,7 +47,7 @@ public void setUp() {
}
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
JvmThreadsMetrics.builder()
.threadBean(mockThreadsBean)
@@ -85,11 +85,11 @@ public void testGoodCase() throws IOException {
"jvm_threads_state{state=\"WAITING\"} 0.0\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testIgnoredMetricNotScraped() {
+ void testIgnoredMetricNotScraped() {
MetricNameFilter filter = MetricNameFilter.builder()
.nameMustNotBeEqualTo("jvm_threads_deadlocked")
.build();
@@ -106,7 +106,7 @@ public void testIgnoredMetricNotScraped() {
}
@Test
- public void testInvalidThreadIds() {
+ void testInvalidThreadIds() {
try {
int javaVersion = Integer.parseInt(System.getProperty("java.version"));
if (javaVersion >= 21) {
@@ -134,9 +134,9 @@ public void testInvalidThreadIds() {
Map actual = getCountByState(registry.scrape());
- Assert.assertEquals(expected.size(), actual.size());
+ Assertions.assertEquals(expected.size(), actual.size());
for (String threadState : expected.keySet()) {
- Assert.assertEquals(expected.get(threadState), actual.get(threadState), 0.0);
+ Assertions.assertEquals(expected.get(threadState), actual.get(threadState), 0.0);
}
} finally {
for (int i = 0; i < numberOfInvalidThreadIds; i++) {
@@ -151,7 +151,7 @@ private Map getCountByState(MetricSnapshots snapshots) {
if (snapshot.getMetadata().getName().equals("jvm_threads_state")) {
for (GaugeSnapshot.GaugeDataPointSnapshot data : ((GaugeSnapshot) snapshot).getDataPoints()) {
String state = data.getLabels().get("state");
- Assert.assertNotNull(state);
+ Assertions.assertNotNull(state);
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 92f286e01..06ac782d9 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
@@ -3,9 +3,9 @@
import io.prometheus.metrics.model.registry.MetricNameFilter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.File;
@@ -20,7 +20,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-public class ProcessMetricsTest {
+class ProcessMetricsTest {
private com.sun.management.UnixOperatingSystemMXBean sunOsBean = Mockito.mock(com.sun.management.UnixOperatingSystemMXBean.class);
private java.lang.management.OperatingSystemMXBean javaOsBean = Mockito.mock(java.lang.management.OperatingSystemMXBean.class);
@@ -28,8 +28,8 @@ public class ProcessMetricsTest {
private ProcessMetrics.Grepper windowsGrepper = Mockito.mock(ProcessMetrics.Grepper.class);
private RuntimeMXBean runtimeBean = Mockito.mock(RuntimeMXBean.class);
- @Before
- public void setUp() throws IOException {
+ @BeforeEach
+ void setUp() throws IOException {
when(sunOsBean.getProcessCpuTime()).thenReturn(TimeUnit.MILLISECONDS.toNanos(72));
when(sunOsBean.getOpenFileDescriptorCount()).thenReturn(127L);
when(sunOsBean.getMaxFileDescriptorCount()).thenReturn(244L);
@@ -39,12 +39,13 @@ public void setUp() throws IOException {
}
@Test
- public void testGoodCase() throws IOException {
+ void testGoodCase() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
ProcessMetrics.builder()
- .osBean(sunOsBean)
- .runtimeBean(runtimeBean)
+ .osBean(sunOsBean)
+ .runtimeBean(runtimeBean)
.grepper(linuxGrepper)
+ .linux(true)
.register(registry);
MetricSnapshots snapshots = registry.scrape();
@@ -73,11 +74,11 @@ public void testGoodCase() throws IOException {
"process_virtual_memory_bytes 6180864.0\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testMinimal() throws IOException {
+ void testMinimal() throws IOException {
PrometheusRegistry registry = new PrometheusRegistry();
ProcessMetrics.builder()
.osBean(javaOsBean)
@@ -93,11 +94,11 @@ public void testMinimal() throws IOException {
"process_start_time_seconds 37.1\n" +
"# EOF\n";
- Assert.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
+ Assertions.assertEquals(expected, convertToOpenMetricsFormat(snapshots));
}
@Test
- public void testIgnoredMetricNotScraped() {
+ void testIgnoredMetricNotScraped() {
MetricNameFilter filter = MetricNameFilter.builder()
.nameMustNotBeEqualTo("process_max_fds")
.build();
diff --git a/prometheus-metrics-model/pom.xml b/prometheus-metrics-model/pom.xml
index f45d5b6fb..a73132d62 100644
--- a/prometheus-metrics-model/pom.xml
+++ b/prometheus-metrics-model/pom.xml
@@ -39,9 +39,8 @@
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-engine
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 91bcf74fc..92a88c835 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
@@ -2,31 +2,23 @@
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.Labels;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.function.Predicate;
-
-public class MetricNameFilterTest {
+class MetricNameFilterTest {
private PrometheusRegistry registry;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
registry = new PrometheusRegistry();
}
@Test
- public void testCounter() {
+ void testCounter() {
registry.register(() -> CounterSnapshot.builder()
.name("counter1")
.help("test counter 1")
@@ -53,28 +45,28 @@ public void testCounter() {
);
MetricNameFilter filter = MetricNameFilter.builder().build();
- Assert.assertEquals(2, registry.scrape(filter).size());
+ Assertions.assertEquals(2, registry.scrape(filter).size());
filter = MetricNameFilter.builder().nameMustStartWith("counter1").build();
MetricSnapshots snapshots = registry.scrape(filter);
- Assert.assertEquals(1, snapshots.size());
- Assert.assertEquals("counter1", snapshots.get(0).getMetadata().getName());
+ Assertions.assertEquals(1, snapshots.size());
+ Assertions.assertEquals("counter1", snapshots.get(0).getMetadata().getName());
filter = MetricNameFilter.builder().nameMustNotStartWith("counter1").build();
snapshots = registry.scrape(filter);
- Assert.assertEquals(1, snapshots.size());
- Assert.assertEquals("counter2", snapshots.get(0).getMetadata().getName());
+ Assertions.assertEquals(1, snapshots.size());
+ Assertions.assertEquals("counter2", snapshots.get(0).getMetadata().getName());
filter = MetricNameFilter.builder()
.nameMustBeEqualTo("counter2_total", "counter1_total")
.build();
snapshots = registry.scrape(filter);
- Assert.assertEquals(2, snapshots.size());
+ Assertions.assertEquals(2, snapshots.size());
filter = MetricNameFilter.builder()
.nameMustBeEqualTo("counter1_total")
.nameMustNotBeEqualTo("counter1_total")
.build();
- Assert.assertEquals(0, registry.scrape(filter).size());
+ Assertions.assertEquals(0, registry.scrape(filter).size());
}
}
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 b36d58aa6..eacda5326 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
@@ -5,9 +5,9 @@
import io.prometheus.metrics.model.snapshots.GaugeSnapshot;
import io.prometheus.metrics.model.snapshots.GaugeSnapshot.GaugeDataPointSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -15,15 +15,15 @@
import java.util.List;
import java.util.function.Predicate;
-public class MultiCollectorNameFilterTest {
+class MultiCollectorNameFilterTest {
private PrometheusRegistry registry;
private boolean[] collectCalled = {false};
private Predicate includedNames = null;
List prometheusNames = new ArrayList<>();
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
registry = new PrometheusRegistry();
collectCalled[0] = false;
includedNames = null;
@@ -55,46 +55,46 @@ public List getPrometheusNames() {
}
@Test
- public void testPartialFilter() {
+ 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());
+ Assertions.assertTrue(collectCalled[0]);
+ Assertions.assertEquals(1, snapshots.size());
+ Assertions.assertEquals("counter_1", snapshots.get(0).getMetadata().getName());
}
@Test
- public void testPartialFilterWithPrometheusNames() {
+ void testPartialFilterWithPrometheusNames() {
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());
+ Assertions.assertTrue(collectCalled[0]);
+ Assertions.assertEquals(1, snapshots.size());
+ Assertions.assertEquals("counter_1", snapshots.get(0).getMetadata().getName());
}
@Test
- public void testCompleteFilter_CollectCalled() {
+ 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());
+ Assertions.assertTrue(collectCalled[0]);
+ Assertions.assertEquals(0, snapshots.size());
}
@Test
- public void testCompleteFilter_CollectNotCalled() {
+ 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());
+ Assertions.assertFalse(collectCalled[0]);
+ Assertions.assertEquals(0, snapshots.size());
}
}
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 498d2354b..4054e2731 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
@@ -4,10 +4,10 @@
import io.prometheus.metrics.model.snapshots.GaugeSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-public class PrometheusRegistryTest {
+class PrometheusRegistryTest {
Collector noName = () -> GaugeSnapshot.builder()
.name("no_name_gauge")
@@ -62,7 +62,7 @@ public String getPrometheusName() {
};
@Test
- public void registerNoName() {
+ void registerNoName() {
PrometheusRegistry registry = new PrometheusRegistry();
// If the collector does not have a name at registration time, there is no conflict during registration.
registry.register(noName);
@@ -71,34 +71,34 @@ public void registerNoName() {
try {
registry.scrape();
} catch (IllegalStateException e) {
- Assert.assertTrue(e.getMessage().contains("duplicate") && e.getMessage().contains("no_name_gauge"));
+ Assertions.assertTrue(e.getMessage().contains("duplicate") && e.getMessage().contains("no_name_gauge"));
return;
}
- Assert.fail("Expected duplicate name exception");
+ Assertions.fail("Expected duplicate name exception");
}
- @Test(expected = IllegalStateException.class)
- public void registerDuplicateName() {
+ @Test
+ void registerDuplicateName() {
PrometheusRegistry registry = new PrometheusRegistry();
registry.register(counterA1);
- registry.register(counterA2);
+ Assertions.assertThrows(IllegalStateException.class, () -> registry.register(counterA2));
}
@Test
- public void registerOk() {
+ void registerOk() {
PrometheusRegistry registry = new PrometheusRegistry();
registry.register(counterA1);
registry.register(counterB);
registry.register(gaugeA);
MetricSnapshots snapshots = registry.scrape();
- Assert.assertEquals(3, snapshots.size());
+ Assertions.assertEquals(3, snapshots.size());
registry.unregister(counterB);
snapshots = registry.scrape();
- Assert.assertEquals(2, snapshots.size());
+ Assertions.assertEquals(2, snapshots.size());
registry.register(counterB);
snapshots = registry.scrape();
- Assert.assertEquals(3, snapshots.size());
+ Assertions.assertEquals(3, snapshots.size());
}
}
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 78bf8c564..dd2cd5862 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,95 +1,101 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-public class ClassicHistogramBucketsTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class ClassicHistogramBucketsTest {
@Test
- public void testGoodCase() {
+ void testGoodCase() {
ClassicHistogramBuckets buckets = ClassicHistogramBuckets.builder()
.bucket(Double.NEGATIVE_INFINITY, 0)
.bucket(-10.0, 7)
.bucket(1024, 3)
.bucket(Double.POSITIVE_INFINITY, 8)
.build();
- Assert.assertEquals(4, buckets.size());
+ Assertions.assertEquals(4, buckets.size());
}
@Test
- public void testSort() {
+ void testSort() {
ClassicHistogramBuckets buckets = ClassicHistogramBuckets.builder()
.bucket(7, 2)
.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));
+ Assertions.assertEquals(3, buckets.size());
+ Assertions.assertEquals(2, buckets.getUpperBound(0), 0.0);
+ Assertions.assertEquals(7, buckets.getUpperBound(1), 0.0);
+ Assertions.assertEquals(Double.POSITIVE_INFINITY, buckets.getUpperBound(2), 0.0);
+ Assertions.assertEquals(0, buckets.getCount(0));
+ Assertions.assertEquals(2, buckets.getCount(1));
+ Assertions.assertEquals(3, buckets.getCount(2));
}
@Test
- public void testMinimalBuckets() {
+ void testMinimalBuckets() {
ClassicHistogramBuckets buckets = ClassicHistogramBuckets.builder()
.bucket(Double.POSITIVE_INFINITY, 0)
.build();
- Assert.assertEquals(1, buckets.size());
+ Assertions.assertEquals(1, buckets.size());
}
- @Test(expected = IllegalArgumentException.class)
- public void testInfBucketMissing() {
- ClassicHistogramBuckets.builder()
- .bucket(Double.NEGATIVE_INFINITY, 0)
- .build();
+ @Test
+ void testInfBucketMissing() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ClassicHistogramBuckets.builder()
+ .bucket(Double.NEGATIVE_INFINITY, 0)
+ .build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testNegativeCount() {
- ClassicHistogramBuckets.builder()
- .bucket(0.0, 10)
- .bucket(Double.POSITIVE_INFINITY, -1)
- .build();
+ @Test
+ void testNegativeCount() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ClassicHistogramBuckets.builder()
+ .bucket(0.0, 10)
+ .bucket(Double.POSITIVE_INFINITY, -1)
+ .build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testNaNBoundary() {
- ClassicHistogramBuckets.builder()
- .bucket(0.0, 1)
- .bucket(Double.NaN, 2)
- .bucket(Double.POSITIVE_INFINITY, 0)
- .build();
+ @Test
+ void testNaNBoundary() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ClassicHistogramBuckets.builder()
+ .bucket(0.0, 1)
+ .bucket(Double.NaN, 2)
+ .bucket(Double.POSITIVE_INFINITY, 0)
+ .build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testDuplicateBoundary() {
- ClassicHistogramBuckets.builder()
- .bucket(1.0, 1)
- .bucket(2.0, 2)
- .bucket(1.0, 2)
- .bucket(Double.POSITIVE_INFINITY, 0)
- .build();
+ @Test
+ void testDuplicateBoundary() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ClassicHistogramBuckets.builder()
+ .bucket(1.0, 1)
+ .bucket(2.0, 2)
+ .bucket(1.0, 2)
+ .bucket(Double.POSITIVE_INFINITY, 0)
+ .build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testEmptyBuckets() {
- ClassicHistogramBuckets.builder().build();
+ @Test
+ void testEmptyBuckets() {
+ assertThrows(IllegalArgumentException.class, () -> ClassicHistogramBuckets.builder().build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testDifferentLength() {
+ @Test
+ 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);
+ assertThrows(IllegalArgumentException.class, () -> ClassicHistogramBuckets.of(upperBounds, counts));
}
- @Test(expected = UnsupportedOperationException.class)
- public void testImmutable() {
+ @Test
+ void testImmutable() {
ClassicHistogramBuckets buckets = ClassicHistogramBuckets.builder()
.bucket(1.0, 7)
.bucket(2.0, 8)
@@ -97,6 +103,6 @@ public void testImmutable() {
.build();
Iterator iterator = buckets.iterator();
iterator.next();
- iterator.remove();
+ assertThrows(UnsupportedOperationException.class, 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 b990de196..a5866f22d 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,16 +1,18 @@
package io.prometheus.metrics.model.snapshots;
import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
-public class CounterSnapshotTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class CounterSnapshotTest {
@Test
- public void testCompleteGoodCase() {
+ void testCompleteGoodCase() {
long createdTimestamp1 = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1);
long createdTimestamp2 = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(2);
long exemplarTimestamp = System.currentTimeMillis();
@@ -47,55 +49,55 @@ public void testCompleteGoodCase() {
)
.build();
SnapshotTestUtil.assertMetadata(snapshot, "http_server_requests_seconds", "total time spent serving requests", "seconds");
- Assert.assertEquals(2, snapshot.getDataPoints().size());
+ Assertions.assertEquals(2, snapshot.getDataPoints().size());
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());
+ Assertions.assertEquals(Labels.of("path", "/hello"), data.getLabels());
+ Assertions.assertEquals(2.0, data.getValue(), 0.0);
+ Assertions.assertEquals(4.0, data.getExemplar().getValue(), 0.0);
+ Assertions.assertEquals(createdTimestamp2, data.getCreatedTimestampMillis());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
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());
+ Assertions.assertEquals(Labels.of("path", "/world"), data.getLabels());
+ Assertions.assertEquals(1.0, data.getValue(), 0.0);
+ Assertions.assertEquals(3.0, data.getExemplar().getValue(), 0.0);
+ Assertions.assertEquals(createdTimestamp1, data.getCreatedTimestampMillis());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
}
@Test
- public void testMinimalGoodCase() {
+ void testMinimalGoodCase() {
CounterSnapshot snapshot = CounterSnapshot.builder()
.name("events")
.dataPoint(CounterDataPointSnapshot.builder().value(1.0).build())
.build();
SnapshotTestUtil.assertMetadata(snapshot, "events", null, null);
- Assert.assertEquals(1, snapshot.getDataPoints().size());
+ Assertions.assertEquals(1, snapshot.getDataPoints().size());
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());
+ Assertions.assertEquals(Labels.EMPTY, data.getLabels());
+ Assertions.assertEquals(1.0, data.getValue(), 0.0);
+ Assertions.assertNull(data.getExemplar());
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
}
@Test
- public void testEmptyCounter() {
+ void testEmptyCounter() {
CounterSnapshot snapshot = CounterSnapshot.builder().name("events").build();
- Assert.assertEquals(0, snapshot.getDataPoints().size());
+ Assertions.assertEquals(0, snapshot.getDataPoints().size());
}
- @Test(expected = IllegalArgumentException.class)
- public void testTotalSuffixPresent() {
- CounterSnapshot.builder().name("test_total").build();
+ @Test
+ void testTotalSuffixPresent() {
+ assertThrows(IllegalArgumentException.class, () -> CounterSnapshot.builder().name("test_total").build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testValueMissing() {
- CounterDataPointSnapshot.builder().build();
+ @Test
+ void testValueMissing() {
+ assertThrows(IllegalArgumentException.class, () -> CounterDataPointSnapshot.builder().build());
}
- @Test(expected = UnsupportedOperationException.class)
- public void testDataImmutable() {
+ @Test
+ void testDataImmutable() {
CounterSnapshot snapshot = CounterSnapshot.builder()
.name("events")
.dataPoint(CounterDataPointSnapshot.builder().labels(Labels.of("a", "a")).value(1.0).build())
@@ -103,6 +105,6 @@ public void testDataImmutable() {
.build();
Iterator iterator = snapshot.getDataPoints().iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, 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 84134b6b3..83705c4de 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,12 +1,12 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-public class ExemplarTest {
+class ExemplarTest {
@Test
- public void testGoodCaseComplete() {
+ void testGoodCaseComplete() {
long timestamp = System.currentTimeMillis();
Exemplar exemplar = Exemplar.builder()
.value(2.2)
@@ -15,62 +15,62 @@ 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());
+ Assertions.assertEquals(2.2, exemplar.getValue(), 0.0);
+ Assertions.assertEquals(Labels.of(Exemplar.TRACE_ID, "abc123abc123", Exemplar.SPAN_ID, "def456def456", "path", "/", "error", "none"), exemplar.getLabels());
+ Assertions.assertTrue(exemplar.hasTimestamp());
+ Assertions.assertEquals(timestamp, exemplar.getTimestampMillis());
}
- @Test(expected = IllegalStateException.class)
- public void testValueMissing() {
- Exemplar.builder().build();
+ @Test
+ void testValueMissing() {
+ Assertions.assertThrows(IllegalStateException.class, () -> Exemplar.builder().build());
}
@Test
- public void testMinimal() {
+ 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());
+ Assertions.assertEquals(0.0, exemplar.getValue(), 0.0);
+ Assertions.assertEquals(Labels.EMPTY, exemplar.getLabels());
+ Assertions.assertFalse(exemplar.hasTimestamp());
}
@Test
- public void testLabelsMergeTraceId() {
+ 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());
+ Assertions.assertEquals(Labels.of("a", "b", "trace_id", "abc"), exemplar.getLabels());
}
@Test
- public void testLabelsMergeSpanId() {
+ 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());
+ Assertions.assertEquals(Labels.of("a", "b", "span_id", "abc"), exemplar.getLabels());
}
@Test
- public void testLabelsMergeTraceIdAndSpanId() {
+ void testLabelsMergeTraceIdAndSpanId() {
Exemplar exemplar = Exemplar.builder()
.value(0.0)
.labels(Labels.of("a", "b"))
.spanId("abc")
.traceId("def")
.build();
- Assert.assertEquals(Labels.of("span_id", "abc", "a", "b", "trace_id", "def"), exemplar.getLabels());
+ Assertions.assertEquals(Labels.of("span_id", "abc", "a", "b", "trace_id", "def"), exemplar.getLabels());
}
@Test
- public void testLabelsMergeNone() {
+ void testLabelsMergeNone() {
Exemplar exemplar = Exemplar.builder()
.value(0.0)
.labels(Labels.of("a", "b"))
.build();
- Assert.assertEquals(Labels.of("a", "b"), exemplar.getLabels());
+ Assertions.assertEquals(Labels.of("a", "b"), exemplar.getLabels());
}
}
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 5549c0efd..c700f69f5 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,33 +1,33 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-public class ExemplarsTest {
+class ExemplarsTest {
@Test
- public void testUpperBound() {
+ void testUpperBound() {
Exemplars exemplars = Exemplars.of(
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));
+ Assertions.assertEquals(3, exemplars.size());
+ Assertions.assertEquals(1.0, exemplars.get(0).getValue(), 0.0);
+ Assertions.assertEquals(3.0, exemplars.get(1).getValue(), 0.0);
+ Assertions.assertEquals(2.0, exemplars.get(2).getValue(), 0.0);
+ Assertions.assertEquals(1.0, exemplars.get(0.0, Double.POSITIVE_INFINITY).getValue(), 0.0);
+ Assertions.assertEquals(1.0, exemplars.get(0.0, 1.0).getValue(), 0.0);
+ Assertions.assertEquals(3.0, exemplars.get(1.0, 4.0).getValue(), 0.0);
+ Assertions.assertEquals(3.0, exemplars.get(2.0, 3.0).getValue(), 0.0);
+ Assertions.assertEquals(2.0, exemplars.get(1.0, 2.1).getValue(), 0.0);
+ Assertions.assertNull(exemplars.get(2.0, 2.1));
}
- @Test(expected = UnsupportedOperationException.class)
- public void testImmutable() {
+ @Test
+ void testImmutable() {
Exemplars exemplars = Exemplars.of(
Exemplar.builder().value(1.0).build(),
Exemplar.builder().value(3.0).build(),
@@ -35,6 +35,6 @@ public void testImmutable() {
);
Iterator iterator = exemplars.iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, iterator::remove);
}
}
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 b64298529..09919afda 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
@@ -2,15 +2,17 @@
import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot;
import io.prometheus.metrics.model.snapshots.GaugeSnapshot.GaugeDataPointSnapshot;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-public class GaugeSnapshotTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class GaugeSnapshotTest {
@Test
- public void testCompleteGoodCase() {
+ void testCompleteGoodCase() {
long exemplarTimestamp = System.currentTimeMillis();
GaugeSnapshot snapshot = GaugeSnapshot.builder()
.name("cache_size_bytes")
@@ -43,62 +45,62 @@ public void testCompleteGoodCase() {
)
.build();
SnapshotTestUtil.assertMetadata(snapshot, "cache_size_bytes", "cache size in Bytes", "bytes");
- Assert.assertEquals(2, snapshot.getDataPoints().size());
+ Assertions.assertEquals(2, snapshot.getDataPoints().size());
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());
+ Assertions.assertEquals(Labels.of("env", "dev"), data.getLabels());
+ Assertions.assertEquals(128.0, data.getValue(), 0.0);
+ Assertions.assertEquals(128.0, data.getExemplar().getValue(), 0.0);
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
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());
+ Assertions.assertEquals(Labels.of("env", "prod"), data.getLabels());
+ Assertions.assertEquals(1024.0, data.getValue(), 0.0);
+ Assertions.assertEquals(1024.0, data.getExemplar().getValue(), 0.0);
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
}
@Test
- public void testMinimalGoodCase() {
+ void testMinimalGoodCase() {
GaugeSnapshot snapshot = GaugeSnapshot.builder()
.name("temperature")
.dataPoint(GaugeDataPointSnapshot.builder().value(23.0).build())
.build();
SnapshotTestUtil.assertMetadata(snapshot, "temperature", null, null);
- Assert.assertEquals(1, snapshot.getDataPoints().size());
+ Assertions.assertEquals(1, snapshot.getDataPoints().size());
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());
+ Assertions.assertEquals(Labels.EMPTY, data.getLabels());
+ Assertions.assertEquals(23.0, data.getValue(), 0.0);
+ Assertions.assertNull(data.getExemplar());
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
}
@Test
- public void testEmptyGauge() {
+ void testEmptyGauge() {
GaugeSnapshot snapshot = GaugeSnapshot.builder()
.name("temperature")
.build();
- Assert.assertEquals(0, snapshot.getDataPoints().size());
+ Assertions.assertEquals(0, snapshot.getDataPoints().size());
}
- @Test(expected = IllegalArgumentException.class)
- public void testTotalSuffixPresent() {
- CounterSnapshot.builder().name("test_total").build();
+ @Test
+ void testTotalSuffixPresent() {
+ assertThrows(IllegalArgumentException.class, () -> CounterSnapshot.builder().name("test_total").build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testTotalSuffixPresentDot() {
- CounterSnapshot.builder().name("test.total").build();
+ @Test
+ void testTotalSuffixPresentDot() {
+ assertThrows(IllegalArgumentException.class, () -> CounterSnapshot.builder().name("test.total").build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testValueMissing() {
- CounterDataPointSnapshot.builder().build();
+ @Test
+ void testValueMissing() {
+ assertThrows(IllegalArgumentException.class, () -> CounterDataPointSnapshot.builder().build());
}
- @Test(expected = UnsupportedOperationException.class)
- public void testDataImmutable() {
+ @Test
+ void testDataImmutable() {
GaugeSnapshot snapshot = GaugeSnapshot.builder()
.name("gauge")
.dataPoint(GaugeDataPointSnapshot.builder().labels(Labels.of("a", "a")).value(23.0).build())
@@ -106,6 +108,6 @@ public void testDataImmutable() {
.build();
Iterator iterator = snapshot.getDataPoints().iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, 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 5ff838dd7..aed57fb6b 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,16 +1,18 @@
package io.prometheus.metrics.model.snapshots;
import io.prometheus.metrics.model.snapshots.HistogramSnapshot.HistogramDataPointSnapshot;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
-public class HistogramSnapshotTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class HistogramSnapshotTest {
@Test
- public void testGoodCaseComplete() {
+ void testGoodCaseComplete() {
long createdTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1);
long scrapeTimestamp = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(2);
long exemplarTimestamp = System.currentTimeMillis();
@@ -76,94 +78,94 @@ public void testGoodCaseComplete() {
.build();
SnapshotTestUtil.assertMetadata(snapshot, "request_size_bytes", "request sizes in bytes", "bytes");
- Assert.assertEquals(2, snapshot.getDataPoints().size());
+ Assertions.assertEquals(2, snapshot.getDataPoints().size());
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());
+ Assertions.assertTrue(data.hasSum());
+ Assertions.assertTrue(data.hasCount());
+ Assertions.assertTrue(data.hasCreatedTimestamp());
+ Assertions.assertTrue(data.hasScrapeTimestamp());
+ Assertions.assertEquals(22, data.getCount());
+ Assertions.assertEquals(27000.0, data.getSum(), 0.0);
+ Assertions.assertEquals(Labels.of("path", "/"), data.getLabels());
+ Assertions.assertEquals(exemplar1.getValue(), data.getExemplars().get(128.0, 1024.0).getValue(), 0.0);
+ Assertions.assertEquals(createdTimestamp, data.getCreatedTimestampMillis());
+ Assertions.assertEquals(scrapeTimestamp, data.getScrapeTimestampMillis());
// 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());
+ Assertions.assertEquals(128.0, bucket.getUpperBound(), 0.0);
+ Assertions.assertEquals(7, bucket.getCount());
break;
case 1:
- Assert.assertEquals(1024.0, bucket.getUpperBound(), 0.0);
- Assert.assertEquals(15, bucket.getCount());
+ Assertions.assertEquals(1024.0, bucket.getUpperBound(), 0.0);
+ Assertions.assertEquals(15, bucket.getCount());
break;
case 2:
- Assert.assertEquals(Double.POSITIVE_INFINITY, bucket.getUpperBound(), 0.0);
- Assert.assertEquals(0, bucket.getCount());
+ Assertions.assertEquals(Double.POSITIVE_INFINITY, bucket.getUpperBound(), 0.0);
+ Assertions.assertEquals(0, bucket.getCount());
break;
}
}
- Assert.assertEquals("expecting 3 classic histogram buckets", 3, i);
+ Assertions.assertEquals(3, i, "expecting 3 classic histogram buckets");
// 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());
+ Assertions.assertEquals(5, data.getNativeSchema());
+ Assertions.assertEquals(2, data.getNativeZeroCount());
+ Assertions.assertEquals(0.0000001, data.getNativeZeroThreshold(), 0.0000001);
+ Assertions.assertEquals(3, data.getNativeBucketsForPositiveValues().size());
i = 0;
for (NativeHistogramBucket bucket : data.getNativeBucketsForPositiveValues()) {
switch (i++) {
case 0:
- Assert.assertEquals(1, bucket.getBucketIndex());
- Assert.assertEquals(12, bucket.getCount());
+ Assertions.assertEquals(1, bucket.getBucketIndex());
+ Assertions.assertEquals(12, bucket.getCount());
break;
case 1:
- Assert.assertEquals(2, bucket.getBucketIndex());
- Assert.assertEquals(3, bucket.getCount());
+ Assertions.assertEquals(2, bucket.getBucketIndex());
+ Assertions.assertEquals(3, bucket.getCount());
break;
case 2:
- Assert.assertEquals(4, bucket.getBucketIndex());
- Assert.assertEquals(2, bucket.getCount());
+ Assertions.assertEquals(4, bucket.getBucketIndex());
+ Assertions.assertEquals(2, bucket.getCount());
break;
}
}
- Assert.assertEquals("expecting 3 native buckets for positive values", 3, i);
+ Assertions.assertEquals(3, i, "expecting 3 native buckets for positive values");
i = 0;
- Assert.assertEquals(2, data.getNativeBucketsForNegativeValues().size());
+ Assertions.assertEquals(2, data.getNativeBucketsForNegativeValues().size());
for (NativeHistogramBucket bucket : data.getNativeBucketsForNegativeValues()) {
switch (i++) {
case 0:
- Assert.assertEquals(-1, bucket.getBucketIndex());
- Assert.assertEquals(1, bucket.getCount());
+ Assertions.assertEquals(-1, bucket.getBucketIndex());
+ Assertions.assertEquals(1, bucket.getCount());
break;
case 1:
- Assert.assertEquals(0, bucket.getBucketIndex());
- Assert.assertEquals(2, bucket.getCount());
+ Assertions.assertEquals(0, bucket.getBucketIndex());
+ Assertions.assertEquals(2, bucket.getCount());
break;
}
}
- Assert.assertEquals("expecting 2 native buckets for positive values", 2, i);
+ Assertions.assertEquals(2, i, "expecting 2 native buckets for positive values");
// 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());
+ Assertions.assertEquals(6, data.getCount());
// 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);
+ Assertions.assertEquals(5, data.getNativeSchema());
+ Assertions.assertEquals(0, data.getNativeZeroCount());
+ Assertions.assertEquals(0, data.getNativeZeroThreshold(), 0);
}
@Test
- public void testEmptyHistogram() {
+ void testEmptyHistogram() {
HistogramSnapshot snapshot = HistogramSnapshot.builder()
.name("empty_histogram")
.build();
- Assert.assertEquals(0, snapshot.getDataPoints().size());
+ Assertions.assertEquals(0, snapshot.getDataPoints().size());
}
@Test
- public void testMinimalClassicHistogram() {
+ void testMinimalClassicHistogram() {
HistogramSnapshot snapshot = HistogramSnapshot.builder()
.name("minimal_histogram")
.dataPoint(HistogramDataPointSnapshot.builder()
@@ -171,33 +173,33 @@ public void testMinimalClassicHistogram() {
.build())
.build();
HistogramDataPointSnapshot data = snapshot.getDataPoints().get(0);
- Assert.assertFalse(data.hasSum());
- Assert.assertEquals(1, snapshot.getDataPoints().get(0).getClassicBuckets().size());
+ Assertions.assertFalse(data.hasSum());
+ Assertions.assertEquals(1, snapshot.getDataPoints().get(0).getClassicBuckets().size());
}
@Test
- public void testMinimalNativeHistogram() {
+ void testMinimalNativeHistogram() {
HistogramSnapshot snapshot = HistogramSnapshot.builder()
.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());
+ Assertions.assertEquals("hist", snapshot.getMetadata().getName());
+ Assertions.assertFalse(snapshot.getMetadata().hasUnit());
+ Assertions.assertEquals(1, snapshot.getDataPoints().size());
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());
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
+ Assertions.assertTrue(data.hasCount());
+ Assertions.assertEquals(0, data.getCount());
+ Assertions.assertFalse(data.hasSum());
+ Assertions.assertEquals(0, data.getNativeBucketsForNegativeValues().size());
+ Assertions.assertEquals(0, data.getNativeBucketsForPositiveValues().size());
}
@Test
- public void testClassicCount() {
+ void testClassicCount() {
HistogramSnapshot snapshot = HistogramSnapshot.builder()
.name("test_histogram")
.dataPoint(HistogramDataPointSnapshot.builder()
@@ -209,28 +211,28 @@ public void testClassicCount() {
.build())
.build();
HistogramDataPointSnapshot data = snapshot.getDataPoints().get(0);
- Assert.assertFalse(data.hasSum());
- Assert.assertTrue(data.hasCount());
- Assert.assertEquals(5, data.getCount());
+ Assertions.assertFalse(data.hasSum());
+ Assertions.assertTrue(data.hasCount());
+ Assertions.assertEquals(5, data.getCount());
}
- @Test(expected = IllegalArgumentException.class)
- public void testEmptyData() {
+ @Test
+ void testEmptyData() {
// This will fail because one of nativeSchema and classicHistogramBuckets is required
- HistogramDataPointSnapshot.builder().build();
+ assertThrows(IllegalArgumentException.class, () -> HistogramDataPointSnapshot.builder().build());
}
@Test
- public void testEmptyNativeData() {
+ void testEmptyNativeData() {
HistogramDataPointSnapshot data = HistogramDataPointSnapshot.builder()
.nativeSchema(5)
.build();
- Assert.assertEquals(0, data.getNativeBucketsForNegativeValues().size());
- Assert.assertEquals(0, data.getNativeBucketsForPositiveValues().size());
+ Assertions.assertEquals(0, data.getNativeBucketsForNegativeValues().size());
+ Assertions.assertEquals(0, data.getNativeBucketsForPositiveValues().size());
}
- @Test(expected = UnsupportedOperationException.class)
- public void testDataImmutable() {
+ @Test
+ void testDataImmutable() {
HistogramSnapshot snapshot = HistogramSnapshot.builder()
.name("test_histogram")
.dataPoint(HistogramDataPointSnapshot.builder()
@@ -244,22 +246,22 @@ public void testDataImmutable() {
.build();
Iterator iterator = snapshot.getDataPoints().iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, iterator::remove);
}
- @Test(expected = IllegalArgumentException.class)
- public void testEmptyClassicBuckets() {
- new HistogramDataPointSnapshot(ClassicHistogramBuckets.EMPTY, Double.NaN, Labels.EMPTY, Exemplars.EMPTY, 0L);
+ @Test
+ void testEmptyClassicBuckets() {
+ assertThrows(IllegalArgumentException.class, () -> new HistogramDataPointSnapshot(ClassicHistogramBuckets.EMPTY, Double.NaN, Labels.EMPTY, Exemplars.EMPTY, 0L));
}
@Test
- public void testMinimalNativeData() {
+ void testMinimalNativeData() {
new HistogramDataPointSnapshot(ClassicHistogramBuckets.EMPTY, 0, 0, 0.0,
NativeHistogramBuckets.EMPTY, NativeHistogramBuckets.EMPTY, Double.NaN, Labels.EMPTY, Exemplars.EMPTY, 0L);
}
@Test
- public void testMinimalClassicData() {
+ void testMinimalClassicData() {
ClassicHistogramBuckets buckets = ClassicHistogramBuckets.builder()
.bucket(Double.POSITIVE_INFINITY, 0)
.build();
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 dd4f2f0cb..1f38131ea 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,14 +1,16 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-public class InfoSnapshotTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class InfoSnapshotTest {
@Test
- public void testCompleteGoodCase() {
+ void testCompleteGoodCase() {
InfoSnapshot snapshot = InfoSnapshot.builder()
.name("target")
.help("Target info")
@@ -16,20 +18,20 @@ 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());
+ Assertions.assertEquals("target", snapshot.getMetadata().getName());
+ Assertions.assertEquals("Target info", snapshot.getMetadata().getHelp());
+ Assertions.assertFalse(snapshot.getMetadata().hasUnit());
+ Assertions.assertEquals(1, snapshot.getDataPoints().size());
}
@Test
- public void testEmptyInfo() {
+ void testEmptyInfo() {
InfoSnapshot snapshot = InfoSnapshot.builder().name("target").build();
- Assert.assertEquals(0, snapshot.getDataPoints().size());
+ Assertions.assertEquals(0, snapshot.getDataPoints().size());
}
- @Test(expected = UnsupportedOperationException.class)
- public void testDataImmutable() {
+ @Test
+ void testDataImmutable() {
InfoSnapshot snapshot = InfoSnapshot.builder()
.name("target")
.dataPoint(InfoSnapshot.InfoDataPointSnapshot.builder()
@@ -41,20 +43,22 @@ public void testDataImmutable() {
.build();
Iterator iterator = snapshot.getDataPoints().iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, iterator::remove);
}
- @Test(expected = IllegalArgumentException.class)
- public void testNameMustNotIncludeSuffix() {
- InfoSnapshot.builder()
- .name("jvm_info")
- .build();
+ @Test
+ void testNameMustNotIncludeSuffix() {
+ assertThrows(IllegalArgumentException.class,
+ () -> InfoSnapshot.builder()
+ .name("jvm_info")
+ .build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testNameMustNotIncludeSuffixDot() {
- InfoSnapshot.builder()
- .name("jvm.info")
- .build();
+ @Test
+ void testNameMustNotIncludeSuffixDot() {
+ assertThrows(IllegalArgumentException.class,
+ () -> 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 d7a3e8b3e..50178bf79 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,25 +1,23 @@
package io.prometheus.metrics.model.snapshots;
-import io.prometheus.metrics.model.snapshots.Labels;
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-import static io.prometheus.metrics.model.snapshots.PrometheusNaming.sanitizeLabelName;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-public class LabelsTest {
+class LabelsTest {
private > void assertLessThan(T a, T b) {
- Assert.assertTrue(a.compareTo(b) < 0);
+ Assertions.assertTrue(a.compareTo(b) < 0);
}
private > void assertGreaterThan(T a, T b) {
- Assert.assertTrue(a.compareTo(b) > 0);
+ Assertions.assertTrue(a.compareTo(b) > 0);
}
@Test
- public void testCompareDifferentLabelNames() {
+ void testCompareDifferentLabelNames() {
Labels labels1 = Labels.of("env", "prod", "status2", "200");
Labels labels2 = Labels.of("env", "prod", "status1", "200");
assertGreaterThan(labels1, labels2);
@@ -29,7 +27,7 @@ public void testCompareDifferentLabelNames() {
}
@Test
- public void testCompareSameLabelNames() {
+ void testCompareSameLabelNames() {
// If all label names are the same, labels should be sorted by label value.
Labels labels1 = Labels.of("env", "prod", "status", "200");
Labels labels2 = Labels.of("env", "prod", "status", "500");
@@ -40,7 +38,7 @@ public void testCompareSameLabelNames() {
}
@Test
- public void testCompareDifferentNumberOfLabels() {
+ void testCompareDifferentNumberOfLabels() {
Labels labels1 = Labels.of("env", "prod", "status", "200");
Labels labels2 = Labels.of("env", "prod", "status", "200", "x_code", "none");
assertLessThan(labels1, labels2);
@@ -50,82 +48,82 @@ public void testCompareDifferentNumberOfLabels() {
}
@Test
- public void testComparePrometheusNames() {
+ void testComparePrometheusNames() {
Labels labels1 = Labels.of("my_a", "val");
Labels labels2 = Labels.of("my.b", "val");
assertLessThan(labels1, labels2); // this is true because it compares "my_a" to "my_b".
}
@Test
- public void testEqualsHashcodeDots() {
+ 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());
+ Assertions.assertEquals(labels1, labels2);
+ Assertions.assertEquals(labels1.hashCode(), labels2.hashCode());
}
@Test
- public void testCompareEquals() {
+ 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);
+ Assertions.assertEquals(0, labels1.compareTo(labels2));
+ Assertions.assertEquals(0, labels2.compareTo(labels1));
+ Assertions.assertEquals(labels1, labels2);
+ Assertions.assertEquals(labels2, labels1);
}
- @Test(expected = IllegalArgumentException.class)
- public void testIllegalLabelName() {
- Labels.of("my_service/status", "200");
+ @Test
+ void testIllegalLabelName() {
+ assertThrows(IllegalArgumentException.class, () -> Labels.of("my_service/status", "200"));
}
- @Test(expected = IllegalArgumentException.class)
- public void testReservedLabelName() {
- Labels.of("__name__", "requests_total");
+ @Test
+ void testReservedLabelName() {
+ assertThrows(IllegalArgumentException.class, () -> Labels.of("__name__", "requests_total"));
}
- @Test(expected = IllegalArgumentException.class)
- public void testDuplicateLabelName() {
- Labels.of("name1", "value1", "name2", "value2", "name1", "value3");
+ @Test
+ void testDuplicateLabelName() {
+ assertThrows(IllegalArgumentException.class, () -> Labels.of("name1", "value1", "name2", "value2", "name1", "value3"));
}
@Test
- public void testMakePrometheusNames() {
+ void testMakePrometheusNames() {
String[] names = new String[]{};
String[] prometheusNames = Labels.makePrometheusNames(names);
- Assert.assertSame(names, prometheusNames);
+ Assertions.assertSame(names, prometheusNames);
names = new String[]{"no_dots", "at_all"};
prometheusNames = Labels.makePrometheusNames(names);
- Assert.assertSame(names, prometheusNames);
+ Assertions.assertSame(names, prometheusNames);
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]);
+ Assertions.assertNotSame(names, prometheusNames);
+ Assertions.assertSame(names[0], prometheusNames[0]);
+ Assertions.assertEquals("here.it.is", names[1]);
+ Assertions.assertEquals("here_it_is", prometheusNames[1]);
}
@Test
- public void testMerge() {
+ 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));
+ Assertions.assertEquals("key.1", merged.getName(0));
+ Assertions.assertEquals("key_2", merged.getName(1));
+ Assertions.assertEquals("key.3", merged.getName(2));
}
- @Test(expected = IllegalArgumentException.class)
- public void testMergeDuplicateName() {
+ @Test
+ void testMergeDuplicateName() {
Labels labels1 = Labels.of("key_one", "v1");
Labels labels2 = Labels.of("key.one", "v2");
- labels2.merge(labels1);
+ assertThrows(IllegalArgumentException.class, () -> labels2.merge(labels1));
}
- @Test(expected = IllegalArgumentException.class)
- public void testDuplicateName() {
- Labels.of("key_one", "v1", "key.one", "v2");
+ @Test
+ void testDuplicateName() {
+ assertThrows(IllegalArgumentException.class, () -> 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 6e76f724a..f386af4ed 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,57 +1,59 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
-import static io.prometheus.metrics.model.snapshots.PrometheusNaming.prometheusName;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
import static io.prometheus.metrics.model.snapshots.PrometheusNaming.sanitizeMetricName;
-public class MetricMetadataTest {
+class MetricMetadataTest {
+
+ @Test
+ void testEmptyName() {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new MetricMetadata(""));
- @Test(expected = IllegalArgumentException.class)
- public void testEmptyName() {
- new MetricMetadata("");
}
- @Test(expected = IllegalArgumentException.class)
- public void testNullName() {
- new MetricMetadata(null);
+ @Test
+ void testNullName() {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new MetricMetadata(null));
}
- @Test(expected = IllegalArgumentException.class)
- public void testIllegalName() {
- new MetricMetadata("my_namespace/http_server_duration"); // let's see when we decide to allow slashes :)
+ @Test
+ void testIllegalName() {
+ // let's see when we decide to allow slashes :)
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new MetricMetadata("my_namespace/http_server_duration"));
}
@Test
- public void testSanitizationIllegalCharacters() {
+ void testSanitizationIllegalCharacters() {
MetricMetadata metadata = new MetricMetadata(sanitizeMetricName("my_namespace/http.server.duration"), "help string", Unit.SECONDS);
- Assert.assertEquals("my_namespace_http.server.duration", metadata.getName());
- Assert.assertEquals("my_namespace_http_server_duration", metadata.getPrometheusName());
- Assert.assertEquals("help string", metadata.getHelp());
- Assert.assertEquals("seconds", metadata.getUnit().toString());
+ Assertions.assertEquals("my_namespace_http.server.duration", metadata.getName());
+ Assertions.assertEquals("my_namespace_http_server_duration", metadata.getPrometheusName());
+ Assertions.assertEquals("help string", metadata.getHelp());
+ Assertions.assertEquals("seconds", metadata.getUnit().toString());
}
@Test
- public void testSanitizationCounter() {
+ void testSanitizationCounter() {
MetricMetadata metadata = new MetricMetadata(sanitizeMetricName("my_events_total"));
- Assert.assertEquals("my_events", metadata.getName());
+ Assertions.assertEquals("my_events", metadata.getName());
}
@Test
- public void testSanitizationInfo() {
+ void testSanitizationInfo() {
MetricMetadata metadata = new MetricMetadata(sanitizeMetricName("target_info"));
- Assert.assertEquals("target", metadata.getName());
+ Assertions.assertEquals("target", metadata.getName());
}
@Test
- public void testSanitizationWeirdCornerCase() {
+ void testSanitizationWeirdCornerCase() {
MetricMetadata metadata = new MetricMetadata(sanitizeMetricName("_total_created"));
- Assert.assertEquals("total", metadata.getName());
+ Assertions.assertEquals("total", metadata.getName());
}
- @Test(expected = IllegalArgumentException.class)
- public void testSanitizeEmptyString() {
- sanitizeMetricName("");
+ @Test
+ void testSanitizeEmptyString() {
+ Assertions.assertThrows(IllegalArgumentException.class, () -> sanitizeMetricName(""));
}
}
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 acd659dbf..5b0d6e6c2 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,13 +1,14 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-public class MetricSnapshotTest {
+class MetricSnapshotTest {
- @Test(expected = IllegalArgumentException.class)
- public void testDuplicateLabels() {
- CounterSnapshot.builder()
+ @Test
+ void testDuplicateLabels() {
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
+ CounterSnapshot.builder()
.name("events")
.dataPoint(CounterSnapshot.CounterDataPointSnapshot.builder()
.labels(Labels.of("path", "/hello", "status", "200"))
@@ -21,17 +22,17 @@ public void testDuplicateLabels() {
.labels(Labels.of("status", "200", "path", "/hello"))
.value(3.0)
.build())
- .build();
+ .build());
}
@Test
- public void testNoData() {
+ void testNoData() {
MetricSnapshot snapshot = CounterSnapshot.builder().name("test").build();
- Assert.assertEquals(0, snapshot.getDataPoints().size());
+ Assertions.assertEquals(0, snapshot.getDataPoints().size());
}
- @Test(expected = NullPointerException.class)
- public void testNullData() {
- new CounterSnapshot(new MetricMetadata("test"), null);
+ @Test
+ void testNullData() {
+ Assertions.assertThrows(NullPointerException.class, () -> 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 61b54cb3a..512e43b71 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,20 +1,22 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-public class MetricSnapshotsTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class MetricSnapshotsTest {
@Test
- public void testEmpty() {
+ void testEmpty() {
MetricSnapshots snapshots = MetricSnapshots.builder().build();
- Assert.assertFalse(snapshots.stream().findAny().isPresent());
+ Assertions.assertFalse(snapshots.stream().findAny().isPresent());
}
@Test
- public void testSort() {
+ void testSort() {
CounterSnapshot c1 = CounterSnapshot.builder()
.name("counter1")
.dataPoint(CounterSnapshot.CounterDataPointSnapshot.builder().value(1.0).build())
@@ -28,14 +30,14 @@ 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());
+ Assertions.assertEquals(3, snapshots.size());
+ Assertions.assertEquals("counter1", snapshots.get(0).getMetadata().getName());
+ Assertions.assertEquals("counter2", snapshots.get(1).getMetadata().getName());
+ Assertions.assertEquals("counter3", snapshots.get(2).getMetadata().getName());
}
- @Test(expected = IllegalArgumentException.class)
- public void testDuplicateName() {
+ @Test
+ 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
// the values "foo_total" and "foo_created" while the gauge will produce the value "foo".
@@ -49,23 +51,23 @@ public void testDuplicateName() {
.name("my_metric")
.dataPoint(GaugeSnapshot.GaugeDataPointSnapshot.builder().value(1.0).build())
.build();
- new MetricSnapshots(c, g);
+ assertThrows(IllegalArgumentException.class, () -> new MetricSnapshots(c, g));
}
@Test
- public void testBuilder() {
+ void testBuilder() {
CounterSnapshot counter = CounterSnapshot.builder()
.name("my_metric")
.dataPoint(CounterSnapshot.CounterDataPointSnapshot.builder().value(1.0).build())
.build();
MetricSnapshots.Builder builder = MetricSnapshots.builder();
- Assert.assertFalse(builder.containsMetricName("my_metric"));
+ Assertions.assertFalse(builder.containsMetricName("my_metric"));
builder.metricSnapshot(counter);
- Assert.assertTrue(builder.containsMetricName("my_metric"));
+ Assertions.assertTrue(builder.containsMetricName("my_metric"));
}
- @Test(expected = UnsupportedOperationException.class)
- public void testImmutable() {
+ @Test
+ void testImmutable() {
CounterSnapshot c1 = CounterSnapshot.builder()
.name("counter1")
.dataPoint(CounterSnapshot.CounterDataPointSnapshot.builder().value(1.0).build())
@@ -81,6 +83,6 @@ public void testImmutable() {
MetricSnapshots snapshots = new MetricSnapshots(c2, c3, c1);
Iterator iterator = snapshots.iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, 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 3c031d682..945f8dcaf 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,63 +1,65 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-public class NativeHistogramBucketsTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class NativeHistogramBucketsTest {
@Test
- public void testGoodCase() {
+ 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));
+ Assertions.assertEquals(2, buckets.size());
+ Assertions.assertEquals(-10, buckets.getBucketIndex(0));
+ Assertions.assertEquals(12, buckets.getCount(0));
+ Assertions.assertEquals(120, buckets.getBucketIndex(1));
+ Assertions.assertEquals(17, buckets.getCount(1));
}
@Test
- public void testEmpty() {
+ void testEmpty() {
NativeHistogramBuckets buckets = NativeHistogramBuckets.builder().build();
- Assert.assertEquals(0, buckets.size());
+ Assertions.assertEquals(0, buckets.size());
}
@Test
- public void testSort() {
+ 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));
+ Assertions.assertEquals(3, buckets.size());
+ Assertions.assertEquals(2, buckets.getBucketIndex(0));
+ Assertions.assertEquals(5, buckets.getBucketIndex(1));
+ Assertions.assertEquals(7, buckets.getBucketIndex(2));
+ Assertions.assertEquals(0, buckets.getCount(0));
+ Assertions.assertEquals(3, buckets.getCount(1));
+ Assertions.assertEquals(4, buckets.getCount(2));
}
- @Test(expected = IllegalArgumentException.class)
- public void testDifferentLength() {
+ @Test
+ void testDifferentLength() {
int[] bucketIndexes = new int[] {0, 1, 2};
long[] cumulativeCounts = new long[] {13, 178, 1024, 3000};
- NativeHistogramBuckets.of(bucketIndexes, cumulativeCounts);
+ assertThrows(IllegalArgumentException.class, () -> NativeHistogramBuckets.of(bucketIndexes, cumulativeCounts));
}
- @Test(expected = UnsupportedOperationException.class)
- public void testImmutable() {
+ @Test
+ void testImmutable() {
NativeHistogramBuckets buckets = NativeHistogramBuckets.builder()
.bucket(1, 1)
.bucket(2, 1)
.build();
Iterator iterator = buckets.iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, 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 d9ba9339d..d9ad9406b 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,34 +1,34 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import static io.prometheus.metrics.model.snapshots.PrometheusNaming.prometheusName;
import static io.prometheus.metrics.model.snapshots.PrometheusNaming.sanitizeLabelName;
import static io.prometheus.metrics.model.snapshots.PrometheusNaming.sanitizeMetricName;
-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"));
+ void testSanitizeMetricName() {
+ Assertions.assertEquals("_abc_def", prometheusName(sanitizeMetricName("0abc.def")));
+ Assertions.assertEquals("___ab_:c0", prometheusName(sanitizeMetricName("___ab.:c0")));
+ Assertions.assertEquals("my_prefix_my_metric", sanitizeMetricName("my_prefix/my_metric"));
+ Assertions.assertEquals("my_counter", prometheusName(sanitizeMetricName("my_counter_total")));
+ Assertions.assertEquals("jvm", sanitizeMetricName("jvm.info"));
+ Assertions.assertEquals("jvm", sanitizeMetricName("jvm_info"));
+ Assertions.assertEquals("jvm", sanitizeMetricName("jvm.info"));
+ Assertions.assertEquals("a.b", sanitizeMetricName("a.b"));
}
@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"));
+ void testSanitizeLabelName() {
+ Assertions.assertEquals("_abc_def", prometheusName(sanitizeLabelName("0abc.def")));
+ Assertions.assertEquals("_abc", prometheusName(sanitizeLabelName("_abc")));
+ Assertions.assertEquals("_abc", prometheusName(sanitizeLabelName("__abc")));
+ Assertions.assertEquals("_abc", prometheusName(sanitizeLabelName("___abc")));
+ Assertions.assertEquals("_abc", prometheusName(sanitizeLabelName("_.abc")));
+ Assertions.assertEquals("abc.def", sanitizeLabelName("abc.def"));
+ Assertions.assertEquals("abc.def2", sanitizeLabelName("abc.def2"));
}
}
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 c0956361d..9e2f75dbd 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,30 +1,32 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-public class QuantilesTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class QuantilesTest {
@Test
- public void testSort() {
+ 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);
+ Assertions.assertEquals(3, quantiles.size());
+ Assertions.assertEquals(0.5, quantiles.get(0).getQuantile(), 0);
+ Assertions.assertEquals(0.2, quantiles.get(0).getValue(), 0);
+ Assertions.assertEquals(0.95, quantiles.get(1).getQuantile(), 0);
+ Assertions.assertEquals(0.22, quantiles.get(1).getValue(), 0);
+ Assertions.assertEquals(0.99, quantiles.get(2).getQuantile(), 0);
+ Assertions.assertEquals(0.23, quantiles.get(2).getValue(), 0);
}
- @Test(expected = UnsupportedOperationException.class)
- public void testImmutable() {
+ @Test
+ void testImmutable() {
Quantiles quantiles = Quantiles.builder()
.quantile(0.99, 0.23)
.quantile(0.5, 0.2)
@@ -32,20 +34,22 @@ public void testImmutable() {
.build();
Iterator iterator = quantiles.iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, iterator::remove);
}
@Test
- public void testEmpty() {
- Assert.assertEquals(0, Quantiles.EMPTY.size());
+ void testEmpty() {
+ Assertions.assertEquals(0, Quantiles.EMPTY.size());
}
- @Test(expected = IllegalArgumentException.class)
- public void testDuplicate() {
- Quantiles.builder()
- .quantile(0.95, 0.23)
- .quantile(0.5, 0.2)
- .quantile(0.95, 0.22)
- .build();
+ @Test
+ void testDuplicate() {
+ assertThrows(IllegalArgumentException.class,
+ () ->
+ 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 54766debd..db7b4f406 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,18 @@
package io.prometheus.metrics.model.snapshots;
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
+
public 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());
+ Assertions.assertEquals(name, snapshot.getMetadata().getName());
+ Assertions.assertEquals(help, snapshot.getMetadata().getHelp());
if (unit != null) {
- Assert.assertEquals(unit, snapshot.getMetadata().getUnit().toString());
+ Assertions.assertEquals(unit, snapshot.getMetadata().getUnit().toString());
} else {
- Assert.assertNull(snapshot.getMetadata().getUnit());
+ Assertions.assertNull(snapshot.getMetadata().getUnit());
}
}
}
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 2795ec165..b40523559 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,15 +1,17 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
-public class StateSetSnapshotTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class StateSetSnapshotTest {
@Test
- public void testCompleteGoodCase() {
+ void testCompleteGoodCase() {
long scrapeTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1);
StateSetSnapshot snapshot = StateSetSnapshot.builder()
.name("my_feature_flags")
@@ -29,46 +31,46 @@ public void testCompleteGoodCase() {
)
.build();
SnapshotTestUtil.assertMetadata(snapshot, "my_feature_flags", "Feature Flags", null);
- Assert.assertEquals(2, snapshot.getDataPoints().size());
+ Assertions.assertEquals(2, snapshot.getDataPoints().size());
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());
+ Assertions.assertEquals(Labels.of("entity", "controller"), data.getLabels());
+ Assertions.assertEquals(2, data.size());
+ Assertions.assertEquals("feature1", data.getName(0));
+ Assertions.assertTrue(data.isTrue(0));
+ Assertions.assertEquals("feature2", data.getName(1));
+ Assertions.assertFalse(data.isTrue(1));
+ Assertions.assertTrue(data.hasScrapeTimestamp());
+ Assertions.assertEquals(scrapeTimestamp, data.getScrapeTimestampMillis());
+ Assertions.assertFalse(data.hasCreatedTimestamp());
}
@Test
- public void testStateSetDataSorted() {
+ void testStateSetDataSorted() {
StateSetSnapshot.StateSetDataPointSnapshot data = StateSetSnapshot.StateSetDataPointSnapshot.builder()
.state("b", true)
.state("d", false)
.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));
+ Assertions.assertEquals(4, data.size());
+ Assertions.assertEquals("a", data.getName(0));
+ Assertions.assertFalse(data.isTrue(0));
+ Assertions.assertEquals("b", data.getName(1));
+ Assertions.assertTrue(data.isTrue(1));
+ Assertions.assertEquals("c", data.getName(2));
+ Assertions.assertTrue(data.isTrue(2));
+ Assertions.assertEquals("d", data.getName(3));
+ Assertions.assertFalse(data.isTrue(3));
}
- @Test(expected = IllegalArgumentException.class)
- public void testMustHaveState() {
+ @Test
+ void testMustHaveState() {
// Must have at least one state.
- StateSetSnapshot.StateSetDataPointSnapshot.builder().build();
+ assertThrows(IllegalArgumentException.class, () -> StateSetSnapshot.StateSetDataPointSnapshot.builder().build());
}
@Test
- public void testMinimal() {
+ void testMinimal() {
StateSetSnapshot snapshot = StateSetSnapshot.builder()
.name("my_flag")
.dataPoint(StateSetSnapshot.StateSetDataPointSnapshot.builder()
@@ -76,19 +78,19 @@ public void testMinimal() {
.build()
)
.build();
- Assert.assertEquals(1, snapshot.dataPoints.size());
+ Assertions.assertEquals(1, snapshot.dataPoints.size());
}
@Test
- public void testEmpty() {
+ void testEmpty() {
StateSetSnapshot snapshot = StateSetSnapshot.builder()
.name("my_flag")
.build();
- Assert.assertEquals(0, snapshot.dataPoints.size());
+ Assertions.assertEquals(0, snapshot.dataPoints.size());
}
- @Test(expected = UnsupportedOperationException.class)
- public void testDataImmutable() {
+ @Test
+ void testDataImmutable() {
StateSetSnapshot.StateSetDataPointSnapshot data = StateSetSnapshot.StateSetDataPointSnapshot.builder()
.state("a", true)
.state("b", true)
@@ -96,20 +98,21 @@ public void testDataImmutable() {
.build();
Iterator iterator = data.iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, iterator::remove);
}
- @Test(expected = IllegalArgumentException.class)
- public void testDuplicateState() {
- StateSetSnapshot.StateSetDataPointSnapshot data = StateSetSnapshot.StateSetDataPointSnapshot.builder()
- .state("a", true)
- .state("b", true)
- .state("a", true)
- .build();
+ @Test
+ void testDuplicateState() {
+ assertThrows(IllegalArgumentException.class,
+ () -> StateSetSnapshot.StateSetDataPointSnapshot.builder()
+ .state("a", true)
+ .state("b", true)
+ .state("a", true)
+ .build());
}
- @Test(expected = UnsupportedOperationException.class)
- public void testStateSetImmutable() {
+ @Test
+ void testStateSetImmutable() {
StateSetSnapshot snapshot = StateSetSnapshot.builder()
.name("flags")
.dataPoint(StateSetSnapshot.StateSetDataPointSnapshot.builder()
@@ -125,21 +128,22 @@ public void testStateSetImmutable() {
.build();
Iterator iterator = snapshot.getDataPoints().iterator();
iterator.next();
- iterator.remove();
+ Assertions.assertThrows(UnsupportedOperationException.class, iterator::remove);
}
- @Test(expected = IllegalArgumentException.class)
- public void testLabelsUnique() {
- StateSetSnapshot.builder()
- .name("flags")
- .dataPoint(StateSetSnapshot.StateSetDataPointSnapshot.builder()
- .state("feature", true)
- .build()
- )
- .dataPoint(StateSetSnapshot.StateSetDataPointSnapshot.builder()
- .state("feature", true)
- .build()
- )
- .build();
+ @Test
+ void testLabelsUnique() {
+ assertThrows(IllegalArgumentException.class,
+ () -> 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 b5067b17e..4206b1993 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,14 +1,13 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-public class SummarySnapshotTest {
+class SummarySnapshotTest {
@Test
- public void testCompleteGoodCase() {
+ void testCompleteGoodCase() {
long createdTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1);
long scrapeTimestamp = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(2);
long exemplarTimestamp = System.currentTimeMillis();
@@ -49,32 +48,32 @@ public void testCompleteGoodCase() {
.build())
.build();
SnapshotTestUtil.assertMetadata(snapshot, "latency_seconds", "latency in seconds", "seconds");
- Assert.assertEquals(2, snapshot.getDataPoints().size());
+ Assertions.assertEquals(2, snapshot.getDataPoints().size());
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());
+ Assertions.assertEquals(Labels.of("endpoint", "/"), data.getLabels());
+ Assertions.assertTrue(data.hasCount());
+ Assertions.assertEquals(1093, data.getCount());
+ Assertions.assertTrue(data.hasSum());
+ Assertions.assertEquals(218.6, data.getSum(), 0);
+ Assertions.assertTrue(data.hasCreatedTimestamp());
+ Assertions.assertEquals(createdTimestamp, data.getCreatedTimestampMillis());
+ Assertions.assertTrue(data.hasScrapeTimestamp());
+ Assertions.assertEquals(scrapeTimestamp, data.getScrapeTimestampMillis());
Quantiles quantiles = data.getQuantiles();
- Assert.assertEquals(3, quantiles.size());
+ Assertions.assertEquals(3, quantiles.size());
// quantiles are tested in QuantilesTest already, skipping here.
- Assert.assertEquals(2, data.getExemplars().size());
+ Assertions.assertEquals(2, data.getExemplars().size());
// 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());
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
+ Assertions.assertTrue(data.hasCount());
+ Assertions.assertTrue(data.hasSum());
}
@Test
- public void testMinimal() {
+ void testMinimal() {
SummarySnapshot snapshot = SummarySnapshot.builder()
.name("size_bytes")
.dataPoint(SummarySnapshot.SummaryDataPointSnapshot.builder()
@@ -82,24 +81,24 @@ public void testMinimal() {
.sum(12.0)
.build())
.build();
- Assert.assertEquals(1, snapshot.getDataPoints().size());
- Assert.assertEquals(Labels.EMPTY, snapshot.getDataPoints().get(0).getLabels());
+ Assertions.assertEquals(1, snapshot.getDataPoints().size());
+ Assertions.assertEquals(Labels.EMPTY, snapshot.getDataPoints().get(0).getLabels());
}
@Test
- public void testEmptySnapshot() {
+ void testEmptySnapshot() {
SummarySnapshot snapshot = SummarySnapshot.builder().name("empty_summary").build();
- Assert.assertEquals(0, snapshot.getDataPoints().size());
+ Assertions.assertEquals(0, snapshot.getDataPoints().size());
}
@Test
- public void testEmptyData() {
+ 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());
+ Assertions.assertEquals(0, data.getQuantiles().size());
+ Assertions.assertFalse(data.hasCount());
+ Assertions.assertFalse(data.hasSum());
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
+ Assertions.assertEquals(0, data.getExemplars().size());
}
}
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 f88458cc3..1f66be2bc 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,14 +1,15 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
-public class UnitTest {
+
+class UnitTest {
@Test
- public void testEmpty() {
+ void testEmpty() {
try {
new Unit(" ");
fail("Expected IllegalArgumentException");
@@ -18,34 +19,34 @@ public void testEmpty() {
}
@Test
- public void testEquals1() {
+ void testEquals1() {
Unit unit1 = Unit.BYTES;
Unit unit2 = new Unit("bytes");
- Assert.assertEquals(unit2, unit1);
+ Assertions.assertEquals(unit2, unit1);
}
@Test
- public void testEquals2() {
+ void testEquals2() {
Unit unit1 = new Unit("bytes ");
Unit unit2 = new Unit("bytes");
- Assert.assertEquals(unit2, unit1);
+ Assertions.assertEquals(unit2, unit1);
}
@Test
- public void testEquals3() {
+ void testEquals3() {
Unit unit1 = new Unit(" bytes");
Unit unit2 = new Unit("bytes");
- Assert.assertEquals(unit2, unit1);
+ Assertions.assertEquals(unit2, unit1);
}
@Test
- public void testEquals4() {
+ void testEquals4() {
Unit unit1 = new Unit(" bytes ");
Unit unit2 = new Unit("bytes");
- Assert.assertEquals(unit2, unit1);
+ Assertions.assertEquals(unit2, unit1);
}
}
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 dfc2e62a7..a8e98edff 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,12 +1,14 @@
package io.prometheus.metrics.model.snapshots;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-public class UnknownSnapshotTest {
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class UnknownSnapshotTest {
@Test
- public void testCompleteGoodCase() {
+ void testCompleteGoodCase() {
long exemplarTimestamp = System.currentTimeMillis();
UnknownSnapshot snapshot = UnknownSnapshot.builder()
.name("my_unknown_seconds")
@@ -33,39 +35,39 @@ public void testCompleteGoodCase() {
)
.build();
SnapshotTestUtil.assertMetadata(snapshot, "my_unknown_seconds", "something in seconds", "seconds");
- Assert.assertEquals(2, snapshot.getDataPoints().size());
+ Assertions.assertEquals(2, snapshot.getDataPoints().size());
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());
+ Assertions.assertEquals(Labels.of("env", "prod"), data.getLabels());
+ Assertions.assertEquals(0.3, data.getValue(), 0.0);
+ Assertions.assertEquals(0.12, data.getExemplar().getValue(), 0.0);
+ Assertions.assertFalse(data.hasCreatedTimestamp());
+ Assertions.assertFalse(data.hasScrapeTimestamp());
}
@Test
- public void testMinimal() {
+ void testMinimal() {
UnknownSnapshot snapshot = UnknownSnapshot.builder()
.name("test")
.dataPoint(UnknownSnapshot.UnknownDataPointSnapshot.builder()
.value(1.0)
.build())
.build();
- Assert.assertEquals(1, snapshot.getDataPoints().size());
+ Assertions.assertEquals(1, snapshot.getDataPoints().size());
}
@Test
- public void testEmpty() {
+ void testEmpty() {
UnknownSnapshot snapshot = UnknownSnapshot.builder().name("test").build();
- Assert.assertEquals(0, snapshot.getDataPoints().size());
+ Assertions.assertEquals(0, snapshot.getDataPoints().size());
}
- @Test(expected = IllegalArgumentException.class)
- public void testNameMissing() {
- UnknownSnapshot.builder().build();
+ @Test
+ void testNameMissing() {
+ assertThrows(IllegalArgumentException.class, () -> UnknownSnapshot.builder().build());
}
- @Test(expected = IllegalArgumentException.class)
- public void testValueMissing() {
- UnknownSnapshot.UnknownDataPointSnapshot.builder().build();
+ @Test
+ void testValueMissing() {
+ assertThrows(IllegalArgumentException.class, () -> UnknownSnapshot.UnknownDataPointSnapshot.builder().build());
}
}
diff --git a/prometheus-metrics-simpleclient-bridge/pom.xml b/prometheus-metrics-simpleclient-bridge/pom.xml
index 10d9ac8d6..6c3ac45f4 100644
--- a/prometheus-metrics-simpleclient-bridge/pom.xml
+++ b/prometheus-metrics-simpleclient-bridge/pom.xml
@@ -56,9 +56,8 @@
- junit
- junit
- 4.13.2
+ org.junit.jupiter
+ junit-jupiter-engine
test
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 9d1e8f1b9..12e471d7d 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
@@ -10,9 +10,9 @@
import io.prometheus.client.exporter.common.TextFormat;
import io.prometheus.metrics.expositionformats.OpenMetricsTextFormatWriter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -23,13 +23,13 @@
import java.util.Collections;
import java.util.List;
-public class SimpleclientCollectorTest {
+class SimpleclientCollectorTest {
private CollectorRegistry origRegistry;
private PrometheusRegistry newRegistry;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
origRegistry = new CollectorRegistry();
newRegistry = new PrometheusRegistry();
SimpleclientCollector.builder()
@@ -38,7 +38,7 @@ public void setUp() {
}
@Test
- public void testCounterComplete() throws IOException, InterruptedException {
+ void testCounterComplete() throws IOException, InterruptedException {
Counter counter = Counter.build()
.name("service_time_seconds_total")
.help("total time spent serving")
@@ -48,21 +48,21 @@ 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()));
+ Assertions.assertEquals(fixTimestamps(sort(origOpenMetrics())), sort(newOpenMetrics()));
}
@Test
- public void testCounterMinimal() throws IOException, InterruptedException {
+ void testCounterMinimal() throws IOException, InterruptedException {
Counter.build()
.name("events")
.help("total number of events")
.register(origRegistry);
- Assert.assertEquals(fixTimestamps(sort(origOpenMetrics())), sort(newOpenMetrics()));
+ Assertions.assertEquals(fixTimestamps(sort(origOpenMetrics())), sort(newOpenMetrics()));
}
@Test
- public void testGaugeComplete() throws IOException, InterruptedException {
+ void testGaugeComplete() throws IOException, InterruptedException {
Gauge gauge = Gauge.build()
.name("disk_usage_ratio")
.help("percentage used")
@@ -73,11 +73,11 @@ public void testGaugeComplete() throws IOException, InterruptedException {
Thread.sleep(3);
gauge.labels("/dev/sda2").set(0.7);
- Assert.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics()));
+ Assertions.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics()));
}
@Test
- public void testGaugeMinimal() throws IOException, InterruptedException {
+ void testGaugeMinimal() throws IOException, InterruptedException {
Gauge gauge = Gauge.build()
.name("temperature_centigrade")
.help("temperature")
@@ -85,11 +85,11 @@ public void testGaugeMinimal() throws IOException, InterruptedException {
.register(origRegistry);
gauge.set(22.3);
- Assert.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics()));
+ Assertions.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics()));
}
@Test
- public void testHistogramComplete() throws IOException, InterruptedException {
+ void testHistogramComplete() throws IOException, InterruptedException {
Histogram histogram = Histogram.build()
.name("response_size_bytes")
.help("response size in Bytes")
@@ -104,21 +104,21 @@ 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()));
+ Assertions.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics()));
}
@Test
- public void testHistogramMinimal() throws IOException, InterruptedException {
+ void testHistogramMinimal() throws IOException, InterruptedException {
Histogram.build()
.name("request_latency")
.help("request latency")
.register(origRegistry);
- Assert.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics()));
+ Assertions.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics()));
}
@Test
- public void testSummaryComplete() throws IOException, InterruptedException {
+ void testSummaryComplete() throws IOException, InterruptedException {
Summary summary = Summary.build()
.name("http_request_duration_seconds")
.help("request duration")
@@ -137,21 +137,21 @@ 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()));
+ Assertions.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics()));
}
@Test
- public void testSummaryMinimal() throws IOException, InterruptedException {
+ 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()));
+ Assertions.assertEquals(fixCounts(fixTimestamps(sort(origOpenMetrics()))), sort(newOpenMetrics()));
}
@Test
- public void testInfoComplete() throws IOException, InterruptedException {
+ void testInfoComplete() throws IOException, InterruptedException {
Info info = Info.build()
.name("version")
.help("version information")
@@ -161,22 +161,22 @@ 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()));
+ Assertions.assertEquals(fixBoolean(sort(origOpenMetrics())), sort(newOpenMetrics()));
}
@Test
- public void testInfoMinimal() throws IOException, InterruptedException {
+ 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()));
+ Assertions.assertEquals(fixBoolean(sort(origOpenMetrics())), sort(newOpenMetrics()));
}
@Test
- public void testStateSetComplete() throws IOException {
+ void testStateSetComplete() throws IOException {
Collector stateSet = new Collector() {
@Override
public List collect() {
@@ -188,11 +188,11 @@ public List collect() {
};
origRegistry.register(stateSet);
- Assert.assertEquals(fixBoolean(sort(origOpenMetrics())), sort(newOpenMetrics()));
+ Assertions.assertEquals(fixBoolean(sort(origOpenMetrics())), sort(newOpenMetrics()));
}
@Test
- public void testUnknownComplete() throws IOException {
+ void testUnknownComplete() throws IOException {
Collector unknown = new Collector() {
@Override
public List collect() {
@@ -204,7 +204,7 @@ public List collect() {
};
origRegistry.register(unknown);
- Assert.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics()));
+ Assertions.assertEquals(sort(origOpenMetrics()), sort(newOpenMetrics()));
}
private String fixBoolean(String s) {
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..b67fa237b 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
@@ -4,7 +4,7 @@
import org.springframework.test.context.ContextConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
@ContextConfiguration
@EnablePrometheusTiming
@@ -23,4 +23,4 @@ public void waitJustAGoshDarnSecond() throws Exception {
public static class MyConfig {
}
-}
\ No newline at end of file
+}