Skip to content

Commit

Permalink
add tests (#1163)
Browse files Browse the repository at this point in the history
* allow java 17 in tests

Signed-off-by: Gregor Zeitlinger <[email protected]>

* allow java 17 in tests

Signed-off-by: Gregor Zeitlinger <[email protected]>

* add coverage

Signed-off-by: Gregor Zeitlinger <[email protected]>

---------

Signed-off-by: Gregor Zeitlinger <[email protected]>
  • Loading branch information
zeitlinger authored Oct 18, 2024
1 parent 28b4048 commit a2d3b20
Show file tree
Hide file tree
Showing 15 changed files with 197 additions and 88 deletions.
1 change: 1 addition & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
java temurin-17.0.7+7
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@
<skip>${coverage.skip}</skip>
<excludes>
<exclude>**/generated/**</exclude>
<exclude>**/*BlockingRejectedExecutionHandler*</exclude>
</excludes>
</configuration>
<executions>
Expand Down Expand Up @@ -310,6 +311,9 @@
<release>${java.version}</release>
<source>${java.version}</source>
<target>${java.version}</target>
<testRelease>17</testRelease>
<testSource>17</testSource>
<testTarget>17</testTarget>
<showWarnings>true</showWarnings>
<compilerArgs>
<arg>-Xlint:all,-serial,-processing,-options</arg>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
Expand All @@ -14,7 +13,7 @@ class ExemplarsPropertiesTest {
void load() {
ExemplarsProperties properties =
load(
ImmutableMap.of(
Map.of(
"io.prometheus.exemplars.minRetentionPeriodSeconds", "1",
"io.prometheus.exemplars.maxRetentionPeriodSeconds", "2",
"io.prometheus.exemplars.sampleIntervalMilliseconds", "3"));
Expand All @@ -23,20 +22,17 @@ void load() {
assertThat(properties.getSampleIntervalMilliseconds()).isEqualTo(3);

assertThatExceptionOfType(PrometheusPropertiesException.class)
.isThrownBy(
() -> load(ImmutableMap.of("io.prometheus.exemplars.minRetentionPeriodSeconds", "-1")))
.isThrownBy(() -> load(Map.of("io.prometheus.exemplars.minRetentionPeriodSeconds", "-1")))
.withMessage(
"io.prometheus.exemplars.minRetentionPeriodSeconds: Expecting value > 0. Found: -1");

assertThatExceptionOfType(PrometheusPropertiesException.class)
.isThrownBy(
() -> load(ImmutableMap.of("io.prometheus.exemplars.maxRetentionPeriodSeconds", "0")))
.isThrownBy(() -> load(Map.of("io.prometheus.exemplars.maxRetentionPeriodSeconds", "0")))
.withMessage(
"io.prometheus.exemplars.maxRetentionPeriodSeconds: Expecting value > 0. Found: 0");

assertThatExceptionOfType(PrometheusPropertiesException.class)
.isThrownBy(
() -> load(ImmutableMap.of("io.prometheus.exemplars.sampleIntervalMilliseconds", "-1")))
.isThrownBy(() -> load(Map.of("io.prometheus.exemplars.sampleIntervalMilliseconds", "-1")))
.withMessage(
"io.prometheus.exemplars.sampleIntervalMilliseconds: Expecting value > 0. Found: -1");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
Expand All @@ -13,7 +12,7 @@ class ExporterFilterPropertiesTest {
void load() {
ExporterFilterProperties properties =
load(
ImmutableMap.of(
Map.of(
"io.prometheus.exporter.filter.metricNameMustBeEqualTo", "a,b,c",
"io.prometheus.exporter.filter.metricNameMustNotBeEqualTo", "d,e,f",
"io.prometheus.exporter.filter.metricNameMustStartWith", "g,h,i",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
Expand All @@ -12,11 +11,11 @@ class ExporterHttpServerPropertiesTest {
@Test
void load() {
ExporterHttpServerProperties properties =
load(ImmutableMap.of("io.prometheus.exporter.httpServer.port", "1"));
load(Map.of("io.prometheus.exporter.httpServer.port", "1"));
assertThat(properties.getPort()).isOne();

assertThatExceptionOfType(PrometheusPropertiesException.class)
.isThrownBy(() -> load(ImmutableMap.of("io.prometheus.exporter.httpServer.port", "0")))
.isThrownBy(() -> load(Map.of("io.prometheus.exporter.httpServer.port", "0")))
.withMessage("io.prometheus.exporter.httpServer.port: Expecting value > 0. Found: 0");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
Expand All @@ -13,7 +12,7 @@ class ExporterOpenTelemetryPropertiesTest {
void load() {
ExporterOpenTelemetryProperties properties =
load(
ImmutableMap.of(
Map.of(
"io.prometheus.exporter.opentelemetry.protocol", "grpc",
"io.prometheus.exporter.opentelemetry.endpoint", "http://localhost:8080",
"io.prometheus.exporter.opentelemetry.headers", "key1=value1,key2=value2",
Expand All @@ -33,15 +32,15 @@ private static void assertValues(ExporterOpenTelemetryProperties properties) {
assertThat(properties.getProtocol()).isEqualTo("grpc");
assertThat(properties.getEndpoint()).isEqualTo("http://localhost:8080");
assertThat(properties.getHeaders())
.containsExactlyInAnyOrderEntriesOf(ImmutableMap.of("key1", "value1", "key2", "value2"));
.containsExactlyInAnyOrderEntriesOf(Map.of("key1", "value1", "key2", "value2"));
assertThat(properties.getInterval()).isEqualTo("10s");
assertThat(properties.getTimeout()).isEqualTo("5s");
assertThat(properties.getServiceName()).isEqualTo("serviceName");
assertThat(properties.getServiceNamespace()).isEqualTo("serviceNamespace");
assertThat(properties.getServiceInstanceId()).isEqualTo("serviceInstanceId");
assertThat(properties.getServiceVersion()).isEqualTo("serviceVersion");
assertThat(properties.getResourceAttributes())
.containsExactlyInAnyOrderEntriesOf(ImmutableMap.of("key1", "value1", "key2", "value2"));
.containsExactlyInAnyOrderEntriesOf(Map.of("key1", "value1", "key2", "value2"));
}

private static ExporterOpenTelemetryProperties load(Map<String, String> map) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
Expand All @@ -15,7 +14,7 @@ void load() {
ExporterProperties properties =
load(
new HashMap<>(
ImmutableMap.of(
Map.of(
"io.prometheus.exporter.includeCreatedTimestamps", "true",
"io.prometheus.exporter.exemplarsOnAllMetricTypes", "true")));
assertThat(properties.getIncludeCreatedTimestamps()).isTrue();
Expand All @@ -26,17 +25,15 @@ void load() {
() ->
load(
new HashMap<>(
ImmutableMap.of(
"io.prometheus.exporter.includeCreatedTimestamps", "invalid"))))
Map.of("io.prometheus.exporter.includeCreatedTimestamps", "invalid"))))
.withMessage(
"io.prometheus.exporter.includeCreatedTimestamps: Expecting 'true' or 'false'. Found: invalid");
assertThatExceptionOfType(PrometheusPropertiesException.class)
.isThrownBy(
() ->
load(
new HashMap<>(
ImmutableMap.of(
"io.prometheus.exporter.exemplarsOnAllMetricTypes", "invalid"))))
Map.of("io.prometheus.exporter.exemplarsOnAllMetricTypes", "invalid"))))
.withMessage(
"io.prometheus.exporter.exemplarsOnAllMetricTypes: Expecting 'true' or 'false'. Found: invalid");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
Expand All @@ -14,7 +13,7 @@ class ExporterPushgatewayPropertiesTest {
void load() {
ExporterPushgatewayProperties properties =
load(
ImmutableMap.of(
Map.of(
"io.prometheus.exporter.pushgateway.address", "http://localhost",
"io.prometheus.exporter.pushgateway.job", "job",
"io.prometheus.exporter.pushgateway.scheme", "http"));
Expand All @@ -24,7 +23,7 @@ void load() {
assertThat(properties.getScheme()).isEqualTo("http");

assertThatExceptionOfType(PrometheusPropertiesException.class)
.isThrownBy(() -> load(ImmutableMap.of("io.prometheus.exporter.pushgateway.scheme", "foo")))
.isThrownBy(() -> load(Map.of("io.prometheus.exporter.pushgateway.scheme", "foo")))
.withMessage(
"io.prometheus.exporter.pushgateway.scheme: Illegal value. Expecting 'http' or 'https'. Found: foo");
}
Expand Down
3 changes: 1 addition & 2 deletions prometheus-metrics-exporter-httpserver/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@

<properties>
<automatic.module.name>io.prometheus.metrics.exporter.httpserver</automatic.module.name>
<!-- we have to set the line coverage to 0.0 because the module is tested with integration tests-->
<jacoco.line-coverage>0.0</jacoco.line-coverage>
<jacoco.line-coverage>0.45</jacoco.line-coverage>
</properties>

<dependencies>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package io.prometheus.metrics.exporter.httpserver;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

class BlockingRejectedExecutionHandler implements RejectedExecutionHandler {

@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
if (!threadPoolExecutor.isShutdown()) {
try {
threadPoolExecutor.getQueue().put(runnable);
} catch (InterruptedException ignored) {
// ignore
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -317,18 +316,4 @@ private void assertNull(Object o, String msg) {
}
}
}

private static class BlockingRejectedExecutionHandler implements RejectedExecutionHandler {

@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
if (!threadPoolExecutor.isShutdown()) {
try {
threadPoolExecutor.getQueue().put(runnable);
} catch (InterruptedException ignored) {
// ignore
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
package io.prometheus.metrics.exporter.httpserver;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpPrincipal;
import com.sun.net.httpserver.HttpsConfigurator;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.model.registry.PrometheusScrapeRequest;
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLContext;
import javax.security.auth.Subject;
import org.junit.jupiter.api.Test;

public class HTTPServerTest {

@Test
@SuppressWarnings({"removal"})
public void testSubjectDoAs() throws Exception {

final String user = "joe";
Expand Down Expand Up @@ -56,11 +66,16 @@ public Result authenticate(HttpExchange exchange) {
.authenticatedSubjectAttributeName("aa")
.buildAndStart();

Socket socket = new Socket();
try {
run(server, "204", "/");
}

private static void run(HTTPServer server, String expected, String path) throws IOException {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress("localhost", server.getPort()));

socket.getOutputStream().write("GET / HTTP/1.1 \r\n".getBytes(StandardCharsets.UTF_8));
socket
.getOutputStream()
.write(("GET " + path + " HTTP/1.1 \r\n").getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().write("HOST: localhost \r\n\r\n".getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().flush();

Expand All @@ -70,10 +85,67 @@ public Result authenticate(HttpExchange exchange) {
if (read > 0) {
actualResponse = new String(resp, 0, read, StandardCharsets.UTF_8);
}
assertThat(actualResponse).contains("204");

} finally {
socket.close();
assertThat(actualResponse).contains(expected);
}
}

@Test
void defaultHandler() throws IOException {
run(HTTPServer.builder().port(0).buildAndStart(), "200", "/");
}

@Test
void metrics() throws IOException {
run(
HTTPServer.builder()
.port(0)
.registry(new PrometheusRegistry())
.executorService(Executors.newFixedThreadPool(1))
.buildAndStart(),
"200",
"/metrics");
}

@Test
void registryThrows() throws IOException {
HTTPServer server =
HTTPServer.builder()
.port(0)
.registry(
new PrometheusRegistry() {
@Override
public MetricSnapshots scrape(PrometheusScrapeRequest scrapeRequest) {
throw new IllegalStateException("test");
}
})
.buildAndStart();
run(server, "500", "/metrics");
}

@Test
void config() throws NoSuchAlgorithmException, IOException {
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(
() ->
HTTPServer.builder()
.port(0)
.hostname("localhost")
.inetAddress(InetAddress.getByName("localhost"))
.buildAndStart())
.withMessage("cannot configure 'inetAddress' and 'hostname' at the same time");

// ssl doesn't work without in tests
run(
HTTPServer.builder()
.port(0)
.httpsConfigurator(new HttpsConfigurator(SSLContext.getDefault()))
.buildAndStart(),
"",
"/");
}

@Test
void health() throws IOException {
run(HTTPServer.builder().port(0).buildAndStart(), "200", "/-/healthy");
}
}
Loading

0 comments on commit a2d3b20

Please sign in to comment.