Browse Source

Add nullability annotations to tests in module/spring-boot-micrometer-metrics

See gh-47263
pull/47626/head
Moritz Halbritter 2 months ago
parent
commit
11d50ae293
  1. 8
      module/spring-boot-micrometer-metrics/build.gradle
  2. 5
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/ValidationFailureAnalyzerTests.java
  3. 16
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/actuate/endpoint/MetricsEndpointTests.java
  4. 5
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryCustomizerTests.java
  5. 31
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryPostProcessorTests.java
  6. 15
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAspectsAutoConfigurationTests.java
  7. 1
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java
  8. 7
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationTests.java
  9. 1
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/PropertiesMeterFilterTests.java
  10. 9
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java
  11. 8
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/startup/StartupTimeMetricsListenerAutoConfigurationTests.java
  12. 16
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/startup/StartupTimeMetricsListenerTests.java

8
module/spring-boot-micrometer-metrics/build.gradle

@ -82,3 +82,11 @@ dependencies {
testRuntimeOnly("ch.qos.logback:logback-classic") testRuntimeOnly("ch.qos.logback:logback-classic")
} }
tasks.named("compileTestJava") {
options.nullability.checking = "tests"
}
tasks.named("compileDockerTestJava") {
options.nullability.checking = "tests"
}

5
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/ValidationFailureAnalyzerTests.java

@ -19,6 +19,7 @@ package org.springframework.boot.micrometer.metrics;
import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.Clock;
import io.micrometer.newrelic.NewRelicConfig; import io.micrometer.newrelic.NewRelicConfig;
import io.micrometer.newrelic.NewRelicMeterRegistry; import io.micrometer.newrelic.NewRelicMeterRegistry;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.diagnostics.FailureAnalysis;
@ -51,7 +52,7 @@ class ValidationFailureAnalyzerTests {
private Exception createFailure(Class<?> configuration) { private Exception createFailure(Class<?> configuration) {
try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(configuration)) { try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(configuration)) {
fail("Expected failure did not occur"); fail("Expected failure did not occur");
return null; throw new AssertionError("Should not be reached");
} }
catch (Exception ex) { catch (Exception ex) {
return ex; return ex;
@ -66,7 +67,7 @@ class ValidationFailureAnalyzerTests {
return new NewRelicMeterRegistry(new NewRelicConfig() { return new NewRelicMeterRegistry(new NewRelicConfig() {
@Override @Override
public String get(String key) { public @Nullable String get(String key) {
return null; return null;
} }

16
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/actuate/endpoint/MetricsEndpointTests.java

@ -30,6 +30,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.endpoint.InvalidEndpointRequestException; import org.springframework.boot.actuate.endpoint.InvalidEndpointRequestException;
import org.springframework.boot.micrometer.metrics.actuate.endpoint.MetricsEndpoint.MetricDescriptor;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@ -85,10 +86,12 @@ class MetricsEndpointTests {
this.registry.counter("cache", "result", "miss", "host", "1").increment(2); this.registry.counter("cache", "result", "miss", "host", "1").increment(2);
this.registry.counter("cache", "result", "hit", "host", "2").increment(2); this.registry.counter("cache", "result", "hit", "host", "2").increment(2);
MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("cache", Collections.emptyList()); MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("cache", Collections.emptyList());
assertThat(response).isNotNull();
assertThat(response.getName()).isEqualTo("cache"); assertThat(response.getName()).isEqualTo("cache");
assertThat(availableTagKeys(response)).containsExactly("result", "host"); assertThat(availableTagKeys(response)).containsExactly("result", "host");
assertThat(getCount(response)).hasValue(6.0); assertThat(getCount(response)).hasValue(6.0);
response = this.endpoint.metric("cache", Collections.singletonList("result:hit")); response = this.endpoint.metric("cache", Collections.singletonList("result:hit"));
assertThat(response).isNotNull();
assertThat(availableTagKeys(response)).containsExactly("host"); assertThat(availableTagKeys(response)).containsExactly("host");
assertThat(getCount(response)).hasValue(4.0); assertThat(getCount(response)).hasValue(4.0);
} }
@ -107,10 +110,12 @@ class MetricsEndpointTests {
secondLevel.counter("cache", "result", "hit", "host", "2").increment(2); secondLevel.counter("cache", "result", "hit", "host", "2").increment(2);
MetricsEndpoint endpoint = new MetricsEndpoint(composite); MetricsEndpoint endpoint = new MetricsEndpoint(composite);
MetricsEndpoint.MetricDescriptor response = endpoint.metric("cache", Collections.emptyList()); MetricsEndpoint.MetricDescriptor response = endpoint.metric("cache", Collections.emptyList());
assertThat(response).isNotNull();
assertThat(response.getName()).isEqualTo("cache"); assertThat(response.getName()).isEqualTo("cache");
assertThat(availableTagKeys(response)).containsExactly("result", "host"); assertThat(availableTagKeys(response)).containsExactly("result", "host");
assertThat(getCount(response)).hasValue(6.0); assertThat(getCount(response)).hasValue(6.0);
response = endpoint.metric("cache", Collections.singletonList("result:hit")); response = endpoint.metric("cache", Collections.singletonList("result:hit"));
assertThat(response).isNotNull();
assertThat(availableTagKeys(response)).containsExactly("host"); assertThat(availableTagKeys(response)).containsExactly("host");
assertThat(getCount(response)).hasValue(4.0); assertThat(getCount(response)).hasValue(4.0);
} }
@ -132,6 +137,7 @@ class MetricsEndpointTests {
this.registry.counter("cache", "host", "1", "region", "east", "result", "hit"); this.registry.counter("cache", "host", "1", "region", "east", "result", "hit");
this.registry.counter("cache", "host", "1", "region", "east", "result", "miss"); this.registry.counter("cache", "host", "1", "region", "east", "result", "miss");
MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("cache", Collections.singletonList("host:1")); MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("cache", Collections.singletonList("host:1"));
assertThat(response).isNotNull();
assertThat(response.getAvailableTags() assertThat(response.getAvailableTags()
.stream() .stream()
.filter((t) -> t.getTag().equals("region")) .filter((t) -> t.getTag().equals("region"))
@ -143,6 +149,7 @@ class MetricsEndpointTests {
this.registry.counter("counter", "key", "a space").increment(2); this.registry.counter("counter", "key", "a space").increment(2);
MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("counter", MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("counter",
Collections.singletonList("key:a space")); Collections.singletonList("key:a space"));
assertThat(response).isNotNull();
assertThat(response.getName()).isEqualTo("counter"); assertThat(response.getName()).isEqualTo("counter");
assertThat(availableTagKeys(response)).isEmpty(); assertThat(availableTagKeys(response)).isEmpty();
assertThat(getCount(response)).hasValue(2.0); assertThat(getCount(response)).hasValue(2.0);
@ -193,11 +200,10 @@ class MetricsEndpointTests {
private void assertMetricHasStatisticEqualTo(MeterRegistry registry, String metricName, Statistic stat, private void assertMetricHasStatisticEqualTo(MeterRegistry registry, String metricName, Statistic stat,
Double value) { Double value) {
MetricsEndpoint endpoint = new MetricsEndpoint(registry); MetricsEndpoint endpoint = new MetricsEndpoint(registry);
assertThat(endpoint.metric(metricName, Collections.emptyList()) MetricDescriptor metric = endpoint.metric(metricName, Collections.emptyList());
.getMeasurements() assertThat(metric).isNotNull();
.stream() assertThat(metric.getMeasurements().stream().filter((sample) -> sample.getStatistic().equals(stat)).findAny())
.filter((sample) -> sample.getStatistic().equals(stat)) .hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value));
.findAny()).hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value));
} }
private Optional<Double> getCount(MetricsEndpoint.MetricDescriptor response) { private Optional<Double> getCount(MetricsEndpoint.MetricDescriptor response) {

5
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryCustomizerTests.java

@ -21,6 +21,7 @@ import io.micrometer.atlas.AtlasMeterRegistry;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.prometheusmetrics.PrometheusConfig; import io.micrometer.prometheusmetrics.PrometheusConfig;
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -43,7 +44,7 @@ class MeterRegistryCustomizerTests {
.withBean(AtlasMeterRegistry.class, () -> new AtlasMeterRegistry(new AtlasConfig() { .withBean(AtlasMeterRegistry.class, () -> new AtlasMeterRegistry(new AtlasConfig() {
@Override @Override
public String get(String k) { public @Nullable String get(String k) {
return null; return null;
} }
@ -51,7 +52,7 @@ class MeterRegistryCustomizerTests {
.withBean(PrometheusMeterRegistry.class, () -> new PrometheusMeterRegistry(new PrometheusConfig() { .withBean(PrometheusMeterRegistry.class, () -> new PrometheusMeterRegistry(new PrometheusConfig() {
@Override @Override
public String get(String key) { public @Nullable String get(String key) {
return null; return null;
} }

31
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryPostProcessorTests.java

@ -33,6 +33,8 @@ import org.mockito.InOrder;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryPostProcessor.CompositeMeterRegistries; import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryPostProcessor.CompositeMeterRegistries;
@ -60,18 +62,23 @@ class MeterRegistryPostProcessorTests {
private final List<MeterBinder> binders = new ArrayList<>(); private final List<MeterBinder> binders = new ArrayList<>();
@Mock @Mock
@SuppressWarnings("NullAway.Init")
private MeterRegistryCustomizer<MeterRegistry> mockCustomizer; private MeterRegistryCustomizer<MeterRegistry> mockCustomizer;
@Mock @Mock
@SuppressWarnings("NullAway.Init")
private MeterFilter mockFilter; private MeterFilter mockFilter;
@Mock @Mock
@SuppressWarnings("NullAway.Init")
private MeterBinder mockBinder; private MeterBinder mockBinder;
@Mock @Mock
@SuppressWarnings("NullAway.Init")
private MeterRegistry mockRegistry; private MeterRegistry mockRegistry;
@Mock @Mock
@SuppressWarnings("NullAway.Init")
private Config mockConfig; private Config mockConfig;
MeterRegistryPostProcessorTests() { MeterRegistryPostProcessorTests() {
@ -94,8 +101,8 @@ class MeterRegistryPostProcessorTests {
void postProcessAndInitializeWhenAutoConfiguredCompositeAppliesCustomizer() { void postProcessAndInitializeWhenAutoConfiguredCompositeAppliesCustomizer() {
this.customizers.add(this.mockCustomizer); this.customizers.add(this.mockCustomizer);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED, MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers), null, createObjectProvider(this.properties), createObjectProvider(this.customizers),
createObjectProvider(this.binders)); createEmptyObjectProvider(), createObjectProvider(this.binders));
AutoConfiguredCompositeMeterRegistry composite = new AutoConfiguredCompositeMeterRegistry(Clock.SYSTEM, AutoConfiguredCompositeMeterRegistry composite = new AutoConfiguredCompositeMeterRegistry(Clock.SYSTEM,
Collections.emptyList()); Collections.emptyList());
postProcessAndInitialize(processor, composite); postProcessAndInitialize(processor, composite);
@ -152,7 +159,8 @@ class MeterRegistryPostProcessorTests {
given(this.mockRegistry.config()).willReturn(this.mockConfig); given(this.mockRegistry.config()).willReturn(this.mockConfig);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor( MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(
CompositeMeterRegistries.ONLY_USER_DEFINED, createObjectProvider(this.properties), CompositeMeterRegistries.ONLY_USER_DEFINED, createObjectProvider(this.properties),
createObjectProvider(this.customizers), createObjectProvider(this.filters), null); createObjectProvider(this.customizers), createObjectProvider(this.filters),
createEmptyObjectProvider());
postProcessAndInitialize(processor, this.mockRegistry); postProcessAndInitialize(processor, this.mockRegistry);
then(this.mockBinder).shouldHaveNoInteractions(); then(this.mockBinder).shouldHaveNoInteractions();
} }
@ -161,8 +169,8 @@ class MeterRegistryPostProcessorTests {
void whenAutoConfiguredCompositeThenPostProcessAndInitializeAutoConfiguredCompositeBindsTo() { void whenAutoConfiguredCompositeThenPostProcessAndInitializeAutoConfiguredCompositeBindsTo() {
this.binders.add(this.mockBinder); this.binders.add(this.mockBinder);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED, MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers), null, createObjectProvider(this.properties), createObjectProvider(this.customizers),
createObjectProvider(this.binders)); createEmptyObjectProvider(), createObjectProvider(this.binders));
AutoConfiguredCompositeMeterRegistry composite = new AutoConfiguredCompositeMeterRegistry(Clock.SYSTEM, AutoConfiguredCompositeMeterRegistry composite = new AutoConfiguredCompositeMeterRegistry(Clock.SYSTEM,
Collections.emptyList()); Collections.emptyList());
postProcessAndInitialize(processor, composite); postProcessAndInitialize(processor, composite);
@ -174,7 +182,7 @@ class MeterRegistryPostProcessorTests {
this.binders.add(this.mockBinder); this.binders.add(this.mockBinder);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED, MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers), createObjectProvider(this.properties), createObjectProvider(this.customizers),
createObjectProvider(this.filters), null); createObjectProvider(this.filters), createEmptyObjectProvider());
CompositeMeterRegistry composite = new CompositeMeterRegistry(); CompositeMeterRegistry composite = new CompositeMeterRegistry();
postProcessAndInitialize(processor, composite); postProcessAndInitialize(processor, composite);
then(this.mockBinder).shouldHaveNoInteractions(); then(this.mockBinder).shouldHaveNoInteractions();
@ -185,7 +193,7 @@ class MeterRegistryPostProcessorTests {
given(this.mockRegistry.config()).willReturn(this.mockConfig); given(this.mockRegistry.config()).willReturn(this.mockConfig);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED, MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers), createObjectProvider(this.properties), createObjectProvider(this.customizers),
createObjectProvider(this.filters), null); createObjectProvider(this.filters), createEmptyObjectProvider());
postProcessAndInitialize(processor, this.mockRegistry); postProcessAndInitialize(processor, this.mockRegistry);
then(this.mockBinder).shouldHaveNoInteractions(); then(this.mockBinder).shouldHaveNoInteractions();
} }
@ -264,4 +272,13 @@ class MeterRegistryPostProcessorTests {
return objectProvider; return objectProvider;
} }
private <T> ObjectProvider<T> createEmptyObjectProvider() {
return new ObjectProvider<T>() {
@Override
public T getObject() throws BeansException {
throw new NoSuchBeanDefinitionException("No bean");
}
};
}
} }

15
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAspectsAutoConfigurationTests.java

@ -16,7 +16,10 @@
package org.springframework.boot.micrometer.metrics.autoconfigure; package org.springframework.boot.micrometer.metrics.autoconfigure;
import java.util.function.Function;
import io.micrometer.common.annotation.ValueExpressionResolver; import io.micrometer.common.annotation.ValueExpressionResolver;
import io.micrometer.common.annotation.ValueResolver;
import io.micrometer.core.aop.CountedAspect; import io.micrometer.core.aop.CountedAspect;
import io.micrometer.core.aop.CountedMeterTagAnnotationHandler; import io.micrometer.core.aop.CountedMeterTagAnnotationHandler;
import io.micrometer.core.aop.MeterTagAnnotationHandler; import io.micrometer.core.aop.MeterTagAnnotationHandler;
@ -78,7 +81,7 @@ class MetricsAspectsAutoConfigurationTests {
void shouldUseUserDefinedMeterTagAnnotationHandler() { void shouldUseUserDefinedMeterTagAnnotationHandler() {
this.contextRunner this.contextRunner
.withBean("customMeterTagAnnotationHandler", MeterTagAnnotationHandler.class, .withBean("customMeterTagAnnotationHandler", MeterTagAnnotationHandler.class,
() -> new MeterTagAnnotationHandler(null, null)) () -> new MeterTagAnnotationHandler(getResolverProvider(), getExpressionResolverProvider()))
.run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(TimedAspect.class).hasSingleBean(MeterTagAnnotationHandler.class); assertThat(context).hasSingleBean(TimedAspect.class).hasSingleBean(MeterTagAnnotationHandler.class);
assertThat(context.getBean(TimedAspect.class)).extracting("meterTagAnnotationHandler") assertThat(context.getBean(TimedAspect.class)).extracting("meterTagAnnotationHandler")
@ -101,7 +104,7 @@ class MetricsAspectsAutoConfigurationTests {
void shouldUseUserDefinedCountedMeterTagAnnotationHandler() { void shouldUseUserDefinedCountedMeterTagAnnotationHandler() {
this.contextRunner this.contextRunner
.withBean("customCountedMeterTagAnnotationHandler", CountedMeterTagAnnotationHandler.class, .withBean("customCountedMeterTagAnnotationHandler", CountedMeterTagAnnotationHandler.class,
() -> new CountedMeterTagAnnotationHandler(null, null)) () -> new CountedMeterTagAnnotationHandler(getResolverProvider(), getExpressionResolverProvider()))
.run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(CountedAspect.class) assertThat(context).hasSingleBean(CountedAspect.class)
.hasSingleBean(CountedMeterTagAnnotationHandler.class); .hasSingleBean(CountedMeterTagAnnotationHandler.class);
@ -144,6 +147,14 @@ class MetricsAspectsAutoConfigurationTests {
}); });
} }
private Function<Class<? extends ValueExpressionResolver>, ValueExpressionResolver> getExpressionResolverProvider() {
return (clazz) -> mock(ValueExpressionResolver.class);
}
private Function<Class<? extends ValueResolver>, ValueResolver> getResolverProvider() {
return (clazz) -> mock(ValueResolver.class);
}
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
static class CustomAspectsConfiguration { static class CustomAspectsConfiguration {

1
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java

@ -131,7 +131,6 @@ class MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests {
if (bean instanceof Bravo) { if (bean instanceof Bravo) {
MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
meterRegistry.gauge("test", 1); meterRegistry.gauge("test", 1);
System.out.println(meterRegistry.find("test").gauge().getId().getTags());
} }
return bean; return bean;
} }

7
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationTests.java

@ -17,7 +17,7 @@
package org.springframework.boot.micrometer.metrics.autoconfigure; package org.springframework.boot.micrometer.metrics.autoconfigure;
import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder; import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.config.MeterFilter; import io.micrometer.core.instrument.config.MeterFilter;
@ -71,9 +71,10 @@ class MetricsAutoConfigurationTests {
MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
MeterFilter[] filters = (MeterFilter[]) ReflectionTestUtils.getField(meterRegistry, "filters"); MeterFilter[] filters = (MeterFilter[]) ReflectionTestUtils.getField(meterRegistry, "filters");
assertThat(filters).hasSize(3); assertThat(filters).hasSize(3);
assertThat(filters[0].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.DENY); Counter counter = meterRegistry.counter("counter");
assertThat(filters[0].accept(counter.getId())).isEqualTo(MeterFilterReply.DENY);
assertThat(filters[1]).isInstanceOf(PropertiesMeterFilter.class); assertThat(filters[1]).isInstanceOf(PropertiesMeterFilter.class);
assertThat(filters[2].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.ACCEPT); assertThat(filters[2].accept(counter.getId())).isEqualTo(MeterFilterReply.ACCEPT);
then((MeterBinder) context.getBean("meterBinder")).should().bindTo(meterRegistry); then((MeterBinder) context.getBean("meterBinder")).should().bindTo(meterRegistry);
then(context.getBean(MeterRegistryCustomizer.class)).should().customize(meterRegistry); then(context.getBean(MeterRegistryCustomizer.class)).should().customize(meterRegistry);
}); });

1
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/PropertiesMeterFilterTests.java

@ -46,6 +46,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
class PropertiesMeterFilterTests { class PropertiesMeterFilterTests {
@Test @Test
@SuppressWarnings("NullAway") // Test null check
void createWhenPropertiesIsNullShouldThrowException() { void createWhenPropertiesIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new PropertiesMeterFilter(null)) assertThatIllegalArgumentException().isThrownBy(() -> new PropertiesMeterFilter(null))
.withMessageContaining("'properties' must not be null"); .withMessageContaining("'properties' must not be null");

9
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java

@ -28,6 +28,7 @@ import io.prometheus.metrics.expositionformats.PrometheusTextFormatWriter;
import io.prometheus.metrics.model.registry.PrometheusRegistry; import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.tracer.common.SpanContext; import io.prometheus.metrics.tracer.common.SpanContext;
import org.assertj.core.api.InstanceOfAssertFactories; import org.assertj.core.api.InstanceOfAssertFactories;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@ -266,7 +267,9 @@ class PrometheusMetricsExportAutoConfigurationTests {
private PushGateway getPushGateway(AssertableApplicationContext context) { private PushGateway getPushGateway(AssertableApplicationContext context) {
assertThat(context).hasSingleBean(PrometheusPushGatewayManager.class); assertThat(context).hasSingleBean(PrometheusPushGatewayManager.class);
PrometheusPushGatewayManager gatewayManager = context.getBean(PrometheusPushGatewayManager.class); PrometheusPushGatewayManager gatewayManager = context.getBean(PrometheusPushGatewayManager.class);
return (PushGateway) ReflectionTestUtils.getField(gatewayManager, "pushGateway"); Object field = ReflectionTestUtils.getField(gatewayManager, "pushGateway");
assertThat(field).isNotNull();
return (PushGateway) field;
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ -335,12 +338,12 @@ class PrometheusMetricsExportAutoConfigurationTests {
return new SpanContext() { return new SpanContext() {
@Override @Override
public String getCurrentTraceId() { public @Nullable String getCurrentTraceId() {
return null; return null;
} }
@Override @Override
public String getCurrentSpanId() { public @Nullable String getCurrentSpanId() {
return null; return null;
} }

8
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/startup/StartupTimeMetricsListenerAutoConfigurationTests.java

@ -53,12 +53,12 @@ class StartupTimeMetricsListenerAutoConfigurationTests {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(StartupTimeMetricsListener.class); assertThat(context).hasSingleBean(StartupTimeMetricsListener.class);
SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class);
context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(1500))); context.getSourceApplicationContext(), Duration.ofMillis(1500)));
TimeGauge startedTimeGage = registry.find("application.started.time").timeGauge(); TimeGauge startedTimeGage = registry.find("application.started.time").timeGauge();
assertThat(startedTimeGage).isNotNull(); assertThat(startedTimeGage).isNotNull();
assertThat(startedTimeGage.value(TimeUnit.MILLISECONDS)).isEqualTo(1500L); assertThat(startedTimeGage.value(TimeUnit.MILLISECONDS)).isEqualTo(1500L);
context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null, context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(2000))); context.getSourceApplicationContext(), Duration.ofMillis(2000)));
TimeGauge readyTimeGage = registry.find("application.ready.time").timeGauge(); TimeGauge readyTimeGage = registry.find("application.ready.time").timeGauge();
assertThat(readyTimeGage).isNotNull(); assertThat(readyTimeGage).isNotNull();
@ -72,9 +72,9 @@ class StartupTimeMetricsListenerAutoConfigurationTests {
.withPropertyValues("management.metrics.enable.application.started.time:false", .withPropertyValues("management.metrics.enable.application.started.time:false",
"management.metrics.enable.application.ready.time:false") "management.metrics.enable.application.ready.time:false")
.run((context) -> { .run((context) -> {
context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(2500))); context.getSourceApplicationContext(), Duration.ofMillis(2500)));
context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null, context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(3000))); context.getSourceApplicationContext(), Duration.ofMillis(3000)));
SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class);
assertThat(registry.find("application.started.time").timeGauge()).isNull(); assertThat(registry.find("application.started.time").timeGauge()).isNull();

16
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/startup/StartupTimeMetricsListenerTests.java

@ -23,12 +23,14 @@ import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.TimeGauge; import io.micrometer.core.instrument.TimeGauge;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -72,7 +74,8 @@ class StartupTimeMetricsListenerTests {
@Test @Test
void metricRecordedWithoutMainAppClassTag() { void metricRecordedWithoutMainAppClassTag() {
SpringApplication application = mock(SpringApplication.class); SpringApplication application = mock(SpringApplication.class);
this.listener.onApplicationEvent(new ApplicationStartedEvent(application, null, null, Duration.ofSeconds(2))); this.listener.onApplicationEvent(new ApplicationStartedEvent(application, new String[0],
mock(ConfigurableApplicationContext.class), Duration.ofSeconds(2)));
TimeGauge applicationStartedGauge = this.registry.find("application.started.time").timeGauge(); TimeGauge applicationStartedGauge = this.registry.find("application.started.time").timeGauge();
assertThat(applicationStartedGauge).isNotNull(); assertThat(applicationStartedGauge).isNotNull();
assertThat(applicationStartedGauge.getId().getTags()).isEmpty(); assertThat(applicationStartedGauge.getId().getTags()).isEmpty();
@ -83,7 +86,8 @@ class StartupTimeMetricsListenerTests {
SpringApplication application = mock(SpringApplication.class); SpringApplication application = mock(SpringApplication.class);
Tags tags = Tags.of("foo", "bar"); Tags tags = Tags.of("foo", "bar");
this.listener = new StartupTimeMetricsListener(this.registry, "started", "ready", tags); this.listener = new StartupTimeMetricsListener(this.registry, "started", "ready", tags);
this.listener.onApplicationEvent(new ApplicationReadyEvent(application, null, null, Duration.ofSeconds(2))); this.listener.onApplicationEvent(new ApplicationReadyEvent(application, new String[0],
mock(ConfigurableApplicationContext.class), Duration.ofSeconds(2)));
TimeGauge applicationReadyGauge = this.registry.find("ready").timeGauge(); TimeGauge applicationReadyGauge = this.registry.find("ready").timeGauge();
assertThat(applicationReadyGauge).isNotNull(); assertThat(applicationReadyGauge).isNotNull();
assertThat(applicationReadyGauge.getId().getTags()).containsExactlyElementsOf(tags); assertThat(applicationReadyGauge.getId().getTags()).containsExactlyElementsOf(tags);
@ -97,17 +101,17 @@ class StartupTimeMetricsListenerTests {
assertThat(this.registry.find("application.ready.time").timeGauge()).isNull(); assertThat(this.registry.find("application.ready.time").timeGauge()).isNull();
} }
private ApplicationStartedEvent applicationStartedEvent(Long startupTimeMs) { private ApplicationStartedEvent applicationStartedEvent(@Nullable Long startupTimeMs) {
SpringApplication application = mock(SpringApplication.class); SpringApplication application = mock(SpringApplication.class);
given(application.getMainApplicationClass()).willAnswer((invocation) -> TestMainApplication.class); given(application.getMainApplicationClass()).willAnswer((invocation) -> TestMainApplication.class);
return new ApplicationStartedEvent(application, null, null, return new ApplicationStartedEvent(application, new String[0], mock(ConfigurableApplicationContext.class),
(startupTimeMs != null) ? Duration.ofMillis(startupTimeMs) : null); (startupTimeMs != null) ? Duration.ofMillis(startupTimeMs) : null);
} }
private ApplicationReadyEvent applicationReadyEvent(Long startupTimeMs) { private ApplicationReadyEvent applicationReadyEvent(@Nullable Long startupTimeMs) {
SpringApplication application = mock(SpringApplication.class); SpringApplication application = mock(SpringApplication.class);
given(application.getMainApplicationClass()).willAnswer((invocation) -> TestMainApplication.class); given(application.getMainApplicationClass()).willAnswer((invocation) -> TestMainApplication.class);
return new ApplicationReadyEvent(application, null, null, return new ApplicationReadyEvent(application, new String[0], mock(ConfigurableApplicationContext.class),
(startupTimeMs != null) ? Duration.ofMillis(startupTimeMs) : null); (startupTimeMs != null) ? Duration.ofMillis(startupTimeMs) : null);
} }

Loading…
Cancel
Save