From 88a6cc72e5a9f5eadd460078b017b0c72bcfc9ea Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 07:36:09 +0000 Subject: [PATCH 1/4] Update spotless packages to v8.11.0 --- buildSrc/build.gradle.kts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 2cb57deefac..b28214d8d52 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -2,7 +2,7 @@ plugins { `kotlin-dsl` // When updating, update below in dependencies too - id("com.diffplug.spotless") version "8.10.4" + id("com.diffplug.spotless") version "8.11.0" } spotless { @@ -37,7 +37,7 @@ dependencies { implementation(enforcedPlatform("com.squareup.wire:wire-bom:7.1.2")) implementation("com.google.auto.value:auto-value-annotations:1.11.1") // When updating, update above in plugins too - implementation("com.diffplug.spotless:spotless-plugin-gradle:8.10.4") + implementation("com.diffplug.spotless:spotless-plugin-gradle:8.11.0") implementation("com.gradle.develocity:com.gradle.develocity.gradle.plugin:4.6.1") implementation("com.fasterxml.jackson.core:jackson-databind:2.22.4") implementation("com.squareup:javapoet:1.13.0") From fa011919349ea471b1d29a3e3eaccd12ac4dd970 Mon Sep 17 00:00:00 2001 From: Jack Berg <34418638+jack-berg@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:24:56 -0600 Subject: [PATCH 2/4] Apply spotless and new column width --- .../io/opentelemetry/all/NoGuavaTest.java | 9 +- .../all/NoSharedInternalCodeTest.java | 9 +- .../io/opentelemetry/all/NullGuardsTest.java | 6 +- .../W3CBaggagePropagatorBenchmark.java | 25 +- .../io/opentelemetry/api/baggage/Baggage.java | 11 +- .../propagation/W3CBaggagePropagator.java | 68 +- .../common/ArrayBackedAttributesBuilder.java | 5 +- .../internal/W3CTraceContextEncoding.java | 13 +- .../io/opentelemetry/api/logs/ValueTest.java | 131 +- .../logs/ExtendedLogsBridgeApiUsageTest.java | 6 +- .../metrics/BoundInstrumentUsageTest.java | 30 +- .../metrics/ExtendedMetricsApiUsageTest.java | 39 +- .../trace/ExtendedTraceApiUsageTest.java | 16 +- .../internal/AbstractDefaultLoggerTest.java | 60 +- .../internal/AbstractDefaultMeterTest.java | 54 +- .../internal/AbstractOpenTelemetryTest.java | 7 +- .../common/impl/ConfigUtilTest.java | 25 +- .../context/StrictContextStorageTest.java | 38 +- .../io/opentelemetry/context/ContextTest.java | 26 +- .../shaded/WeakConcurrentMapTest.java | 9 +- .../internal/TlsConfigHelperTest.java | 14 +- .../exporter/internal/TlsUtilTest.java | 29 +- .../internal/marshal/MarshalerTest.java | 43 +- .../otlp/AbstractOtlpStdoutExporterTest.java | 26 +- .../otlp/OtlpStdoutMetricExporterTest.java | 8 +- .../otlp/internal/GrpcExporterBuilder.java | 19 +- .../otlp/internal/HttpExporterBuilder.java | 19 +- .../internal/OtlpDeclarativeConfigUtil.java | 15 +- .../otlp/internal/GrpcExporterTest.java | 148 +- .../otlp/internal/HttpExporterTest.java | 136 +- .../otlp/internal/OtlpConfigUtilTest.java | 15 +- .../OtlpLogRecordExporterProviderTest.java | 9 +- .../OtlpMetricExporterProviderTest.java | 9 +- .../OtlpSpanExporterProviderTest.java | 9 +- .../otlp/internal/OtlpUserAgentTest.java | 9 +- ...tlpHttpMetricExporterOkHttpSenderTest.java | 8 +- .../metrics/OtlpGrpcMetricExporterTest.java | 8 +- .../OtlpHttpMetricExporterJdkSenderTest.java | 8 +- .../otlp/internal/GrpcExporterTest.java | 15 +- .../otlp/internal/HttpExporterTest.java | 10 +- .../internal/otlp/GrpcGzipBenchmark.java | 24 +- .../MetricsRequestMarshalerBenchmark.java | 5 +- .../internal/otlp/AttributeKeyValue.java | 7 +- .../internal/otlp/KeyValueMarshaler.java | 23 +- .../otlp/logs/LogReusableDataMarshaler.java | 9 +- .../metrics/MetricReusableDataMarshaler.java | 9 +- .../traces/SpanReusableDataMarshaler.java | 9 +- ...AllocationMetricsRequestMarshalerTest.java | 231 ++- .../metrics/MetricsRequestMarshalerTest.java | 8 +- .../LogsRequestMarshalerIncubatingTest.java | 9 +- .../AbstractGrpcTelemetryExporterTest.java | 221 +-- .../AbstractHttpTelemetryExporterTest.java | 233 +-- .../prometheus/Otel2PrometheusConverter.java | 56 +- .../Otel2PrometheusConverterTest.java | 13 +- .../prometheus/PrometheusHttpServerTest.java | 13 +- .../prometheus/PrometheusIntegrationTest.java | 81 +- .../PrometheusMetricReaderTest.java | 18 +- .../PrometheusMetricReaderProviderTest.java | 22 +- .../sender/jdk/internal/JdkHttpSender.java | 40 +- .../jdk/internal/JdkHttpSenderTest.java | 38 +- .../okhttp/internal/OkHttpGrpcSender.java | 102 +- .../okhttp/internal/OkHttpHttpSender.java | 29 +- .../okhttp/internal/OkHttpGrpcSenderTest.java | 54 +- .../okhttp/internal/OkHttpHttpSenderTest.java | 103 +- .../internal/OkHttpHttpSuppressionTest.java | 2 +- .../okhttp/internal/OkHttpUtilTest.java | 11 +- .../okhttp/internal/RetryInterceptorTest.java | 19 +- .../trace/propagation/JaegerPropagator.java | 25 +- .../trace/propagation/OtTracePropagator.java | 25 +- .../graal/IncubatingApiTests.java | 28 +- ...stAutoConfigurationCustomizerProvider.java | 10 +- .../B3PropagationIntegrationTest.java | 20 +- .../javadocs/JavaDocsCrawler.java | 36 +- .../OpenCensusMetricProducer.java | 9 +- .../opencensusshim/OpenTelemetrySpanImpl.java | 15 +- .../opencensusshim/SpanConverter.java | 15 +- .../opencensusshim/DelegatingSpanTest.java | 17 +- .../opencensusshim/MetricAdapterTest.java | 188 +- .../OpenCensusMetricProducerTest.java | 54 +- .../opencensusshim/OpenCensusMetricsTest.java | 15 +- .../opentracingshim/SpanContextShim.java | 5 +- .../ActiveSpanReplacementTest.java | 45 +- .../testbed/actorpropagation/Actor.java | 66 +- .../baggagehandling/BaggageHandlingTest.java | 39 +- .../Client.java | 41 +- .../errorreporting/ErrorReportingTest.java | 19 +- .../latespanfinish/LateSpanFinishTest.java | 46 +- .../testbed/listenerperrequest/Client.java | 13 +- .../testbed/multiplecallbacks/Client.java | 37 +- .../nestedcallbacks/NestedCallbacksTest.java | 33 +- .../testbed/promisepropagation/Promise.java | 58 +- .../PromisePropagationTest.java | 31 +- .../statelesscommonrequesthandler/Client.java | 17 +- .../perf/OtlpPipelineStressTest.java | 62 +- .../spi/internal/DefaultConfigProperties.java | 27 +- .../spi/internal/ConfigPropertiesTest.java | 76 +- ...AutoConfiguredOpenTelemetrySdkBuilder.java | 39 +- .../MeterProviderConfiguration.java | 24 +- .../AutoConfiguredOpenTelemetrySdkTest.java | 219 ++- .../LogRecordExporterConfigurationTest.java | 44 +- .../LoggerProviderConfigurationTest.java | 20 +- .../PropagatorConfigurationTest.java | 26 +- .../ResourceConfigurationTest.java | 26 +- .../TracerProviderConfigurationTest.java | 74 +- .../AutoConfiguredOpenTelemetrySdkTest.java | 9 +- .../ConfigurableLogRecordExporterTest.java | 14 +- .../ConfigurableMetricExporterTest.java | 18 +- .../ConfigurableSpanExporterTest.java | 64 +- .../sdk/autoconfigure/FullConfigTest.java | 179 +- .../LogRecordExporterConfigurationTest.java | 15 +- .../LoggerProviderConfigurationTest.java | 75 +- .../MeterProviderConfigurationTest.java | 13 +- .../MetricExporterConfigurationTest.java | 22 +- .../ResourceConfigurationTest.java | 77 +- .../SpanExporterConfigurationTest.java | 7 +- .../TracerProviderConfigurationTest.java | 18 +- .../provider/LogRecordCustomizer.java | 9 +- .../provider/MetricCustomizer.java | 21 +- .../provider/SpanCustomizer.java | 19 +- .../TestTracerProviderConfigurer.java | 5 +- .../DeclarativeConfigurationTest.java | 24 +- .../FullDeclarativeConfigTest.java | 150 +- .../ComposableRuleBasedSamplerFactory.java | 74 +- .../DeclarativeConfigContext.java | 16 +- .../LoggerProviderFactory.java | 7 +- .../MeterProviderFactory.java | 40 +- .../declarativeconfig/PropagatorFactory.java | 13 +- .../TracerProviderFactory.java | 6 +- .../YamlDeclarativeConfigProperties.java | 33 +- .../AttributeListFactoryTest.java | 6 +- .../DeclarativeConfigContextTest.java | 30 +- .../DeclarativeConfigurationCreateTest.java | 30 +- .../DeclarativeConfigurationParseTest.java | 7 +- .../InstrumentSelectorFactoryTest.java | 7 +- .../LogRecordExporterFactoryTest.java | 10 +- .../LoggerProviderFactoryTest.java | 11 +- .../MetricExporterFactoryTest.java | 11 +- ...OpenTelemetryConfigurationFactoryTest.java | 11 +- .../PropagatorFactoryTest.java | 7 +- .../ResourceFactoryTest.java | 9 +- .../SpanExporterFactoryTest.java | 8 +- ...rativeConfigurationCustomizerProvider.java | 47 +- .../YamlDeclarativeConfigPropertiesTest.java | 9 +- .../model/ModelPackageBoundaryTest.java | 31 +- .../trace/LeakDetectingSpanProcessor.java | 5 +- .../logs/EventToSpanEventBridgeTest.java | 52 +- .../trace/LeakDetectingSpanProcessorTest.java | 22 +- .../trace/OnStartSpanProcessorTest.java | 9 +- .../JaegerRemoteSamplerIntegrationTest.java | 9 +- .../JaegerRemoteSamplerProviderTest.java | 47 +- .../sampler/JaegerRemoteSamplerTest.java | 79 +- .../JaegerRemoteSamplerGrpcNettyTest.java | 71 +- .../sdk/OpenTelemetrySdkTest.java | 5 +- .../sdk/ScopeConfiguratorTest.java | 100 +- .../internal/StacktraceRenderBenchmark.java | 17 +- .../sdk/common/CompletableResultCode.java | 33 +- .../opentelemetry/sdk/resources/Resource.java | 26 +- .../sdk/resources/ResourceBuilder.java | 7 +- .../internal/AttributeCheckUtil.java | 13 +- .../sdk/common/CompletableResultCodeTest.java | 102 +- .../internal/ComponentRegistryTest.java | 15 +- .../internal/IncludeExcludePredicateTest.java | 25 +- .../sdk/common/internal/RateLimiterTest.java | 15 +- .../sdk/resources/ResourceTest.java | 23 +- .../resources/internal/EntityUtilTest.java | 18 +- .../sdk/logs/LogsBenchmarks.java | 7 +- .../sdk/logs/SdkLoggerProvider.java | 15 +- .../logs/export/BatchLogRecordProcessor.java | 24 +- ...gacyLogRecordProcessorInstrumentation.java | 7 +- .../logs/export/SimpleLogRecordProcessor.java | 35 +- .../sdk/logs/SdkLogRecordBuilderTest.java | 13 +- .../logs/SdkLoggerProviderMetricsTest.java | 364 ++-- .../sdk/logs/SdkLoggerProviderTest.java | 47 +- .../opentelemetry/sdk/logs/ValueBodyTest.java | 143 +- .../export/BatchLogRecordProcessorTest.java | 50 +- .../export/SimpleLogRecordProcessorTest.java | 7 +- .../sdk/logs/ExtendedLoggerBuilderTest.java | 52 +- .../sdk/logs/LoggerConfigTest.java | 17 +- ...trumentGarbageCollectionBenchmarkTest.java | 68 +- .../state/tester/AsyncCounterTester.java | 13 +- .../state/tester/DoubleLastValueTester.java | 11 +- .../state/tester/LongLastValueTester.java | 11 +- .../sdk/metrics/SdkMeterProvider.java | 27 +- .../metrics/export/PeriodicMetricReader.java | 37 +- .../state/AsynchronousMetricStorage.java | 103 +- .../CumulativeSynchronousMetricStorage.java | 29 +- .../state/DeltaSynchronousMetricStorage.java | 89 +- .../sdk/metrics/CardinalityTest.java | 625 +++---- .../ExplicitBucketBoundariesAdviceTest.java | 89 +- .../sdk/metrics/IdentityTest.java | 186 +- .../sdk/metrics/SdkBatchCallbackTest.java | 136 +- .../sdk/metrics/SdkDoubleCounterTest.java | 121 +- .../sdk/metrics/SdkDoubleGaugeTest.java | 256 ++- .../sdk/metrics/SdkDoubleHistogramTest.java | 308 ++-- .../metrics/SdkDoubleUpDownCounterTest.java | 132 +- .../sdk/metrics/SdkLongCounterTest.java | 129 +- .../sdk/metrics/SdkLongGaugeTest.java | 254 ++- .../sdk/metrics/SdkLongHistogramTest.java | 515 +++--- .../sdk/metrics/SdkLongUpDownCounterTest.java | 123 +- .../metrics/SdkMeterProviderMetricsTest.java | 43 +- .../sdk/metrics/SdkMeterProviderTest.java | 715 ++++---- .../sdk/metrics/SdkMeterRegistryTest.java | 25 +- .../SdkObservableDoubleCounterTest.java | 179 +- .../SdkObservableDoubleUpDownCounterTest.java | 166 +- .../metrics/SdkObservableLongCounterTest.java | 165 +- .../SdkObservableLongUpDownCounterTest.java | 165 +- .../metrics/data/ImmutableMetricDataTest.java | 75 +- .../export/PeriodicMetricReaderTest.java | 20 +- ...se2ExponentialHistogramAggregatorTest.java | 66 +- ...ExplicitBucketHistogramAggregatorTest.java | 20 +- .../DoubleLastValueAggregatorTest.java | 16 +- .../aggregator/DoubleSumAggregatorTest.java | 20 +- .../aggregator/LongSumAggregatorTest.java | 20 +- .../data/MutableHistogramPointDataTest.java | 83 +- .../HistogramExemplarReservoirTest.java | 64 +- .../RandomFixedSizeExemplarReservoirTest.java | 48 +- .../state/AsynchronousMetricStorageTest.java | 361 ++-- .../internal/state/PooledHashMapTest.java | 13 +- .../state/SynchronousMetricStorageTest.java | 475 ++--- ...xplicitBucketHistogramAggregationTest.java | 44 +- .../internal/view/FilteredAttributesTest.java | 41 +- .../sdk/metrics/AttributesAdviceTest.java | 50 +- .../metrics/BoundInstrumentExemplarTest.java | 33 +- .../sdk/metrics/MeterConfigTest.java | 71 +- .../SynchronousInstrumentStressTest.java | 397 ++-- .../sdk/testing/assertj/TracesAssert.java | 23 +- .../assertj/AttributeAssertionTest.java | 9 +- .../testing/assertj/LogAssertionsTest.java | 242 ++- .../testing/assertj/MetricAssertionsTest.java | 1603 ++++++++--------- .../testing/assertj/TraceAssertionsTest.java | 673 +++---- .../testing/junit4/OpenTelemetryRuleTest.java | 20 +- .../junit5/OpenTelemetryExtensionTest.java | 33 +- .../export/BatchSpanProcessorMetrics.java | 9 +- .../sdk/trace/SdkTracerProvider.java | 15 +- .../sdk/trace/export/BatchSpanProcessor.java | 24 +- .../LegacySpanProcessorInstrumentation.java | 9 +- .../sdk/trace/export/SimpleSpanProcessor.java | 35 +- .../opentelemetry/sdk/trace/SdkSpanTest.java | 114 +- .../trace/SdkTracerProviderMetricsTest.java | 1497 ++++++++------- .../sdk/trace/StressTestRunner.java | 17 +- .../trace/export/BatchSpanProcessorTest.java | 66 +- .../trace/export/SimpleSpanProcessorTest.java | 7 +- .../ExtendedSpanProcessorUsageTest.java | 11 +- .../ActiveSpanReplacementTest.java | 49 +- .../trace/testbed/actorpropagation/Actor.java | 70 +- .../Client.java | 39 +- .../errorreporting/ErrorReportingTest.java | 38 +- .../latespanfinish/LateSpanFinishTest.java | 46 +- .../testbed/listenerperrequest/Client.java | 13 +- .../testbed/multiplecallbacks/Client.java | 21 +- .../nestedcallbacks/NestedCallbacksTest.java | 33 +- .../testbed/promisepropagation/Promise.java | 42 +- .../PromisePropagationTest.java | 31 +- .../statelesscommonrequesthandler/Client.java | 15 +- 254 files changed, 8209 insertions(+), 9945 deletions(-) diff --git a/all/src/test/java/io/opentelemetry/all/NoGuavaTest.java b/all/src/test/java/io/opentelemetry/all/NoGuavaTest.java index b8d44a75522..d89b587a5c0 100644 --- a/all/src/test/java/io/opentelemetry/all/NoGuavaTest.java +++ b/all/src/test/java/io/opentelemetry/all/NoGuavaTest.java @@ -52,10 +52,9 @@ void noGuavaReferences(String artifactId, String absolutePath) throws IOExceptio private static Stream artifactsAndJars() throws IOException { return Files.readAllLines(Path.of(System.getenv("ARTIFACTS_AND_JARS"))).stream() - .map( - line -> { - String[] parts = line.split(":", 2); - return Arguments.argumentSet(parts[0], parts[0], parts[1]); - }); + .map(line -> { + String[] parts = line.split(":", 2); + return Arguments.argumentSet(parts[0], parts[0], parts[1]); + }); } } diff --git a/all/src/test/java/io/opentelemetry/all/NoSharedInternalCodeTest.java b/all/src/test/java/io/opentelemetry/all/NoSharedInternalCodeTest.java index 58f276b290e..cc15768021d 100644 --- a/all/src/test/java/io/opentelemetry/all/NoSharedInternalCodeTest.java +++ b/all/src/test/java/io/opentelemetry/all/NoSharedInternalCodeTest.java @@ -110,10 +110,9 @@ public boolean test(JavaClass javaClass) { private static Stream artifactsAndJars() throws IOException { List lines = Files.readAllLines(Path.of(System.getenv("ARTIFACTS_AND_JARS"))); return lines.stream() - .map( - line -> { - String[] parts = line.split(":", 2); - return Arguments.argumentSet(parts[0], parts[0], parts[1]); - }); + .map(line -> { + String[] parts = line.split(":", 2); + return Arguments.argumentSet(parts[0], parts[0], parts[1]); + }); } } diff --git a/all/src/test/java/io/opentelemetry/all/NullGuardsTest.java b/all/src/test/java/io/opentelemetry/all/NullGuardsTest.java index a0697adab0f..01ad07589ef 100644 --- a/all/src/test/java/io/opentelemetry/all/NullGuardsTest.java +++ b/all/src/test/java/io/opentelemetry/all/NullGuardsTest.java @@ -416,10 +416,8 @@ private static boolean visitSupertype( private static boolean declaresMethod(ClassModel cls, String name, String desc) { return cls.methods().stream() .filter(m -> !m.flags().has(AccessFlag.STATIC) && !m.flags().has(AccessFlag.PRIVATE)) - .anyMatch( - m -> - name.equals(m.methodName().stringValue()) - && desc.equals(m.methodType().stringValue())); + .anyMatch(m -> + name.equals(m.methodName().stringValue()) && desc.equals(m.methodType().stringValue())); } private static boolean isInAuditablePackage(ClassModel cls) { diff --git a/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java b/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java index 5f24acee5b5..a348e69e19e 100644 --- a/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java +++ b/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java @@ -34,19 +34,18 @@ public class W3CBaggagePropagatorBenchmark { static { List baggages = IntStream.range(0, 100) - .mapToObj( - i -> - "key" - + i - + " = value" - + i - + ";metaKey" - + i - + "=\tmetaVal" - + i - + ",broken)key" - + i - + "=value") + .mapToObj(i -> + "key" + + i + + " = value" + + i + + ";metaKey" + + i + + "=\tmetaVal" + + i + + ",broken)key" + + i + + "=value") .collect(Collectors.toList()); SMALL_BAGGAGE = Collections.singletonMap("baggage", String.join(",", baggages.subList(0, 5))); LARGE_BAGGAGE = Collections.singletonMap("baggage", String.join(",", baggages)); diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java b/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java index bdbf5cb2ace..3b6ae74710f 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java @@ -127,12 +127,11 @@ default BaggageEntry getEntry(String entryKey) { return null; } BaggageEntry[] result = new BaggageEntry[] {null}; - forEach( - (key, entry) -> { - if (entryKey.equals(key)) { - result[0] = entry; - } - }); + forEach((key, entry) -> { + if (entryKey.equals(key)) { + result[0] = entry; + } + }); return result[0]; } } diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java index 214c85c06b4..227c0f4b62b 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java @@ -74,41 +74,39 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se private static String baggageToString(Baggage baggage) { StringBuilder headerContent = new StringBuilder(); int[] entryCount = {0}; - baggage.forEach( - (key, baggageEntry) -> { - if (!isValidBaggageKey(key)) { - LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid key"); - return; - } - if (!isValidBaggageValue(baggageEntry.getValue())) { - LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid value"); - return; - } - if (!isValidBaggageMetadata(baggageEntry.getMetadata().getValue())) { - LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid metadata"); - return; - } - if (entryCount[0] >= MAX_BAGGAGE_ENTRIES) { - return; - } - String encodedValue = encodeValue(baggageEntry.getValue()); - String metadataValue = baggageEntry.getMetadata().getValue(); - String metadata = - (metadataValue != null && !metadataValue.isEmpty()) ? metadataValue : null; - // Exit early if adding this entry causes the total length to exceed the limit - // encodedEntryLength includes a trailing comma; the final string trims exactly one, - // so the net contribution to the final length is entryLength - 1. - if (headerContent.length() + encodedEntryLength(key, encodedValue, metadata) - 1 - > MAX_BAGGAGE_BYTES) { - return; - } - headerContent.append(key).append("=").append(encodedValue); - if (metadata != null) { - headerContent.append(";").append(metadata); - } - headerContent.append(","); - entryCount[0]++; - }); + baggage.forEach((key, baggageEntry) -> { + if (!isValidBaggageKey(key)) { + LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid key"); + return; + } + if (!isValidBaggageValue(baggageEntry.getValue())) { + LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid value"); + return; + } + if (!isValidBaggageMetadata(baggageEntry.getMetadata().getValue())) { + LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid metadata"); + return; + } + if (entryCount[0] >= MAX_BAGGAGE_ENTRIES) { + return; + } + String encodedValue = encodeValue(baggageEntry.getValue()); + String metadataValue = baggageEntry.getMetadata().getValue(); + String metadata = (metadataValue != null && !metadataValue.isEmpty()) ? metadataValue : null; + // Exit early if adding this entry causes the total length to exceed the limit + // encodedEntryLength includes a trailing comma; the final string trims exactly one, + // so the net contribution to the final length is entryLength - 1. + if (headerContent.length() + encodedEntryLength(key, encodedValue, metadata) - 1 + > MAX_BAGGAGE_BYTES) { + return; + } + headerContent.append(key).append("=").append(encodedValue); + if (metadata != null) { + headerContent.append(";").append(metadata); + } + headerContent.append(","); + entryCount[0]++; + }); if (headerContent.length() == 0) { return ""; diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java b/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java index 14f26c2f938..7fabcf990d0 100644 --- a/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java @@ -189,9 +189,8 @@ public AttributesBuilder remove(AttributeKey key) { if (key.getKey().isEmpty()) { return this; } - return removeIf( - entryKey -> - key.getKey().equals(entryKey.getKey()) && key.getType().equals(entryKey.getType())); + return removeIf(entryKey -> + key.getKey().equals(entryKey.getKey()) && key.getType().equals(entryKey.getType())); } @Override diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java b/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java index 70ee231a6e9..b21093b09e7 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java @@ -78,13 +78,12 @@ public static String encodeTraceState(TraceState traceState) { return ""; } StringBuilder builder = new StringBuilder(TRACESTATE_MAX_SIZE); - traceState.forEach( - (key, value) -> { - if (builder.length() != 0) { - builder.append(TRACESTATE_ENTRY_DELIMITER); - } - builder.append(key).append(TRACESTATE_KEY_VALUE_DELIMITER).append(value); - }); + traceState.forEach((key, value) -> { + if (builder.length() != 0) { + builder.append(TRACESTATE_ENTRY_DELIMITER); + } + builder.append(key).append(TRACESTATE_KEY_VALUE_DELIMITER).append(value); + }); return builder.toString(); } } diff --git a/api/all/src/test/java/io/opentelemetry/api/logs/ValueTest.java b/api/all/src/test/java/io/opentelemetry/api/logs/ValueTest.java index 3a55a20fd9f..1be1bc97700 100644 --- a/api/all/src/test/java/io/opentelemetry/api/logs/ValueTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/logs/ValueTest.java @@ -33,90 +33,82 @@ class ValueTest { @Test void value_OfString() { assertThat(Value.of("foo")) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.STRING); - assertThat(value.getValue()).isEqualTo("foo"); - assertThat(value).hasSameHashCodeAs(Value.of("foo")); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.STRING); + assertThat(value.getValue()).isEqualTo("foo"); + assertThat(value).hasSameHashCodeAs(Value.of("foo")); + }); } @Test void value_OfBoolean() { assertThat(Value.of(true)) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.BOOLEAN); - assertThat(value.getValue()).isEqualTo(true); - assertThat(value).hasSameHashCodeAs(Value.of(true)); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.BOOLEAN); + assertThat(value.getValue()).isEqualTo(true); + assertThat(value).hasSameHashCodeAs(Value.of(true)); + }); } @Test void value_OfLong() { assertThat(Value.of(1L)) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.LONG); - assertThat(value.getValue()).isEqualTo(1L); - assertThat(value).hasSameHashCodeAs(Value.of(1L)); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.LONG); + assertThat(value.getValue()).isEqualTo(1L); + assertThat(value).hasSameHashCodeAs(Value.of(1L)); + }); } @Test void value_OfDouble() { assertThat(Value.of(1.1)) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.DOUBLE); - assertThat(value.getValue()).isEqualTo(1.1); - assertThat(value).hasSameHashCodeAs(Value.of(1.1)); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.DOUBLE); + assertThat(value.getValue()).isEqualTo(1.1); + assertThat(value).hasSameHashCodeAs(Value.of(1.1)); + }); } @Test void value_OfByteArray() { assertThat(Value.of(new byte[] {'a', 'b'})) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.BYTES); - ByteBuffer buf = value.getValue(); - // ValueBytes returns read only view of ByteBuffer - assertThatThrownBy(buf::array).isInstanceOf(ReadOnlyBufferException.class); - byte[] bytes = new byte[buf.remaining()]; - buf.get(bytes); - assertThat(bytes).isEqualTo(new byte[] {'a', 'b'}); - assertThat(value).hasSameHashCodeAs(Value.of(new byte[] {'a', 'b'})); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.BYTES); + ByteBuffer buf = value.getValue(); + // ValueBytes returns read only view of ByteBuffer + assertThatThrownBy(buf::array).isInstanceOf(ReadOnlyBufferException.class); + byte[] bytes = new byte[buf.remaining()]; + buf.get(bytes); + assertThat(bytes).isEqualTo(new byte[] {'a', 'b'}); + assertThat(value).hasSameHashCodeAs(Value.of(new byte[] {'a', 'b'})); + }); } @Test void value_OfvalueArray() { assertThat(Value.of(Value.of(true), Value.of(1L))) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.ARRAY); - assertThat(value.getValue()).isEqualTo(Arrays.asList(Value.of(true), Value.of(1L))); - assertThat(value).hasSameHashCodeAs(Value.of(Value.of(true), Value.of(1L))); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.ARRAY); + assertThat(value.getValue()).isEqualTo(Arrays.asList(Value.of(true), Value.of(1L))); + assertThat(value).hasSameHashCodeAs(Value.of(Value.of(true), Value.of(1L))); + }); } @Test @SuppressWarnings("DoubleBraceInitialization") void value_OfKeyValueList() { assertThat(Value.of(KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); - assertThat(value.getValue()) - .isEqualTo( - Arrays.asList( - KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); - assertThat(value) - .hasSameHashCodeAs( - Value.of( - KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); + assertThat(value.getValue()) + .isEqualTo( + Arrays.asList( + KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); + assertThat(value) + .hasSameHashCodeAs( + Value.of(KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); + }); assertThat( Value.of( @@ -126,23 +118,22 @@ void value_OfKeyValueList() { put("long", Value.of(1L)); } })) - .satisfies( - value -> { - assertThat(value.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); - assertThat(value.getValue()) - .isEqualTo( - Arrays.asList( - KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); - assertThat(value) - .hasSameHashCodeAs( - Value.of( - new LinkedHashMap>() { - { - put("bool", Value.of(true)); - put("long", Value.of(1L)); - } - })); - }); + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); + assertThat(value.getValue()) + .isEqualTo( + Arrays.asList( + KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); + assertThat(value) + .hasSameHashCodeAs( + Value.of( + new LinkedHashMap>() { + { + put("bool", Value.of(true)); + put("long", Value.of(1L)); + } + })); + }); } @Test diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java index f02c7a7aea7..b8c8f48c6a7 100644 --- a/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java @@ -68,10 +68,8 @@ void loggerEnabled() { // omitted from the results even if logs were emitted. The check if enabled simply avoids // unnecessary computation. assertThat(exporter.getFinishedLogRecordItems()) - .allSatisfy( - logRecordData -> - assertThat(logRecordData.getInstrumentationScopeInfo().getName()) - .isEqualTo("loggerA")); + .allSatisfy(logRecordData -> + assertThat(logRecordData.getInstrumentationScopeInfo().getName()).isEqualTo("loggerA")); } private static final Random random = new Random(); diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java index 6361914ded1..dfbd103fdf1 100644 --- a/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java @@ -111,22 +111,20 @@ void rollTheDice() { // One cumulative data point per die face, each with the exact roll count recorded above. assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("dice.rolls") - .hasDescription("The number of times each side of the die was rolled") - .hasUnit("{roll}") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> point.hasAttributes(ROLL_1).hasValue(counts[1]), - point -> point.hasAttributes(ROLL_2).hasValue(counts[2]), - point -> point.hasAttributes(ROLL_3).hasValue(counts[3]), - point -> point.hasAttributes(ROLL_4).hasValue(counts[4]), - point -> point.hasAttributes(ROLL_5).hasValue(counts[5]), - point -> point.hasAttributes(ROLL_6).hasValue(counts[6])))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("dice.rolls") + .hasDescription("The number of times each side of the die was rolled") + .hasUnit("{roll}") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying( + point -> point.hasAttributes(ROLL_1).hasValue(counts[1]), + point -> point.hasAttributes(ROLL_2).hasValue(counts[2]), + point -> point.hasAttributes(ROLL_3).hasValue(counts[3]), + point -> point.hasAttributes(ROLL_4).hasValue(counts[4]), + point -> point.hasAttributes(ROLL_5).hasValue(counts[5]), + point -> point.hasAttributes(ROLL_6).hasValue(counts[6])))); } } } diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java index fb38819007c..e7f679557fe 100644 --- a/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java @@ -68,9 +68,8 @@ void meterEnabled() { // omitted from the results even if values were recorded. The check if enabled simply avoids // unnecessary computation. assertThat(reader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric.getInstrumentationScopeInfo().getName()).isEqualTo("meterA")); + .allSatisfy(metric -> + assertThat(metric.getInstrumentationScopeInfo().getName()).isEqualTo("meterA")); } private static final Random random = new Random(); @@ -124,27 +123,23 @@ void attributesAdvice() { metricData -> assertThat(metricData) .hasName("counter1") - .hasLongSumSatisfying( - sumAssert -> - sumAssert.hasPointsSatisfying( - point -> - point - .hasValue(1L) - .hasAttributes( - Attributes.builder() - .put("key1", "value1") - .put("key2", "value2") - .build()))), + .hasLongSumSatisfying(sumAssert -> + sumAssert.hasPointsSatisfying(point -> + point + .hasValue(1L) + .hasAttributes( + Attributes.builder() + .put("key1", "value1") + .put("key2", "value2") + .build()))), metricData -> assertThat(metricData) .hasName("counter2") - .hasLongSumSatisfying( - sumAssert -> - sumAssert.hasPointsSatisfying( - point -> - point - .hasValue(1L) - .hasAttributes( - Attributes.builder().put("key1", "value1").build())))); + .hasLongSumSatisfying(sumAssert -> + sumAssert.hasPointsSatisfying(point -> + point + .hasValue(1L) + .hasAttributes( + Attributes.builder().put("key1", "value1").build())))); } } diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java index 333c2d7e291..5759b6923b9 100644 --- a/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java @@ -80,9 +80,8 @@ void tracerEnabled() { // omitted from the results even if spans were recorded. The check if enabled simply avoids // unnecessary computation. assertThat(exporter.getFinishedSpanItems()) - .allSatisfy( - spanData -> - assertThat(spanData.getInstrumentationScopeInfo().getName()).isEqualTo("tracerA")); + .allSatisfy(spanData -> + assertThat(spanData.getInstrumentationScopeInfo().getName()).isEqualTo("tracerA")); } private static final Random random = new Random(); @@ -138,12 +137,11 @@ void setParentFrom() { // Verify the span has the correct parent context assertThat(spanExporter.getFinishedSpanItems()) - .satisfiesExactly( - span -> - assertThat(span) - .hasName("local_root") - .hasParentSpanId(remoteParentContext.getSpanId()) - .hasTraceId(remoteParentContext.getTraceId())); + .satisfiesExactly(span -> + assertThat(span) + .hasName("local_root") + .hasParentSpanId(remoteParentContext.getSpanId()) + .hasTraceId(remoteParentContext.getTraceId())); } /** diff --git a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultLoggerTest.java b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultLoggerTest.java index a72abfd1794..9ea2e794c86 100644 --- a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultLoggerTest.java +++ b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultLoggerTest.java @@ -32,13 +32,12 @@ void noopLoggerProvider_doesNotThrow() { assertThat(provider).isSameAs(getLoggerProvider()); assertThatCode(() -> provider.get("scope-name")).doesNotThrowAnyException(); - assertThatCode( - () -> - provider - .loggerBuilder("scope-name") - .setInstrumentationVersion("1.0") - .setSchemaUrl("http://schema.com") - .build()) + assertThatCode(() -> + provider + .loggerBuilder("scope-name") + .setInstrumentationVersion("1.0") + .setSchemaUrl("http://schema.com") + .build()) .doesNotThrowAnyException(); assertThatCode(() -> provider.loggerBuilder("scope-name").build().logRecordBuilder()) @@ -53,30 +52,29 @@ void defaultIsEnabled() { @Test void buildAndEmit() { - assertThatCode( - () -> - getLogger() - .logRecordBuilder() - .setEventName("event name") - .setTimestamp(100, TimeUnit.SECONDS) - .setTimestamp(Instant.now()) - .setObservedTimestamp(100, TimeUnit.SECONDS) - .setObservedTimestamp(Instant.now()) - .setContext(Context.root()) - .setSeverity(Severity.DEBUG) - .setSeverityText("debug") - .setBody("body") - .setBody(Value.of("body")) - .setAttribute(AttributeKey.stringKey("key1"), "value1") - .setAttribute("stringKey", "value") - .setAttribute("longKey", 100L) - .setAttribute("intKey", 100) - .setAttribute("doubleKey", 1.23) - .setAttribute("boolKey", true) - .setAttribute("valueKey", Value.of("value")) - .setAllAttributes(Attributes.builder().put("key2", "value2").build()) - .setException(new RuntimeException("error")) - .emit()) + assertThatCode(() -> + getLogger() + .logRecordBuilder() + .setEventName("event name") + .setTimestamp(100, TimeUnit.SECONDS) + .setTimestamp(Instant.now()) + .setObservedTimestamp(100, TimeUnit.SECONDS) + .setObservedTimestamp(Instant.now()) + .setContext(Context.root()) + .setSeverity(Severity.DEBUG) + .setSeverityText("debug") + .setBody("body") + .setBody(Value.of("body")) + .setAttribute(AttributeKey.stringKey("key1"), "value1") + .setAttribute("stringKey", "value") + .setAttribute("longKey", 100L) + .setAttribute("intKey", 100) + .setAttribute("doubleKey", 1.23) + .setAttribute("boolKey", true) + .setAttribute("valueKey", Value.of("value")) + .setAllAttributes(Attributes.builder().put("key2", "value2").build()) + .setException(new RuntimeException("error")) + .emit()) .doesNotThrowAnyException(); } } diff --git a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultMeterTest.java b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultMeterTest.java index 235a4e451b2..282abaeef73 100644 --- a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultMeterTest.java +++ b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultMeterTest.java @@ -211,11 +211,10 @@ void noopObservableLongGauge_doesNotThrow() { .ofLongs() .setDescription("The current temperature") .setUnit("C") - .buildWithCallback( - m -> { - m.record(1); - m.record(2, Attributes.of(stringKey("thing"), "engine")); - }); + .buildWithCallback(m -> { + m.record(1); + m.record(2, Attributes.of(stringKey("thing"), "engine")); + }); } @Test @@ -246,11 +245,10 @@ void noopObservableDoubleGauge_doesNotThrow() { .gaugeBuilder("temperature") .setDescription("The current temperature") .setUnit("C") - .buildWithCallback( - m -> { - m.record(1.0e1); - m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); - }); + .buildWithCallback(m -> { + m.record(1.0e1); + m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); + }); } @Test @@ -259,11 +257,10 @@ void noopObservableLongCounter_doesNotThrow() { .counterBuilder("temperature") .setDescription("The current temperature") .setUnit("C") - .buildWithCallback( - m -> { - m.record(1); - m.record(2, Attributes.of(stringKey("thing"), "engine")); - }); + .buildWithCallback(m -> { + m.record(1); + m.record(2, Attributes.of(stringKey("thing"), "engine")); + }); } @Test @@ -273,11 +270,10 @@ void noopObservableDoubleCounter_doesNotThrow() { .ofDoubles() .setDescription("The current temperature") .setUnit("C") - .buildWithCallback( - m -> { - m.record(1.0e1); - m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); - }); + .buildWithCallback(m -> { + m.record(1.0e1); + m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); + }); } @Test @@ -286,11 +282,10 @@ void noopObservableLongUpDownCounter_doesNotThrow() { .upDownCounterBuilder("temperature") .setDescription("The current temperature") .setUnit("C") - .buildWithCallback( - m -> { - m.record(1); - m.record(2, Attributes.of(stringKey("thing"), "engine")); - }); + .buildWithCallback(m -> { + m.record(1); + m.record(2, Attributes.of(stringKey("thing"), "engine")); + }); } @Test @@ -300,11 +295,10 @@ void noopObservableDoubleUpDownCounter_doesNotThrow() { .ofDoubles() .setDescription("The current temperature") .setUnit("C") - .buildWithCallback( - m -> { - m.record(1.0e1); - m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); - }); + .buildWithCallback(m -> { + m.record(1.0e1); + m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); + }); } @Test diff --git a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractOpenTelemetryTest.java b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractOpenTelemetryTest.java index f1f4d54ed95..d613a16fd27 100644 --- a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractOpenTelemetryTest.java +++ b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractOpenTelemetryTest.java @@ -105,10 +105,9 @@ void getThenSet() { // Call GlobalOpenTelemetry.get() using a utility method so we can later assert it was // responsible for setting GlobalOpenTelemetry. assertThat(getGlobalOpenTelemetry()) - .satisfies( - instance -> - assertThat(instance.getClass().getName()) - .isEqualTo("io.opentelemetry.api.GlobalOpenTelemetry$ObfuscatedOpenTelemetry")) + .satisfies(instance -> + assertThat(instance.getClass().getName()) + .isEqualTo("io.opentelemetry.api.GlobalOpenTelemetry$ObfuscatedOpenTelemetry")) .extracting("delegate") .isSameAs(OpenTelemetry.noop()); diff --git a/common/src/test/java/io/opentelemetry/common/impl/ConfigUtilTest.java b/common/src/test/java/io/opentelemetry/common/impl/ConfigUtilTest.java index de13d2bf69a..851465e0009 100644 --- a/common/src/test/java/io/opentelemetry/common/impl/ConfigUtilTest.java +++ b/common/src/test/java/io/opentelemetry/common/impl/ConfigUtilTest.java @@ -71,20 +71,19 @@ void systemPropertiesConcurrentAccess() throws ExecutionException, InterruptedEx List> futures = new ArrayList<>(); for (int i = 0; i < threads; i++) { futures.add( - executor.submit( - () -> { - try { - latch.await(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } + executor.submit(() -> { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } - for (int j = 0; j < cycles; j++) { - String property = "prop " + j; - System.setProperty(property, "a"); - System.getProperties().remove(property); - } - })); + for (int j = 0; j < cycles; j++) { + String property = "prop " + j; + System.setProperty(property, "a"); + System.getProperties().remove(property); + } + })); } latch.countDown(); diff --git a/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java b/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java index 262edb84150..7d68d975978 100644 --- a/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java +++ b/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java @@ -120,14 +120,13 @@ void scope_close_onWrongThread(Supplier method, String methodName) throws AtomicReference errorCatcher = new AtomicReference<>(); Thread t2 = - new Thread( - () -> { - try { - closeable.get().close(); - } catch (Throwable t) { - errorCatcher.set(t); - } - }); + new Thread(() -> { + try { + closeable.get().close(); + } catch (Throwable t) { + errorCatcher.set(t); + } + }); t2.setName("t2"); t2.start(); t2.join(); @@ -135,10 +134,9 @@ void scope_close_onWrongThread(Supplier method, String methodName) throws assertThat(errorCatcher.get()) .isInstanceOf(IllegalStateException.class) .hasMessage("Thread [t1] opened scope, but thread [t2] closed it") - .satisfies( - e -> - assertThat(e.getCause().getMessage()) - .matches("Thread \\[t1\\] opened scope for .* here:")); + .satisfies(e -> + assertThat(e.getCause().getMessage()) + .matches("Thread \\[t1\\] opened scope for .* here:")); } @SuppressWarnings("ReturnValueIgnored") @@ -175,14 +173,12 @@ void garbageCollectedScope() { await() .atMost(Duration.ofSeconds(30)) - .untilAsserted( - () -> { - System.gc(); - LoggingEvent log = - logs.assertContains("Scope garbage collected before being closed."); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - assertThat(log.getThrowable().getMessage()) - .matches("Thread \\[Test worker\\] opened a scope of .* here:"); - }); + .untilAsserted(() -> { + System.gc(); + LoggingEvent log = logs.assertContains("Scope garbage collected before being closed."); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + assertThat(log.getThrowable().getMessage()) + .matches("Thread \\[Test worker\\] opened a scope of .* here:"); + }); } } diff --git a/context/src/test/java/io/opentelemetry/context/ContextTest.java b/context/src/test/java/io/opentelemetry/context/ContextTest.java index 04fcada02cd..0f671dade48 100644 --- a/context/src/test/java/io/opentelemetry/context/ContextTest.java +++ b/context/src/test/java/io/opentelemetry/context/ContextTest.java @@ -718,13 +718,12 @@ void scheduleAtFixedRate() { assertThat(future).isNotNull(); await() .await() - .untilAsserted( - () -> { - if (!future.isCancelled()) { - future.cancel(true); - } - assertThat(longAdder.intValue()).isGreaterThan(1); - }); + .untilAsserted(() -> { + if (!future.isCancelled()) { + future.cancel(true); + } + assertThat(longAdder.intValue()).isGreaterThan(1); + }); assertThat(longAdder.intValue()).isGreaterThan(1); } @@ -736,13 +735,12 @@ void scheduleWithFixedDelay() { assertThat(future).isNotNull(); await() .await() - .untilAsserted( - () -> { - if (!future.isCancelled()) { - future.cancel(true); - } - assertThat(longAdder.intValue()).isGreaterThan(1); - }); + .untilAsserted(() -> { + if (!future.isCancelled()) { + future.cancel(true); + } + assertThat(longAdder.intValue()).isGreaterThan(1); + }); } } diff --git a/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java b/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java index 6adfb18821f..5319e689fe8 100644 --- a/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java +++ b/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java @@ -153,11 +153,10 @@ void doTest() throws Exception { key1 = key2 = null; // Make eligible for GC System.gc(); await() - .untilAsserted( - () -> { - triggerClean(); - assertThat(map.approximateSize(), is(2)); - }); + .untilAsserted(() -> { + triggerClean(); + assertThat(map.approximateSize(), is(2)); + }); assertThat(map.get(key3), is(value3)); assertThat(map.getIfPresent(key3), is(value3)); assertThat(map.get(key4), is(value4)); diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsConfigHelperTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsConfigHelperTest.java index 267d13da0da..1ac3a304b36 100644 --- a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsConfigHelperTest.java +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsConfigHelperTest.java @@ -60,20 +60,18 @@ void createKeyManager() throws CertificateEncodingException { void createKeyManager_AlreadyExists_Throws() throws Exception { helper.setKeyManagerFromCerts( serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded()); - assertThatThrownBy( - () -> - helper.setKeyManagerFromCerts( - serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded())) + assertThatThrownBy(() -> + helper.setKeyManagerFromCerts( + serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("keyManager has been previously configured"); helper = new TlsConfigHelper(); helper.setSslContext( SSLContext.getInstance("TLS"), TlsUtil.trustManager(serverTls.certificate().getEncoded())); - assertThatThrownBy( - () -> - helper.setKeyManagerFromCerts( - serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded())) + assertThatThrownBy(() -> + helper.setKeyManagerFromCerts( + serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("sslContext has been previously configured"); } diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsUtilTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsUtilTest.java index 5710ee12ebd..7733c6ba8f5 100644 --- a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsUtilTest.java +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsUtilTest.java @@ -58,19 +58,16 @@ void setup() throws CertificateException { @Test void keyManager_Rsa() { - assertThatCode( - () -> - TlsUtil.keyManager( - rsaCertificate.key().getEncoded(), rsaCertificate.cert().getEncoded())) + assertThatCode(() -> + TlsUtil.keyManager( + rsaCertificate.key().getEncoded(), rsaCertificate.cert().getEncoded())) .doesNotThrowAnyException(); } @Test void keyManager_Ec() { - assertThatCode( - () -> - TlsUtil.keyManager( - ecCertificate.key().getEncoded(), ecCertificate.cert().getEncoded())) + assertThatCode(() -> + TlsUtil.keyManager(ecCertificate.key().getEncoded(), ecCertificate.cert().getEncoded())) .doesNotThrowAnyException(); } @@ -78,10 +75,9 @@ void keyManager_Ec() { void generatePrivateKey_Invalid() { PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(TlsUtil.decodePem(rsaCertificate.key().getEncoded())); - assertThatCode( - () -> - TlsUtil.generatePrivateKey( - keySpec, Collections.singletonList(KeyFactory.getInstance("EC")))) + assertThatCode(() -> + TlsUtil.generatePrivateKey( + keySpec, Collections.singletonList(KeyFactory.getInstance("EC")))) .isInstanceOf(SSLException.class) .hasMessage("Unable to generate key from supported algorithms: [EC]"); } @@ -137,11 +133,10 @@ void keyManager_CertWithExplanatoryText(SelfSignedCertificate selfSignedCertific StandardOpenOption.APPEND); Files.write(certificate, "\n".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); - assertThatCode( - () -> - TlsUtil.keyManager( - com.google.common.io.Files.toByteArray(selfSignedCertificate.privateKey()), - com.google.common.io.Files.toByteArray(new File(certificate.toString())))) + assertThatCode(() -> + TlsUtil.keyManager( + com.google.common.io.Files.toByteArray(selfSignedCertificate.privateKey()), + com.google.common.io.Files.toByteArray(new File(certificate.toString())))) .doesNotThrowAnyException(); } diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/MarshalerTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/MarshalerTest.java index 6ea83a5ce0a..d635fe7da8a 100644 --- a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/MarshalerTest.java +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/MarshalerTest.java @@ -101,33 +101,30 @@ private static Stream writeToArgs() { return Stream.of( Arguments.argumentSet( "repeated message collection", - asWriter( - output -> - output.serializeRepeatedMessageWithContext( - fieldInfo, - Collections.singleton("value"), - throwingMarshaler, - context, - MarshalerContext.key()))), + asWriter(output -> + output.serializeRepeatedMessageWithContext( + fieldInfo, + Collections.singleton("value"), + throwingMarshaler, + context, + MarshalerContext.key()))), Arguments.argumentSet( "repeated message map", - asWriter( - output -> - output.serializeRepeatedMessageWithContext( - fieldInfo, - Collections.singletonMap("key", "value"), - throwingMarshaler2, - context, - MarshalerContext.key()))), + asWriter(output -> + output.serializeRepeatedMessageWithContext( + fieldInfo, + Collections.singletonMap("key", "value"), + throwingMarshaler2, + context, + MarshalerContext.key()))), Arguments.argumentSet( "repeated message attributes", - asWriter( - output -> - output.serializeRepeatedMessageWithContext( - fieldInfo, - Attributes.builder().put("key", "value").build(), - throwingMarshaler2Attributes, - context)))); + asWriter(output -> + output.serializeRepeatedMessageWithContext( + fieldInfo, + Attributes.builder().put("key", "value").build(), + throwingMarshaler2Attributes, + context)))); } private static Writer asWriter(Writer writer) { diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/AbstractOtlpStdoutExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/AbstractOtlpStdoutExporterTest.java index b97558948d2..9b5f06029cb 100644 --- a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/AbstractOtlpStdoutExporterTest.java +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/AbstractOtlpStdoutExporterTest.java @@ -385,11 +385,10 @@ protected T exporterFromComponentProvider(DeclarativeConfigProperties properties return (T) StreamSupport.stream( properties.getComponentLoader().load(ComponentProvider.class).spliterator(), false) - .filter( - p -> { - return "otlp_file/development".equals(p.getName()) - && p.getType().equals(componentProviderType); - }) + .filter(p -> { + return "otlp_file/development".equals(p.getName()) + && p.getType().equals(componentProviderType); + }) .findFirst() .orElseThrow(() -> new IllegalStateException("No provider found")) .create(properties); @@ -413,15 +412,14 @@ protected T exporterFromProvider(ConfigProperties config) { private Object loadProvider(ConfigProperties config) { return StreamSupport.stream( config.getComponentLoader().load(providerClass).spliterator(), false) - .filter( - p -> { - try { - return AbstractOtlpStdoutExporterTest.TYPE.equals( - p.getClass().getDeclaredMethod("getName").invoke(p)); - } catch (Exception e) { - throw new RuntimeException(e); - } - }) + .filter(p -> { + try { + return AbstractOtlpStdoutExporterTest.TYPE.equals( + p.getClass().getDeclaredMethod("getName").invoke(p)); + } catch (Exception e) { + throw new RuntimeException(e); + } + }) .findFirst() .orElseThrow(() -> new IllegalStateException("No provider found")); } diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutMetricExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutMetricExporterTest.java index 28b0b2e3587..4331dc443e5 100644 --- a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutMetricExporterTest.java +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutMetricExporterTest.java @@ -96,11 +96,9 @@ void componentProviderMetricConfig() { @Test void validMetricConfig() { - assertThatCode( - () -> - OtlpStdoutMetricExporter.builder() - .setAggregationTemporalitySelector( - AggregationTemporalitySelector.deltaPreferred())) + assertThatCode(() -> + OtlpStdoutMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) .doesNotThrowAnyException(); assertThat( OtlpStdoutMetricExporter.builder() diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilder.java index ce0a45b384f..a1190a4ef79 100644 --- a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilder.java +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilder.java @@ -216,16 +216,15 @@ public GrpcExporter build() { supplierResult.forEach( (key, value) -> result.put(key, Collections.singletonList(value))); } - constantHeaders.forEach( - (key, value) -> - result.merge( - key, - Collections.singletonList(value), - (v1, v2) -> { - List merged = new ArrayList<>(v1); - merged.addAll(v2); - return merged; - })); + constantHeaders.forEach((key, value) -> + result.merge( + key, + Collections.singletonList(value), + (v1, v2) -> { + List merged = new ArrayList<>(v1); + merged.addAll(v2); + return merged; + })); return result; }; diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilder.java index 6bb5f3d328e..999acda451e 100644 --- a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilder.java +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilder.java @@ -231,16 +231,15 @@ public HttpExporter build() { supplierResult.forEach( (key, value) -> result.put(key, Collections.singletonList(value))); } - constantHeaders.forEach( - (key, value) -> - result.merge( - key, - Collections.singletonList(value), - (v1, v2) -> { - List merged = new ArrayList<>(v1); - merged.addAll(v2); - return merged; - })); + constantHeaders.forEach((key, value) -> + result.merge( + key, + Collections.singletonList(value), + (v1, v2) -> { + List merged = new ArrayList<>(v1); + merged.addAll(v2); + return merged; + })); return result; }; diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpDeclarativeConfigUtil.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpDeclarativeConfigUtil.java index 80b0b4e0418..52a5a91dabf 100644 --- a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpDeclarativeConfigUtil.java +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpDeclarativeConfigUtil.java @@ -89,14 +89,13 @@ public static void configureOtlpExporterBuilder( List headers = config.getStructuredList("headers"); if (headers != null) { - headers.forEach( - header -> { - String name = header.getString("name"); - String value = header.getString("value"); - if (name != null && value != null) { - addHeader.accept(name, value); - } - }); + headers.forEach(header -> { + String name = header.getString("name"); + String value = header.getString("value"); + if (name != null && value != null) { + addHeader.accept(name, value); + } + }); } String compression = config.getString("compression"); diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java index 5f9767b0092..2587d6101ed 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java @@ -108,18 +108,14 @@ public int getContentLength() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(1) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName(signalMetricPrefix + "inflight") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.isNotMonotonic() - .hasPointsSatisfying( - pa -> - pa.hasAttributes(expectedAttributes) - .hasValue(42)))); + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.isNotMonotonic() + .hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42)))); onResponse.accept(grpcResponse(GrpcStatusCode.OK)); @@ -153,75 +149,65 @@ public int getContentLength() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(3) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName(signalMetricPrefix + "inflight") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName(signalMetricPrefix + "exported") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributes(expectedAttributes).hasValue(42), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "" + UNAVAILABLE.getValue()) - .build()) - .hasValue(15), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "java.io.IOException") - .build()) - .hasValue(7)))) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName("otel.sdk.exporter.operation.duration") - .hasUnit("s") - .hasHistogramSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.RPC_RESPONSE_STATUS_CODE, - GrpcStatusCode.OK.name()) - .build()) - .hasBucketCounts(1), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "" + UNAVAILABLE.getValue()) - .put( - SemConvConstants.RPC_RESPONSE_STATUS_CODE, - UNAVAILABLE.name()) - .build()) - .hasBucketCounts(1), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "java.io.IOException") - .build()) - .hasBucketCounts(1)))); + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "exported") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.ERROR_TYPE, + "" + UNAVAILABLE.getValue()) + .build()) + .hasValue(15), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasValue(7)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasUnit("s") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.RPC_RESPONSE_STATUS_CODE, + GrpcStatusCode.OK.name()) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.ERROR_TYPE, + "" + UNAVAILABLE.getValue()) + .put( + SemConvConstants.RPC_RESPONSE_STATUS_CODE, + UNAVAILABLE.name()) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasBucketCounts(1)))); } } diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java index 3fbaac9d4a5..3e8fcf31dac 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java @@ -113,18 +113,14 @@ public int getContentLength() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(1) - .anySatisfy( - metric -> - assertThat(metric) - .hasName(signalMetricPrefix + "inflight") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.isNotMonotonic() - .hasPointsSatisfying( - pa -> - pa.hasAttributes(expectedAttributes) - .hasValue(42)))); + .anySatisfy(metric -> + assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.isNotMonotonic() + .hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42)))); onResponse.accept(new FakeHttpResponse(200, "Ok")); return null; @@ -156,71 +152,57 @@ public int getContentLength() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(3) - .anySatisfy( - metric -> - assertThat(metric) - .hasName(signalMetricPrefix + "inflight") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) - .anySatisfy( - metric -> - assertThat(metric) - .hasName(signalMetricPrefix + "exported") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributes(expectedAttributes).hasValue(42), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put(SemConvConstants.ERROR_TYPE, "404") - .build()) - .hasValue(15), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "java.io.IOException") - .build()) - .hasValue(7)))) - .anySatisfy( - metric -> - assertThat(metric) - .hasName("otel.sdk.exporter.operation.duration") - .hasUnit("s") - .hasHistogramSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.HTTP_RESPONSE_STATUS_CODE, - 200) - .build()) - .hasBucketCounts(1), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put(SemConvConstants.ERROR_TYPE, "404") - .put( - SemConvConstants.HTTP_RESPONSE_STATUS_CODE, - 404) - .build()) - .hasBucketCounts(1), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "java.io.IOException") - .build()) - .hasBucketCounts(1)))); + .anySatisfy(metric -> + assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) + .anySatisfy(metric -> + assertThat(metric) + .hasName(signalMetricPrefix + "exported") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "404") + .build()) + .hasValue(15), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasValue(7)))) + .anySatisfy(metric -> + assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasUnit("s") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.HTTP_RESPONSE_STATUS_CODE, 200) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "404") + .put(SemConvConstants.HTTP_RESPONSE_STATUS_CODE, 404) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasBucketCounts(1)))); } } diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtilTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtilTest.java index 35e4a1647f6..d4972b56ad5 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtilTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtilTest.java @@ -392,10 +392,9 @@ private static String configureEndpoint(String dataType, Map pro @Test void configureOtlpAggregationTemporality() { - assertThatThrownBy( - () -> - configureAggregationTemporality( - ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "foo"))) + assertThatThrownBy(() -> + configureAggregationTemporality( + ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "foo"))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unrecognized aggregation temporality:"); @@ -429,11 +428,9 @@ private static AggregationTemporality configureAggregationTemporality( @Test void configureOtlpHistogramDefaultAggregation() { - assertThatThrownBy( - () -> - configureHistogramDefaultAggregation( - ImmutableMap.of( - "otel.exporter.otlp.metrics.default.histogram.aggregation", "foo"))) + assertThatThrownBy(() -> + configureHistogramDefaultAggregation( + ImmutableMap.of("otel.exporter.otlp.metrics.default.histogram.aggregation", "foo"))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unrecognized default histogram aggregation:"); assertThat( diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProviderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProviderTest.java index 9fe5bad7681..887d9dd89b1 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProviderTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProviderTest.java @@ -91,11 +91,10 @@ void getName() { @Test void createExporter_UnsupportedProtocol() { - assertThatThrownBy( - () -> - provider.createExporter( - DefaultConfigProperties.createFromMap( - Collections.singletonMap("otel.exporter.otlp.protocol", "foo")))) + assertThatThrownBy(() -> + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.protocol", "foo")))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP logs protocol: foo"); } diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProviderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProviderTest.java index 0bcd064c97d..58b6f59d276 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProviderTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProviderTest.java @@ -97,11 +97,10 @@ void getName() { @Test void createExporter_UnsupportedProtocol() { - assertThatThrownBy( - () -> - provider.createExporter( - DefaultConfigProperties.createFromMap( - singletonMap("otel.exporter.otlp.protocol", "foo")))) + assertThatThrownBy(() -> + provider.createExporter( + DefaultConfigProperties.createFromMap( + singletonMap("otel.exporter.otlp.protocol", "foo")))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP metrics protocol: foo"); } diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProviderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProviderTest.java index 827fdc009ba..837231e27c2 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProviderTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProviderTest.java @@ -92,11 +92,10 @@ void getName() { @Test void createExporter_UnsupportedProtocol() { - assertThatThrownBy( - () -> - provider.createExporter( - DefaultConfigProperties.createFromMap( - Collections.singletonMap("otel.exporter.otlp.protocol", "foo")))) + assertThatThrownBy(() -> + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.protocol", "foo")))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP traces protocol: foo"); } diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgentTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgentTest.java index ce0723833fe..0cbb4adf4e7 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgentTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgentTest.java @@ -21,11 +21,10 @@ void getUserAgent() { void addUserAgentHeader() { AtomicReference keyRef = new AtomicReference<>(); AtomicReference valueRef = new AtomicReference<>(); - OtlpUserAgent.addUserAgentHeader( - (key, value) -> { - keyRef.set(key); - valueRef.set(value); - }); + OtlpUserAgent.addUserAgentHeader((key, value) -> { + keyRef.set(key); + valueRef.set(value); + }); assertThat(keyRef.get()).isEqualTo("User-Agent"); assertThat(valueRef.get()).matches("OTel-OTLP-Exporter-Java/1\\..*"); } diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterOkHttpSenderTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterOkHttpSenderTest.java index a2b18d2bed0..aadff167009 100644 --- a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterOkHttpSenderTest.java +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterOkHttpSenderTest.java @@ -38,11 +38,9 @@ protected OtlpHttpMetricExporterOkHttpSenderTest() { /** Test configuration specific to metric exporter. */ @Test void validMetricConfig() { - assertThatCode( - () -> - OtlpHttpMetricExporter.builder() - .setAggregationTemporalitySelector( - AggregationTemporalitySelector.deltaPreferred())) + assertThatCode(() -> + OtlpHttpMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) .doesNotThrowAnyException(); assertThat( OtlpHttpMetricExporter.builder() diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java index 956a5350076..cabe7bc60b2 100644 --- a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java @@ -39,11 +39,9 @@ class OtlpGrpcMetricExporterTest /** Test configuration specific to metric exporter. */ @Test void validMetricConfig() { - assertThatCode( - () -> - OtlpGrpcMetricExporter.builder() - .setAggregationTemporalitySelector( - AggregationTemporalitySelector.deltaPreferred())) + assertThatCode(() -> + OtlpGrpcMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) .doesNotThrowAnyException(); assertThat( OtlpGrpcMetricExporter.builder() diff --git a/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterJdkSenderTest.java b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterJdkSenderTest.java index 58cfe8cb1bb..021831a4e89 100644 --- a/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterJdkSenderTest.java +++ b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterJdkSenderTest.java @@ -39,11 +39,9 @@ protected OtlpHttpMetricExporterJdkSenderTest() { /** Test configuration specific to metric exporter. */ @Test void validMetricConfig() { - assertThatCode( - () -> - OtlpHttpMetricExporter.builder() - .setAggregationTemporalitySelector( - AggregationTemporalitySelector.deltaPreferred())) + assertThatCode(() -> + OtlpHttpMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) .doesNotThrowAnyException(); assertThat( OtlpHttpMetricExporter.builder() diff --git a/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java index 548b5616946..76077386a60 100644 --- a/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java +++ b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java @@ -16,14 +16,13 @@ class GrpcExporterTest { @Test void build_NoGrpcSenderProvider() { - assertThatThrownBy( - () -> - new GrpcExporterBuilder( - StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER, - Duration.ofSeconds(10), - new URI("http://localhost"), - "service/method") - .build()) + assertThatThrownBy(() -> + new GrpcExporterBuilder( + StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER, + Duration.ofSeconds(10), + new URI("http://localhost"), + "service/method") + .build()) .isInstanceOf(IllegalStateException.class) .hasMessage( "No GrpcSenderProvider found on classpath. Please add dependency on " diff --git a/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java index 4b90ab55a21..a8e2c7013c7 100644 --- a/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java +++ b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java @@ -14,12 +14,10 @@ class HttpExporterTest { @Test void build_NoHttpSenderProvider() { - assertThatThrownBy( - () -> - new HttpExporterBuilder( - StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER, - "http://localhost") - .build()) + assertThatThrownBy(() -> + new HttpExporterBuilder( + StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER, "http://localhost") + .build()) .isInstanceOf(IllegalStateException.class) .hasMessage( "No HttpSenderProvider found on classpath. Please add dependency on " diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java index 21a98f5546c..1a18de10e10 100644 --- a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java @@ -80,9 +80,8 @@ public class GrpcGzipBenchmark { .setDescription("gauge description") .setUnit("unit") .ofLongs() - .buildWithCallback( - measurement -> - measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); + .buildWithCallback(measurement -> + measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); LongCounter longCounter = meter1 .counterBuilder("counter") @@ -125,16 +124,15 @@ public class GrpcGzipBenchmark { List resourceMetrics = Arrays.stream(ResourceMetricsMarshaler.create(metricData)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - return ResourceMetrics.parseFrom(bos.toByteArray()); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) + .map(marshaler -> { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + return ResourceMetrics.parseFrom(bos.toByteArray()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) .collect(Collectors.toList()); METRICS_REQUEST = ExportMetricsServiceRequest.newBuilder().addAllResourceMetrics(resourceMetrics).build(); diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java index 95d652c3533..7ce2fa1a3c1 100644 --- a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java @@ -74,9 +74,8 @@ public class MetricsRequestMarshalerBenchmark { .setDescription("gauge description") .setUnit("unit") .ofLongs() - .buildWithCallback( - measurement -> - measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); + .buildWithCallback(measurement -> + measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); LongCounter longCounter = meter1 .counterBuilder("counter") diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValue.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValue.java index 2b3cc82519e..3f3ff738074 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValue.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValue.java @@ -35,10 +35,9 @@ static AttributeKeyValue of(AttributeKey attributeKey, T value) { @SuppressWarnings("unchecked") static List> of(Attributes attributes) { List> result = new ArrayList<>(attributes.size()); - attributes.forEach( - (key, value) -> { - result.add(of((AttributeKey) key, (T) value)); - }); + attributes.forEach((key, value) -> { + result.add(of((AttributeKey) key, (T) value)); + }); return result; } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java index 8cf231b0c86..b2f77128b73 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java @@ -74,18 +74,17 @@ public static KeyValueMarshaler[] createRepeated(List> item } KeyValueMarshaler[] keyValueMarshalers = new KeyValueMarshaler[items.size()]; - items.forEach( - item -> - new Consumer>() { - int index = 0; - - @Override - public void accept(AttributeKeyValue attributeKeyValue) { - keyValueMarshalers[index++] = - KeyValueMarshaler.create( - attributeKeyValue.getAttributeKey(), attributeKeyValue.getValue()); - } - }); + items.forEach(item -> + new Consumer>() { + int index = 0; + + @Override + public void accept(AttributeKeyValue attributeKeyValue) { + keyValueMarshalers[index++] = + KeyValueMarshaler.create( + attributeKeyValue.getAttributeKey(), attributeKeyValue.getValue()); + } + }); return keyValueMarshalers; } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogReusableDataMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogReusableDataMarshaler.java index fadaaa09bc4..e43684fe030 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogReusableDataMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogReusableDataMarshaler.java @@ -46,11 +46,10 @@ public CompletableResultCode export(Collection logs) { exportMarshaler.initialize(logs); return doExport .apply(exportMarshaler, logs.size()) - .whenComplete( - () -> { - exportMarshaler.reset(); - marshalerPool.add(exportMarshaler); - }); + .whenComplete(() -> { + exportMarshaler.reset(); + marshalerPool.add(exportMarshaler); + }); } // MemoryMode == MemoryMode.IMMUTABLE_DATA LogsRequestMarshaler request = LogsRequestMarshaler.create(logs); diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricReusableDataMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricReusableDataMarshaler.java index a3d7187698b..42c48b6a690 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricReusableDataMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricReusableDataMarshaler.java @@ -46,11 +46,10 @@ public CompletableResultCode export(Collection metrics) { exportMarshaler.initialize(metrics); return doExport .apply(exportMarshaler, metrics.size()) - .whenComplete( - () -> { - exportMarshaler.reset(); - marshalerPool.add(exportMarshaler); - }); + .whenComplete(() -> { + exportMarshaler.reset(); + marshalerPool.add(exportMarshaler); + }); } // MemoryMode == MemoryMode.IMMUTABLE_DATA MetricsRequestMarshaler request = MetricsRequestMarshaler.create(metrics); diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanReusableDataMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanReusableDataMarshaler.java index b359b6cc30c..ff54280b610 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanReusableDataMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanReusableDataMarshaler.java @@ -46,11 +46,10 @@ public CompletableResultCode export(Collection spans) { exportMarshaler.initialize(spans); return doExport .apply(exportMarshaler, spans.size()) - .whenComplete( - () -> { - exportMarshaler.reset(); - marshalerPool.add(exportMarshaler); - }); + .whenComplete(() -> { + exportMarshaler.reset(); + marshalerPool.add(exportMarshaler); + }); } // MemoryMode == MemoryMode.IMMUTABLE_DATA TraceRequestMarshaler request = TraceRequestMarshaler.create(spans); diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshalerTest.java index 6ae3fa94a4f..dfb20b9723b 100644 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshalerTest.java +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshalerTest.java @@ -242,157 +242,140 @@ public Stream provideArguments( arguments( named( "long gauge", - metrics( - meterProvider -> - meterProvider - .get("long gauge") - .gaugeBuilder("gauge") - .setDescription("gauge description") - .setUnit("unit") - .ofLongs() - .buildWithCallback( - measurement -> - measurement.record( - 5, - Attributes.of( - AttributeKey.stringKey("key"), "value")))))), + metrics(meterProvider -> + meterProvider + .get("long gauge") + .gaugeBuilder("gauge") + .setDescription("gauge description") + .setUnit("unit") + .ofLongs() + .buildWithCallback(measurement -> + measurement.record( + 5, Attributes.of(AttributeKey.stringKey("key"), "value")))))), arguments( named( "long counter", - metrics( - meterProvider -> { - LongCounter longCounter = - meterProvider - .get("long counter") - .counterBuilder("counter") - .setDescription("counter description") - .setUnit("unit") - .build(); - longCounter.add(1); - longCounter.add(2, Attributes.of(AttributeKey.longKey("lives"), 9L)); - longCounter.add(3); - }))), + metrics(meterProvider -> { + LongCounter longCounter = + meterProvider + .get("long counter") + .counterBuilder("counter") + .setDescription("counter description") + .setUnit("unit") + .build(); + longCounter.add(1); + longCounter.add(2, Attributes.of(AttributeKey.longKey("lives"), 9L)); + longCounter.add(3); + }))), arguments( named( "long updowncounter", - metrics( - meterProvider -> { - LongUpDownCounter longUpDownCounter = - meterProvider - .get("long updowncounter") - .upDownCounterBuilder("updowncounter") - .setDescription("updowncounter description") - .setUnit("unit") - .build(); - longUpDownCounter.add(1); - longUpDownCounter.add( - -1, Attributes.of(AttributeKey.booleanKey("on"), true)); - longUpDownCounter.add(1); - }))), + metrics(meterProvider -> { + LongUpDownCounter longUpDownCounter = + meterProvider + .get("long updowncounter") + .upDownCounterBuilder("updowncounter") + .setDescription("updowncounter description") + .setUnit("unit") + .build(); + longUpDownCounter.add(1); + longUpDownCounter.add(-1, Attributes.of(AttributeKey.booleanKey("on"), true)); + longUpDownCounter.add(1); + }))), arguments( named( "double gauge", - metrics( - meterProvider -> - meterProvider - .get("double gauge") - .gaugeBuilder("doublegauge") - .setDescription("doublegauge") - .setUnit("unit") - .buildWithCallback(measurement -> measurement.record(5.0))))), + metrics(meterProvider -> + meterProvider + .get("double gauge") + .gaugeBuilder("doublegauge") + .setDescription("doublegauge") + .setUnit("unit") + .buildWithCallback(measurement -> measurement.record(5.0))))), arguments( named( "double counter", - metrics( - meterProvider -> { - DoubleCounter doubleCounter = - meterProvider - .get("double counter") - .counterBuilder("doublecounter") - .ofDoubles() - .build(); - doubleCounter.add(1.0); - doubleCounter.add(2.0); - }))), + metrics(meterProvider -> { + DoubleCounter doubleCounter = + meterProvider + .get("double counter") + .counterBuilder("doublecounter") + .ofDoubles() + .build(); + doubleCounter.add(1.0); + doubleCounter.add(2.0); + }))), arguments( named( "double updowncounter", - metrics( - meterProvider -> { - DoubleUpDownCounter doubleUpDownCounter = - meterProvider - .get("double updowncounter") - .upDownCounterBuilder("doubleupdown") - .ofDoubles() - .build(); - doubleUpDownCounter.add(1.0); - doubleUpDownCounter.add(-1.0); - }))), + metrics(meterProvider -> { + DoubleUpDownCounter doubleUpDownCounter = + meterProvider + .get("double updowncounter") + .upDownCounterBuilder("doubleupdown") + .ofDoubles() + .build(); + doubleUpDownCounter.add(1.0); + doubleUpDownCounter.add(-1.0); + }))), arguments( named( "double histogram", - metrics( - meterProvider -> { - DoubleHistogram histogram = - meterProvider - .get("double histogram") - .histogramBuilder("histogram") - .build(); - histogram.record(1.0); - histogram.record(2.0); - histogram.record(3.0); - histogram.record(4.0); - histogram.record(5.0); - }))), + metrics(meterProvider -> { + DoubleHistogram histogram = + meterProvider.get("double histogram").histogramBuilder("histogram").build(); + histogram.record(1.0); + histogram.record(2.0); + histogram.record(3.0); + histogram.record(4.0); + histogram.record(5.0); + }))), arguments( named( "long histogram", - metrics( - meterProvider -> { - LongHistogram histogram = - meterProvider - .get("long histogram") - .histogramBuilder("histogram") - .ofLongs() - .build(); - histogram.record(1); - histogram.record(2); - histogram.record(3); - histogram.record(4); - histogram.record(5); - }))), + metrics(meterProvider -> { + LongHistogram histogram = + meterProvider + .get("long histogram") + .histogramBuilder("histogram") + .ofLongs() + .build(); + histogram.record(1); + histogram.record(2); + histogram.record(3); + histogram.record(4); + histogram.record(5); + }))), arguments( named( "double exponential histogram", - metrics( - meterProvider -> { - DoubleHistogram histogram = - meterProvider - .get("double exponential histogram") - .histogramBuilder("exponentialhistogram") - .build(); - histogram.record(1.0); - histogram.record(2.0); - histogram.record(3.0); - histogram.record(4.0); - histogram.record(5.0); - }))), + metrics(meterProvider -> { + DoubleHistogram histogram = + meterProvider + .get("double exponential histogram") + .histogramBuilder("exponentialhistogram") + .build(); + histogram.record(1.0); + histogram.record(2.0); + histogram.record(3.0); + histogram.record(4.0); + histogram.record(5.0); + }))), arguments( named( "long exponential histogram", - metrics( - meterProvider -> { - DoubleHistogram histogram = - meterProvider - .get("long exponential histogram") - .histogramBuilder("exponentialhistogram") - .build(); - histogram.record(1); - histogram.record(2); - histogram.record(3); - histogram.record(4); - histogram.record(5); - })))); + metrics(meterProvider -> { + DoubleHistogram histogram = + meterProvider + .get("long exponential histogram") + .histogramBuilder("exponentialhistogram") + .build(); + histogram.record(1); + histogram.record(2); + histogram.record(3); + histogram.record(4); + histogram.record(5); + })))); } } diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java index f32a297028a..f91b10e71c9 100644 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java @@ -1229,11 +1229,9 @@ private static List toHistogramDataPoints( private static List toExponentialHistogramDataPoints( MarshalerSource marshalerSource, Collection points) { return points.stream() - .map( - point -> - parse( - ExponentialHistogramDataPoint.getDefaultInstance(), - marshalerSource.create(point))) + .map(point -> + parse( + ExponentialHistogramDataPoint.getDefaultInstance(), marshalerSource.create(point))) .collect(Collectors.toList()); } diff --git a/exporters/otlp/common/src/testIncubating/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerIncubatingTest.java b/exporters/otlp/common/src/testIncubating/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerIncubatingTest.java index 8cb055672cc..1b5e92fba0c 100644 --- a/exporters/otlp/common/src/testIncubating/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerIncubatingTest.java +++ b/exporters/otlp/common/src/testIncubating/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerIncubatingTest.java @@ -63,11 +63,10 @@ class LogsRequestMarshalerIncubatingTest { @ParameterizedTest @EnumSource(MarshalerSource.class) void toProtoLogRecord_NotExtendedLogRecordData_DoesNotThrow(MarshalerSource marshalerSource) { - assertThatCode( - () -> - parse( - LogRecord.getDefaultInstance(), - marshalerSource.create(TestLogRecordData.builder().build()))) + assertThatCode(() -> + parse( + LogRecord.getDefaultInstance(), + marshalerSource.create(TestLogRecordData.builder().build()))) .doesNotThrowAnyException(); } diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java index d1ab21ff3e3..d77054b2c5e 100644 --- a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java @@ -374,10 +374,8 @@ void export() { // Assert request contains OTLP spec compliant User-Agent header assertThat(httpRequests) .singleElement() - .satisfies( - req -> - assertThat(req.headers().get("User-Agent")) - .matches("OTel-OTLP-Exporter-Java/1\\..*")); + .satisfies(req -> + assertThat(req.headers().get("User-Agent")).matches("OTel-OTLP-Exporter-Java/1\\..*")); } @Test @@ -408,10 +406,9 @@ void responseBodyBounds() { ex -> assertThat(requireNonNull(ex.getResponse())) .isNotNull() - .satisfies( - grpcResponse -> - assertThat(grpcResponse.getStatusCode()) - .isEqualTo(GrpcStatusCode.RESOURCE_EXHAUSTED))); + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.RESOURCE_EXHAUSTED))); } @Test @@ -442,10 +439,9 @@ void responseBodyBoundsGzipCompressed() throws IOException { FailedExportException.GrpcExportException.class, ex -> assertThat(requireNonNull(ex.getResponse())) - .satisfies( - grpcResponse -> - assertThat(grpcResponse.getStatusCode()) - .isEqualTo(GrpcStatusCode.RESOURCE_EXHAUSTED))); + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.RESOURCE_EXHAUSTED))); } // Verifies that a response with an unrecognized grpc-encoding fails with INTERNAL rather than @@ -469,10 +465,9 @@ void unsupportedGrpcMessageEncoding() { FailedExportException.GrpcExportException.class, ex -> assertThat(requireNonNull(ex.getResponse())) - .satisfies( - grpcResponse -> - assertThat(grpcResponse.getStatusCode()) - .isEqualTo(GrpcStatusCode.INTERNAL))); + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.INTERNAL))); } } @@ -499,10 +494,9 @@ void identityGrpcMessageEncodingWithCompressedFlagRejected() { FailedExportException.GrpcExportException.class, ex -> assertThat(requireNonNull(ex.getResponse())) - .satisfies( - grpcResponse -> - assertThat(grpcResponse.getStatusCode()) - .isEqualTo(GrpcStatusCode.INTERNAL))); + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.INTERNAL))); } } @@ -693,11 +687,10 @@ void tls_untrusted() { @Test void tls_badCert() { - assertThatThrownBy( - () -> - exporterBuilder() - .setEndpoint(server.httpsUri().toString()) - .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + exporterBuilder() + .setEndpoint(server.httpsUri().toString()) + .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Error creating X509TrustManager with provided certs."); } @@ -754,11 +747,10 @@ void connectTimeout() { .asInstanceOf( InstanceOfAssertFactories.throwable(FailedExportException.GrpcExportException.class)) .returns(false, Assertions.from(FailedExportException::failedWithResponse)) - .satisfies( - ex -> { - assertThat(ex.getResponse()).isNull(); - assertThat(ex.getCause()).isNotNull(); - }); + .satisfies(ex -> { + assertThat(ex.getResponse()).isNull(); + assertThat(ex.getCause()).isNotNull(); + }); // Assert that the export request fails well before the default connect timeout of 10s // Note: Connection failures to non-routable IPs can take 1-5 seconds depending on OS/network @@ -825,15 +817,14 @@ void error() { .asInstanceOf( InstanceOfAssertFactories.throwable(FailedExportException.GrpcExportException.class)) .returns(true, Assertions.from(FailedExportException::failedWithResponse)) - .satisfies( - ex -> { - assertThat(ex.getResponse()) - .isNotNull() - .extracting(GrpcResponse::getStatusCode) - .isEqualTo(statusCode); + .satisfies(ex -> { + assertThat(ex.getResponse()) + .isNotNull() + .extracting(GrpcResponse::getStatusCode) + .isEqualTo(statusCode); - assertThat(ex.getCause()).isNull(); - }); + assertThat(ex.getCause()).isNull(); + }); LoggingEvent log = logs.assertContains( @@ -858,12 +849,11 @@ void errorWithUnknownError() { .asInstanceOf( InstanceOfAssertFactories.throwable(FailedExportException.GrpcExportException.class)) .returns(true, Assertions.from(FailedExportException::failedWithResponse)) - .satisfies( - ex -> { - assertThat(ex.getResponse()).isNotNull(); + .satisfies(ex -> { + assertThat(ex.getResponse()).isNotNull(); - assertThat(ex.getCause()).isNull(); - }); + assertThat(ex.getCause()).isNull(); + }); } } @@ -1119,10 +1109,8 @@ void validConfig() { .doesNotThrowAnyException(); assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofMillis(0)))) .doesNotThrowAnyException(); - assertThatCode( - () -> - buildAndShutdown( - exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.NANOSECONDS))) + assertThatCode(() -> + buildAndShutdown(exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.NANOSECONDS))) .doesNotThrowAnyException(); assertThatCode( () -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofNanos(Long.MAX_VALUE)))) @@ -1222,9 +1210,8 @@ void invalidConfig() { assertThatThrownBy(() -> exporterBuilder().setTimeout(null)) .isInstanceOf(NullPointerException.class) .hasMessage("timeout"); - assertThatThrownBy( - () -> - buildAndShutdown(exporterBuilder().setTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + assertThatThrownBy(() -> + buildAndShutdown(exporterBuilder().setTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) .isInstanceOf(ArithmeticException.class); assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(-1, TimeUnit.MILLISECONDS)) @@ -1236,10 +1223,9 @@ void invalidConfig() { assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(null)) .isInstanceOf(NullPointerException.class) .hasMessage("timeout"); - assertThatThrownBy( - () -> - buildAndShutdown( - exporterBuilder().setConnectTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + assertThatThrownBy(() -> + buildAndShutdown( + exporterBuilder().setConnectTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) .isInstanceOf(ArithmeticException.class); assertThatThrownBy(() -> exporterBuilder().setEndpoint(null)) @@ -1450,40 +1436,26 @@ void latestInternalTelemetry() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(3) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .satisfies( - m -> - assertThat(m.getName()) - .matches( - "otel.sdk.exporter.(span|metric_data_point|log).inflight")) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributesSatisfying(expectedAttributes)))) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .satisfies( - m -> - assertThat(m.getName()) - .matches( - "otel.sdk.exporter.(span|metric_data_point|log).exported")) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributesSatisfying(expectedAttributes)))) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName("otel.sdk.exporter.operation.duration") - .hasHistogramSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributesSatisfying(expectedAttributes) - .hasBucketCounts(1)))); + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).inflight")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).exported")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying(expectedAttributes).hasBucketCounts(1)))); } } @@ -1507,30 +1479,22 @@ void legacyInternalTelemetry() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(2) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName("otlp.exporter.seen") - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributesSatisfying( - satisfies( - stringKey("type"), - str -> str.matches("log|span|metric")))))) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName("otlp.exporter.exported") - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributesSatisfying( - satisfies( - stringKey("type"), - str -> str.matches("log|span|metric")))))); + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otlp.exporter.seen") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otlp.exporter.exported") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))); } } @@ -1544,23 +1508,22 @@ void legacyInternalTelemetry() { private List toProto(List telemetry) { return Arrays.stream(toMarshalers(telemetry)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - @SuppressWarnings("unchecked") - U result = - (U) - resourceTelemetryInstance - .newBuilderForType() - .mergeFrom(bos.toByteArray()) - .build(); - return result; - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) + .map(marshaler -> { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + @SuppressWarnings("unchecked") + U result = + (U) + resourceTelemetryInstance + .newBuilderForType() + .mergeFrom(bos.toByteArray()) + .build(); + return result; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) .collect(Collectors.toList()); } diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractHttpTelemetryExporterTest.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractHttpTelemetryExporterTest.java index 32745f4521c..31fe91aff4e 100644 --- a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractHttpTelemetryExporterTest.java +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractHttpTelemetryExporterTest.java @@ -178,24 +178,23 @@ public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) { attempts.incrementAndGet(); CompletableFuture responseFuture = req.aggregate() - .thenApply( - aggReq -> { - T request; - try { - byte[] requestBody = maybeInflate(aggReq.headers(), aggReq.content().array()); - request = parse.extractThrows(requestBody); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - exportedResourceTelemetry.addAll(getResourceTelemetry.apply(request)); - HttpResponse errorResponse = httpErrors.poll(); - return errorResponse != null - ? errorResponse - : HttpResponse.of( - HttpStatus.OK, - MediaType.parse("application/x-protobuf"), - successResponseBytes); - }); + .thenApply(aggReq -> { + T request; + try { + byte[] requestBody = maybeInflate(aggReq.headers(), aggReq.content().array()); + request = parse.extractThrows(requestBody); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + exportedResourceTelemetry.addAll(getResourceTelemetry.apply(request)); + HttpResponse errorResponse = httpErrors.poll(); + return errorResponse != null + ? errorResponse + : HttpResponse.of( + HttpStatus.OK, + MediaType.parse("application/x-protobuf"), + successResponseBytes); + }); return HttpResponse.of(responseFuture); } @@ -290,10 +289,8 @@ void export() { // Assert request contains OTLP spec compliant User-Agent header assertThat(httpRequests) .singleElement() - .satisfies( - req -> - assertThat(req.headers().get("User-Agent")) - .matches("OTel-OTLP-Exporter-Java/1\\..*")); + .satisfies(req -> + assertThat(req.headers().get("User-Agent")).matches("OTel-OTLP-Exporter-Java/1\\..*")); } @Test @@ -467,11 +464,10 @@ void tls_untrusted() { @Test void tls_badCert() { - assertThatThrownBy( - () -> - exporterBuilder() - .setEndpoint(server.httpsUri() + path) - .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + exporterBuilder() + .setEndpoint(server.httpsUri() + path) + .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Error creating X509TrustManager with provided certs"); } @@ -525,11 +521,10 @@ void connectTimeout() { .asInstanceOf( InstanceOfAssertFactories.throwable(FailedExportException.HttpExportException.class)) .returns(false, Assertions.from(FailedExportException::failedWithResponse)) - .satisfies( - ex -> { - assertThat(ex.getResponse()).isNull(); - assertThat(ex.getCause()).isNotNull(); - }); + .satisfies(ex -> { + assertThat(ex.getResponse()).isNull(); + assertThat(ex.getCause()).isNotNull(); + }); // Assert that the export request fails well before the default connect timeout of 10s // Note: Connection failures to non-routable IPs can take 1-5 seconds depending on OS/network @@ -594,22 +589,19 @@ void error() { .asInstanceOf( InstanceOfAssertFactories.throwable(FailedExportException.HttpExportException.class)) .returns(true, Assertions.from(FailedExportException::failedWithResponse)) - .satisfies( - ex -> { - assertThat(ex.getResponse()) - .isNotNull() - .satisfies( - response -> { - assertThat(response) - .extracting( - io.opentelemetry.sdk.common.export.HttpResponse::getStatusCode) - .isEqualTo(statusCode); - - assertThatCode(response::getResponseBody).doesNotThrowAnyException(); - }); - - assertThat(ex.getCause()).isNull(); - }); + .satisfies(ex -> { + assertThat(ex.getResponse()) + .isNotNull() + .satisfies(response -> { + assertThat(response) + .extracting(io.opentelemetry.sdk.common.export.HttpResponse::getStatusCode) + .isEqualTo(statusCode); + + assertThatCode(response::getResponseBody).doesNotThrowAnyException(); + }); + + assertThat(ex.getCause()).isNull(); + }); LoggingEvent log = logs.assertContains( @@ -900,10 +892,8 @@ void validConfig() { .doesNotThrowAnyException(); assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofMillis(0)))) .doesNotThrowAnyException(); - assertThatCode( - () -> - buildAndShutdown( - exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.NANOSECONDS))) + assertThatCode(() -> + buildAndShutdown(exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.NANOSECONDS))) .doesNotThrowAnyException(); assertThatCode( () -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofNanos(Long.MAX_VALUE)))) @@ -972,9 +962,8 @@ void invalidConfig() { assertThatThrownBy(() -> exporterBuilder().setTimeout(null)) .isInstanceOf(NullPointerException.class) .hasMessage("timeout"); - assertThatThrownBy( - () -> - buildAndShutdown(exporterBuilder().setTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + assertThatThrownBy(() -> + buildAndShutdown(exporterBuilder().setTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) .isInstanceOf(ArithmeticException.class); assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(-1, TimeUnit.MILLISECONDS)) @@ -986,10 +975,9 @@ void invalidConfig() { assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(null)) .isInstanceOf(NullPointerException.class) .hasMessage("timeout"); - assertThatThrownBy( - () -> - buildAndShutdown( - exporterBuilder().setConnectTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + assertThatThrownBy(() -> + buildAndShutdown( + exporterBuilder().setConnectTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) .isInstanceOf(ArithmeticException.class); assertThatThrownBy(() -> exporterBuilder().setEndpoint(null)) @@ -1230,40 +1218,26 @@ void latestInternalTelemetry() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(3) - .anySatisfy( - metric -> - assertThat(metric) - .satisfies( - m -> - assertThat(m.getName()) - .matches( - "otel.sdk.exporter.(span|metric_data_point|log).inflight")) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributesSatisfying(expectedAttributes)))) - .anySatisfy( - metric -> - assertThat(metric) - .satisfies( - m -> - assertThat(m.getName()) - .matches( - "otel.sdk.exporter.(span|metric_data_point|log).exported")) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributesSatisfying(expectedAttributes)))) - .anySatisfy( - metric -> - assertThat(metric) - .hasName("otel.sdk.exporter.operation.duration") - .hasHistogramSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributesSatisfying(expectedAttributes) - .hasBucketCounts(1)))); + .anySatisfy(metric -> + assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).inflight")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).exported")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying(expectedAttributes).hasBucketCounts(1)))); } } @@ -1283,30 +1257,22 @@ void legacyInternalTelemetry() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(2) - .anySatisfy( - metric -> - assertThat(metric) - .hasName("otlp.exporter.seen") - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributesSatisfying( - satisfies( - stringKey("type"), - str -> str.matches("log|span|metric")))))) - .anySatisfy( - metric -> - assertThat(metric) - .hasName("otlp.exporter.exported") - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributesSatisfying( - satisfies( - stringKey("type"), - str -> str.matches("log|span|metric")))))); + .anySatisfy(metric -> + assertThat(metric) + .hasName("otlp.exporter.seen") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))) + .anySatisfy(metric -> + assertThat(metric) + .hasName("otlp.exporter.exported") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))); } } @@ -1320,23 +1286,22 @@ void legacyInternalTelemetry() { private List toProto(List telemetry) { return Arrays.stream(toMarshalers(telemetry)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - @SuppressWarnings("unchecked") - U result = - (U) - resourceTelemetryInstance - .newBuilderForType() - .mergeFrom(bos.toByteArray()) - .build(); - return result; - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) + .map(marshaler -> { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + @SuppressWarnings("unchecked") + U result = + (U) + resourceTelemetryInstance + .newBuilderForType() + .mergeFrom(bos.toByteArray()) + .build(); + return result; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) .collect(Collectors.toList()); } diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverter.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverter.java index 15d3ab1b2a3..79af0e49fce 100644 --- a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverter.java +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverter.java @@ -556,11 +556,9 @@ private Labels convertAttributes( } scope .getAttributes() - .forEach( - (key, value) -> - labelNameToValue.putIfAbsent( - OTEL_SCOPE_ATTRIBUTE_PREFIX + key.getKey(), - toLabelValue(key.getType(), value))); + .forEach((key, value) -> + labelNameToValue.putIfAbsent( + OTEL_SCOPE_ATTRIBUTE_PREFIX + key.getKey(), toLabelValue(key.getType(), value))); } if (resource != null) { @@ -570,12 +568,11 @@ private Labels convertAttributes( String[] names = new String[labelNameToValue.size()]; String[] values = new String[labelNameToValue.size()]; int[] pos = new int[] {0}; - labelNameToValue.forEach( - (name, value) -> { - names[pos[0]] = name; - values[pos[0]] = value; - pos[0] += 1; - }); + labelNameToValue.forEach((name, value) -> { + names[pos[0]] = name; + values[pos[0]] = value; + pos[0] += 1; + }); return Labels.of(names, values); } @@ -590,27 +587,25 @@ private Labels convertAttributes( private Map buildAttributeLabels(Attributes attributes) { Map labels = new LinkedHashMap<>(); if (!shouldEscape(translationStrategy)) { - attributes.forEach( - (key, value) -> - labels.put(convertLabelName(key.getKey()), toLabelValue(key.getType(), value))); + attributes.forEach((key, value) -> + labels.put(convertLabelName(key.getKey()), toLabelValue(key.getType(), value))); return labels; } // Fast path: insert directly. Stop inserting on first detected collision but finish // iterating so forEach can complete. boolean[] hasCollision = {false}; - attributes.forEach( - (key, value) -> { - if (hasCollision[0]) { - return; - } - String labelName = convertLabelName(key.getKey()); - if (labels.containsKey(labelName)) { - hasCollision[0] = true; - } else { - labels.put(labelName, toLabelValue(key.getType(), value)); - } - }); + attributes.forEach((key, value) -> { + if (hasCollision[0]) { + return; + } + String labelName = convertLabelName(key.getKey()); + if (labels.containsKey(labelName)) { + hasCollision[0] = true; + } else { + labels.put(labelName, toLabelValue(key.getType(), value)); + } + }); if (!hasCollision[0]) { return labels; // common case: done, no extra allocation @@ -619,11 +614,10 @@ private Map buildAttributeLabels(Attributes attributes) { // Collision path: discard partial state and rebuild with merged values. labels.clear(); Map> groups = new LinkedHashMap<>(); - attributes.forEach( - (key, value) -> - groups - .computeIfAbsent(convertLabelName(key.getKey()), ignored -> new ArrayList<>()) - .add(new OriginalLabelKeyValue(key.getKey(), toLabelValue(key.getType(), value)))); + attributes.forEach((key, value) -> + groups + .computeIfAbsent(convertLabelName(key.getKey()), ignored -> new ArrayList<>()) + .add(new OriginalLabelKeyValue(key.getKey(), toLabelValue(key.getType(), value)))); groups.forEach((labelName, entries) -> labels.put(labelName, mergeValues(entries))); return labels; } diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverterTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverterTest.java index 023616f2e0a..9f8388a24e3 100644 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverterTest.java +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverterTest.java @@ -1298,13 +1298,12 @@ void stripReservedMetricSuffixesHandlesReservedNameOnly() throws Exception { @Test void validateNormalizedMetricNameRejectsEmptyName() { - assertThatThrownBy( - () -> - invokePrivate( - "validateNormalizedMetricName", - new Class[] {String.class, String.class}, - "orig", - "")) + assertThatThrownBy(() -> + invokePrivate( + "validateNormalizedMetricName", + new Class[] {String.class, String.class}, + "orig", + "")) .hasCauseInstanceOf(IllegalArgumentException.class) .hasRootCauseMessage("normalization for metric \"orig\" resulted in empty name"); } diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java index 389d81943f5..40febbb6469 100644 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java @@ -192,13 +192,12 @@ public Collection collectAllMetrics() { List threads = new ArrayList<>(); for (int i = 0; i < 4; i++) { Thread thread = - new Thread( - () -> { - for (int j = 0; j < 10; j++) { - AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); - assertThat(response.status()).isEqualTo(HttpStatus.OK); - } - }); + new Thread(() -> { + for (int j = 0; j < 10; j++) { + AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + } + }); thread.setDaemon(true); thread.start(); threads.add(thread); diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusIntegrationTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusIntegrationTest.java index ce178566030..6e309325890 100644 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusIntegrationTest.java +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusIntegrationTest.java @@ -90,47 +90,46 @@ void endToEnd() { WebClient promClient = WebClient.of("http://localhost:" + prometheus.getMappedPort(9090)); JSON json = JSON.builder().register(new JrSimpleTreeExtension()).build(); await() - .untilAsserted( - () -> { - TreeNode response = - json.treeFrom( - promClient - .get("/api/v1/query?query=requests_total") - .aggregate() - .join() - .contentUtf8()); - assertThat(response.get("status")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); - TreeNode result = response.get("data").get("result").get(0); - assertThat(result).isNotNull(); - assertThat(result.get("metric").get("__name__")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("requests_total")); - assertThat(result.get("metric").get("animal")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("bear")); - assertThat(result.get("value").get(1)) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("3")); + .untilAsserted(() -> { + TreeNode response = + json.treeFrom( + promClient + .get("/api/v1/query?query=requests_total") + .aggregate() + .join() + .contentUtf8()); + assertThat(response.get("status")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); + TreeNode result = response.get("data").get("result").get(0); + assertThat(result).isNotNull(); + assertThat(result.get("metric").get("__name__")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("requests_total")); + assertThat(result.get("metric").get("animal")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("bear")); + assertThat(result.get("value").get(1)) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("3")); - response = - json.treeFrom( - promClient.get("/api/v1/query?query=lives").aggregate().join().contentUtf8()); - assertThat(response.get("status")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); - result = response.get("data").get("result").get(0); - assertThat(result).isNotNull(); - assertThat(result.get("metric").get("__name__")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("lives")); - assertThat(result.get("metric").get("animal")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("cat")); - assertThat(result.get("value").get(1)) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("9")); - }); + response = + json.treeFrom( + promClient.get("/api/v1/query?query=lives").aggregate().join().contentUtf8()); + assertThat(response.get("status")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); + result = response.get("data").get("result").get(0); + assertThat(result).isNotNull(); + assertThat(result.get("metric").get("__name__")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("lives")); + assertThat(result.get("metric").get("animal")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("cat")); + assertThat(result.get("value").get(1)) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("9")); + }); } } diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderTest.java index 792ee828a54..55c9b943d4b 100644 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderTest.java +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderTest.java @@ -294,11 +294,10 @@ void longGaugeComplete() throws IOException { .setUnit("Cel") .setDescription("help text") .ofLongs() - .buildWithCallback( - m -> { - m.record(23, Attributes.builder().put("location", "inside").build()); - m.record(17, Attributes.builder().put("location", "outside").build()); - }); + .buildWithCallback(m -> { + m.record(23, Attributes.builder().put("location", "inside").build()); + m.record(17, Attributes.builder().put("location", "outside").build()); + }); assertGaugeComplete(reader.collect()); } @@ -308,11 +307,10 @@ void doubleGaugeComplete() throws IOException { .gaugeBuilder("temperature") .setUnit("Cel") .setDescription("help text") - .buildWithCallback( - m -> { - m.record(23.0, Attributes.builder().put("location", "inside").build()); - m.record(17.0, Attributes.builder().put("location", "outside").build()); - }); + .buildWithCallback(m -> { + m.record(23.0, Attributes.builder().put("location", "inside").build()); + m.record(17.0, Attributes.builder().put("location", "outside").build()); + }); assertGaugeComplete(reader.collect()); } diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProviderTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProviderTest.java index 2f07730a198..9f19c5edd6f 100644 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProviderTest.java +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProviderTest.java @@ -57,12 +57,11 @@ void createMetricReader_Default() throws IOException { .isInstanceOf(PrometheusHttpServer.class) .extracting("httpServer", as(InstanceOfAssertFactories.type(HTTPServer.class))) .extracting("server", as(InstanceOfAssertFactories.type(HttpServer.class))) - .satisfies( - server -> { - assertThat(server.getAddress().getHostName()) - .isIn("localhost", "127.0.0.1", "kubernetes.docker.internal"); - assertThat(server.getAddress().getPort()).isEqualTo(9464); - }); + .satisfies(server -> { + assertThat(server.getAddress().getHostName()) + .isIn("localhost", "127.0.0.1", "kubernetes.docker.internal"); + assertThat(server.getAddress().getPort()).isEqualTo(9464); + }); assertThat(metricReader.getMemoryMode()).isEqualTo(MemoryMode.REUSABLE_DATA); assertThat(metricReader.getDefaultAggregation(InstrumentType.HISTOGRAM)) .isEqualTo(Aggregation.defaultAggregation()); @@ -95,12 +94,11 @@ void createMetricReader_WithConfiguration() throws IOException { assertThat(metricReader) .extracting("httpServer", as(InstanceOfAssertFactories.type(HTTPServer.class))) .extracting("server", as(InstanceOfAssertFactories.type(HttpServer.class))) - .satisfies( - server -> { - assertThat(server.getAddress().getHostName()) - .isIn("localhost", "127.0.0.1", "kubernetes.docker.internal"); - assertThat(server.getAddress().getPort()).isEqualTo(port); - }); + .satisfies(server -> { + assertThat(server.getAddress().getHostName()) + .isIn("localhost", "127.0.0.1", "kubernetes.docker.internal"); + assertThat(server.getAddress().getPort()).isEqualTo(port); + }); assertThat(metricReader.getMemoryMode()).isEqualTo(MemoryMode.IMMUTABLE_DATA); assertThat(metricReader.getDefaultAggregation(InstrumentType.HISTOGRAM)) .isEqualTo(Aggregation.base2ExponentialBucketHistogram()); diff --git a/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSender.java b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSender.java index 4cde4300af6..695c69ee074 100644 --- a/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSender.java +++ b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSender.java @@ -171,27 +171,25 @@ private static HttpClient configureClient( public void send( MessageWriter messageWriter, Consumer onResponse, Consumer onError) { try { - InstrumentationUtil.suppressInstrumentation( - () -> { - CompletableFuture unused = - CompletableFuture.supplyAsync( - () -> { - try { - return sendInternal(messageWriter); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }, - executorService) - .whenComplete( - (httpResponse, throwable) -> { - if (throwable != null) { - onError.accept(unwrap(throwable)); - return; - } - onResponse.accept(httpResponse); - }); - }); + InstrumentationUtil.suppressInstrumentation(() -> { + CompletableFuture unused = + CompletableFuture.supplyAsync( + () -> { + try { + return sendInternal(messageWriter); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }, + executorService) + .whenComplete((httpResponse, throwable) -> { + if (throwable != null) { + onError.accept(unwrap(throwable)); + return; + } + onResponse.accept(httpResponse); + }); + }); } catch (RejectedExecutionException e) { onError.accept(e); } diff --git a/exporters/sender/jdk/src/test/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderTest.java b/exporters/sender/jdk/src/test/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderTest.java index 9096ba1aeee..3fce0d6d0b8 100644 --- a/exporters/sender/jdk/src/test/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderTest.java +++ b/exporters/sender/jdk/src/test/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderTest.java @@ -70,9 +70,8 @@ void setup() throws IOException, InterruptedException { // Can't directly spy on HttpClient for some reason, so create a real instance and a mock that // delegates to the real thing when(mockHttpClient.send(any(), any())) - .thenAnswer( - invocation -> - realHttpClient.send(invocation.getArgument(0), invocation.getArgument(1))); + .thenAnswer(invocation -> + realHttpClient.send(invocation.getArgument(0), invocation.getArgument(1))); sender = new JdkHttpSender( mockHttpClient, @@ -154,10 +153,9 @@ void shutdown_nonManagedExecutor_doesNotShutDownExecutor() { @Test void sendInternal_RetryableConnectTimeoutException() throws IOException, InterruptedException { assertThatThrownBy(() -> sender.sendInternal(new NoOpRequestBodyWriter())) - .satisfies( - e -> - assertThat((e instanceof HttpConnectTimeoutException) || (e instanceof IOException)) - .isTrue()); + .satisfies(e -> + assertThat((e instanceof HttpConnectTimeoutException) || (e instanceof IOException)) + .isTrue()); verify(mockHttpClient, times(2)).send(any(), any()); } @@ -180,12 +178,10 @@ void sendInternal_RetryableConnectException() throws IOException, InterruptedExc Long.MAX_VALUE); assertThatThrownBy(() -> sender.sendInternal(new NoOpRequestBodyWriter())) - .satisfies( - e -> - assertThat( - (e instanceof ConnectException) - || (e instanceof HttpConnectTimeoutException)) - .isTrue()); + .satisfies(e -> + assertThat( + (e instanceof ConnectException) || (e instanceof HttpConnectTimeoutException)) + .isTrue()); verify(mockHttpClient, times(2)).send(any(), any()); } @@ -242,12 +238,11 @@ void defaultExecutor_isBounded() { assertThat(defaultSender) .extracting( "executorService", as(InstanceOfAssertFactories.type(ThreadPoolExecutor.class))) - .satisfies( - executor -> { - assertThat(executor.getMaximumPoolSize()).isEqualTo(expectedMax); - assertThat(executor.getRejectedExecutionHandler()) - .isInstanceOf(ThreadPoolExecutor.AbortPolicy.class); - }); + .satisfies(executor -> { + assertThat(executor.getMaximumPoolSize()).isEqualTo(expectedMax); + assertThat(executor.getRejectedExecutionHandler()) + .isInstanceOf(ThreadPoolExecutor.AbortPolicy.class); + }); } finally { defaultSender.shutdown(); } @@ -272,9 +267,8 @@ void connectTimeout() { assertThat(sender) .extracting("client", as(InstanceOfAssertFactories.type(HttpClient.class))) - .satisfies( - httpClient -> - assertThat(httpClient.connectTimeout().get()).isEqualTo(Duration.ofSeconds(10))); + .satisfies(httpClient -> + assertThat(httpClient.connectTimeout().get()).isEqualTo(Duration.ofSeconds(10))); } @SuppressWarnings("unchecked") diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSender.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSender.java index a5d03b3fc02..0783861083a 100644 --- a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSender.java +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSender.java @@ -207,60 +207,54 @@ private void sendAttempt( @Nullable RetryState retryState) { try { - InstrumentationUtil.suppressInstrumentation( - () -> { - Call call = client.newCall(requestBuilder.build()); - if (retryState != null && !retryState.configureCallTimeout(call)) { - onError.accept(new SocketTimeoutException("Call timed out")); - return; - } - startCall( - call, - attempt, - new Callback() { - @Override - public void onFailure(Call call, IOException e) { - if (!call.isCanceled() - && retryState != null - && retryState.canRetry(attempt) - && retryState.shouldRetryOnException(e) - && retryState.backoff(OptionalLong.empty())) { - sendAttempt( - requestBuilder, - messageWriter, - onResponse, - onError, - attempt + 1, - retryState); - } else { - onError.accept(e); - } - } - - @Override - public void onResponse(Call call, Response response) { - handleResponse( - response, - (resolvedResponse, canRetry) -> { - if (retryState != null - && retryState.canRetry(attempt) - && canRetry - && isRetryable(resolvedResponse) - && retryState.backoff(OptionalLong.empty())) { - sendAttempt( - requestBuilder, - messageWriter, - onResponse, - onError, - attempt + 1, - retryState); - } else { - onResponse.accept(resolvedResponse); - } - }); - } - }); - }); + InstrumentationUtil.suppressInstrumentation(() -> { + Call call = client.newCall(requestBuilder.build()); + if (retryState != null && !retryState.configureCallTimeout(call)) { + onError.accept(new SocketTimeoutException("Call timed out")); + return; + } + startCall( + call, + attempt, + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + if (!call.isCanceled() + && retryState != null + && retryState.canRetry(attempt) + && retryState.shouldRetryOnException(e) + && retryState.backoff(OptionalLong.empty())) { + sendAttempt( + requestBuilder, messageWriter, onResponse, onError, attempt + 1, retryState); + } else { + onError.accept(e); + } + } + + @Override + public void onResponse(Call call, Response response) { + handleResponse( + response, + (resolvedResponse, canRetry) -> { + if (retryState != null + && retryState.canRetry(attempt) + && canRetry + && isRetryable(resolvedResponse) + && retryState.backoff(OptionalLong.empty())) { + sendAttempt( + requestBuilder, + messageWriter, + onResponse, + onError, + attempt + 1, + retryState); + } else { + onResponse.accept(resolvedResponse); + } + }); + } + }); + }); } catch (RejectedExecutionException e) { onError.accept(e); } diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java index 25ba4b5e5de..6c5db44535f 100644 --- a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java @@ -171,22 +171,21 @@ public void send( requestBuilder.post(new RequestBodyImpl(messageWriter, compressor, mediaType)); try { - InstrumentationUtil.suppressInstrumentation( - () -> - client - .newCall(requestBuilder.build()) - .enqueue( - new Callback() { - @Override - public void onFailure(Call call, IOException e) { - onError.accept(e); - } + InstrumentationUtil.suppressInstrumentation(() -> + client + .newCall(requestBuilder.build()) + .enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + onError.accept(e); + } - @Override - public void onResponse(Call call, Response response) { - handleResponse(response, onResponse, onError); - } - })); + @Override + public void onResponse(Call call, Response response) { + handleResponse(response, onResponse, onError); + } + })); } catch (RejectedExecutionException e) { onError.accept(e); } diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderTest.java index 02ba0234f6c..ac95ac99ac5 100644 --- a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderTest.java +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderTest.java @@ -395,20 +395,19 @@ void constructor_usesDefaultTrustManagerWhenTrustManagerIsNull() throws Exceptio SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); - assertThatCode( - () -> - new OkHttpGrpcSender( - "https://localhost", - null, - Duration.ofSeconds(10), - Duration.ofSeconds(10), - Collections::emptyMap, - null, - sslContext, - null, - null, - Long.MAX_VALUE, - null)) + assertThatCode(() -> + new OkHttpGrpcSender( + "https://localhost", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) .doesNotThrowAnyException(); } @@ -422,20 +421,19 @@ void constructor_wrapsDefaultTrustManagerFailure() throws Exception { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); - assertThatThrownBy( - () -> - new OkHttpGrpcSender( - "https://localhost", - null, - Duration.ofSeconds(10), - Duration.ofSeconds(10), - Collections::emptyMap, - null, - sslContext, - null, - null, - Long.MAX_VALUE, - null)) + assertThatThrownBy(() -> + new OkHttpGrpcSender( + "https://localhost", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) .isInstanceOf(IllegalStateException.class) .hasMessage("Unable to initialize default trust manager") .hasCauseInstanceOf(SSLException.class); diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderTest.java index 994e9a99985..9642b889f63 100644 --- a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderTest.java +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderTest.java @@ -247,28 +247,27 @@ void enabledProtocols_legacyTls() throws Exception { int port = serverSocket.getLocalPort(); Thread serverThread = - new Thread( - () -> { - try (SSLSocket conn = (SSLSocket) serverSocket.accept()) { - InputStream is = conn.getInputStream(); - OutputStream os = conn.getOutputStream(); - // Read until end of HTTP headers. - StringBuilder sb = new StringBuilder(); - while (!sb.toString().endsWith("\r\n\r\n")) { - int b = is.read(); - if (b < 0) { - break; - } - sb.append((char) b); - } - os.write( - "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" - .getBytes(StandardCharsets.US_ASCII)); - os.flush(); - } catch (Exception e) { - throw new RuntimeException(e); + new Thread(() -> { + try (SSLSocket conn = (SSLSocket) serverSocket.accept()) { + InputStream is = conn.getInputStream(); + OutputStream os = conn.getOutputStream(); + // Read until end of HTTP headers. + StringBuilder sb = new StringBuilder(); + while (!sb.toString().endsWith("\r\n\r\n")) { + int b = is.read(); + if (b < 0) { + break; } - }); + sb.append((char) b); + } + os.write( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + .getBytes(StandardCharsets.US_ASCII)); + os.flush(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); serverThread.setDaemon(true); serverThread.start(); @@ -346,22 +345,21 @@ void constructor_usesDefaultTrustManagerWhenTrustManagerIsNull() throws Exceptio SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); - assertThatCode( - () -> - new OkHttpHttpSender( - URI.create("https://localhost"), - "text/plain", - null, - Duration.ofSeconds(10), - Duration.ofSeconds(10), - Collections::emptyMap, - null, - null, - sslContext, - null, - null, - Long.MAX_VALUE, - null)) + assertThatCode(() -> + new OkHttpHttpSender( + URI.create("https://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) .doesNotThrowAnyException(); } @@ -375,22 +373,21 @@ void constructor_wrapsDefaultTrustManagerFailure() throws Exception { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); - assertThatThrownBy( - () -> - new OkHttpHttpSender( - URI.create("https://localhost"), - "text/plain", - null, - Duration.ofSeconds(10), - Duration.ofSeconds(10), - Collections::emptyMap, - null, - null, - sslContext, - null, - null, - Long.MAX_VALUE, - null)) + assertThatThrownBy(() -> + new OkHttpHttpSender( + URI.create("https://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) .isInstanceOf(IllegalStateException.class) .hasMessage("Unable to initialize default trust manager") .hasCauseInstanceOf(SSLException.class); diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSuppressionTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSuppressionTest.java index 5dbfd913a55..fa519e9ef5b 100644 --- a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSuppressionTest.java +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSuppressionTest.java @@ -30,7 +30,7 @@ public int getContentLength() { return content.length; } }; - sender.send(requestBodyWriter, (response) -> onSuccess.run(), (error) -> onFailure.run()); + sender.send(requestBodyWriter, response -> onSuccess.run(), error -> onFailure.run()); } @Override diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtilTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtilTest.java index aeee5899bda..5830d5046f2 100644 --- a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtilTest.java +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtilTest.java @@ -25,12 +25,11 @@ void newDispatcher_isBounded() { assertThat(dispatcher.getMaxRequestsPerHost()).isEqualTo(5); assertThat(dispatcher.executorService()) .asInstanceOf(type(ThreadPoolExecutor.class)) - .satisfies( - executor -> { - assertThat(executor.getMaximumPoolSize()).isEqualTo(EXPECTED_MAX_REQUESTS); - assertThat(executor.getRejectedExecutionHandler()) - .isInstanceOf(ThreadPoolExecutor.AbortPolicy.class); - }); + .satisfies(executor -> { + assertThat(executor.getMaximumPoolSize()).isEqualTo(EXPECTED_MAX_REQUESTS); + assertThat(executor.getRejectedExecutionHandler()) + .isInstanceOf(ThreadPoolExecutor.AbortPolicy.class); + }); } finally { dispatcher.executorService().shutdownNow(); } diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptorTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptorTest.java index ec99d5b2a05..d4074bc950a 100644 --- a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptorTest.java +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptorTest.java @@ -240,9 +240,8 @@ void connectTimeout() throws Exception { doNothing().when(sleeper).sleep(anyLong()); // Connecting to a non-routable IP address to trigger connection error - assertThatThrownBy( - () -> - client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) + assertThatThrownBy(() -> + client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) .isInstanceOfAny(SocketTimeoutException.class, SocketException.class); verify(retryExceptionPredicate, times(5)).test(any()); @@ -258,11 +257,10 @@ void connectException() throws Exception { // Connecting to localhost on an unused port address to trigger java.net.ConnectException int openPort = freePort(); - assertThatThrownBy( - () -> - client - .newCall(new Request.Builder().url("http://localhost:" + openPort).build()) - .execute()) + assertThatThrownBy(() -> + client + .newCall(new Request.Builder().url("http://localhost:" + openPort).build()) + .execute()) .isInstanceOfAny(ConnectException.class, SocketTimeoutException.class); verify(retryExceptionPredicate, times(5)).test(any()); @@ -285,9 +283,8 @@ void nonRetryableException() throws InterruptedException { when(retryExceptionPredicate.test(any())).thenReturn(false); // Connecting to a non-routable IP address to trigger connection timeout - assertThatThrownBy( - () -> - client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) + assertThatThrownBy(() -> + client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) .isInstanceOfAny(SocketTimeoutException.class, SocketException.class); verify(retryExceptionPredicate, times(1)).test(any()); diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java index f7f539b3e35..a6171d0deb6 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java @@ -137,19 +137,18 @@ private static void injectBaggage( Baggage baggage, @Nullable C carrier, TextMapSetter setter) { int[] entriesEmitted = {0}; int[] bytesEmitted = {0}; - baggage.forEach( - (key, baggageEntry) -> { - if (entriesEmitted[0] >= MAX_BAGGAGE_ENTRIES) { - return; - } - String value = baggageEntry.getValue(); - if (bytesEmitted[0] + key.length() + value.length() > MAX_BAGGAGE_BYTES) { - return; - } - setter.set(carrier, BAGGAGE_PREFIX + key, value); - entriesEmitted[0]++; - bytesEmitted[0] += key.length() + value.length(); - }); + baggage.forEach((key, baggageEntry) -> { + if (entriesEmitted[0] >= MAX_BAGGAGE_ENTRIES) { + return; + } + String value = baggageEntry.getValue(); + if (bytesEmitted[0] + key.length() + value.length() > MAX_BAGGAGE_BYTES) { + return; + } + setter.set(carrier, BAGGAGE_PREFIX + key, value); + entriesEmitted[0]++; + bytesEmitted[0] += key.length() + value.length(); + }); } @Override diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java index 406ff0976f1..cb63235b6f7 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java @@ -91,19 +91,18 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se // Metadata is not supported by OpenTracing int[] entriesEmitted = {0}; int[] bytesEmitted = {0}; - baggage.forEach( - (key, baggageEntry) -> { - if (entriesEmitted[0] >= MAX_BAGGAGE_ENTRIES) { - return; - } - String value = baggageEntry.getValue(); - if (bytesEmitted[0] + key.length() + value.length() > MAX_BAGGAGE_BYTES) { - return; - } - setter.set(carrier, PREFIX_BAGGAGE_HEADER + key, value); - entriesEmitted[0]++; - bytesEmitted[0] += key.length() + value.length(); - }); + baggage.forEach((key, baggageEntry) -> { + if (entriesEmitted[0] >= MAX_BAGGAGE_ENTRIES) { + return; + } + String value = baggageEntry.getValue(); + if (bytesEmitted[0] + key.length() + value.length() > MAX_BAGGAGE_BYTES) { + return; + } + setter.set(carrier, PREFIX_BAGGAGE_HEADER + key, value); + entriesEmitted[0]++; + bytesEmitted[0] += key.length() + value.length(); + }); } } diff --git a/integration-tests/graal-incubating/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingApiTests.java b/integration-tests/graal-incubating/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingApiTests.java index 5ada0345ea0..40c278d8646 100644 --- a/integration-tests/graal-incubating/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingApiTests.java +++ b/integration-tests/graal-incubating/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingApiTests.java @@ -109,20 +109,20 @@ void parseDeclarativeConfiguration() { // make sure to test enums too: "instrument_type: histogram" String string = """ - file_format: "1.2" - tracer_provider: - processors: - - batch: - exporter: - console: {} - meter_provider: - views: - - selector: - instrument_type: histogram - stream: - aggregation: - drop: {} - """; + file_format: "1.2" + tracer_provider: + processors: + - batch: + exporter: + console: {} + meter_provider: + views: + - selector: + instrument_type: histogram + stream: + aggregation: + drop: {} + """; // should not throw DeclarativeConfiguration.parse( new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8))); diff --git a/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestAutoConfigurationCustomizerProvider.java b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestAutoConfigurationCustomizerProvider.java index 830b4f5e123..b742aceeda9 100644 --- a/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestAutoConfigurationCustomizerProvider.java +++ b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestAutoConfigurationCustomizerProvider.java @@ -16,11 +16,9 @@ public class TestAutoConfigurationCustomizerProvider @Override public void customize(AutoConfigurationCustomizer autoConfiguration) { - autoConfiguration.addResourceCustomizer( - (resource, config) -> - resource.merge( - Resource.create( - Attributes.of( - AttributeKey.stringKey("test.customizer"), "test-osgi-customizer")))); + autoConfiguration.addResourceCustomizer((resource, config) -> + resource.merge( + Resource.create( + Attributes.of(AttributeKey.stringKey("test.customizer"), "test-osgi-customizer")))); } } diff --git a/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java b/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java index 8fde24367ba..e3477eb83aa 100644 --- a/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java +++ b/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java @@ -80,11 +80,10 @@ public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) { .get() .get("/backend") .aggregate() - .thenApply( - unused -> { - span.end(); - return HttpResponse.of("OK"); - })); + .thenApply(unused -> { + span.end(); + return HttpResponse.of("OK"); + })); } } } @@ -196,12 +195,11 @@ void noClientTracing(WebClient client) { private static WebClient createPropagatingClient(URI uri, TextMapPropagator propagator) { return WebClient.builder(uri) - .decorator( - (delegate, ctx, req) -> { - propagator.inject( - Context.current(), ctx, ClientRequestContext::addAdditionalRequestHeader); - return delegate.execute(ctx, req); - }) + .decorator((delegate, ctx, req) -> { + propagator.inject( + Context.current(), ctx, ClientRequestContext::addAdditionalRequestHeader); + return delegate.execute(ctx, req); + }) .build(); } diff --git a/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/JavaDocsCrawler.java b/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/JavaDocsCrawler.java index 496680fc4db..89c941ffbd3 100644 --- a/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/JavaDocsCrawler.java +++ b/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/JavaDocsCrawler.java @@ -91,12 +91,11 @@ static List getArtifacts(HttpClient client, String group) Optional.ofNullable(map) .map(mavenResult -> (Map) mavenResult.get("response")) .map(response -> (Integer) response.get("numFound")) - .orElseThrow( - () -> - new IOException( - "Maven Central response for group " - + group - + " did not contain response.numFound")); + .orElseThrow(() -> + new IOException( + "Maven Central response for group " + + group + + " did not contain response.numFound")); List artifacts = convertToArtifacts(map); if (artifacts.size() < numFound) { @@ -116,19 +115,18 @@ private static List convertToArtifacts(Map map) { return Optional.ofNullable(map) .map(mavenResults -> (Map) mavenResults.get("response")) .map(response -> (List) response.get("docs")) - .map( - docs -> { - List artifacts = new ArrayList<>(); - for (Object doc : docs) { - Map docMap = (Map) doc; - String group = Objects.requireNonNull((String) docMap.get("g"), "g"); - String artifact = Objects.requireNonNull((String) docMap.get("a"), "a"); - String version = - Objects.requireNonNull((String) docMap.get("latestVersion"), "latestVersion"); - artifacts.add(new Artifact(Objects.requireNonNull(group), artifact, version)); - } - return artifacts; - }) + .map(docs -> { + List artifacts = new ArrayList<>(); + for (Object doc : docs) { + Map docMap = (Map) doc; + String group = Objects.requireNonNull((String) docMap.get("g"), "g"); + String artifact = Objects.requireNonNull((String) docMap.get("a"), "a"); + String version = + Objects.requireNonNull((String) docMap.get("latestVersion"), "latestVersion"); + artifacts.add(new Artifact(Objects.requireNonNull(group), artifact, version)); + } + return artifacts; + }) .orElseGet(ArrayList::new); } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducer.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducer.java index 3450fd0b63e..20f301833c9 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducer.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducer.java @@ -52,11 +52,10 @@ public Collection produce(Resource resource) { List result = new ArrayList<>(); openCensusMetricStorage .getAllMetricProducer() - .forEach( - producer -> - producer - .getMetrics() - .forEach(metric -> result.add(MetricAdapter.convert(resource, metric)))); + .forEach(producer -> + producer + .getMetrics() + .forEach(metric -> result.add(MetricAdapter.convert(resource, metric)))); return result; } } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java index 64ea4f1a861..4e68d9c144c 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java @@ -168,13 +168,12 @@ public boolean isRecording() { private static void mapAttributes( Map attributes, AttributesBuilder attributesBuilder) { - attributes.forEach( - (s, attributeValue) -> - attributeValue.match( - setStringAttribute(attributesBuilder, s), - setBooleanAttribute(attributesBuilder, s), - setLongAttribute(attributesBuilder, s), - setDoubleAttribute(attributesBuilder, s), - arg -> null)); + attributes.forEach((s, attributeValue) -> + attributeValue.match( + setStringAttribute(attributesBuilder, s), + setBooleanAttribute(attributesBuilder, s), + setLongAttribute(attributesBuilder, s), + setDoubleAttribute(attributesBuilder, s), + arg -> null)); } } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java index 22a54d9666c..b60d38d835c 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java @@ -84,14 +84,13 @@ private static TraceState mapTracestate(Tracestate tracestate) { static Tracestate mapTracestate(TraceState traceState) { Tracestate.Builder tracestateBuilder = Tracestate.builder(); - traceState.forEach( - (key, value) -> { - // OpenCensus does not accept the W3C multi-tenant key format (tenant-id@system-id) that - // OpenTelemetry allows. Drop such entries instead of failing the whole conversion. - if (key.indexOf('@') < 0) { - tracestateBuilder.set(key, value); - } - }); + traceState.forEach((key, value) -> { + // OpenCensus does not accept the W3C multi-tenant key format (tenant-id@system-id) that + // OpenTelemetry allows. Drop such entries instead of failing the whole conversion. + if (key.indexOf('@') < 0) { + tracestateBuilder.set(key, value); + } + }); return tracestateBuilder.build(); } diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/DelegatingSpanTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/DelegatingSpanTest.java index da361e0f3c2..e86a12c05a6 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/DelegatingSpanTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/DelegatingSpanTest.java @@ -50,15 +50,14 @@ flexibility for special cases (e.g. getSpanContext() and isRecording()) void verifyAllMethodsAreUnderTest() { List methods = delegateMethodsProvider() - .map( - pm -> { - try { - return getInterfaceMethod( - Span.class, (String) pm.get()[0], (Class[]) pm.get()[1]); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - }) + .map(pm -> { + try { + return getInterfaceMethod( + Span.class, (String) pm.get()[0], (Class[]) pm.get()[1]); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + }) .collect(Collectors.toList()); assertThat(methods) diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/MetricAdapterTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/MetricAdapterTest.java index 7022477dce6..8ec647286f5 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/MetricAdapterTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/MetricAdapterTest.java @@ -78,15 +78,13 @@ void convertsLongGauge() { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(4) - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")))); + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(4) + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")))); } @Test @@ -111,15 +109,13 @@ void convertsDoubleGauge() { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasValue(4))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasValue(4))); } @Test @@ -144,17 +140,15 @@ void convertsLongSum() { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasValue(4))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasValue(4))); } @Test @@ -179,17 +173,15 @@ void convertsDoubleSum() { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasValue(4))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasValue(4))); } @Test @@ -237,31 +229,29 @@ void convertHistogram() { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasSum(5) - .hasCount(10) - .hasBucketBoundaries(2.0, 5.0) - .hasBucketCounts(2, 6, 2) - .hasExemplars( - ImmutableDoubleExemplarData.create( - Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), - ImmutableDoubleExemplarData.create( - Attributes.empty(), - 1000000, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 4.0)))); + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasSum(5) + .hasCount(10) + .hasBucketBoundaries(2.0, 5.0) + .hasBucketCounts(2, 6, 2) + .hasExemplars( + ImmutableDoubleExemplarData.create( + Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), + ImmutableDoubleExemplarData.create( + Attributes.empty(), + 1000000, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 4.0)))); } @Test @@ -296,17 +286,15 @@ void convertSummary() { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasCount(10) - .hasSum(5) - .hasValuesSatisfying(value -> value.hasValue(200.0).hasQuantile(1.0)))); + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasCount(10) + .hasSum(5) + .hasValuesSatisfying(value -> value.hasValue(200.0).hasQuantile(1.0)))); } @Test @@ -353,30 +341,28 @@ void convertGaugeHistogram() { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(2000000000) - .hasEpochNanos(2000000000) - .hasSum(5) - .hasCount(10) - .hasBucketBoundaries(2.0, 5.0) - .hasBucketCounts(2, 6, 2) - .hasExemplars( - ImmutableDoubleExemplarData.create( - Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), - ImmutableDoubleExemplarData.create( - Attributes.empty(), - 1000000, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 4.0)))); + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(2000000000) + .hasEpochNanos(2000000000) + .hasSum(5) + .hasCount(10) + .hasBucketBoundaries(2.0, 5.0) + .hasBucketCounts(2, 6, 2) + .hasExemplars( + ImmutableDoubleExemplarData.create( + Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), + ImmutableDoubleExemplarData.create( + Attributes.empty(), + 1000000, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 4.0)))); } } diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducerTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducerTest.java index c4fbca32ff3..cb2748bd2f2 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducerTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducerTest.java @@ -67,37 +67,27 @@ void extractHistogram() throws InterruptedException { Awaitility.await() .atMost(Duration.ofSeconds(10)) - .untilAsserted( - () -> - assertThat(openCensusMetrics.produce(Resource.empty())) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("task_latency_distribution") - .hasDescription("The distribution of the task latencies.") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasSum(50) - .hasCount(1) - .hasBucketCounts(1, 0, 0, 0, 0, 0, 0) - .hasBucketBoundaries( - 100d, 200d, 400d, 1000d, 2000d, 4000d) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasFilteredAttributes( - Attributes.empty()) - .hasValue(50) - .hasTraceId( - TRACE_ID.toLowerBase16()) - .hasSpanId( - SPAN_ID - .toLowerBase16())))))); + .untilAsserted(() -> + assertThat(openCensusMetrics.produce(Resource.empty())) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("task_latency_distribution") + .hasDescription("The distribution of the task latencies.") + .hasUnit("ms") + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasSum(50) + .hasCount(1) + .hasBucketCounts(1, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries(100d, 200d, 400d, 1000d, 2000d, 4000d) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasFilteredAttributes(Attributes.empty()) + .hasValue(50) + .hasTraceId(TRACE_ID.toLowerBase16()) + .hasSpanId(SPAN_ID.toLowerBase16())))))); } } diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricsTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricsTest.java index 3c0db5297b1..a41b4b92f6b 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricsTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricsTest.java @@ -48,13 +48,12 @@ void capturesOpenCensusAndOtelMetrics() throws InterruptedException { // Wait for OpenCensus propagation. Awaitility.await() .atMost(Duration.ofSeconds(5)) - .untilAsserted( - () -> - assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric).hasName("otel.sum").hasLongSumSatisfying(sum -> {}), - metric -> - assertThat(metric).hasName("oc.sum").hasLongSumSatisfying(sum -> {}))); + .untilAsserted(() -> + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metric -> + assertThat(metric).hasName("otel.sum").hasLongSumSatisfying(sum -> {}), + metric -> + assertThat(metric).hasName("oc.sum").hasLongSumSatisfying(sum -> {}))); } } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java index 5684182381c..5eff8ca7f80 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java @@ -53,9 +53,8 @@ public String toSpanId() { @Override public Iterable> baggageItems() { List> items = new ArrayList<>(baggage.size()); - baggage.forEach( - (key, baggageEntry) -> - items.add(new AbstractMap.SimpleImmutableEntry<>(key, baggageEntry.getValue()))); + baggage.forEach((key, baggageEntry) -> + items.add(new AbstractMap.SimpleImmutableEntry<>(key, baggageEntry.getValue()))); return items; } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java index bb3378f2e60..a6dd57e5969 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java @@ -63,30 +63,29 @@ void test() throws Exception { private void submitAnotherTask(Span initialSpan) { - executor.submit( - () -> { - // Create a new Span for this task - Span taskSpan = tracer.buildSpan("task").start(); - try (Scope scope = tracer.scopeManager().activate(taskSpan)) { + executor.submit(() -> { + // Create a new Span for this task + Span taskSpan = tracer.buildSpan("task").start(); + try (Scope scope = tracer.scopeManager().activate(taskSpan)) { - // Simulate work strictly related to the initial Span - // and finish it. - try (Scope initialScope = tracer.scopeManager().activate(initialSpan)) { - sleep(50); - } finally { - initialSpan.finish(); - } + // Simulate work strictly related to the initial Span + // and finish it. + try (Scope initialScope = tracer.scopeManager().activate(initialSpan)) { + sleep(50); + } finally { + initialSpan.finish(); + } - // Restore the span for this task and create a subspan - Span subTaskSpan = tracer.buildSpan("subtask").start(); - try (Scope subTaskScope = tracer.scopeManager().activate(subTaskSpan)) { - sleep(50); - } finally { - subTaskSpan.finish(); - } - } finally { - taskSpan.finish(); - } - }); + // Restore the span for this task and create a subspan + Span subTaskSpan = tracer.buildSpan("subtask").start(); + try (Scope subTaskScope = tracer.scopeManager().activate(subTaskSpan)) { + sleep(50); + } finally { + subTaskSpan.finish(); + } + } finally { + taskSpan.finish(); + } + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java index 8cb9c38648f..2a07c13b32b 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java @@ -36,50 +36,48 @@ public void close() { public Future tell(String message) { Span parent = tracer.scopeManager().activeSpan(); phaser.register(); - return executor.submit( - () -> { - Span child = + return executor.submit(() -> { + Span child = + tracer + .buildSpan("received") + .addReference(References.FOLLOWS_FROM, parent.context()) + .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER) + .start(); + try (Scope scope = tracer.activateSpan(child)) { + phaser.arriveAndAwaitAdvance(); // child tracer started + child.log("received " + message); + phaser.arriveAndAwaitAdvance(); // assert size + } finally { + child.finish(); + } + + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + }); + } + + public Future ask(String message) { + Span parent = tracer.scopeManager().activeSpan(); + phaser.register(); + Future future = + executor.submit(() -> { + Span span = tracer .buildSpan("received") .addReference(References.FOLLOWS_FROM, parent.context()) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER) .start(); - try (Scope scope = tracer.activateSpan(child)) { + try { phaser.arriveAndAwaitAdvance(); // child tracer started - child.log("received " + message); phaser.arriveAndAwaitAdvance(); // assert size + return "received " + message; } finally { - child.finish(); - } + span.finish(); - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + } }); - } - - public Future ask(String message) { - Span parent = tracer.scopeManager().activeSpan(); - phaser.register(); - Future future = - executor.submit( - () -> { - Span span = - tracer - .buildSpan("received") - .addReference(References.FOLLOWS_FROM, parent.context()) - .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER) - .start(); - try { - phaser.arriveAndAwaitAdvance(); // child tracer started - phaser.arriveAndAwaitAdvance(); // assert size - return "received " + message; - } finally { - span.finish(); - - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size - } - }); return future; } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java index e604b9c45e9..b270fe3dbe3 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java @@ -32,26 +32,25 @@ void test_multithreaded() throws Exception { span.setBaggageItem("key1", "value1"); Future f = - executor.submit( - () -> { - /* Override the previous value... */ - span.setBaggageItem("key1", "value2"); - - /* add a new baggage item... */ - span.setBaggageItem("newkey", "newvalue"); - - /* have a child that updates its own baggage - * (should not be reflected in the original Span). */ - Span childSpan = tracer.buildSpan("child").start(); - try { - childSpan.setBaggageItem("key1", "childvalue"); - } finally { - childSpan.finish(); - } - - /* and finish the Span. */ - span.finish(); - }); + executor.submit(() -> { + /* Override the previous value... */ + span.setBaggageItem("key1", "value2"); + + /* add a new baggage item... */ + span.setBaggageItem("newkey", "newvalue"); + + /* have a child that updates its own baggage + * (should not be reflected in the original Span). */ + Span childSpan = tracer.buildSpan("child").start(); + try { + childSpan.setBaggageItem("key1", "childvalue"); + } finally { + childSpan.finish(); + } + + /* and finish the Span. */ + span.finish(); + }); /* Single call, no need to use await() */ f.get(5, TimeUnit.SECONDS); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java index 6a633b3ce37..be126002433 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java @@ -26,27 +26,24 @@ public Client(RequestHandler requestHandler) { public Future send(Object message) { Context context = new Context(); - return executor.submit( - () -> { - logger.info("send {}", message); - TestUtils.sleep(); - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.beforeRequest(message, context); - }) - .get(); - - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.afterResponse(message, context); - }) - .get(); - - return message + ":response"; - }); + return executor.submit(() -> { + logger.info("send {}", message); + TestUtils.sleep(); + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.beforeRequest(message, context); + }) + .get(); + + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.afterResponse(message, context); + }) + .get(); + + return message + ":response"; + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java index 16a3be7a03f..f81c0204e7a 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java @@ -60,16 +60,15 @@ void testSimpleError() { @Test void testCallbackError() { Span span = tracer.buildSpan("one").start(); - executor.submit( - () -> { - try (Scope scope = tracer.activateSpan(span)) { - throw new RuntimeException("Invalid state"); - } catch (RuntimeException exc) { - Tags.ERROR.set(span, true); - } finally { - span.finish(); - } - }); + executor.submit(() -> { + try (Scope scope = tracer.activateSpan(span)) { + throw new RuntimeException("Invalid state"); + } catch (RuntimeException exc) { + Tags.ERROR.set(span, true); + } finally { + span.finish(); + } + }); await().atMost(Duration.ofSeconds(5)).until(finishedSpansSize(otelTesting), equalTo(1)); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java index 4a531eb4878..afe0b14e3f2 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java @@ -62,30 +62,28 @@ void test() throws Exception { */ private void submitTasks(Span parentSpan) { - executor.submit( - () -> { - /* Alternative to calling activate() is to pass it manually to asChildOf() for each - * created Span. */ - try (Scope scope = tracer.scopeManager().activate(parentSpan)) { - Span childSpan = tracer.buildSpan("task1").start(); - try (Scope childScope = tracer.scopeManager().activate(childSpan)) { - sleep(55); - } finally { - childSpan.finish(); - } - } - }); + executor.submit(() -> { + /* Alternative to calling activate() is to pass it manually to asChildOf() for each + * created Span. */ + try (Scope scope = tracer.scopeManager().activate(parentSpan)) { + Span childSpan = tracer.buildSpan("task1").start(); + try (Scope childScope = tracer.scopeManager().activate(childSpan)) { + sleep(55); + } finally { + childSpan.finish(); + } + } + }); - executor.submit( - () -> { - try (Scope scope = tracer.scopeManager().activate(parentSpan)) { - Span childSpan = tracer.buildSpan("task2").start(); - try (Scope childScope = tracer.scopeManager().activate(childSpan)) { - sleep(85); - } finally { - childSpan.finish(); - } - } - }); + executor.submit(() -> { + try (Scope scope = tracer.scopeManager().activate(parentSpan)) { + Span childSpan = tracer.buildSpan("task2").start(); + try (Scope childScope = tracer.scopeManager().activate(childSpan)) { + sleep(85); + } finally { + childSpan.finish(); + } + } + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java index d8f8f964ebe..61d1b341194 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java @@ -22,13 +22,12 @@ public Client(Tracer tracer) { /** Async execution. */ private Future execute(Object message, ResponseListener responseListener) { - return executor.submit( - () -> { - // send via wire and get response - Object response = message + ":response"; - responseListener.onResponse(response); - return response; - }); + return executor.submit(() -> { + // send via wire and get response + Object response = message + ":response"; + responseListener.onResponse(response); + return response; + }); } public Future send(Object message) { diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java index d45692966d4..ce1ffccdea6 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java @@ -32,24 +32,23 @@ public Client(Tracer tracer, CountDownLatch parentDoneLatch) { public Future send(Object message) { SpanContext parentSpanContext = tracer.activeSpan().context(); - return executor.submit( - () -> { - logger.info("Child thread with message '{}' started", message); - - Span span = - tracer - .buildSpan("subtask") - .addReference(References.FOLLOWS_FROM, parentSpanContext) - .start(); - try (Scope subtaskScope = tracer.activateSpan(span)) { - // Simulate work - make sure we finish *after* the parent Span. - parentDoneLatch.await(); - } finally { - span.finish(); - } - - logger.info("Child thread with message '{}' finished", message); - return message + "::response"; - }); + return executor.submit(() -> { + logger.info("Child thread with message '{}' started", message); + + Span span = + tracer + .buildSpan("subtask") + .addReference(References.FOLLOWS_FROM, parentSpanContext) + .start(); + try (Scope subtaskScope = tracer.activateSpan(span)) { + // Simulate work - make sure we finish *after* the parent Span. + parentDoneLatch.await(); + } finally { + span.finish(); + } + + logger.info("Child thread with message '{}' finished", message); + return message + "::response"; + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java index b9b15339501..a50cd4ccdcb 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java @@ -57,27 +57,24 @@ void test() { private void submitCallbacks(Span span) { - executor.submit( - () -> { - try (Scope scope = tracer.scopeManager().activate(span)) { - span.setTag("key1", "1"); + executor.submit(() -> { + try (Scope scope = tracer.scopeManager().activate(span)) { + span.setTag("key1", "1"); - executor.submit( - () -> { - try (Scope scope12 = tracer.scopeManager().activate(span)) { - span.setTag("key2", "2"); + executor.submit(() -> { + try (Scope scope12 = tracer.scopeManager().activate(span)) { + span.setTag("key2", "2"); - executor.submit( - () -> { - try (Scope scope1 = tracer.scopeManager().activate(span)) { - span.setTag("key3", "3"); - } finally { - span.finish(); - } - }); - } - }); + executor.submit(() -> { + try (Scope scope1 = tracer.scopeManager().activate(span)) { + span.setTag("key3", "3"); + } finally { + span.finish(); + } + }); } }); + } + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java index 244e3d0451e..fa441086958 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java @@ -40,42 +40,40 @@ public void onError(ErrorCallback errorCallback) { @SuppressWarnings("FutureReturnValueIgnored") public void success(T result) { for (SuccessCallback callback : successCallbacks) { - context.submit( - () -> { - Span childSpan = - tracer - .buildSpan("success") - .addReference(References.FOLLOWS_FROM, parentSpan.context()) - .withTag(Tags.COMPONENT.getKey(), "success") - .start(); - try (Scope childScope = tracer.activateSpan(childSpan)) { - callback.accept(result); - } finally { - childSpan.finish(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = + tracer + .buildSpan("success") + .addReference(References.FOLLOWS_FROM, parentSpan.context()) + .withTag(Tags.COMPONENT.getKey(), "success") + .start(); + try (Scope childScope = tracer.activateSpan(childSpan)) { + callback.accept(result); + } finally { + childSpan.finish(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } @SuppressWarnings("FutureReturnValueIgnored") public void error(Throwable error) { for (ErrorCallback callback : errorCallbacks) { - context.submit( - () -> { - Span childSpan = - tracer - .buildSpan("error") - .addReference(References.FOLLOWS_FROM, parentSpan.context()) - .withTag(Tags.COMPONENT.getKey(), "error") - .start(); - try (Scope childScope = tracer.activateSpan(childSpan)) { - callback.accept(error); - } finally { - childSpan.finish(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = + tracer + .buildSpan("error") + .addReference(References.FOLLOWS_FROM, parentSpan.context()) + .withTag(Tags.COMPONENT.getKey(), "error") + .start(); + try (Scope childScope = tracer.activateSpan(childSpan)) { + callback.accept(error); + } finally { + childSpan.finish(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java index deb5cb1933b..ea357060381 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java @@ -59,26 +59,23 @@ void testPromiseCallback() { try (Scope parentScope = tracer.activateSpan(parentSpan)) { Promise successPromise = new Promise<>(context, tracer); - successPromise.onSuccess( - s -> { - tracer.activeSpan().log("Promised 1 " + s); - successResult1.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); - successPromise.onSuccess( - s -> { - tracer.activeSpan().log("Promised 2 " + s); - successResult2.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); + successPromise.onSuccess(s -> { + tracer.activeSpan().log("Promised 1 " + s); + successResult1.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); + successPromise.onSuccess(s -> { + tracer.activeSpan().log("Promised 2 " + s); + successResult2.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); Promise errorPromise = new Promise<>(context, tracer); - errorPromise.onError( - t -> { - errorResult.set(t); - phaser.arriveAndAwaitAdvance(); // result set - }); + errorPromise.onError(t -> { + errorResult.set(t); + phaser.arriveAndAwaitAdvance(); // result set + }); assertThat(otelTesting.getSpans().size()).isEqualTo(0); successPromise.success("success!"); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java index af24b8dd8a3..02510c7c4ea 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java @@ -26,16 +26,15 @@ public Client(RequestHandler requestHandler) { /** Send a request....... */ public Future send(Object message) { - return executor.submit( - () -> { - logger.info("send {}", message); - TestUtils.sleep(); - requestHandler.beforeRequest(message); + return executor.submit(() -> { + logger.info("send {}", message); + TestUtils.sleep(); + requestHandler.beforeRequest(message); - TestUtils.sleep(); - requestHandler.afterResponse(message); + TestUtils.sleep(); + requestHandler.afterResponse(message); - return message + ":response"; - }); + return message + ":response"; + }); } } diff --git a/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java b/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java index 8a6ee630916..237fb4fb298 100644 --- a/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java +++ b/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java @@ -80,17 +80,16 @@ public class OtlpPipelineStressTest { MountableFile.forClasspathResource("otel-collector-config-perf.yaml"), "/etc/otel-collector-config-perf.yaml") .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("otel-collector"))) - .withLogConsumer( - outputFrame -> { - String logline = outputFrame.getUtf8String(); - String spanExportPrefix = "TracesExporter\t{\"#spans\": "; - int start = logline.indexOf(spanExportPrefix); - int end = logline.indexOf("}"); - if (start > 0) { - String substring = logline.substring(start + spanExportPrefix.length(), end); - totalSpansReceivedByCollector.addAndGet(Long.parseLong(substring)); - } - }) + .withLogConsumer(outputFrame -> { + String logline = outputFrame.getUtf8String(); + String spanExportPrefix = "TracesExporter\t{\"#spans\": "; + int start = logline.indexOf(spanExportPrefix); + int end = logline.indexOf("}"); + if (start > 0) { + String substring = logline.substring(start + spanExportPrefix.length(), end); + totalSpansReceivedByCollector.addAndGet(Long.parseLong(substring)); + } + }) .waitingFor(new LogMessageWaitStrategy().withRegEx(".*Everything is ready.*")); @Container @@ -160,16 +159,15 @@ void otlpExportWithFlakyCollector() throws IOException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < numberOfThreads; i++) { - executorService.submit( - () -> { - try { - latch.await(); - runOnce(null, 30_000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted", e); - } - }); + executorService.submit(() -> { + try { + latch.await(); + runOnce(null, 30_000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted", e); + } + }); } latch.countDown(); @@ -194,18 +192,16 @@ void otlpExportWithFlakyCollector() throws IOException, InterruptedException { private static void reportMetrics(List finishedMetricItems) { Map> metricsByName = finishedMetricItems.stream().collect(Collectors.groupingBy(MetricData::getName)); - metricsByName.forEach( - (name, metricData) -> { - Stream longPointStream = - metricData.stream().flatMap(md -> md.getLongSumData().getPoints().stream()); - Map> pointsByAttributes = - longPointStream.collect(Collectors.groupingBy(PointData::getAttributes)); - pointsByAttributes.forEach( - (attributes, longPoints) -> { - long total = longPoints.get(longPoints.size() - 1).getValue(); - logger.info("{} : {} : {}", name, attributes, total); - }); - }); + metricsByName.forEach((name, metricData) -> { + Stream longPointStream = + metricData.stream().flatMap(md -> md.getLongSumData().getPoints().stream()); + Map> pointsByAttributes = + longPointStream.collect(Collectors.groupingBy(PointData::getAttributes)); + pointsByAttributes.forEach((attributes, longPoints) -> { + long total = longPoints.get(longPoints.size() - 1).getValue(); + logger.info("{} : {} : {}", name, attributes, total); + }); + }); } private void runOnce(Integer numberOfSpans, int numberOfMillisToRunFor) diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DefaultConfigProperties.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DefaultConfigProperties.java index 60654e40a8d..d9e1e4d2615 100644 --- a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DefaultConfigProperties.java +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DefaultConfigProperties.java @@ -75,9 +75,8 @@ private DefaultConfigProperties( (name, value) -> config.put(ConfigUtil.normalizePropertyKey(name), value)); environmentVariables.forEach( (name, value) -> config.put(ConfigUtil.normalizeEnvironmentVariableKey(name), value)); - systemProperties.forEach( - (key, value) -> - config.put(ConfigUtil.normalizePropertyKey(key.toString()), value.toString())); + systemProperties.forEach((key, value) -> + config.put(ConfigUtil.normalizePropertyKey(key.toString()), value.toString())); this.config = config; this.componentLoader = componentLoader; @@ -220,20 +219,18 @@ public static Set getSet(ConfigProperties config, String name) { @Override public Map getMap(String name) { return getList(ConfigUtil.normalizePropertyKey(name)).stream() - .map( - entry -> { - String[] split = entry.split("=", 2); - if (split.length != 2 || split[0].isEmpty()) { - throw new ConfigurationException("Invalid map property: " + name); - } - return filterBlanksAndNulls(split); - }) + .map(entry -> { + String[] split = entry.split("=", 2); + if (split.length != 2 || split[0].isEmpty()) { + throw new ConfigurationException("Invalid map property: " + name); + } + return filterBlanksAndNulls(split); + }) // Filter entries with an empty value, i.e. "foo=" .filter(splitKeyValuePairs -> splitKeyValuePairs.size() == 2) - .map( - splitKeyValuePairs -> - new AbstractMap.SimpleImmutableEntry<>( - splitKeyValuePairs.get(0), splitKeyValuePairs.get(1))) + .map(splitKeyValuePairs -> + new AbstractMap.SimpleImmutableEntry<>( + splitKeyValuePairs.get(0), splitKeyValuePairs.get(1))) // If duplicate keys, prioritize later ones similar to duplicate system properties on a // Java command line. .collect( diff --git a/sdk-extensions/autoconfigure-spi/src/test/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigPropertiesTest.java b/sdk-extensions/autoconfigure-spi/src/test/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigPropertiesTest.java index 4981c8c4f07..abc85b8e95a 100644 --- a/sdk-extensions/autoconfigure-spi/src/test/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigPropertiesTest.java +++ b/sdk-extensions/autoconfigure-spi/src/test/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigPropertiesTest.java @@ -91,50 +91,44 @@ void allEmpty() { @Test void invalidInt() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap(Collections.singletonMap("int", "bar")) - .getInt("int")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("int", "bar")) + .getInt("int")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid value for property int=bar. Must be a integer."); - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap( - Collections.singletonMap("int", "999999999999999")) - .getInt("int")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap( + Collections.singletonMap("int", "999999999999999")) + .getInt("int")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid value for property int=999999999999999. Must be a integer."); } @Test void invalidLong() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap(Collections.singletonMap("long", "bar")) - .getLong("long")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("long", "bar")) + .getLong("long")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid value for property long=bar. Must be a long."); - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap( - Collections.singletonMap("long", "99223372036854775807")) - .getLong("long")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap( + Collections.singletonMap("long", "99223372036854775807")) + .getLong("long")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid value for property long=99223372036854775807. Must be a long."); } @Test void invalidDouble() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap(Collections.singletonMap("double", "bar")) - .getDouble("double")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("double", "bar")) + .getDouble("double")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid value for property double=bar. Must be a double."); - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap(Collections.singletonMap("double", "1.0.1")) - .getDouble("double")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("double", "1.0.1")) + .getDouble("double")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid value for property double=1.0.1. Must be a double."); } @@ -159,33 +153,29 @@ void uncleanMap() { @Test void invalidMap() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap( - Collections.singletonMap("map", "authorization=Bearer s3cr3t,malformed")) - .getMap("map")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap( + Collections.singletonMap("map", "authorization=Bearer s3cr3t,malformed")) + .getMap("map")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid map property: map"); - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap(Collections.singletonMap("map", "a=1,=b")) - .getMap("map")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("map", "a=1,=b")) + .getMap("map")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid map property: map"); } @Test void invalidDuration() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "1a1ms")) - .getDuration("duration")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "1a1ms")) + .getDuration("duration")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid duration property duration=1a1ms. Expected number, found: 1a1"); - assertThatThrownBy( - () -> - DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "9mm")) - .getDuration("duration")) + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "9mm")) + .getDuration("duration")) .isInstanceOf(ConfigurationException.class) .hasMessage("Invalid duration property duration=9mm. Invalid duration string, found: mm"); } diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java index 43bce400737..95faa9284eb 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java @@ -431,12 +431,11 @@ public AutoConfiguredOpenTelemetrySdk build() { return buildImpl(); } AtomicReference autoConfiguredRef = new AtomicReference<>(); - GlobalOpenTelemetry.set( - () -> { - AutoConfiguredOpenTelemetrySdk sdk = buildImpl(); - autoConfiguredRef.set(sdk); - return sdk.getOpenTelemetrySdk(); - }); + GlobalOpenTelemetry.set(() -> { + AutoConfiguredOpenTelemetrySdk sdk = buildImpl(); + autoConfiguredRef.set(sdk); + return sdk.getOpenTelemetrySdk(); + }); AutoConfiguredOpenTelemetrySdk sdk = Objects.requireNonNull(autoConfiguredRef.get()); logger.log( Level.FINE, @@ -613,11 +612,10 @@ void callAutoConfigureListeners(SpiHelper spiHelper, OpenTelemetrySdk openTeleme void mergeSdkTracerProviderConfigurer() { for (SdkTracerProviderConfigurer configurer : componentLoader.load(SdkTracerProviderConfigurer.class)) { - addTracerProviderCustomizer( - (builder, config) -> { - configurer.configure(builder, config); - return builder; - }); + addTracerProviderCustomizer((builder, config) -> { + configurer.configure(builder, config); + return builder; + }); } } @@ -642,16 +640,15 @@ private ConfigProperties computeConfigProperties() { // Visible for testing @SuppressWarnings("SystemOut") Thread shutdownHook(OpenTelemetrySdk sdk) { - return new Thread( - () -> { - try { - sdk.close(); - } catch (Throwable e) { - // https://github.com/open-telemetry/opentelemetry-java/issues/6827 - // logging deps might not be on the classpath at this point - System.out.printf("%s Flush failed during shutdown: %s%n", Level.WARNING, e); - } - }); + return new Thread(() -> { + try { + sdk.close(); + } catch (Throwable e) { + // https://github.com/open-telemetry/opentelemetry-java/issues/6827 + // logging deps might not be on the classpath at this point + System.out.printf("%s Flush failed during shutdown: %s%n", Level.WARNING, e); + } + }); } private static BiFunction mergeCustomizer( diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java index 18128f4422e..8e17b0670f3 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java @@ -59,10 +59,9 @@ static void configureMeterProvider( configureMetricReaders( config, spiHelper, metricReaderCustomizer, metricExporterCustomizer, closeables) - .forEach( - reader -> - meterProviderBuilder.registerMetricReader( - reader, instrumentType -> resolvedCardinalityLimit)); + .forEach(reader -> + meterProviderBuilder.registerMetricReader( + reader, instrumentType -> resolvedCardinalityLimit)); } static List configureMetricReaders( @@ -86,15 +85,14 @@ static List configureMetricReaders( exporterNames = Collections.singleton("otlp"); } return exporterNames.stream() - .map( - exporterName -> - MetricExporterConfiguration.configureReader( - exporterName, - config, - spiHelper, - metricReaderCustomizer, - metricExporterCustomizer, - closeables)) + .map(exporterName -> + MetricExporterConfiguration.configureReader( + exporterName, + config, + spiHelper, + metricReaderCustomizer, + metricExporterCustomizer, + closeables)) .collect(Collectors.toList()); } diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java index 2b4ee7bd306..daf12698cd5 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java @@ -169,11 +169,10 @@ void builder_addTracerProviderCustomizer() { Span span = builder - .addTracerProviderCustomizer( - (tracerProviderBuilder, config) -> - tracerProviderBuilder - .setIdGenerator(idGenerator) - .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop()))) + .addTracerProviderCustomizer((tracerProviderBuilder, config) -> + tracerProviderBuilder + .setIdGenerator(idGenerator) + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop()))) .build() .getOpenTelemetrySdk() .getTracer("test") @@ -195,16 +194,14 @@ void builder_addPropagatorCustomizer() { OpenTelemetrySdk sdk = builder .addPropertiesSupplier(() -> singletonMap("otel.propagators", "tracecontext")) - .addPropagatorCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(W3CTraceContextPropagator.getInstance()); - return propagator1; - }) - .addPropagatorCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(propagator1); - return propagator2; - }) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(W3CTraceContextPropagator.getInstance()); + return propagator1; + }) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(propagator1); + return propagator2; + }) .build() .getOpenTelemetrySdk(); @@ -219,9 +216,8 @@ void builder_addPropagatorCustomizer() { void builder_addResourceCustomizer() { Resource autoConfiguredResource = builder - .addResourceCustomizer( - (resource, config) -> - resource.merge(Resource.builder().put("key2", "value2").build())) + .addResourceCustomizer((resource, config) -> + resource.merge(Resource.builder().put("key2", "value2").build())) .build() .getResource(); @@ -232,16 +228,14 @@ void builder_addResourceCustomizer() { void builder_addSamplerCustomizer() { SdkTracerProvider sdkTracerProvider = builder - .addSamplerCustomizer( - (previous, config) -> { - assertThat(previous).isEqualTo(Sampler.parentBased(Sampler.alwaysOn())); - return sampler1; - }) - .addSamplerCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(sampler1); - return sampler2; - }) + .addSamplerCustomizer((previous, config) -> { + assertThat(previous).isEqualTo(Sampler.parentBased(Sampler.alwaysOn())); + return sampler1; + }) + .addSamplerCustomizer((previous, config) -> { + assertThat(previous).isSameAs(sampler1); + return sampler2; + }) .build() .getOpenTelemetrySdk() .getSdkTracerProvider(); @@ -306,15 +300,14 @@ void builder_addPropertiesCustomizer() { builder .addPropertiesSupplier(() -> singletonMap("some-key", "defaultValue")) .addPropertiesSupplier(() -> singletonMap("otel.service.name", "default-service-name")) - .addPropertiesCustomizer( - config -> { - Map overrides = new HashMap<>(); - overrides.put("some-key", "override"); - overrides.put( - "otel.service.name", - config.getString("otel.service.name", "").replace("default", "overridden")); - return overrides; - }) + .addPropertiesCustomizer(config -> { + Map overrides = new HashMap<>(); + overrides.put("some-key", "override"); + overrides.put( + "otel.service.name", + config.getString("otel.service.name", "").replace("default", "overridden")); + return overrides; + }) .addPropertiesCustomizer( config -> singletonMap("some-key", config.getString("some-key", "") + "-2")) .build(); @@ -350,9 +343,8 @@ void builder_addMeterProviderCustomizer() { SdkMeterProvider sdkMeterProvider = builder - .addMeterProviderCustomizer( - (meterProviderBuilder, configProperties) -> - meterProviderBuilder.registerMetricReader(metricReader)) + .addMeterProviderCustomizer((meterProviderBuilder, configProperties) -> + meterProviderBuilder.registerMetricReader(metricReader)) .build() .getOpenTelemetrySdk() .getSdkMeterProvider(); @@ -370,9 +362,8 @@ void builder_addLoggerProviderCustomizer() { SdkLoggerProvider sdkLoggerProvider = builder - .addLoggerProviderCustomizer( - (loggerProviderBuilder, configProperties) -> - loggerProviderBuilder.addLogRecordProcessor(logRecordProcessor)) + .addLoggerProviderCustomizer((loggerProviderBuilder, configProperties) -> + loggerProviderBuilder.addLogRecordProcessor(logRecordProcessor)) .build() .getOpenTelemetrySdk() .getSdkLoggerProvider(); @@ -508,16 +499,14 @@ void disableSdk_PropagatorCustomizer() { AutoConfiguredOpenTelemetrySdk.builder() .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) .addPropertiesSupplier(() -> singletonMap("otel.propagators", "tracecontext")) - .addPropagatorCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(W3CTraceContextPropagator.getInstance()); - return propagator1; - }) - .addPropagatorCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(propagator1); - return propagator2; - }) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(W3CTraceContextPropagator.getInstance()); + return propagator1; + }) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(propagator1); + return propagator2; + }) .build(); // When the SDK is disabled, propagators are still configured @@ -536,12 +525,11 @@ void tracerProviderCustomizer() { InMemorySpanExporter spanExporter = InMemorySpanExporter.create(); AutoConfiguredOpenTelemetrySdkBuilder autoConfiguration = AutoConfiguredOpenTelemetrySdk.builder() - .addTracerProviderCustomizer( - (tracerProviderBuilder, config) -> { - tracerProviderBuilder.setResource(Resource.builder().put("cat", "meow").build()); - return tracerProviderBuilder.addSpanProcessor( - SimpleSpanProcessor.create(spanExporter)); - }) + .addTracerProviderCustomizer((tracerProviderBuilder, config) -> { + tracerProviderBuilder.setResource(Resource.builder().put("cat", "meow").build()); + return tracerProviderBuilder.addSpanProcessor( + SimpleSpanProcessor.create(spanExporter)); + }) .addResourceCustomizer( (resource, config) -> resource.merge(Resource.builder().put("cow", "moo").build())) .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) @@ -596,19 +584,18 @@ void configurationError_propagators() { BiFunction logCustomizer = getLoggerProviderBuilderSpy(); - assertThatThrownBy( - () -> - // Override the provider builders with mocks which we can verify are closed - AutoConfiguredOpenTelemetrySdk.builder() - .addTracerProviderCustomizer(traceCustomizer) - .addMeterProviderCustomizer(metricCustomizer) - .addLoggerProviderCustomizer(logCustomizer) - .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.propagators", "foo")) - .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) - .build()) + assertThatThrownBy(() -> + // Override the provider builders with mocks which we can verify are closed + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer(traceCustomizer) + .addMeterProviderCustomizer(metricCustomizer) + .addLoggerProviderCustomizer(logCustomizer) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.propagators", "foo")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) + .build()) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unrecognized value for otel.propagators"); @@ -618,19 +605,18 @@ void configurationError_propagators() { verify(metricCustomizer, never()).apply(any(), any()); verify(logCustomizer, never()).apply(any(), any()); - assertThatThrownBy( - () -> - // Override the provider builders with mocks which we can verify are closed - AutoConfiguredOpenTelemetrySdk.builder() - .addTracerProviderCustomizer(traceCustomizer) - .addMeterProviderCustomizer(metricCustomizer) - .addLoggerProviderCustomizer(logCustomizer) - .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.propagators", "foo")) - .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) - .build()) + assertThatThrownBy(() -> + // Override the provider builders with mocks which we can verify are closed + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer(traceCustomizer) + .addMeterProviderCustomizer(metricCustomizer) + .addLoggerProviderCustomizer(logCustomizer) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.propagators", "foo")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) + .build()) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unrecognized value for otel.propagators"); @@ -653,17 +639,16 @@ void configurationError_runtime() { doThrow(new RuntimeException()).when(traceCustomizer).apply(any(), any()); - assertThatThrownBy( - () -> - AutoConfiguredOpenTelemetrySdk.builder() - .addTracerProviderCustomizer(traceCustomizer) - .addMeterProviderCustomizer(metricCustomizer) - .addLoggerProviderCustomizer(logCustomizer) - .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) - .build()) + assertThatThrownBy(() -> + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer(traceCustomizer) + .addMeterProviderCustomizer(metricCustomizer) + .addLoggerProviderCustomizer(logCustomizer) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) + .build()) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unexpected configuration error"); } @@ -688,18 +673,17 @@ void configurationError_ClosesResources() { // Throw an error when closing and verify other resources are still closed doThrow(new IOException("Error!")).when(tracerProvider).close(); - assertThatThrownBy( - () -> - // Override the provider builders with mocks which we can verify are closed - AutoConfiguredOpenTelemetrySdk.builder() - .addTracerProviderCustomizer((u1, u2) -> tracerProviderBuilder) - .addMeterProviderCustomizer((u1, u2) -> meterProviderBuilder) - .addLoggerProviderCustomizer((u1, u2) -> loggerProviderBuilder) - .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) - .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "foo")) - .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) - .build()) + assertThatThrownBy(() -> + // Override the provider builders with mocks which we can verify are closed + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer((u1, u2) -> tracerProviderBuilder) + .addMeterProviderCustomizer((u1, u2) -> meterProviderBuilder) + .addLoggerProviderCustomizer((u1, u2) -> loggerProviderBuilder) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "foo")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) + .build()) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unrecognized value for otel.logs.exporter: foo"); @@ -721,16 +705,15 @@ void globalOpenTelemetryLock() throws InterruptedException, ExecutionException, CompletableFuture.supplyAsync( () -> builder - .addLoggerProviderCustomizer( - (sdkLoggerProviderBuilder, configProperties) -> { - autoconfigStarted.countDown(); - try { - completeAutoconfig.await(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - return sdkLoggerProviderBuilder; - }) + .addLoggerProviderCustomizer((sdkLoggerProviderBuilder, configProperties) -> { + autoconfigStarted.countDown(); + try { + completeAutoconfig.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return sdkLoggerProviderBuilder; + }) .setResultAsGlobal() .build() .getOpenTelemetrySdk(), diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java index b8577cebf41..cbdc3dfdc94 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java @@ -66,14 +66,13 @@ void configureExporter_KnownSpiExportersNotOnClasspath() { void configureLogRecordExporters_duplicates() { List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - LogRecordExporterConfiguration.configureLogRecordExporters( - DefaultConfigProperties.createFromMap( - ImmutableMap.of("otel.logs.exporter", "otlp,otlp")), - spiHelper, - (a, unused) -> a, - closeables)) + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.logs.exporter", "otlp,otlp")), + spiHelper, + (a, unused) -> a, + closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.logs.exporter contains duplicates: [otlp]"); cleanup.addCloseables(closeables); @@ -84,14 +83,12 @@ void configureLogRecordExporters_duplicates() { void configureLogRecordExporters_unrecognized() { List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - LogRecordExporterConfiguration.configureLogRecordExporters( - DefaultConfigProperties.createFromMap( - ImmutableMap.of("otel.logs.exporter", "foo")), - spiHelper, - (a, unused) -> a, - new ArrayList<>())) + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + DefaultConfigProperties.createFromMap(ImmutableMap.of("otel.logs.exporter", "foo")), + spiHelper, + (a, unused) -> a, + new ArrayList<>())) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unrecognized value for otel.logs.exporter: foo"); cleanup.addCloseables(closeables); @@ -102,14 +99,13 @@ void configureLogRecordExporters_unrecognized() { void configureLogRecordExporters_multipleWithNone() { List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - LogRecordExporterConfiguration.configureLogRecordExporters( - DefaultConfigProperties.createFromMap( - ImmutableMap.of("otel.logs.exporter", "otlp,none")), - spiHelper, - (a, unused) -> a, - closeables)) + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.logs.exporter", "otlp,none")), + spiHelper, + (a, unused) -> a, + closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.logs.exporter contains none along with other exporters"); cleanup.addCloseables(closeables); diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java index f28bb44f3fd..b7c4f9c50bb 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java @@ -55,17 +55,15 @@ void configureLoggerProvider() { try (SdkLoggerProvider loggerProvider = builder.build()) { assertThat(loggerProvider) .extracting("sharedState") - .satisfies( - sharedState -> { - assertThat(sharedState) - .extracting("logRecordProcessor") - .isEqualTo(LogRecordProcessor.composite()); - assertThat(sharedState) - .extracting( - "logLimitsSupplier", as(InstanceOfAssertFactories.type(Supplier.class))) - .extracting(supplier -> (LogLimits) supplier.get()) - .isEqualTo(LogLimits.builder().setMaxNumberOfAttributes(5).build()); - }); + .satisfies(sharedState -> { + assertThat(sharedState) + .extracting("logRecordProcessor") + .isEqualTo(LogRecordProcessor.composite()); + assertThat(sharedState) + .extracting("logLimitsSupplier", as(InstanceOfAssertFactories.type(Supplier.class))) + .extracting(supplier -> (LogLimits) supplier.get()) + .isEqualTo(LogLimits.builder().setMaxNumberOfAttributes(5).build()); + }); assertThat(closeables).isEmpty(); } } diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java index 85a79540f95..b5afae9845d 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java @@ -46,26 +46,24 @@ void configurePropagators_none() { @Test void configurePropagators_none_withOthers() { - assertThatThrownBy( - () -> - PropagatorConfiguration.configurePropagators( - DefaultConfigProperties.createFromMap( - Collections.singletonMap("otel.propagators", "none,blather")), - spiHelper, - (a, unused) -> a)) + assertThatThrownBy(() -> + PropagatorConfiguration.configurePropagators( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.propagators", "none,blather")), + spiHelper, + (a, unused) -> a)) .isInstanceOf(ConfigurationException.class) .hasMessage("otel.propagators contains 'none' along with other propagators"); } @Test void configurePropagators_NotOnClasspath() { - assertThatThrownBy( - () -> - PropagatorConfiguration.configurePropagators( - DefaultConfigProperties.createFromMap( - Collections.singletonMap("otel.propagators", "b3")), - spiHelper, - (a, config) -> a)) + assertThatThrownBy(() -> + PropagatorConfiguration.configurePropagators( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.propagators", "b3")), + spiHelper, + (a, config) -> a)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unrecognized value for otel.propagators: b3"); } diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java index bfd87be917c..03e36f32962 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java @@ -246,22 +246,20 @@ void filterAttributes() { resourceNoSchema.toBuilder().setSchemaUrl("http://example.com").build(); assertThat(ResourceConfiguration.filterAttributes(resourceNoSchema, configProperties)) - .satisfies( - resource -> { - assertThat(resource.getSchemaUrl()).isNull(); - assertThat(resource.getAttributes()).containsEntry("baz", "val"); - assertThat(resource.getAttributes().get(stringKey("foo"))).isNull(); - assertThat(resource.getAttributes().get(stringKey("bar"))).isNull(); - }); + .satisfies(resource -> { + assertThat(resource.getSchemaUrl()).isNull(); + assertThat(resource.getAttributes()).containsEntry("baz", "val"); + assertThat(resource.getAttributes().get(stringKey("foo"))).isNull(); + assertThat(resource.getAttributes().get(stringKey("bar"))).isNull(); + }); assertThat(ResourceConfiguration.filterAttributes(resourceWithSchema, configProperties)) - .satisfies( - resource -> { - assertThat(resource.getSchemaUrl()).isEqualTo("http://example.com"); - assertThat(resource.getAttributes()).containsEntry("baz", "val"); - assertThat(resource.getAttributes().get(stringKey("foo"))).isNull(); - assertThat(resource.getAttributes().get(stringKey("bar"))).isNull(); - }); + .satisfies(resource -> { + assertThat(resource.getSchemaUrl()).isEqualTo("http://example.com"); + assertThat(resource.getAttributes()).containsEntry("baz", "val"); + assertThat(resource.getAttributes().get(stringKey("foo"))).isNull(); + assertThat(resource.getAttributes().get(stringKey("bar"))).isNull(); + }); } @ParameterizedTest diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java index 450c98cacad..42919587ba1 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java @@ -88,11 +88,10 @@ void configureTracerProvider() { assertThat(tracerProvider) .extracting("sharedState") - .satisfies( - sharedState -> - assertThat(sharedState) - .extracting("activeSpanProcessor") - .isEqualTo(SpanProcessor.composite())); + .satisfies(sharedState -> + assertThat(sharedState) + .extracting("activeSpanProcessor") + .isEqualTo(SpanProcessor.composite())); assertThat(closeables).isEmpty(); } } @@ -104,21 +103,20 @@ void configureBatchSpanProcessor_empty() { EMPTY, mockSpanExporter, InternalTelemetryVersion.LEGACY, MeterProvider.noop())) { assertThat(processor) .extracting("worker") - .satisfies( - worker -> { - assertThat(worker) - .extracting("scheduleDelayNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(5000)); - assertThat(worker) - .extracting("exporterTimeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); - assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); - assertThat(worker) - .extracting("queue") - .isInstanceOfSatisfying( - Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2048)); - assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); - }); + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(5000)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2048)); + assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); + }); } } @@ -138,21 +136,20 @@ void configureBatchSpanProcessor_configured() { MeterProvider.noop())) { assertThat(processor) .extracting("worker") - .satisfies( - worker -> { - assertThat(worker) - .extracting("scheduleDelayNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(100000)); - assertThat(worker) - .extracting("exporterTimeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(4)); - assertThat(worker).extracting("maxExportBatchSize").isEqualTo(2); - assertThat(worker) - .extracting("queue") - .isInstanceOfSatisfying( - Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2)); - assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); - }); + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(100000)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(4)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(2); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2)); + assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); + }); } } @@ -232,10 +229,9 @@ void configureSampler() { () -> TracerProviderConfiguration.configureSampler("catsampler", EMPTY, spiHelper)) .isInstanceOf(ConfigurationException.class) .hasMessage("Unrecognized value for otel.traces.sampler: catsampler"); - assertThatThrownBy( - () -> - TracerProviderConfiguration.configureSampler( - "parentbased_jaeger_remote", EMPTY, spiHelper)) + assertThatThrownBy(() -> + TracerProviderConfiguration.configureSampler( + "parentbased_jaeger_remote", EMPTY, spiHelper)) .isInstanceOf(ConfigurationException.class) .hasMessage( "parentbased_jaeger_remote configured but opentelemetry-sdk-extension-jaeger-remote-sampler not on classpath"); diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java index ee313c33a61..9886e84409e 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java @@ -40,11 +40,10 @@ void build_addMetricReaderCustomizerPrometheus() { builder.addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "prometheus")); int port = FreePortFinder.getFreePort(); - builder.addMetricReaderCustomizer( - (reader, config) -> { - assertThat(reader).isInstanceOf(PrometheusHttpServer.class); - return PrometheusHttpServer.builder().setPort(port).build(); - }); + builder.addMetricReaderCustomizer((reader, config) -> { + assertThat(reader).isInstanceOf(PrometheusHttpServer.class); + return PrometheusHttpServer.builder().setPort(port).build(); + }); try (OpenTelemetrySdk ignored = builder.build().getOpenTelemetrySdk()) { WebClient client = WebClient.builder("http://localhost:" + port).build(); diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableLogRecordExporterTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableLogRecordExporterTest.java index 7025de0084e..9cce9b26ba2 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableLogRecordExporterTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableLogRecordExporterTest.java @@ -69,10 +69,9 @@ void configureLogRecordExporters_emptyClassLoader() { List closeables = new ArrayList<>(); SpiHelper spiHelper = SpiHelper.create(new URLClassLoader(new URL[0], null)); - assertThatThrownBy( - () -> - LogRecordExporterConfiguration.configureLogRecordExporters( - config, spiHelper, (a, unused) -> a, closeables)) + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + config, spiHelper, (a, unused) -> a, closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("testExporter"); cleanup.addCloseables(closeables); @@ -82,10 +81,9 @@ void configureLogRecordExporters_emptyClassLoader() { @Test void configureExporter_NotFound() { - assertThatThrownBy( - () -> - LogRecordExporterConfiguration.configureExporter( - "catExporter", NamedSpiManager.createEmpty())) + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureExporter( + "catExporter", NamedSpiManager.createEmpty())) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("catExporter"); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java index e46d0bd7718..7392c1bd86e 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java @@ -86,10 +86,9 @@ void configureMetricReaders_multipleWithNone() { ImmutableMap.of("otel.metrics.exporter", "otlp,none")); List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - MeterProviderConfiguration.configureMetricReaders( - config, spiHelper, (a, unused) -> a, (a, unused) -> a, closeables)) + assertThatThrownBy(() -> + MeterProviderConfiguration.configureMetricReaders( + config, spiHelper, (a, unused) -> a, (a, unused) -> a, closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.metrics.exporter contains none along with other exporters"); cleanup.addCloseables(closeables); @@ -112,12 +111,11 @@ void configureMetricReaders_defaultExporter() { cleanup.addCloseables(closeables); assertThat(metricReaders) - .satisfiesExactly( - metricReader -> - assertThat(metricReader) - .isInstanceOf(PeriodicMetricReader.class) - .extracting("exporter") - .isInstanceOf(OtlpGrpcMetricExporter.class)); + .satisfiesExactly(metricReader -> + assertThat(metricReader) + .isInstanceOf(PeriodicMetricReader.class) + .extracting("exporter") + .isInstanceOf(OtlpGrpcMetricExporter.class)); assertThat(closeables) .hasExactlyElementsOfTypes(OtlpGrpcMetricExporter.class, PeriodicMetricReader.class); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java index aeea76a4d87..9ee26ec2365 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java @@ -80,13 +80,12 @@ void configureSpanExporters_emptyClassLoader() { ImmutableMap.of("test.option", "true", "otel.traces.exporter", "testExporter")); List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureSpanExporters( - config, - SpiHelper.create(new URLClassLoader(new URL[0], null)), - (a, unused) -> a, - new ArrayList<>())) + assertThatThrownBy(() -> + SpanExporterConfiguration.configureSpanExporters( + config, + SpiHelper.create(new URLClassLoader(new URL[0], null)), + (a, unused) -> a, + new ArrayList<>())) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("testExporter"); cleanup.addCloseables(closeables); @@ -101,10 +100,9 @@ void configureSpanExporters_duplicates() { ImmutableMap.of("otel.traces.exporter", "otlp,otlp,logging")); List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureSpanExporters( - config, spiHelper, (a, unused) -> a, closeables)) + assertThatThrownBy(() -> + SpanExporterConfiguration.configureSpanExporters( + config, spiHelper, (a, unused) -> a, closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.traces.exporter contains duplicates: [otlp]"); cleanup.addCloseables(closeables); @@ -117,10 +115,9 @@ void configureSpanExporters_multipleWithNone() { DefaultConfigProperties.createFromMap(ImmutableMap.of("otel.traces.exporter", "otlp,none")); List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureSpanExporters( - config, spiHelper, (a, unused) -> a, closeables)) + assertThatThrownBy(() -> + SpanExporterConfiguration.configureSpanExporters( + config, spiHelper, (a, unused) -> a, closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.traces.exporter contains none along with other exporters"); cleanup.addCloseables(closeables); @@ -129,10 +126,9 @@ void configureSpanExporters_multipleWithNone() { @Test void configureExporter_NotFound() { - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "catExporter", NamedSpiManager.createEmpty())) + assertThatThrownBy(() -> + SpanExporterConfiguration.configureExporter( + "catExporter", NamedSpiManager.createEmpty())) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("catExporter"); } @@ -201,22 +197,20 @@ void configureSpanProcessors_multipleExporters() { .extracting("worker") .extracting("spanExporter") .asInstanceOf(InstanceOfAssertFactories.type(SpanExporter.class)) - .satisfies( - spanExporter -> { - assertThat(spanExporter) - .extracting(spanExporter1 -> spanExporter1.getClass().getSimpleName()) - .isEqualTo("MultiSpanExporter"); - assertThat(spanExporter) - .extracting("spanExporters") - .asInstanceOf(InstanceOfAssertFactories.type(SpanExporter[].class)) - .satisfies( - spanExporters -> { - assertThat(spanExporters.length).isEqualTo(2); - assertThat(spanExporters) - .hasAtLeastOneElementOfType(SpanExporter.noop().getClass()) - .hasAtLeastOneElementOfType(OtlpGrpcSpanExporter.class); - }); - }); + .satisfies(spanExporter -> { + assertThat(spanExporter) + .extracting(spanExporter1 -> spanExporter1.getClass().getSimpleName()) + .isEqualTo("MultiSpanExporter"); + assertThat(spanExporter) + .extracting("spanExporters") + .asInstanceOf(InstanceOfAssertFactories.type(SpanExporter[].class)) + .satisfies(spanExporters -> { + assertThat(spanExporters.length).isEqualTo(2); + assertThat(spanExporters) + .hasAtLeastOneElementOfType(SpanExporter.noop().getClass()) + .hasAtLeastOneElementOfType(OtlpGrpcSpanExporter.class); + }); + }); assertThat(closeables).hasExactlyElementsOfTypes(BatchSpanProcessor.class); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java index dae6767299d..3cfc260edcd 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java @@ -227,94 +227,81 @@ void configures() throws Exception { // await on assertions since metrics may come in different order for BatchSpanProcessor, // exporter, or the ones we created in the test. await() - .untilAsserted( - () -> { - ExportMetricsServiceRequest metricRequest = otlpMetricsRequests.take(); + .untilAsserted(() -> { + ExportMetricsServiceRequest metricRequest = otlpMetricsRequests.take(); - assertThat(metricRequest.getResourceMetricsList()) - .satisfiesExactly( - resourceMetrics -> { - List metricResourceAttributes = - resourceMetrics.getResource().getAttributesList(); - assertHasKeyValue(metricResourceAttributes, "service.name", "test"); - assertHasKeyValue(metricResourceAttributes, "cat", "meow"); - assertThat(resourceMetrics.getScopeMetricsList()) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()).isEqualTo("test"); - assertThat(scopeMetrics.getMetricsList()) - .satisfiesExactly( - metric -> { - // SPI was loaded - assertThat(metric.getName()).isEqualTo("my-metric"); - // TestMeterProviderConfigurer configures a view that - // only passes an attribute named "allowed" - // configured-test - assertHasKeyValue( - getFirstDataPointLabels(metric), "allowed", "bear"); - }); - }) - // This verifies that AutoConfigureListener was invoked and the OTLP - // span / log exporters received the autoconfigured OpenTelemetrySdk - // instance as well as setting telemetry version. - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo( - "io.opentelemetry.exporters.otlp_grpc_metric_exporter"); - assertMetricNames( - scopeMetrics, - "otel.sdk.exporter.metric_data_point.inflight", - "otel.sdk.exporter.operation.duration", - "otel.sdk.exporter.metric_data_point.exported"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo( - "io.opentelemetry.exporters.otlp_grpc_log_exporter"); - assertMetricNames( - scopeMetrics, - "otel.sdk.exporter.log.inflight", - "otel.sdk.exporter.operation.duration", - "otel.sdk.exporter.log.exported"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo( - "io.opentelemetry.exporters.otlp_grpc_span_exporter"); - assertMetricNames( - scopeMetrics, - "otel.sdk.exporter.span.inflight", - "otel.sdk.exporter.operation.duration", - "otel.sdk.exporter.span.exported"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo("io.opentelemetry.sdk.logs"); - assertMetricNames( - scopeMetrics, - "otel.sdk.log.created", - "otel.sdk.processor.log.processed", - "otel.sdk.processor.log.queue.capacity", - "otel.sdk.processor.log.queue.size"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo("io.opentelemetry.sdk.trace"); - assertMetricNames( - scopeMetrics, - "otel.sdk.span.live", - "otel.sdk.span.started", - "otel.sdk.processor.span.processed", - "otel.sdk.processor.span.queue.capacity", - "otel.sdk.processor.span.queue.size"); - }); - }); - }); + assertThat(metricRequest.getResourceMetricsList()) + .satisfiesExactly(resourceMetrics -> { + List metricResourceAttributes = + resourceMetrics.getResource().getAttributesList(); + assertHasKeyValue(metricResourceAttributes, "service.name", "test"); + assertHasKeyValue(metricResourceAttributes, "cat", "meow"); + assertThat(resourceMetrics.getScopeMetricsList()) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()).isEqualTo("test"); + assertThat(scopeMetrics.getMetricsList()) + .satisfiesExactly(metric -> { + // SPI was loaded + assertThat(metric.getName()).isEqualTo("my-metric"); + // TestMeterProviderConfigurer configures a view that + // only passes an attribute named "allowed" + // configured-test + assertHasKeyValue(getFirstDataPointLabels(metric), "allowed", "bear"); + }); + }) + // This verifies that AutoConfigureListener was invoked and the OTLP + // span / log exporters received the autoconfigured OpenTelemetrySdk + // instance as well as setting telemetry version. + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_metric_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.metric_data_point.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.metric_data_point.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_log_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.log.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.log.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_span_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.span.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.span.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.logs"); + assertMetricNames( + scopeMetrics, + "otel.sdk.log.created", + "otel.sdk.processor.log.processed", + "otel.sdk.processor.log.queue.capacity", + "otel.sdk.processor.log.queue.size"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.trace"); + assertMetricNames( + scopeMetrics, + "otel.sdk.span.live", + "otel.sdk.span.started", + "otel.sdk.processor.span.processed", + "otel.sdk.processor.span.queue.capacity", + "otel.sdk.processor.span.queue.size"); + }); + }); + }); await().untilAsserted(() -> assertThat(otlpLogsRequests).hasSize(1)); ExportLogsServiceRequest logRequest = otlpLogsRequests.take(); @@ -326,16 +313,14 @@ void configures() throws Exception { assertThat(logRequest.getResourceLogs(0).getScopeLogs(0).getLogRecordsList()) // LogRecordCustomizer customizes BatchLogProcessor to add an extra attribute on every log // record - .allSatisfy( - logRecord -> - assertHasKeyValue(logRecord.getAttributesList(), "extra-key", "extra-value")) - .satisfiesExactlyInAnyOrder( - logRecord -> { - // LogRecordCustomizer filters logs not whose level is less than Severity.INFO - assertThat(logRecord.getBody().getStringValue()).isEqualTo("info log message"); - assertThat(logRecord.getSeverityNumberValue()) - .isEqualTo(Severity.INFO.getSeverityNumber()); - }); + .allSatisfy(logRecord -> + assertHasKeyValue(logRecord.getAttributesList(), "extra-key", "extra-value")) + .satisfiesExactlyInAnyOrder(logRecord -> { + // LogRecordCustomizer filters logs not whose level is less than Severity.INFO + assertThat(logRecord.getBody().getStringValue()).isEqualTo("info log message"); + assertThat(logRecord.getSeverityNumberValue()) + .isEqualTo(Severity.INFO.getSeverityNumber()); + }); } private static void assertHasKeyValue(List keyValues, String key, boolean value) { diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java index 9043a70cdc6..de9b275bb1a 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java @@ -49,14 +49,13 @@ void configureExporter_KnownSpiExportersOnClasspath() { @Test void configureExporter_UnsupportedOtlpProtocol() { - assertThatThrownBy( - () -> - LogRecordExporterConfiguration.configureExporter( - "otlp", - LogRecordExporterConfiguration.logRecordExporterSpiManager( - DefaultConfigProperties.createFromMap( - ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), - spiHelper))) + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureExporter( + "otlp", + LogRecordExporterConfiguration.logRecordExporterSpiManager( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), + spiHelper))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP logs protocol: foo"); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java index f76bcad0fe8..1e64a151538 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java @@ -54,27 +54,25 @@ void configureLoggerProvider() { try (SdkLoggerProvider loggerProvider = builder.build()) { assertThat(loggerProvider) .extracting("sharedState") - .satisfies( - sharedState -> - assertThat(sharedState) - .extracting("logRecordProcessor") - .isInstanceOf(BatchLogRecordProcessor.class) - .extracting("worker") - .satisfies( - worker -> { - assertThat(worker) - .extracting("scheduleDelayNanos") - .isEqualTo(TimeUnit.SECONDS.toNanos(1)); - assertThat(worker) - .extracting("exporterTimeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); - assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); - assertThat(worker) - .extracting("queue") - .isInstanceOfSatisfying( - ArrayBlockingQueue.class, - queue -> assertThat(queue.remainingCapacity()).isEqualTo(2048)); - })); + .satisfies(sharedState -> + assertThat(sharedState) + .extracting("logRecordProcessor") + .isInstanceOf(BatchLogRecordProcessor.class) + .extracting("worker") + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.SECONDS.toNanos(1)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + ArrayBlockingQueue.class, + queue -> assertThat(queue.remainingCapacity()).isEqualTo(2048)); + })); assertThat(closeables) .hasExactlyElementsOfTypes( OtlpGrpcLogRecordExporter.class, BatchLogRecordProcessor.class); @@ -129,24 +127,23 @@ void configureBatchLogRecordProcessor() { MeterProvider.noop())) { assertThat(processor) .extracting("worker") - .satisfies( - worker -> { - assertThat(worker) - .extracting("scheduleDelayNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(100000)); - assertThat(worker) - .extracting("exporterTimeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(4)); - assertThat(worker).extracting("maxExportBatchSize").isEqualTo(2); - assertThat(worker) - .extracting("queue") - .isInstanceOfSatisfying( - ArrayBlockingQueue.class, - queue -> assertThat(queue.remainingCapacity()).isEqualTo(2)); - assertThat(worker) - .extracting("logRecordExporter") - .isInstanceOf(SystemOutLogRecordExporter.class); - }); + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(100000)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(4)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(2); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + ArrayBlockingQueue.class, + queue -> assertThat(queue.remainingCapacity()).isEqualTo(2)); + assertThat(worker) + .extracting("logRecordExporter") + .isInstanceOf(SystemOutLogRecordExporter.class); + }); } } } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java index 8ae576294d9..2a8a31a5dac 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java @@ -97,12 +97,11 @@ private static void assertCardinalityLimit( "metricReaders", as(InstanceOfAssertFactories.map(MetricReader.class, CardinalityLimitSelector.class))) .hasSizeGreaterThan(0) - .allSatisfy( - (metricReader, cardinalityLimitSelector) -> { - for (InstrumentType instrumentType : InstrumentType.values()) { - assertThat(cardinalityLimitSelector.getCardinalityLimit(instrumentType)) - .isEqualTo(expectedCardinalityLimit); - } - }); + .allSatisfy((metricReader, cardinalityLimitSelector) -> { + for (InstrumentType instrumentType : InstrumentType.values()) { + assertThat(cardinalityLimitSelector.getCardinalityLimit(instrumentType)) + .isEqualTo(expectedCardinalityLimit); + } + }); } } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java index b1c1a05b510..387dd991364 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java @@ -143,10 +143,9 @@ void configureReader_periodicMetricReader_invalidMaxExportBatchSize() { DefaultConfigProperties.createFromMap( ImmutableMap.of("otel.metric.export.max.batch.size", "0")); - assertThatThrownBy( - () -> - MetricExporterConfiguration.configureReader( - "otlp", config, spiHelper, (a, b) -> a, (a, b) -> a, closeables)) + assertThatThrownBy(() -> + MetricExporterConfiguration.configureReader( + "otlp", config, spiHelper, (a, b) -> a, (a, b) -> a, closeables)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("maxExportBatchSize must be positive"); cleanup.addCloseables(closeables); @@ -193,14 +192,13 @@ private static Stream knownReaders() { @Test void configureOtlpMetricsUnsupportedProtocol() { - assertThatThrownBy( - () -> - MetricExporterConfiguration.configureExporter( - "otlp", - MetricExporterConfiguration.metricExporterSpiManager( - DefaultConfigProperties.createFromMap( - ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), - spiHelper))) + assertThatThrownBy(() -> + MetricExporterConfiguration.configureExporter( + "otlp", + MetricExporterConfiguration.metricExporterSpiManager( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), + spiHelper))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP metrics protocol: foo"); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java index 7e590119be3..d169918a157 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java @@ -101,72 +101,65 @@ private static Stream configureResourceArgs() { "default", null, null, - attributeConsumer( - attr -> - attr.containsEntry("service.name", "test") - .containsEntry("cat", "meow") - .containsEntry("service.instance.id", "override-id"))), + attributeConsumer(attr -> + attr.containsEntry("service.name", "test") + .containsEntry("cat", "meow") + .containsEntry("service.instance.id", "override-id"))), Arguments.argumentSet( "only enabled animal provider", "io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", null, - attributeConsumer( - attr -> - attr.containsEntry("service.name", "unknown_service:java") - .doesNotContainKey("cat") - .containsEntry("animal", "cat") - .doesNotContainKey("color"))), + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .containsEntry("animal", "cat") + .doesNotContainKey("color"))), Arguments.argumentSet( "only disabled color provider", null, "io.opentelemetry.sdk.autoconfigure.provider.TestColorResourceProvider", - attributeConsumer( - attr -> - attr.containsEntry("service.name", "test") - .containsEntry("cat", "meow") - .containsEntry("animal", "cat") - .doesNotContainKey("color"))), + attributeConsumer(attr -> + attr.containsEntry("service.name", "test") + .containsEntry("cat", "meow") + .containsEntry("animal", "cat") + .doesNotContainKey("color"))), Arguments.argumentSet( "enabled animal disabled color", "io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", "io.opentelemetry.sdk.autoconfigure.provider.TestColorResourceProvider", - attributeConsumer( - attr -> - attr.containsEntry("service.name", "unknown_service:java") - .doesNotContainKey("cat") - .containsEntry("animal", "cat") - .doesNotContainKey("color"))), + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .containsEntry("animal", "cat") + .doesNotContainKey("color"))), Arguments.argumentSet( "enabled animal disabled color and animal", "io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", "io.opentelemetry.sdk.autoconfigure.provider.TestColorResourceProvider,io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", - attributeConsumer( - attr -> - attr.containsEntry("service.name", "unknown_service:java") - .doesNotContainKey("cat") - .doesNotContainKey("animal") - .doesNotContainKey("color"))), + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .doesNotContainKey("animal") + .doesNotContainKey("color"))), Arguments.argumentSet( "only environment provider enabled", "io.opentelemetry.sdk.autoconfigure.EnvironmentResourceProvider", null, - attributeConsumer( - attr -> - attr.containsEntry("service.name", "test") - .containsEntry("cat", "meow") - .doesNotContainKey("service.instance.id") - .doesNotContainKey("animal") - .doesNotContainKey("color"))), + attributeConsumer(attr -> + attr.containsEntry("service.name", "test") + .containsEntry("cat", "meow") + .doesNotContainKey("service.instance.id") + .doesNotContainKey("animal") + .doesNotContainKey("color"))), Arguments.argumentSet( "environment provider disabled", null, "io.opentelemetry.sdk.autoconfigure.EnvironmentResourceProvider", - attributeConsumer( - attr -> - attr.containsEntry("service.name", "unknown_service:java") - .doesNotContainKey("cat") - .containsEntry("animal", "cat") - .containsEntry("color", "blue")))); + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .containsEntry("animal", "cat") + .containsEntry("color", "blue")))); } private static Consumer attributeConsumer( diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java index a31280c4177..d0c3d312963 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java @@ -48,10 +48,9 @@ void configureOtlpSpansUnsupportedProtocol() { ConfigProperties config = DefaultConfigProperties.createFromMap( ImmutableMap.of("otel.exporter.otlp.protocol", "foo")); - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", SpanExporterConfiguration.spanExporterSpiManager(config, spiHelper))) + assertThatThrownBy(() -> + SpanExporterConfiguration.configureExporter( + "otlp", SpanExporterConfiguration.spanExporterSpiManager(config, spiHelper))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP traces protocol: foo"); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java index 8e574bb559e..6f60fa9fa8f 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java @@ -46,22 +46,20 @@ void configuration() { void emptyClassLoader() { ConfigProperties config = DefaultConfigProperties.createFromMap(ImmutableMap.of("test.option", "true")); - assertThatThrownBy( - () -> - TracerProviderConfiguration.configureSampler( - "testSampler", config, SpiHelper.create(new URLClassLoader(new URL[0], null)))) + assertThatThrownBy(() -> + TracerProviderConfiguration.configureSampler( + "testSampler", config, SpiHelper.create(new URLClassLoader(new URL[0], null)))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("testSampler"); } @Test void samplerNotFound() { - assertThatThrownBy( - () -> - TracerProviderConfiguration.configureSampler( - "catSampler", - DefaultConfigProperties.createFromMap(Collections.emptyMap()), - spiHelper)) + assertThatThrownBy(() -> + TracerProviderConfiguration.configureSampler( + "catSampler", + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + spiHelper)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("catSampler"); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/LogRecordCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/LogRecordCustomizer.java index 78c21104ff2..ff4a694e40e 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/LogRecordCustomizer.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/LogRecordCustomizer.java @@ -55,11 +55,10 @@ private static LogRecordExporter exporterCustomizer( public CompletableResultCode export(Collection logs) { Collection filtered = logs.stream() - .filter( - log -> - log.getSeverity() == Severity.UNDEFINED_SEVERITY_NUMBER - || log.getSeverity().getSeverityNumber() - >= Severity.INFO.getSeverityNumber()) + .filter(log -> + log.getSeverity() == Severity.UNDEFINED_SEVERITY_NUMBER + || log.getSeverity().getSeverityNumber() + >= Severity.INFO.getSeverityNumber()) .collect(Collectors.toList()); return delegate.export(filtered); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/MetricCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/MetricCustomizer.java index 3171f8d91e5..53da532f574 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/MetricCustomizer.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/MetricCustomizer.java @@ -49,17 +49,16 @@ public CompletableResultCode export(Collection metrics) { // please configure the SdkMeterProvider with the appropriate view. Collection filtered = metrics.stream() - .filter( - metricData -> - metricData.getName().equals("my-metric") - || metricData - .getInstrumentationScopeInfo() - .getName() - .startsWith("io.opentelemetry.exporters") - || metricData - .getInstrumentationScopeInfo() - .getName() - .startsWith("io.opentelemetry.sdk")) + .filter(metricData -> + metricData.getName().equals("my-metric") + || metricData + .getInstrumentationScopeInfo() + .getName() + .startsWith("io.opentelemetry.exporters") + || metricData + .getInstrumentationScopeInfo() + .getName() + .startsWith("io.opentelemetry.sdk")) .collect(Collectors.toList()); return delegate.export(filtered); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/SpanCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/SpanCustomizer.java index 5fa8c41b3ca..1e937dff970 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/SpanCustomizer.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/SpanCustomizer.java @@ -75,16 +75,15 @@ private static SpanExporter exporterCustomizer(SpanExporter delegate, ConfigProp public CompletableResultCode export(Collection spans) { return delegate.export( spans.stream() - .map( - span -> - new DelegatingSpanData(span) { - @Override - public Attributes getAttributes() { - return span.getAttributes().toBuilder() - .put("wrapped", config.getInt("otel.test.wrapped")) - .build(); - } - }) + .map(span -> + new DelegatingSpanData(span) { + @Override + public Attributes getAttributes() { + return span.getAttributes().toBuilder() + .put("wrapped", config.getInt("otel.test.wrapped")) + .build(); + } + }) .collect(Collectors.toList())); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestTracerProviderConfigurer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestTracerProviderConfigurer.java index 25cdbd51c33..ca47b0503fe 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestTracerProviderConfigurer.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestTracerProviderConfigurer.java @@ -15,8 +15,7 @@ public class TestTracerProviderConfigurer implements SdkTracerProviderConfigurer @Override public void configure(SdkTracerProviderBuilder tracerProvider, ConfigProperties config) { tracerProvider.addSpanProcessor( - OnStartSpanProcessor.create( - (ctx, span) -> - span.setAttribute("configured", config.getBoolean("otel.test.configured")))); + OnStartSpanProcessor.create((ctx, span) -> + span.setAttribute("configured", config.getBoolean("otel.test.configured")))); } } diff --git a/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java index c69923a9fce..a8e30d9f6d1 100644 --- a/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java @@ -91,22 +91,20 @@ void setup() throws IOException { @Test @SuppressLogger(AutoConfiguredOpenTelemetrySdkBuilder.class) void configFile_fileNotFound() { - assertThatThrownBy( - () -> - AutoConfiguredOpenTelemetrySdk.builder() - .setConfig( - DefaultConfigProperties.createFromMap( - Collections.singletonMap("otel.config.file", "foo"))) - .build()) + assertThatThrownBy(() -> + AutoConfiguredOpenTelemetrySdk.builder() + .setConfig( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", "foo"))) + .build()) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Configuration file not found"); - assertThatCode( - () -> - AutoConfiguredOpenTelemetrySdk.builder() - .addPropertiesSupplier(() -> singletonMap("otel.config.file", "")) - .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) - .build()) + assertThatCode(() -> + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> singletonMap("otel.config.file", "")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) + .build()) .doesNotThrowAnyException(); } diff --git a/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/FullDeclarativeConfigTest.java b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/FullDeclarativeConfigTest.java index ad1e5d0a60a..bfba04a1140 100644 --- a/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/FullDeclarativeConfigTest.java +++ b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/FullDeclarativeConfigTest.java @@ -233,82 +233,71 @@ void configures() throws Exception { // await on assertions since metrics may come in different order for BatchSpanProcessor, // exporter, or the ones we created in the test. await() - .untilAsserted( - () -> { - ExportMetricsServiceRequest metricRequest = otlpMetricsRequests.take(); + .untilAsserted(() -> { + ExportMetricsServiceRequest metricRequest = otlpMetricsRequests.take(); - assertThat(metricRequest.getResourceMetricsList()) - .satisfiesExactly( - resourceMetrics -> { - List metricResourceAttributes = - resourceMetrics.getResource().getAttributesList(); - assertHasKeyValue(metricResourceAttributes, "service.name", "test"); - assertThat(resourceMetrics.getScopeMetricsList()) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()).isEqualTo("test"); - assertMetricNames(scopeMetrics, "my-metric"); - }) - // This verifies that MeterProvider was injected into OTLP exporters and - // the internal telemetry version was set. - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo( - "io.opentelemetry.exporters.otlp_grpc_metric_exporter"); - assertMetricNames( - scopeMetrics, - "otel.sdk.exporter.metric_data_point.inflight", - "otel.sdk.exporter.operation.duration", - "otel.sdk.exporter.metric_data_point.exported"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo( - "io.opentelemetry.exporters.otlp_grpc_log_exporter"); - assertMetricNames( - scopeMetrics, - "otel.sdk.exporter.log.inflight", - "otel.sdk.exporter.operation.duration", - "otel.sdk.exporter.log.exported"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo( - "io.opentelemetry.exporters.otlp_grpc_span_exporter"); - assertMetricNames( - scopeMetrics, - "otel.sdk.exporter.span.inflight", - "otel.sdk.exporter.operation.duration", - "otel.sdk.exporter.span.exported"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo("io.opentelemetry.sdk.logs"); - assertMetricNames( - scopeMetrics, - "otel.sdk.log.created", - "otel.sdk.processor.log.processed", - "otel.sdk.processor.log.queue.capacity", - "otel.sdk.processor.log.queue.size"); - }) - .anySatisfy( - scopeMetrics -> { - assertThat(scopeMetrics.getScope().getName()) - .isEqualTo("io.opentelemetry.sdk.trace"); - assertMetricNames( - scopeMetrics, - "otel.sdk.span.live", - "otel.sdk.span.started", - "otel.sdk.processor.span.processed", - "otel.sdk.processor.span.queue.capacity", - "otel.sdk.processor.span.queue.size"); - }); - }); - }); + assertThat(metricRequest.getResourceMetricsList()) + .satisfiesExactly(resourceMetrics -> { + List metricResourceAttributes = + resourceMetrics.getResource().getAttributesList(); + assertHasKeyValue(metricResourceAttributes, "service.name", "test"); + assertThat(resourceMetrics.getScopeMetricsList()) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()).isEqualTo("test"); + assertMetricNames(scopeMetrics, "my-metric"); + }) + // This verifies that MeterProvider was injected into OTLP exporters and + // the internal telemetry version was set. + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_metric_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.metric_data_point.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.metric_data_point.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_log_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.log.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.log.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_span_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.span.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.span.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.logs"); + assertMetricNames( + scopeMetrics, + "otel.sdk.log.created", + "otel.sdk.processor.log.processed", + "otel.sdk.processor.log.queue.capacity", + "otel.sdk.processor.log.queue.size"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.trace"); + assertMetricNames( + scopeMetrics, + "otel.sdk.span.live", + "otel.sdk.span.started", + "otel.sdk.processor.span.processed", + "otel.sdk.processor.span.queue.capacity", + "otel.sdk.processor.span.queue.size"); + }); + }); + }); await().untilAsserted(() -> assertThat(otlpLogsRequests).hasSize(1)); ExportLogsServiceRequest logRequest = otlpLogsRequests.take(); @@ -317,12 +306,11 @@ void configures() throws Exception { assertHasKeyValue(logResourceAttributes, "service.name", "test"); assertThat(logRequest.getResourceLogs(0).getScopeLogs(0).getLogRecordsList()) - .satisfiesExactlyInAnyOrder( - logRecord -> { - assertThat(logRecord.getBody().getStringValue()).isEqualTo("info log message"); - assertThat(logRecord.getSeverityNumberValue()) - .isEqualTo(Severity.INFO.getSeverityNumber()); - }); + .satisfiesExactlyInAnyOrder(logRecord -> { + assertThat(logRecord.getBody().getStringValue()).isEqualTo("info log message"); + assertThat(logRecord.getSeverityNumberValue()) + .isEqualTo(Severity.INFO.getSeverityNumber()); + }); } private static void assertHasKeyValue(List keyValues, String key, String value) { diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactory.java index 9b4f9b9a63c..4c6de8b0d3c 100644 --- a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactory.java +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactory.java @@ -51,29 +51,28 @@ public ComposableSampler create( List rules = model.getRules(); if (rules != null) { - rules.forEach( - rule -> { - AttributeMatcher valueMatcher = attributeValuesMatcher(rule.getAttributeValues()); - AttributeMatcher patternMatcher = attributePatternsMatcher(rule.getAttributePatterns()); - Set matchingParents = - rule.getParent() != null && !rule.getParent().isEmpty() - ? new HashSet<>(rule.getParent()) - : null; - Set matchingSpanKinds = - rule.getSpanKinds() != null && !rule.getSpanKinds().isEmpty() - ? rule.getSpanKinds().stream() - .map(DeclarativeConfigSamplingPredicate::toSpanKind) - .collect(toSet()) - : null; - - SamplingPredicate predicate = - new DeclarativeConfigSamplingPredicate( - valueMatcher, patternMatcher, matchingParents, matchingSpanKinds); - ComposableSampler sampler = - ComposableSamplerFactory.getInstance() - .create(requireNonNull(rule.getSampler(), "rule sampler"), context); - builder.add(predicate, sampler); - }); + rules.forEach(rule -> { + AttributeMatcher valueMatcher = attributeValuesMatcher(rule.getAttributeValues()); + AttributeMatcher patternMatcher = attributePatternsMatcher(rule.getAttributePatterns()); + Set matchingParents = + rule.getParent() != null && !rule.getParent().isEmpty() + ? new HashSet<>(rule.getParent()) + : null; + Set matchingSpanKinds = + rule.getSpanKinds() != null && !rule.getSpanKinds().isEmpty() + ? rule.getSpanKinds().stream() + .map(DeclarativeConfigSamplingPredicate::toSpanKind) + .collect(toSet()) + : null; + + SamplingPredicate predicate = + new DeclarativeConfigSamplingPredicate( + valueMatcher, patternMatcher, matchingParents, matchingSpanKinds); + ComposableSampler sampler = + ComposableSamplerFactory.getInstance() + .create(requireNonNull(rule.getSampler(), "rule sampler"), context); + builder.add(predicate, sampler); + }); } return builder.build(); @@ -171,23 +170,22 @@ public boolean matches( private static boolean attributesMatch(AttributeMatcher matcher, Attributes attributes) { boolean[] match = new boolean[] {false}; - attributes.forEach( - (key, value) -> { - if (!matcher.matchesKey(key.getKey())) { - return; - } - if (value instanceof List) { - // For array attributes, it is a match if any item matches - for (Object item : (List) value) { - if (matcher.matchesValue(String.valueOf(item))) { - match[0] = true; - return; - } - } - } else if (matcher.matchesValue(String.valueOf(value))) { + attributes.forEach((key, value) -> { + if (!matcher.matchesKey(key.getKey())) { + return; + } + if (value instanceof List) { + // For array attributes, it is a match if any item matches + for (Object item : (List) value) { + if (matcher.matchesValue(String.valueOf(item))) { match[0] = true; + return; } - }); + } + } else if (matcher.matchesValue(String.valueOf(value))) { + match[0] = true; + } + }); return match[0]; } diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContext.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContext.java index 5508d87f577..8d5244640c5 100644 --- a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContext.java +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContext.java @@ -152,9 +152,8 @@ T loadComponent(Class type, ConfigKeyValue configKeyValue) { } List matchedProviders = componentProviders.stream() - .filter( - componentProvider -> - componentProvider.getType() == type && name.equals(componentProvider.getName())) + .filter(componentProvider -> + componentProvider.getType() == type && name.equals(componentProvider.getName())) .collect(Collectors.toList()); if (matchedProviders.isEmpty()) { throw new DeclarativeConfigException( @@ -205,12 +204,11 @@ public String toString() { @Override public Iterable load(Class spiClass) { List result = ComponentLoader.loadList(componentLoader, spiClass); - result.forEach( - entry -> { - if (entry instanceof AutoConfigureListener) { - listeners.add((AutoConfigureListener) entry); - } - }); + result.forEach(entry -> { + if (entry instanceof AutoConfigureListener) { + listeners.add((AutoConfigureListener) entry); + } + }); return result; } diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactory.java index 4cceee77991..a67ac48d781 100644 --- a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactory.java +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactory.java @@ -58,10 +58,9 @@ public SdkLoggerProviderBuilder create( List processors = loggerProviderModel.getProcessors(); if (processors != null) { - processors.forEach( - processor -> - builder.addLogRecordProcessor( - LogRecordProcessorFactory.getInstance().create(processor, context))); + processors.forEach(processor -> + builder.addLogRecordProcessor( + LogRecordProcessorFactory.getInstance().create(processor, context))); } ExperimentalLoggerConfiguratorModel loggerConfiguratorModel = diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactory.java index 4eb8a061b01..1eb96c282c6 100644 --- a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactory.java +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactory.java @@ -43,31 +43,29 @@ public SdkMeterProviderBuilder create( List readerModels = model.getReaders(); if (readerModels != null) { - readerModels.forEach( - readerModel -> { - MetricReaderAndCardinalityLimits readerAndCardinalityLimits = - MetricReaderFactory.getInstance().create(readerModel, context); - CardinalityLimitSelector cardinalityLimits = - readerAndCardinalityLimits.getCardinalityLimitsSelector(); - if (cardinalityLimits == null) { - builder.registerMetricReader(readerAndCardinalityLimits.getMetricReader()); - } else { - builder.registerMetricReader( - readerAndCardinalityLimits.getMetricReader(), cardinalityLimits); - } - }); + readerModels.forEach(readerModel -> { + MetricReaderAndCardinalityLimits readerAndCardinalityLimits = + MetricReaderFactory.getInstance().create(readerModel, context); + CardinalityLimitSelector cardinalityLimits = + readerAndCardinalityLimits.getCardinalityLimitsSelector(); + if (cardinalityLimits == null) { + builder.registerMetricReader(readerAndCardinalityLimits.getMetricReader()); + } else { + builder.registerMetricReader( + readerAndCardinalityLimits.getMetricReader(), cardinalityLimits); + } + }); } List viewModels = model.getViews(); if (viewModels != null) { - viewModels.forEach( - viewModel -> { - ViewSelectorModel selector = requireNonNull(viewModel.getSelector(), "view selector"); - ViewStreamModel stream = requireNonNull(viewModel.getStream(), "view stream"); - builder.registerView( - InstrumentSelectorFactory.getInstance().create(selector, context), - ViewFactory.getInstance().create(stream, context)); - }); + viewModels.forEach(viewModel -> { + ViewSelectorModel selector = requireNonNull(viewModel.getSelector(), "view selector"); + ViewStreamModel stream = requireNonNull(viewModel.getStream(), "view stream"); + builder.registerView( + InstrumentSelectorFactory.getInstance().create(selector, context), + ViewFactory.getInstance().create(stream, context)); + }); } ExperimentalMeterConfiguratorModel meterConfiguratorModel = diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactory.java index f2de7b59508..d01195d2202 100644 --- a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactory.java +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactory.java @@ -33,13 +33,12 @@ public ContextPropagators create(PropagatorModel model, DeclarativeConfigContext Set propagatorNames = new HashSet<>(); List textMapPropagators = new ArrayList<>(); if (textMapPropagatorModels != null) { - textMapPropagatorModels.forEach( - textMapPropagatorModel -> { - TextMapPropagatorAndName propagatorAndName = - TextMapPropagatorFactory.getInstance().create(textMapPropagatorModel, context); - textMapPropagators.add(propagatorAndName.getTextMapPropagator()); - propagatorNames.add(propagatorAndName.getName()); - }); + textMapPropagatorModels.forEach(textMapPropagatorModel -> { + TextMapPropagatorAndName propagatorAndName = + TextMapPropagatorFactory.getInstance().create(textMapPropagatorModel, context); + textMapPropagators.add(propagatorAndName.getTextMapPropagator()); + propagatorNames.add(propagatorAndName.getName()); + }); } String compositeList = model.getCompositeList(); diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactory.java index 961ef5c893f..a51d09c6b37 100644 --- a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactory.java +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactory.java @@ -61,10 +61,8 @@ public SdkTracerProviderBuilder create( List processors = tracerProviderModel.getProcessors(); if (processors != null) { - processors.forEach( - processor -> - builder.addSpanProcessor( - SpanProcessorFactory.getInstance().create(processor, context))); + processors.forEach(processor -> + builder.addSpanProcessor(SpanProcessorFactory.getInstance().create(processor, context))); } if (tracerProviderModel.getIdGenerator() != null) { diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigProperties.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigProperties.java index 43a4bb16ef1..6a1df886b25 100644 --- a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigProperties.java +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigProperties.java @@ -136,11 +136,9 @@ private static boolean isListOfMaps(Object object) { if (object instanceof List) { List list = (List) object; return list.stream() - .allMatch( - entry -> - entry instanceof Map - && ((Map) entry) - .keySet().stream().allMatch(key -> key instanceof String)); + .allMatch(entry -> + entry instanceof Map + && ((Map) entry).keySet().stream().allMatch(key -> key instanceof String)); } return false; } @@ -252,19 +250,18 @@ public List getScalarList(String name, Class scalarType) { } List result = objectList.stream() - .map( - entry -> { - if (scalarType == String.class) { - return stringOrNull(entry, name); - } else if (scalarType == Boolean.class) { - return booleanOrNull(entry, name); - } else if (scalarType == Long.class) { - return longOrNull(entry, name); - } else if (scalarType == Double.class) { - return doubleOrNull(entry, name); - } - return null; - }) + .map(entry -> { + if (scalarType == String.class) { + return stringOrNull(entry, name); + } else if (scalarType == Boolean.class) { + return booleanOrNull(entry, name); + } else if (scalarType == Long.class) { + return longOrNull(entry, name); + } else if (scalarType == Double.class) { + return doubleOrNull(entry, name); + } + return null; + }) .filter(Objects::nonNull) .map(scalarType::cast) .collect(toList()); diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactoryTest.java index 79d3f55ffce..a6f2f521959 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactoryTest.java @@ -28,10 +28,8 @@ class AttributeListFactoryTest { @ParameterizedTest @MethodSource("invalidAttributes") void create_InvalidAttributes(List model, String expectedMessage) { - assertThatThrownBy( - () -> - AttributeListFactory.getInstance() - .create(model, mock(DeclarativeConfigContext.class))) + assertThatThrownBy(() -> + AttributeListFactory.getInstance().create(model, mock(DeclarativeConfigContext.class))) .isInstanceOf(DeclarativeConfigException.class) .hasMessageContaining(expectedMessage); } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContextTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContextTest.java index 7b650174e98..e4540d01ba5 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContextTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContextTest.java @@ -32,26 +32,24 @@ class DeclarativeConfigContextTest { @Test void componentProvidersCached() { // First loadComponent call should load providers - assertThatThrownBy( - () -> - context.loadComponent( - Resource.class, - ConfigKeyValue.of( - "nonexistent", - YamlDeclarativeConfigProperties.create( - Collections.emptyMap(), componentLoader)))) + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "nonexistent", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) .isInstanceOf(DeclarativeConfigException.class) .hasMessageContaining("No component provider detected"); // Second loadComponent call should use cached providers, not reload - assertThatThrownBy( - () -> - context.loadComponent( - Resource.class, - ConfigKeyValue.of( - "another", - YamlDeclarativeConfigProperties.create( - Collections.emptyMap(), componentLoader)))) + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "another", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) .isInstanceOf(DeclarativeConfigException.class) .hasMessageContaining("No component provider detected"); diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCreateTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCreateTest.java index 86b8f3608a3..fa15f2ae8ad 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCreateTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCreateTest.java @@ -142,10 +142,9 @@ void parseAndCreate_Exception_CleansUpPartials() { + " exporter:\n" + " foo: {}\n"; - assertThatThrownBy( - () -> - DeclarativeConfiguration.parseAndCreate( - new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)))) + assertThatThrownBy(() -> + DeclarativeConfiguration.parseAndCreate( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)))) .isInstanceOf(DeclarativeConfigException.class) .hasMessage( "No component provider detected for io.opentelemetry.sdk.logs.export.LogRecordExporter with name \"foo\"."); @@ -167,10 +166,9 @@ void parseAndCreate_EmptyComponentProviderConfig() { + " processors:\n" + " - test:\n"; - assertThatCode( - () -> - DeclarativeConfiguration.parseAndCreate( - new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)))) + assertThatCode(() -> + DeclarativeConfiguration.parseAndCreate( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)))) .doesNotThrowAnyException(); } @@ -205,15 +203,13 @@ void callAutoConfigureListeners_exceptionIsCaught() { DeclarativeConfigContext context = mock(DeclarativeConfigContext.class); when(context.getListeners()) .thenReturn( - Collections.singleton( - sdk -> { - throw new RuntimeException("Test exception from AutoConfigureListener"); - })); - - assertThatCode( - () -> - DeclarativeConfiguration.callAutoConfigureListeners( - context, OpenTelemetrySdk.builder().build())) + Collections.singleton(sdk -> { + throw new RuntimeException("Test exception from AutoConfigureListener"); + })); + + assertThatCode(() -> + DeclarativeConfiguration.callAutoConfigureListeners( + context, OpenTelemetrySdk.builder().build())) .doesNotThrowAnyException(); } } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationParseTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationParseTest.java index 6646403853f..e3faf818b5c 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationParseTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationParseTest.java @@ -40,10 +40,9 @@ class DeclarativeConfigurationParseTest { @Test void parse_BadInputStream() { - assertThatThrownBy( - () -> - DeclarativeConfiguration.parseAndCreate( - new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)))) + assertThatThrownBy(() -> + DeclarativeConfiguration.parseAndCreate( + new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)))) .isInstanceOf(DeclarativeConfigException.class) .hasMessage("Unable to parse configuration input stream"); } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactoryTest.java index 028fab07677..a8508fb0d17 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactoryTest.java @@ -20,10 +20,9 @@ class InstrumentSelectorFactoryTest { @Test void create_Defaults() { - assertThatThrownBy( - () -> - InstrumentSelectorFactory.getInstance() - .create(new ViewSelectorModel(), mock(DeclarativeConfigContext.class))) + assertThatThrownBy(() -> + InstrumentSelectorFactory.getInstance() + .create(new ViewSelectorModel(), mock(DeclarativeConfigContext.class))) .isInstanceOf(DeclarativeConfigException.class) .hasMessage("Invalid selector"); } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactoryTest.java index fe80bc26e83..c155ec3272a 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactoryTest.java @@ -258,12 +258,10 @@ void create_Customizer_ReturnsNull() { .getBuilder() .addLogRecordExporterCustomizer(LogRecordExporter.class, (exporter, properties) -> null); - assertThatThrownBy( - () -> - LogRecordExporterFactory.getInstance() - .create( - new LogRecordExporterModel().setConsole(new ConsoleExporterModel()), - context)) + assertThatThrownBy(() -> + LogRecordExporterFactory.getInstance() + .create( + new LogRecordExporterModel().setConsole(new ConsoleExporterModel()), context)) .isInstanceOf(DeclarativeConfigException.class) .hasMessageContaining("Customizer returned null for LogRecordExporter: console"); } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactoryTest.java index 84c7fc2fcb7..1a27625e7ec 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactoryTest.java @@ -119,12 +119,11 @@ private static Stream createArguments() { .setMinimumSeverity(Severity.INFO) .build()) .build()) - .setLogLimits( - () -> - LogLimits.builder() - .setMaxNumberOfAttributes(1) - .setMaxAttributeValueLength(2) - .build()) + .setLogLimits(() -> + LogLimits.builder() + .setMaxNumberOfAttributes(1) + .setMaxAttributeValueLength(2) + .build()) .addLogRecordProcessor( BatchLogRecordProcessor.builder( OtlpHttpLogRecordExporter.builder().setComponentLoader(context).build()) diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactoryTest.java index f229ab8e60b..b9b5e050873 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactoryTest.java @@ -294,12 +294,11 @@ void create_Customizer_ReturnsNull() { .getBuilder() .addMetricExporterCustomizer(MetricExporter.class, (exporter, properties) -> null); - assertThatThrownBy( - () -> - MetricExporterFactory.getInstance() - .create( - new PushMetricExporterModel().setConsole(new ConsoleMetricExporterModel()), - context)) + assertThatThrownBy(() -> + MetricExporterFactory.getInstance() + .create( + new PushMetricExporterModel().setConsole(new ConsoleMetricExporterModel()), + context)) .isInstanceOf(DeclarativeConfigException.class) .hasMessageContaining("Customizer returned null for MetricExporter: console"); } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactoryTest.java index cd9c6604474..72f3f9d4f02 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactoryTest.java @@ -322,12 +322,11 @@ void create_Configured() throws NoSuchFieldException { .setLoggerProvider( SdkLoggerProvider.builder() .setResource(expectedResource) - .setLogLimits( - () -> - LogLimits.builder() - .setMaxAttributeValueLength(1) - .setMaxNumberOfAttributes(2) - .build()) + .setLogLimits(() -> + LogLimits.builder() + .setMaxAttributeValueLength(1) + .setMaxNumberOfAttributes(2) + .build()) .addLogRecordProcessor( BatchLogRecordProcessor.builder( OtlpHttpLogRecordExporter.builder() diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactoryTest.java index 862ef7efad9..2cf618bf2a8 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactoryTest.java @@ -122,10 +122,9 @@ private static Stream createArguments() { @Test void create_SpiPropagator_Unknown() { - assertThatThrownBy( - () -> - PropagatorFactory.getInstance() - .create(new PropagatorModel().setCompositeList("foo"), context)) + assertThatThrownBy(() -> + PropagatorFactory.getInstance() + .create(new PropagatorModel().setCompositeList("foo"), context)) .isInstanceOf(DeclarativeConfigException.class) .hasMessage( "No component provider detected for io.opentelemetry.context.propagation.TextMapPropagator with name \"foo\"."); diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactoryTest.java index a991a0822f9..e7dfca7d244 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactoryTest.java @@ -207,11 +207,10 @@ void entityFiltering( } else { assertThat(EntityUtil.getEntities(resource)) .singleElement() - .satisfies( - filtered -> { - assertThat(filtered.getId()).isEqualTo(expectedId); - assertThat(filtered.getDescription()).isEqualTo(expectedDescription); - }); + .satisfies(filtered -> { + assertThat(filtered.getId()).isEqualTo(expectedId); + assertThat(filtered.getDescription()).isEqualTo(expectedDescription); + }); } assertThat(resource.getAttributes()) .isEqualTo( diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactoryTest.java index 4e6a6cead30..2044a7abf10 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactoryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactoryTest.java @@ -266,11 +266,9 @@ void create_Customizer_ReturnsNull() { .getBuilder() .addSpanExporterCustomizer(SpanExporter.class, (exporter, properties) -> null); - assertThatThrownBy( - () -> - SpanExporterFactory.getInstance() - .create( - new SpanExporterModel().setConsole(new ConsoleExporterModel()), context)) + assertThatThrownBy(() -> + SpanExporterFactory.getInstance() + .create(new SpanExporterModel().setConsole(new ConsoleExporterModel()), context)) .isInstanceOf(DeclarativeConfigException.class) .hasMessageContaining("Customizer returned null for SpanExporter: console"); } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TestDeclarativeConfigurationCustomizerProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TestDeclarativeConfigurationCustomizerProvider.java index 1a4c7c50b52..d633fbb9da4 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TestDeclarativeConfigurationCustomizerProvider.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TestDeclarativeConfigurationCustomizerProvider.java @@ -16,29 +16,28 @@ public class TestDeclarativeConfigurationCustomizerProvider @Override public void customize(DeclarativeConfigurationCustomizer customizer) { - customizer.addModelCustomizer( - model -> { - ResourceModel resource = model.getResource(); - if (resource == null) { - resource = new ResourceModel(); - model.setResource(resource); - } - List attributes = resource.getAttributes(); - if (attributes == null) { - attributes = new ArrayList<>(); - resource.setAttributes(attributes); - } - attributes.add( - new AttributeNameValueModel() - .setName("foo") - .setType(AttributeTypeModel.STRING) - .setValue("bar")); - attributes.add( - new AttributeNameValueModel() - .setName("color") - .setType(AttributeTypeModel.STRING) - .setValue("blue")); - return model; - }); + customizer.addModelCustomizer(model -> { + ResourceModel resource = model.getResource(); + if (resource == null) { + resource = new ResourceModel(); + model.setResource(resource); + } + List attributes = resource.getAttributes(); + if (attributes == null) { + attributes = new ArrayList<>(); + resource.setAttributes(attributes); + } + attributes.add( + new AttributeNameValueModel() + .setName("foo") + .setType(AttributeTypeModel.STRING) + .setValue("bar")); + attributes.add( + new AttributeNameValueModel() + .setName("color") + .setType(AttributeTypeModel.STRING) + .setValue("blue")); + return model; + }); } } diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigPropertiesTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigPropertiesTest.java index 210af6c14cc..57d67aad5e8 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigPropertiesTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigPropertiesTest.java @@ -86,11 +86,10 @@ void configurationSchema() { resourceProps.getStructuredList("attributes"); assertThat(resourceAttributesList) .isNotNull() - .satisfiesExactly( - attributeEntry -> { - assertThat(attributeEntry.getString("name")).isEqualTo("service.name"); - assertThat(attributeEntry.getString("value")).isEqualTo("unknown_service"); - }); + .satisfiesExactly(attributeEntry -> { + assertThat(attributeEntry.getString("name")).isEqualTo("service.name"); + assertThat(attributeEntry.getString("value")).isEqualTo("unknown_service"); + }); } @Test diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelPackageBoundaryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelPackageBoundaryTest.java index dec71f24aef..3f2476f2ed1 100644 --- a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelPackageBoundaryTest.java +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelPackageBoundaryTest.java @@ -49,21 +49,20 @@ void experimentalTypesAreExactlyTheInternalPackage() throws IOException { .isNotEmpty(); assertThat(generated) - .allSatisfy( - clazz -> { - boolean inInternal = clazz.getPackage().getName().equals(INTERNAL_PACKAGE); - boolean experimental = clazz.getSimpleName().startsWith(EXPERIMENTAL_PREFIX); - // Internal utility classes are exempt from the Experimental prefix requirement. - boolean isInfrastructure = - clazz.getSimpleName().endsWith("Accessor") - || clazz.getSimpleName().equals("ModelMapper") - || clazz.getSimpleName().equals("ExtensionPropertyUtil"); - assertThat(experimental || isInfrastructure) - .as( - "%s: experimental types (name starts with %s) and internal infrastructure " - + "classes must live in %s, all other types in %s", - clazz.getName(), EXPERIMENTAL_PREFIX, INTERNAL_PACKAGE, MODEL_PACKAGE) - .isEqualTo(inInternal); - }); + .allSatisfy(clazz -> { + boolean inInternal = clazz.getPackage().getName().equals(INTERNAL_PACKAGE); + boolean experimental = clazz.getSimpleName().startsWith(EXPERIMENTAL_PREFIX); + // Internal utility classes are exempt from the Experimental prefix requirement. + boolean isInfrastructure = + clazz.getSimpleName().endsWith("Accessor") + || clazz.getSimpleName().equals("ModelMapper") + || clazz.getSimpleName().equals("ExtensionPropertyUtil"); + assertThat(experimental || isInfrastructure) + .as( + "%s: experimental types (name starts with %s) and internal infrastructure " + + "classes must live in %s, all other types in %s", + clazz.getName(), EXPERIMENTAL_PREFIX, INTERNAL_PACKAGE, MODEL_PACKAGE) + .isEqualTo(inInternal); + }); } } diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java index 9adcba424da..e76d469a8ff 100644 --- a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java @@ -37,9 +37,8 @@ public final class LeakDetectingSpanProcessor implements SpanProcessor { * garbage collected. */ public static LeakDetectingSpanProcessor create() { - return new LeakDetectingSpanProcessor( - (message, throwable) -> - logger.log(Level.WARNING, "Span garbage collected before being ended.", throwable)); + return new LeakDetectingSpanProcessor((message, throwable) -> + logger.log(Level.WARNING, "Span garbage collected before being ended.", throwable)); } // Visible for testing diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridgeTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridgeTest.java index ee313d08958..4dde80170e5 100644 --- a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridgeTest.java +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridgeTest.java @@ -90,19 +90,17 @@ void withRecordingSpan_bridgesEventWithAttributes() { } assertThat(spanExporter.getFinishedSpanItems()) - .satisfiesExactly( - spanData -> - assertThat(spanData) - .hasName("span") - .hasEventsSatisfyingExactly( - spanEvent -> - spanEvent - .hasName("my.event-name") - .hasTimestamp(100, TimeUnit.NANOSECONDS) - .hasAttributes( - Attributes.of( - stringKey("color"), "red", - stringKey("shape"), "square")))); + .satisfiesExactly(spanData -> + assertThat(spanData) + .hasName("span") + .hasEventsSatisfyingExactly(spanEvent -> + spanEvent + .hasName("my.event-name") + .hasTimestamp(100, TimeUnit.NANOSECONDS) + .hasAttributes( + Attributes.of( + stringKey("color"), "red", + stringKey("shape"), "square")))); } @Test @@ -119,16 +117,15 @@ void timestamp_fallsBackToObservedTimestamp() { } assertThat(spanExporter.getFinishedSpanItems()) - .satisfiesExactly( - spanData -> - assertThat(spanData) - .hasName("span") - .hasEventsSatisfyingExactly( - // observedTimestamp is 1ms = 1_000_000 ns - spanEvent -> - spanEvent - .hasName("my.event-name") - .hasTimestamp(1_000_000, TimeUnit.NANOSECONDS))); + .satisfiesExactly(spanData -> + assertThat(spanData) + .hasName("span") + .hasEventsSatisfyingExactly( + // observedTimestamp is 1ms = 1_000_000 ns + spanEvent -> + spanEvent + .hasName("my.event-name") + .hasTimestamp(1_000_000, TimeUnit.NANOSECONDS))); } @Test @@ -197,11 +194,10 @@ void noEventName_doesNotBridgeEvent() { } assertThat(spanExporter.getFinishedSpanItems()) - .satisfiesExactly( - spanData -> - assertThat(spanData) - .hasName("span") - .hasEventsSatisfying(events -> assertThat(events).isEmpty())); + .satisfiesExactly(spanData -> + assertThat(spanData) + .hasName("span") + .hasEventsSatisfying(events -> assertThat(events).isEmpty())); } @Test diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java index 27ef612e2a3..fc340ba5240 100644 --- a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java @@ -41,18 +41,16 @@ void garbageCollectedUnendedSpan() { await() .atMost(Duration.ofSeconds(30)) - .untilAsserted( - () -> { - System.gc(); - assertThat(logs) - .singleElement() - .satisfies( - callerStackTrace -> - assertThat(callerStackTrace.getMessage()) - .matches( - "Span garbage collected before being ended\\. " - + "Thread: \\[.*\\] started span : .*")); - }); + .untilAsserted(() -> { + System.gc(); + assertThat(logs) + .singleElement() + .satisfies(callerStackTrace -> + assertThat(callerStackTrace.getMessage()) + .matches( + "Span garbage collected before being ended\\. " + + "Thread: \\[.*\\] started span : .*")); + }); } @Test diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessorTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessorTest.java index 245486ec9e2..9b4dd4feae0 100644 --- a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessorTest.java +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessorTest.java @@ -24,11 +24,10 @@ void startOnly() { ReadWriteSpan inputSpan = mock(ReadWriteSpan.class); SpanProcessor processor = - OnStartSpanProcessor.create( - (ctx, span) -> { - seenContext.set(ctx); - seenSpan.set(span); - }); + OnStartSpanProcessor.create((ctx, span) -> { + seenContext.set(ctx); + seenSpan.set(span); + }); assertThat(processor.isStartRequired()).isTrue(); assertThat(processor.isEndRequired()).isFalse(); diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java index 8fcceac649f..15ed44e3c76 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java @@ -91,11 +91,10 @@ void remoteSampling_defaultStrategy() { .build()) { await() .atMost(Duration.ofSeconds(10)) - .untilAsserted( - () -> - assertThat(remoteSampler.getDescription()) - .contains("TraceIdRatioBased") - .contains("0.8")); + .untilAsserted(() -> + assertThat(remoteSampler.getDescription()) + .contains("TraceIdRatioBased") + .contains("0.8")); } } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java index c5e033a3904..edf14a7d9a6 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java @@ -44,25 +44,22 @@ void serviceProvider() { Sampler sampler = Sampler.parentBased(Sampler.traceIdRatioBased(samplingRate)); assertThat(samplerProviders) .singleElement(type(JaegerRemoteSamplerProvider.class)) - .satisfies( - provider -> { - try (JaegerRemoteSampler s = - (JaegerRemoteSampler) provider.createSampler(mockConfig)) { - assertThat(s) - .extracting("sampler", type(Sampler.class)) - .asString() - .isEqualTo(sampler.toString()); - assertThat(s).extracting("serviceName").isEqualTo("test_service"); - assertThat(s) - .extracting("grpcSender") - .extracting("url") - .satisfies( - url -> - assertThat(url.toString()) - .isEqualTo( - "http://localhost:9999/jaeger.api_v2.SamplingManager/GetSamplingStrategy")); - } - }); + .satisfies(provider -> { + try (JaegerRemoteSampler s = (JaegerRemoteSampler) provider.createSampler(mockConfig)) { + assertThat(s) + .extracting("sampler", type(Sampler.class)) + .asString() + .isEqualTo(sampler.toString()); + assertThat(s).extracting("serviceName").isEqualTo("test_service"); + assertThat(s) + .extracting("grpcSender") + .extracting("url") + .satisfies(url -> + assertThat(url.toString()) + .isEqualTo( + "http://localhost:9999/jaeger.api_v2.SamplingManager/GetSamplingStrategy")); + } + }); } @Test @@ -77,12 +74,10 @@ void serviceNameInAttributeProperties() { ServiceLoader.load(ConfigurableSamplerProvider.class); assertThat(samplerProviders) .singleElement(type(JaegerRemoteSamplerProvider.class)) - .satisfies( - provider -> { - try (JaegerRemoteSampler s = - (JaegerRemoteSampler) provider.createSampler(mockConfig)) { - assertThat(s).extracting("serviceName").isEqualTo("test_service2"); - } - }); + .satisfies(provider -> { + try (JaegerRemoteSampler s = (JaegerRemoteSampler) provider.createSampler(mockConfig)) { + assertThat(s).extracting("serviceName").isEqualTo("test_service2"); + } + }); } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java index 5b42ca9f0d8..3efcffe2901 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java @@ -130,11 +130,10 @@ public void getSamplingStrategy( sb.http(0); sb.https(0); sb.tls(TlsKeyPair.of(certificate.privateKey(), certificate.certificate())); - sb.tlsCustomizer( - ssl -> { - ssl.clientAuth(ClientAuth.OPTIONAL); - ssl.trustManager(clientCertificate.certificate()); - }); + sb.tlsCustomizer(ssl -> { + ssl.clientAuth(ClientAuth.OPTIONAL); + ssl.trustManager(clientCertificate.certificate()); + }); } }; @@ -398,13 +397,12 @@ void perOperationSampling() { assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); await() - .untilAsserted( - () -> { - assertThat(sampler.getDescription()) - .startsWith( - "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); - assertThat(sampler.getDescription()).contains("bar"); - }); + .untilAsserted(() -> { + assertThat(sampler.getDescription()) + .startsWith( + "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); + assertThat(sampler.getDescription()).contains("bar"); + }); } } @@ -441,11 +439,10 @@ void perOperationSampling_zeroRateLimiting() { assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); await() - .untilAsserted( - () -> - assertThat(sampler.getDescription()) - .startsWith( - "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}}}")); + .untilAsserted(() -> + assertThat(sampler.getDescription()) + .startsWith( + "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}}}")); } } @@ -465,12 +462,11 @@ void internal_error_server_response() { .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = - logs.assertContains(" Server responded with gRPC status code INTERNAL"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - }); + .untilAsserted(() -> { + LoggingEvent log = + logs.assertContains(" Server responded with gRPC status code INTERNAL"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + }); } } @@ -490,11 +486,10 @@ void unavailable_error_server_response() { .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } @@ -514,11 +509,10 @@ void unimplemented_error_server_response() { .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } @@ -533,19 +527,16 @@ void builder_ValidConfig() { assertThatCode(() -> JaegerRemoteSampler.builder().setEndpoint("http://foo:bar@localhost")) .doesNotThrowAnyException(); - assertThatCode( - () -> - JaegerRemoteSampler.builder() - .setTrustedCertificates( - Files.readAllBytes(certificate.certificateFile().toPath()))) + assertThatCode(() -> + JaegerRemoteSampler.builder() + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath()))) .doesNotThrowAnyException(); - assertThatCode( - () -> - JaegerRemoteSampler.builder() - .setClientTls( - Files.readAllBytes(clientCertificate.privateKeyFile().toPath()), - Files.readAllBytes(clientCertificate.certificateFile().toPath()))) + assertThatCode(() -> + JaegerRemoteSampler.builder() + .setClientTls( + Files.readAllBytes(clientCertificate.privateKeyFile().toPath()), + Files.readAllBytes(clientCertificate.certificateFile().toPath()))) .doesNotThrowAnyException(); } diff --git a/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java b/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java index 7ef47608f9f..2371c41fb7a 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java @@ -112,21 +112,20 @@ public void before() { private ManagedChannel managedChannel() { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.httpUri().getAuthority()).usePlaintext().build(); - cleanup.addCloseable( - () -> { - // Graceful shutdown ensures the server has processed all in-flight requests before - // the next test starts, preventing stale requests from consuming errors added to the - // queue by a subsequent test. - channel.shutdown(); - try { - if (!channel.awaitTermination(10, TimeUnit.SECONDS)) { - channel.shutdownNow(); - } - } catch (InterruptedException e) { - channel.shutdownNow(); - Thread.currentThread().interrupt(); - } - }); + cleanup.addCloseable(() -> { + // Graceful shutdown ensures the server has processed all in-flight requests before + // the next test starts, preventing stale requests from consuming errors added to the + // queue by a subsequent test. + channel.shutdown(); + try { + if (!channel.awaitTermination(10, TimeUnit.SECONDS)) { + channel.shutdownNow(); + } + } catch (InterruptedException e) { + channel.shutdownNow(); + Thread.currentThread().interrupt(); + } + }); return channel; } @@ -274,13 +273,12 @@ void perOperationSampling() { assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); await() - .untilAsserted( - () -> { - assertThat(sampler.getDescription()) - .startsWith( - "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); - assertThat(sampler.getDescription()).contains("bar"); - }); + .untilAsserted(() -> { + assertThat(sampler.getDescription()) + .startsWith( + "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); + assertThat(sampler.getDescription()).contains("bar"); + }); } } @@ -301,12 +299,11 @@ void internal_error_server_response() { .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = - logs.assertContains(" Server responded with gRPC status code INTERNAL"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - }); + .untilAsserted(() -> { + LoggingEvent log = + logs.assertContains(" Server responded with gRPC status code INTERNAL"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + }); } } @@ -327,11 +324,10 @@ void unavailable_error_server_response() { .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } @@ -352,11 +348,10 @@ void unimplemented_error_server_response() { .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } diff --git a/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java b/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java index e934ebe2802..8186aebdb13 100644 --- a/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java +++ b/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java @@ -375,9 +375,8 @@ void shutdown() { assertThat(logCapturer.getEvents()) .hasSize(2) - .allSatisfy( - loggingEvent -> - assertThat(loggingEvent.getMessage()).isEqualTo("Multiple shutdown calls")); + .allSatisfy(loggingEvent -> + assertThat(loggingEvent.getMessage()).isEqualTo("Multiple shutdown calls")); } @Test diff --git a/sdk/all/src/test/java/io/opentelemetry/sdk/ScopeConfiguratorTest.java b/sdk/all/src/test/java/io/opentelemetry/sdk/ScopeConfiguratorTest.java index fab55c723b9..39d4a6395bc 100644 --- a/sdk/all/src/test/java/io/opentelemetry/sdk/ScopeConfiguratorTest.java +++ b/sdk/all/src/test/java/io/opentelemetry/sdk/ScopeConfiguratorTest.java @@ -82,35 +82,31 @@ void disableScopeB() { // Collect all the telemetry. Ensure we don't see any from scopeB, and that the telemetry from // scopeA and scopeC is valid. assertThat(spanExporter.getFinishedSpanItems()) - .satisfies( - spans -> { - Map> spansByScope = - spans.stream() - .collect(Collectors.groupingBy(SpanData::getInstrumentationScopeInfo)); - assertThat(spansByScope.get(scopeA)).hasSize(1); - assertThat(spansByScope.get(scopeB)).isNull(); - assertThat(spansByScope.get(scopeC)).hasSize(1); - }); + .satisfies(spans -> { + Map> spansByScope = + spans.stream().collect(Collectors.groupingBy(SpanData::getInstrumentationScopeInfo)); + assertThat(spansByScope.get(scopeA)).hasSize(1); + assertThat(spansByScope.get(scopeB)).isNull(); + assertThat(spansByScope.get(scopeC)).hasSize(1); + }); assertThat(metricReader.collectAllMetrics()) - .satisfies( - metrics -> { - Map> metricsByScope = - metrics.stream() - .collect(Collectors.groupingBy(MetricData::getInstrumentationScopeInfo)); - assertThat(metricsByScope.get(scopeA)).hasSize(1); - assertThat(metricsByScope.get(scopeB)).isNull(); - assertThat(metricsByScope.get(scopeC)).hasSize(1); - }); + .satisfies(metrics -> { + Map> metricsByScope = + metrics.stream() + .collect(Collectors.groupingBy(MetricData::getInstrumentationScopeInfo)); + assertThat(metricsByScope.get(scopeA)).hasSize(1); + assertThat(metricsByScope.get(scopeB)).isNull(); + assertThat(metricsByScope.get(scopeC)).hasSize(1); + }); assertThat(logRecordExporter.getFinishedLogRecordItems()) - .satisfies( - logs -> { - Map> logsByScope = - logs.stream() - .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); - assertThat(logsByScope.get(scopeA)).hasSize(1); - assertThat(logsByScope.get(scopeB)).isNull(); - assertThat(logsByScope.get(scopeC)).hasSize(1); - }); + .satisfies(logs -> { + Map> logsByScope = + logs.stream() + .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); + assertThat(logsByScope.get(scopeA)).hasSize(1); + assertThat(logsByScope.get(scopeB)).isNull(); + assertThat(logsByScope.get(scopeC)).hasSize(1); + }); } /** Disable all scopes by default and enable a single scope. */ @@ -157,35 +153,31 @@ void disableAllScopesExceptB() { // Collect all the telemetry. Ensure we only see telemetry from scopeB, since other scopes have // been disabled by default. assertThat(spanExporter.getFinishedSpanItems()) - .satisfies( - spans -> { - Map> spansByScope = - spans.stream() - .collect(Collectors.groupingBy(SpanData::getInstrumentationScopeInfo)); - assertThat(spansByScope.get(scopeA)).isNull(); - assertThat(spansByScope.get(scopeB)).hasSize(1); - assertThat(spansByScope.get(scopeC)).isNull(); - }); + .satisfies(spans -> { + Map> spansByScope = + spans.stream().collect(Collectors.groupingBy(SpanData::getInstrumentationScopeInfo)); + assertThat(spansByScope.get(scopeA)).isNull(); + assertThat(spansByScope.get(scopeB)).hasSize(1); + assertThat(spansByScope.get(scopeC)).isNull(); + }); assertThat(metricReader.collectAllMetrics()) - .satisfies( - metrics -> { - Map> metricsByScope = - metrics.stream() - .collect(Collectors.groupingBy(MetricData::getInstrumentationScopeInfo)); - assertThat(metricsByScope.get(scopeA)).isNull(); - assertThat(metricsByScope.get(scopeB)).hasSize(1); - assertThat(metricsByScope.get(scopeC)).isNull(); - }); + .satisfies(metrics -> { + Map> metricsByScope = + metrics.stream() + .collect(Collectors.groupingBy(MetricData::getInstrumentationScopeInfo)); + assertThat(metricsByScope.get(scopeA)).isNull(); + assertThat(metricsByScope.get(scopeB)).hasSize(1); + assertThat(metricsByScope.get(scopeC)).isNull(); + }); assertThat(logRecordExporter.getFinishedLogRecordItems()) - .satisfies( - logs -> { - Map> logsByScope = - logs.stream() - .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); - assertThat(logsByScope.get(scopeA)).isNull(); - assertThat(logsByScope.get(scopeB)).hasSize(1); - assertThat(logsByScope.get(scopeC)).isNull(); - }); + .satisfies(logs -> { + Map> logsByScope = + logs.stream() + .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); + assertThat(logsByScope.get(scopeA)).isNull(); + assertThat(logsByScope.get(scopeB)).hasSize(1); + assertThat(logsByScope.get(scopeC)).isNull(); + }); } /** diff --git a/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/StacktraceRenderBenchmark.java b/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/StacktraceRenderBenchmark.java index e7bd41c08d8..0421592df51 100644 --- a/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/StacktraceRenderBenchmark.java +++ b/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/StacktraceRenderBenchmark.java @@ -56,15 +56,14 @@ public static class BenchmarkState { @SuppressWarnings("ImmutableEnumChecker") public enum Renderer { - JDK( - (throwable, limit) -> { - StringWriter stringWriter = new StringWriter(); - try (PrintWriter printWriter = new PrintWriter(stringWriter)) { - throwable.printStackTrace(printWriter); - } - String stacktrace = stringWriter.toString(); - return stacktrace.substring(0, Math.min(stacktrace.length(), limit)); - }), + JDK((throwable, limit) -> { + StringWriter stringWriter = new StringWriter(); + try (PrintWriter printWriter = new PrintWriter(stringWriter)) { + throwable.printStackTrace(printWriter); + } + String stacktrace = stringWriter.toString(); + return stacktrace.substring(0, Math.min(stacktrace.length(), limit)); + }), CUSTOM((throwable, limit) -> new StackTraceRenderer(throwable, limit).render()); private final BiFunction renderer; diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java index ff949081e30..f53cbf95d38 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java @@ -65,23 +65,22 @@ public static CompletableResultCode ofAll(Collection code AtomicBoolean failed = new AtomicBoolean(); AtomicReference throwableRef = new AtomicReference<>(); for (CompletableResultCode code : codes) { - code.whenComplete( - () -> { - if (!code.isSuccess()) { - failed.set(true); - Throwable codeThrowable = code.getFailureThrowable(); - if (codeThrowable != null) { - throwableRef.compareAndSet(null, codeThrowable); - } - } - if (pending.decrementAndGet() == 0) { - if (failed.get()) { - result.failInternal(throwableRef.get()); - } else { - result.succeed(); - } - } - }); + code.whenComplete(() -> { + if (!code.isSuccess()) { + failed.set(true); + Throwable codeThrowable = code.getFailureThrowable(); + if (codeThrowable != null) { + throwableRef.compareAndSet(null, codeThrowable); + } + } + if (pending.decrementAndGet() == 0) { + if (failed.get()) { + result.failInternal(throwableRef.get()); + } else { + result.succeed(); + } + } + }); } return result; } diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java index 1552c399299..aed76474408 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java @@ -136,26 +136,24 @@ static Resource create( putEntityAttributes(entity.getId(), entityKeys, fullAttributes); putEntityAttributes(entity.getDescription(), entityKeys, fullAttributes); } - attributes.forEach( - (key, value) -> { - if (entityKeys.contains(key.getKey())) { - throw new IllegalArgumentException( - "Unassociated attributes must not overlap entity attributes."); - } - }); + attributes.forEach((key, value) -> { + if (entityKeys.contains(key.getKey())) { + throw new IllegalArgumentException( + "Unassociated attributes must not overlap entity attributes."); + } + }); fullAttributes.putAll(attributes); return new AutoValue_Resource(schemaUrl, immutableEntities, fullAttributes.build()); } private static void putEntityAttributes( Attributes attributes, Set entityKeys, AttributesBuilder fullAttributes) { - attributes.forEach( - (key, value) -> { - if (!entityKeys.add(key.getKey())) { - throw new IllegalArgumentException( - "Entity attribute keys must have a single owner and classification."); - } - }); + attributes.forEach((key, value) -> { + if (!entityKeys.add(key.getKey())) { + throw new IllegalArgumentException( + "Entity attribute keys must have a single owner and classification."); + } + }); fullAttributes.putAll(attributes); } diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java index 694d5cc92a3..e073bf7c29a 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java @@ -419,10 +419,9 @@ private void removeEntityAssociations() { private static boolean hasAttributeOverride(Attributes current, Attributes incoming) { // Map lookup compares attribute types without valueKey's type coercion. return incoming.asMap().entrySet().stream() - .anyMatch( - entry -> - EntityUtil.hasAttributeKey(current, entry.getKey().getKey()) - && !Objects.equals(current.asMap().get(entry.getKey()), entry.getValue())); + .anyMatch(entry -> + EntityUtil.hasAttributeKey(current, entry.getKey().getKey()) + && !Objects.equals(current.asMap().get(entry.getKey()), entry.getValue())); } /** Returns the schema URL shared by all entities that declare one, or null if they differ. */ diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/AttributeCheckUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/AttributeCheckUtil.java index 21ce643f9a2..941828539d3 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/AttributeCheckUtil.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/AttributeCheckUtil.java @@ -31,13 +31,12 @@ private AttributeCheckUtil() {} /** Determine if the set of attributes if valid for Resource / Entity. */ public static void checkAttributes(Attributes attributes) { - attributes.forEach( - (key, value) -> { - if (!isValidAndNotEmpty(key)) { - throw new IllegalArgumentException("Attribute key" + ERROR_MESSAGE_INVALID_CHARS); - } - Objects.requireNonNull(value, "Attribute value" + ERROR_MESSAGE_INVALID_VALUE); - }); + attributes.forEach((key, value) -> { + if (!isValidAndNotEmpty(key)) { + throw new IllegalArgumentException("Attribute key" + ERROR_MESSAGE_INVALID_CHARS); + } + Objects.requireNonNull(value, "Attribute value" + ERROR_MESSAGE_INVALID_VALUE); + }); } /** diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java index 30117873bf4..9f83d6d082e 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java @@ -25,31 +25,28 @@ class CompletableResultCodeTest { @Test void ofSuccess() { assertThat(CompletableResultCode.ofSuccess()) - .satisfies( - code -> { - assertThat(code.isSuccess()).isTrue(); - assertThat(code.getFailureThrowable()).isNull(); - }); + .satisfies(code -> { + assertThat(code.isSuccess()).isTrue(); + assertThat(code.getFailureThrowable()).isNull(); + }); } @Test void ofFailure() { assertThat(CompletableResultCode.ofFailure()) - .satisfies( - code -> { - assertThat(code.isSuccess()).isFalse(); - assertThat(code.getFailureThrowable()).isNull(); - }); + .satisfies(code -> { + assertThat(code.isSuccess()).isFalse(); + assertThat(code.getFailureThrowable()).isNull(); + }); } @Test void ofExceptionalFailure() { assertThat(CompletableResultCode.ofExceptionalFailure(new Exception("error"))) - .satisfies( - code -> { - assertThat(code.isSuccess()).isFalse(); - assertThat(code.getFailureThrowable()).hasMessage("error"); - }); + .satisfies(code -> { + assertThat(code.isSuccess()).isFalse(); + assertThat(code.getFailureThrowable()).hasMessage("error"); + }); } @Test @@ -114,12 +111,11 @@ void whenDoublyNestedComplete() throws InterruptedException { new Thread(resultCode::succeed).start(); - resultCode.whenComplete( - () -> { - completions.countDown(); + resultCode.whenComplete(() -> { + completions.countDown(); - resultCode.whenComplete(completions::countDown); - }); + resultCode.whenComplete(completions::countDown); + }); completions.await(3, TimeUnit.SECONDS); @@ -191,12 +187,11 @@ void ofAllWithExceptionalFailure() { CompletableResultCode.ofExceptionalFailure(new Exception("error1")), CompletableResultCode.ofExceptionalFailure(new Exception("error2")), CompletableResultCode.ofSuccess()))) - .satisfies( - code -> { - assertThat(code.isSuccess()).isFalse(); - // failure throwable is set to first throwable seen in the collection - assertThat(code.getFailureThrowable()).hasMessage("error1"); - }); + .satisfies(code -> { + assertThat(code.isSuccess()).isFalse(); + // failure throwable is set to first throwable seen in the collection + assertThat(code.getFailureThrowable()).hasMessage("error1"); + }); } @Test @@ -225,11 +220,10 @@ void joinInterrupted() { CompletableResultCode result = new CompletableResultCode(); AtomicReference interrupted = new AtomicReference<>(); Thread thread = - new Thread( - () -> { - result.join(10, TimeUnit.SECONDS); - interrupted.set(Thread.currentThread().isInterrupted()); - }); + new Thread(() -> { + result.join(10, TimeUnit.SECONDS); + interrupted.set(Thread.currentThread().isInterrupted()); + }); thread.start(); thread.interrupt(); // Different thread so wait a bit for result to be propagated. @@ -245,19 +239,17 @@ void callbackCompletionAnotherResultDoesNotDeadlock() throws InterruptedExceptio CountDownLatch callbackEntered = new CountDownLatch(2); CountDownLatch release = new CountDownLatch(1); - first.whenComplete( - () -> { - callbackEntered.countDown(); - Uninterruptibles.awaitUninterruptibly(release); - second.succeed(); - }); + first.whenComplete(() -> { + callbackEntered.countDown(); + Uninterruptibles.awaitUninterruptibly(release); + second.succeed(); + }); - second.whenComplete( - () -> { - callbackEntered.countDown(); - Uninterruptibles.awaitUninterruptibly(release); - first.succeed(); - }); + second.whenComplete(() -> { + callbackEntered.countDown(); + Uninterruptibles.awaitUninterruptibly(release); + first.succeed(); + }); Thread firstThread = new Thread(first::succeed, "complete-first"); Thread secondThread = new Thread(second::succeed, "complete-second"); @@ -284,10 +276,9 @@ void completionActionExceptionDoesNotAbortLaterActions() { CompletableResultCode result = new CompletableResultCode(); AtomicBoolean actionInvoked = new AtomicBoolean(); - result.whenComplete( - () -> { - throw new RuntimeException("callback failure"); - }); + result.whenComplete(() -> { + throw new RuntimeException("callback failure"); + }); result.whenComplete(() -> actionInvoked.set(true)); assertThatThrownBy(result::succeed) .isInstanceOf(RuntimeException.class) @@ -304,10 +295,9 @@ void completionActionExceptionDoesNotPreventOfAllCompletion() { CompletableResultCode other = new CompletableResultCode(); // Registered before ofAll so that it runs before ofAll's bookkeeping action. - source.whenComplete( - () -> { - throw new RuntimeException("callback failure"); - }); + source.whenComplete(() -> { + throw new RuntimeException("callback failure"); + }); CompletableResultCode all = CompletableResultCode.ofAll(Arrays.asList(source, other)); other.succeed(); @@ -324,12 +314,10 @@ void completionActionExceptionDoesNotPreventOfAllCompletion() { void completionActionExceptionPropagatesWhenAlreadyComplete() { CompletableResultCode result = new CompletableResultCode().succeed(); - assertThatThrownBy( - () -> - result.whenComplete( - () -> { - throw new RuntimeException("callback failure"); - })) + assertThatThrownBy(() -> + result.whenComplete(() -> { + throw new RuntimeException("callback failure"); + })) .isInstanceOf(RuntimeException.class) .hasMessage("callback failure"); } diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentRegistryTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentRegistryTest.java index de85e92e069..f7cb137e028 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentRegistryTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentRegistryTest.java @@ -72,14 +72,13 @@ void getComponents_HighConcurrency() throws ExecutionException, InterruptedExcep try { for (int i = 0; i < 100; i++) { futures.add( - executor.submit( - () -> { - String name = - IntStream.range(0, 20) - .mapToObj(unused -> String.valueOf((char) random.nextInt(26))) - .collect(joining()); - registry.get(name, null, null, Attributes.empty()); - })); + executor.submit(() -> { + String name = + IntStream.range(0, 20) + .mapToObj(unused -> String.valueOf((char) random.nextInt(26))) + .collect(joining()); + registry.get(name, null, null, Attributes.empty()); + })); futures.add( executor.submit(() -> registry.getComponents().forEach(TestComponent::hashCode))); } diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicateTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicateTest.java index 0d4e0376501..0585845214c 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicateTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicateTest.java @@ -159,19 +159,18 @@ void emptyOrNullShouldIncludeAll() { private static void shouldIncludeAll( @Nullable Collection included, @Nullable Collection excluded) { Arrays.asList("foo", "fooo", "fOo", "FOO", "bar", "bAr", "barr", "bArr", "baz") - .forEach( - s -> { - Predicate exactMatching = - IncludeExcludePredicate.createExactMatching(included, excluded); - assertThat(exactMatching.test(s)).isTrue(); - assertThat(exactMatching.toString()) - .isEqualTo("IncludeExcludePredicate{globMatchingEnabled=false}"); - Predicate patternMatching = - IncludeExcludePredicate.createPatternMatching(included, excluded); - assertThat(patternMatching.test(s)).isTrue(); - assertThat(patternMatching.toString()) - .isEqualTo("IncludeExcludePredicate{globMatchingEnabled=true}"); - }); + .forEach(s -> { + Predicate exactMatching = + IncludeExcludePredicate.createExactMatching(included, excluded); + assertThat(exactMatching.test(s)).isTrue(); + assertThat(exactMatching.toString()) + .isEqualTo("IncludeExcludePredicate{globMatchingEnabled=false}"); + Predicate patternMatching = + IncludeExcludePredicate.createPatternMatching(included, excluded); + assertThat(patternMatching.test(s)).isTrue(); + assertThat(patternMatching.toString()) + .isEqualTo("IncludeExcludePredicate{globMatchingEnabled=true}"); + }); } @Test diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/RateLimiterTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/RateLimiterTest.java index d135ab3b8cb..ba0bcee3e37 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/RateLimiterTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/RateLimiterTest.java @@ -161,14 +161,13 @@ void testRateLimiterConcurrency() throws InterruptedException, ExecutionExceptio List> futures = new ArrayList<>(numWorkers); for (int w = 0; w < numWorkers; ++w) { Future future = - executorService.submit( - () -> { - for (int i = 0; i < creditsPerWorker * 2; ++i) { - if (limiter.trySpend(1)) { - count.getAndIncrement(); // count allowed operations - } - } - }); + executorService.submit(() -> { + for (int i = 0; i < creditsPerWorker * 2; ++i) { + if (limiter.trySpend(1)) { + count.getAndIncrement(); // count allowed operations + } + } + }); futures.add(future); } for (Future future : futures) { diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java index 97ed3921d93..6bb519ed929 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java @@ -663,11 +663,10 @@ void filterEntityAttributes() { Resource original = Resource.builder().addEntity(host).put("raw", "remove").build(); Resource filtered = original.toBuilder() - .removeIf( - key -> - key.getKey().equals("host.id") - || key.getKey().equals("host.name") - || key.getKey().equals("raw")) + .removeIf(key -> + key.getKey().equals("host.id") + || key.getKey().equals("host.name") + || key.getKey().equals("raw")) .build(); assertThat(filtered.getEntities()).isEmpty(); @@ -725,11 +724,10 @@ void filterDescriptionPreservesAssociation() { assertThat(filtered.getEntities()) .singleElement() - .satisfies( - entity -> { - assertThat(entity.getId()).isEqualTo(host.getId()); - assertThat(entity.getDescription()).isEqualTo(Attributes.empty()); - }); + .satisfies(entity -> { + assertThat(entity.getId()).isEqualTo(host.getId()); + assertThat(entity.getDescription()).isEqualTo(Attributes.empty()); + }); assertThat(filtered.getAttributes()).isEqualTo(host.getId()); assertThat(filtered.getUnassociatedAttributes()).isEqualTo(Attributes.empty()); logs.assertContains( @@ -969,9 +967,8 @@ public void removeIf() { Resource.builder() .put("key1", "value1A") .put("key1", true) - .removeIf( - key -> - key.getKey().equals("key1") && key.getType().equals(AttributeType.STRING)) + .removeIf(key -> + key.getKey().equals("key1") && key.getType().equals(AttributeType.STRING)) .build()) .isEqualTo(Resource.builder().put("key1", true).build()); assertThat( diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/EntityUtilTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/EntityUtilTest.java index 9048e66e462..6e9ccfed38e 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/EntityUtilTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/EntityUtilTest.java @@ -180,17 +180,13 @@ void mergeAbsentSchemaRepresentations( assertThat(EntityUtil.getEntities(merged)) .singleElement() - .satisfies( - entity -> { - assertThat(entity.getId()).isEqualTo(id); - assertThat(entity.getDescription()) - .isEqualTo( - Attributes.builder() - .put("host.arch", "arm64") - .put("host.name", "new") - .build()); - assertThat(entity.getSchemaUrl()).isNull(); - }); + .satisfies(entity -> { + assertThat(entity.getId()).isEqualTo(id); + assertThat(entity.getDescription()) + .isEqualTo( + Attributes.builder().put("host.arch", "arm64").put("host.name", "new").build()); + assertThat(entity.getSchemaUrl()).isNull(); + }); assertThat(merged.getSchemaUrl()).isNull(); logs.assertDoesNotContain("Replacing entity"); } diff --git a/sdk/logs/src/jmh/java/io/opentelemetry/sdk/logs/LogsBenchmarks.java b/sdk/logs/src/jmh/java/io/opentelemetry/sdk/logs/LogsBenchmarks.java index 5d0cfd05f68..5efaa173e82 100644 --- a/sdk/logs/src/jmh/java/io/opentelemetry/sdk/logs/LogsBenchmarks.java +++ b/sdk/logs/src/jmh/java/io/opentelemetry/sdk/logs/LogsBenchmarks.java @@ -39,10 +39,9 @@ public static class BenchmarkState { private final SdkLoggerProvider sdk = SdkLoggerProvider.builder() - .addLogRecordProcessor( - (context, logRecord) -> { - // Do nothing - }) + .addLogRecordProcessor((context, logRecord) -> { + // Do nothing + }) .build(); private List loggerNames; diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProvider.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProvider.java index 099686c8c0a..905127d867d 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProvider.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProvider.java @@ -75,12 +75,9 @@ public static SdkLoggerProviderBuilder builder() { exceptionAttributeResolver, new SdkLoggerInstrumentation(meterProvider)); this.loggerComponentRegistry = - new ComponentRegistry<>( - instrumentationScopeInfo -> - SdkLogger.create( - sharedState, - instrumentationScopeInfo, - getLoggerConfig(instrumentationScopeInfo))); + new ComponentRegistry<>(instrumentationScopeInfo -> + SdkLogger.create( + sharedState, instrumentationScopeInfo, getLoggerConfig(instrumentationScopeInfo))); this.loggerConfigurator = loggerConfigurator; this.isNoopLogRecordProcessor = logRecordProcessor instanceof NoopLogRecordProcessor; } @@ -141,10 +138,8 @@ void setLoggerConfigurator(ScopeConfigurator loggerConfigurator) { this.loggerConfigurator = loggerConfigurator; this.loggerComponentRegistry .getComponents() - .forEach( - sdkLogger -> - sdkLogger.updateLoggerConfig( - getLoggerConfig(sdkLogger.getInstrumentationScopeInfo()))); + .forEach(sdkLogger -> + sdkLogger.updateLoggerConfig(getLoggerConfig(sdkLogger.getInstrumentationScopeInfo()))); } /** diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessor.java index 306ca41f66d..13ce175e6b7 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessor.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessor.java @@ -258,19 +258,17 @@ private CompletableResultCode shutdown() { CompletableResultCode result = new CompletableResultCode(); CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - continueWork = false; - CompletableResultCode shutdownResult = logRecordExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); + flushResult.whenComplete(() -> { + continueWork = false; + CompletableResultCode shutdownResult = logRecordExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); return result; } diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LegacyLogRecordProcessorInstrumentation.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LegacyLogRecordProcessorInstrumentation.java index 33549cadc87..d95d64a15ec 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LegacyLogRecordProcessorInstrumentation.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LegacyLogRecordProcessorInstrumentation.java @@ -67,10 +67,9 @@ public void buildQueueMetricsOnce(long unusedCapacity, LongCallable getSize) { .ofLongs() .setDescription("The number of items queued") .setUnit("1") - .buildWithCallback( - result -> - result.record( - getSize.get(), Attributes.of(PROCESSOR_TYPE_LABEL, PROCESSOR_TYPE_VALUE))); + .buildWithCallback(result -> + result.record( + getSize.get(), Attributes.of(PROCESSOR_TYPE_LABEL, PROCESSOR_TYPE_VALUE))); // No capacity metric when legacy. } diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessor.java index 218018e2afd..7c1b1f8aec6 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessor.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessor.java @@ -103,13 +103,12 @@ public void onEmit(Context context, ReadWriteLogRecord logRecord) { } pendingExports.add(result); - result.whenComplete( - () -> { - pendingExports.remove(result); - if (!result.isSuccess()) { - logger.log(Level.FINE, "Exporter failed"); - } - }); + result.whenComplete(() -> { + pendingExports.remove(result); + if (!result.isSuccess()) { + logger.log(Level.FINE, "Exporter failed"); + } + }); } catch (Throwable t) { ThrowableUtil.propagateIfFatal(t); logger.log(Level.WARNING, "Exporter threw an Exception", t); @@ -124,18 +123,16 @@ public CompletableResultCode shutdown() { CompletableResultCode result = new CompletableResultCode(); CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - CompletableResultCode shutdownResult = logRecordExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); + flushResult.whenComplete(() -> { + CompletableResultCode shutdownResult = logRecordExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); return result; } diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilderTest.java index a89426c5363..42fe8dd3fa9 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilderTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilderTest.java @@ -190,13 +190,10 @@ void setException_UserAttributesTakePrecedence() { .emit(); assertThat(emittedLog.get().toLogRecordData()) - .hasAttributesSatisfying( - attributes -> { - assertThat(attributes.get(stringKey("exception.type"))) - .isEqualTo("java.lang.Exception"); - assertThat(attributes.get(stringKey("exception.message"))) - .isEqualTo("custom message"); - assertThat(attributes.get(stringKey("exception.stacktrace"))).isNotNull(); - }); + .hasAttributesSatisfying(attributes -> { + assertThat(attributes.get(stringKey("exception.type"))).isEqualTo("java.lang.Exception"); + assertThat(attributes.get(stringKey("exception.message"))).isEqualTo("custom message"); + assertThat(attributes.get(stringKey("exception.stacktrace"))).isNotNull(); + }); } } diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderMetricsTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderMetricsTest.java index e20b72a2cde..345e69dbf5c 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderMetricsTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderMetricsTest.java @@ -67,17 +67,15 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.log.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_log_processor/0", - OTEL_COMPONENT_TYPE, - "simple_log_processor"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor"))))); logger.logRecordBuilder().emit(); assertThat(metricReader.collectAllMetrics()) @@ -90,17 +88,15 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.log.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_log_processor/0", - OTEL_COMPONENT_TYPE, - "simple_log_processor"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor"))))); // Logs rejected after the call to shutdown, regardless of completion so no join. processor.shutdown(); @@ -116,27 +112,26 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.log.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_log_processor/0", - OTEL_COMPONENT_TYPE, - "simple_log_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_log_processor/0", - OTEL_COMPONENT_TYPE, - "simple_log_processor", - ERROR_TYPE, - "already_shutdown"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor", + ERROR_TYPE, + "already_shutdown"))))); } @Test @@ -180,55 +175,50 @@ void batch() throws Exception { m -> assertThat(m) .hasName("otel.sdk.processor.log.queue.capacity") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.log.queue.size") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.log.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor", - ERROR_TYPE, - "queue_full")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "queue_full")))), m -> assertThat(m) .hasName("otel.sdk.log.created") @@ -244,55 +234,50 @@ void batch() throws Exception { m -> assertThat(m) .hasName("otel.sdk.processor.log.queue.capacity") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.log.queue.size") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.log.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor", - ERROR_TYPE, - "queue_full")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "queue_full")))), m -> assertThat(m) .hasName("otel.sdk.log.created") @@ -309,65 +294,60 @@ void batch() throws Exception { m -> assertThat(m) .hasName("otel.sdk.processor.log.queue.capacity") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.log.queue.size") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.log.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor", - ERROR_TYPE, - "already_shutdown")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_log_processor/0", - OTEL_COMPONENT_TYPE, - "batching_log_processor", - ERROR_TYPE, - "queue_full")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "already_shutdown")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "queue_full")))), m -> assertThat(m) .hasName("otel.sdk.log.created") @@ -401,17 +381,15 @@ void simpleExportError() { m -> assertThat(m) .hasName("otel.sdk.processor.log.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_log_processor/0", - OTEL_COMPONENT_TYPE, - "simple_log_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor")))), m -> assertThat(m) .hasName("otel.sdk.log.created") diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderTest.java index e887c8ea6f8..c74cac09e59 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderTest.java @@ -136,17 +136,16 @@ void builder_multipleProcessors() { .build()) .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) .extracting(LoggerSharedState::getLogRecordProcessor) - .satisfies( - activeLogRecordProcessor -> { - assertThat(activeLogRecordProcessor).isInstanceOf(MultiLogRecordProcessor.class); - assertThat(activeLogRecordProcessor) - .extracting( - "logRecordProcessors", - as(InstanceOfAssertFactories.list(LogRecordProcessor.class))) - .hasSize(3) - .first() - .isEqualTo(firstProcessor); - }); + .satisfies(activeLogRecordProcessor -> { + assertThat(activeLogRecordProcessor).isInstanceOf(MultiLogRecordProcessor.class); + assertThat(activeLogRecordProcessor) + .extracting( + "logRecordProcessors", + as(InstanceOfAssertFactories.list(LogRecordProcessor.class))) + .hasSize(3) + .first() + .isEqualTo(firstProcessor); + }); } @Test @@ -239,15 +238,14 @@ void loggerBuilder_WithLogRecordProcessor() { sdkLoggerProvider = SdkLoggerProvider.builder() .setResource(resource) - .addLogRecordProcessor( - (unused, logRecord) -> { - logRecord.setAttribute(null, null); - // Overwrite k1 - logRecord.setAttribute(AttributeKey.stringKey("k1"), "new-v1"); - // Add new attribute k3 - logRecord.setAttribute(AttributeKey.stringKey("k3"), "v3"); - logRecordData.set(logRecord.toLogRecordData()); - }) + .addLogRecordProcessor((unused, logRecord) -> { + logRecord.setAttribute(null, null); + // Overwrite k1 + logRecord.setAttribute(AttributeKey.stringKey("k1"), "new-v1"); + // Add new attribute k3 + logRecord.setAttribute(AttributeKey.stringKey("k3"), "v3"); + logRecordData.set(logRecord.toLogRecordData()); + }) .build(); SpanContext spanContext = @@ -289,11 +287,10 @@ void loggerBuilder_ProcessorWithContext() { sdkLoggerProvider = SdkLoggerProvider.builder() - .addLogRecordProcessor( - (context, logRecord) -> - logRecord.setAttribute( - AttributeKey.stringKey("my-context-key"), - Optional.ofNullable(context.get(contextKey)).orElse(""))) + .addLogRecordProcessor((context, logRecord) -> + logRecord.setAttribute( + AttributeKey.stringKey("my-context-key"), + Optional.ofNullable(context.get(contextKey)).orElse(""))) .addLogRecordProcessor( (unused, logRecord) -> logRecordData.set(logRecord.toLogRecordData())) .build(); diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ValueBodyTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ValueBodyTest.java index 5f2ad1bc90c..a1c329ad4d7 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ValueBodyTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ValueBodyTest.java @@ -34,16 +34,14 @@ void valueBody() { logger.logRecordBuilder().setBody(Value.of(1)).emit(); assertThat(exporter.getFinishedLogRecordItems()) .hasSize(1) - .satisfiesExactly( - logRecordData -> { - assertThat(logRecordData.getBodyValue()) - .isNotNull() - .satisfies( - body -> { - assertThat(body.getType()).isEqualTo(ValueType.LONG); - assertThat((Long) body.getValue()).isEqualTo(1L); - }); - }); + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.LONG); + assertThat((Long) body.getValue()).isEqualTo(1L); + }); + }); exporter.reset(); // ...or a byte array of raw data @@ -53,18 +51,15 @@ void valueBody() { .emit(); assertThat(exporter.getFinishedLogRecordItems()) .hasSize(1) - .satisfiesExactly( - logRecordData -> { - assertThat(logRecordData.getBodyValue()) - .isNotNull() - .satisfies( - body -> { - assertThat(body.getType()).isEqualTo(ValueType.BYTES); - assertThat((ByteBuffer) body.getValue()) - .isEqualTo( - ByteBuffer.wrap("hello world".getBytes(StandardCharsets.UTF_8))); - }); - }); + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.BYTES); + assertThat((ByteBuffer) body.getValue()) + .isEqualTo(ByteBuffer.wrap("hello world".getBytes(StandardCharsets.UTF_8))); + }); + }); exporter.reset(); // But most commonly it will be used to represent complex structured like a map @@ -99,50 +94,47 @@ void valueBody() { .emit(); assertThat(exporter.getFinishedLogRecordItems()) .hasSize(1) - .satisfiesExactly( - logRecordData -> { - assertThat(logRecordData.getBodyValue()) - .isNotNull() - // TODO: use fluent asserts when available. See - // https://github.com/open-telemetry/opentelemetry-java/pull/6509 - .satisfies( - body -> { - assertThat(body.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); - assertThat(body) - .isEqualTo( + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + // TODO: use fluent asserts when available. See + // https://github.com/open-telemetry/opentelemetry-java/pull/6509 + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); + assertThat(body) + .isEqualTo( + Value.of( + KeyValue.of("str_key", Value.of("value")), + KeyValue.of("bool_key", Value.of(true)), + KeyValue.of("long_key", Value.of(1L)), + KeyValue.of("double_key", Value.of(1.1)), + KeyValue.of( + "bytes_key", Value.of("bytes".getBytes(StandardCharsets.UTF_8))), + KeyValue.of( + "arr_key", + Value.of(Value.of("entry1"), Value.of(2), Value.of(3.3))), + KeyValue.of( + "key_value_list_key", Value.of( - KeyValue.of("str_key", Value.of("value")), - KeyValue.of("bool_key", Value.of(true)), - KeyValue.of("long_key", Value.of(1L)), - KeyValue.of("double_key", Value.of(1.1)), - KeyValue.of( - "bytes_key", - Value.of("bytes".getBytes(StandardCharsets.UTF_8))), - KeyValue.of( - "arr_key", - Value.of(Value.of("entry1"), Value.of(2), Value.of(3.3))), - KeyValue.of( - "key_value_list_key", - Value.of( - new LinkedHashMap>() { - { - put("child_str_key1", Value.of("child_value1")); - put("child_str_key2", Value.of("child_value2")); - } - })))); - assertThat(body.asString()) - .isEqualTo( - "{" - + "\"str_key\":\"value\"," - + "\"bool_key\":true," - + "\"long_key\":1," - + "\"double_key\":1.1," - + "\"bytes_key\":\"Ynl0ZXM=\"," - + "\"arr_key\":[\"entry1\",2,3.3]," - + "\"key_value_list_key\":{\"child_str_key1\":\"child_value1\",\"child_str_key2\":\"child_value2\"}" - + "}"); - }); - }); + new LinkedHashMap>() { + { + put("child_str_key1", Value.of("child_value1")); + put("child_str_key2", Value.of("child_value2")); + } + })))); + assertThat(body.asString()) + .isEqualTo( + "{" + + "\"str_key\":\"value\"," + + "\"bool_key\":true," + + "\"long_key\":1," + + "\"double_key\":1.1," + + "\"bytes_key\":\"Ynl0ZXM=\"," + + "\"arr_key\":[\"entry1\",2,3.3]," + + "\"key_value_list_key\":{\"child_str_key1\":\"child_value1\",\"child_str_key2\":\"child_value2\"}" + + "}"); + }); + }); exporter.reset(); // ..or an array (optionally with heterogeneous types) @@ -152,18 +144,15 @@ void valueBody() { .emit(); assertThat(exporter.getFinishedLogRecordItems()) .hasSize(1) - .satisfiesExactly( - logRecordData -> { - assertThat(logRecordData.getBodyValue()) - .isNotNull() - .satisfies( - body -> { - assertThat(body.getType()).isEqualTo(ValueType.ARRAY); - assertThat(body) - .isEqualTo( - Value.of(Value.of("entry1"), Value.of("entry2"), Value.of(3))); - }); - }); + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.ARRAY); + assertThat(body) + .isEqualTo(Value.of(Value.of("entry1"), Value.of("entry2"), Value.of(3))); + }); + }); exporter.reset(); } } diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorTest.java index 579d6d2bc02..1b86ba63dee 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorTest.java @@ -87,10 +87,9 @@ void builderDefaults() { @Test void builderInvalidConfig() { - assertThatThrownBy( - () -> - BatchLogRecordProcessor.builder(mockLogRecordExporter) - .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + BatchLogRecordProcessor.builder(mockLogRecordExporter) + .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("delay must be non-negative"); assertThatThrownBy( @@ -101,15 +100,13 @@ void builderInvalidConfig() { () -> BatchLogRecordProcessor.builder(mockLogRecordExporter).setScheduleDelay(null)) .isInstanceOf(NullPointerException.class) .hasMessage("delay"); - assertThatThrownBy( - () -> - BatchLogRecordProcessor.builder(mockLogRecordExporter) - .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + BatchLogRecordProcessor.builder(mockLogRecordExporter) + .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("timeout must be non-negative"); - assertThatThrownBy( - () -> - BatchLogRecordProcessor.builder(mockLogRecordExporter).setExporterTimeout(1, null)) + assertThatThrownBy(() -> + BatchLogRecordProcessor.builder(mockLogRecordExporter).setExporterTimeout(1, null)) .isInstanceOf(NullPointerException.class) .hasMessage("unit"); assertThatThrownBy( @@ -207,11 +204,10 @@ void emitMoreLogsThanBufferSize() { logRecordExporter.succeed(); await() - .untilAsserted( - () -> - assertThat(logRecordExporter.getExported()) - .hasSize(6) - .allSatisfy(logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_1))); + .untilAsserted(() -> + assertThat(logRecordExporter.getExported()) + .hasSize(6) + .allSatisfy(logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_1))); } @Test @@ -423,12 +419,11 @@ public void continuesIfExporterTimesOut() throws InterruptedException { CountDownLatch exported = new CountDownLatch(1); // We return a result we never complete, meaning it will timeout. when(mockLogRecordExporter.export( - argThat( - logs -> { - assertThat(logs).anySatisfy(log -> assertThat(log).hasBody(LOG_MESSAGE_1)); - exported.countDown(); - return true; - }))) + argThat(logs -> { + assertThat(logs).anySatisfy(log -> assertThat(log).hasBody(LOG_MESSAGE_1)); + exported.countDown(); + return true; + }))) .thenReturn(new CompletableResultCode()); emitLog(sdkLoggerProvider, LOG_MESSAGE_1); exported.await(); @@ -440,12 +435,11 @@ public void continuesIfExporterTimesOut() throws InterruptedException { reset(mockLogRecordExporter); when(mockLogRecordExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); when(mockLogRecordExporter.export( - argThat( - logs -> { - assertThat(logs).anySatisfy(log -> assertThat(log).hasBody(LOG_MESSAGE_2)); - exportedAgain.countDown(); - return true; - }))) + argThat(logs -> { + assertThat(logs).anySatisfy(log -> assertThat(log).hasBody(LOG_MESSAGE_2)); + exportedAgain.countDown(); + return true; + }))) .thenReturn(CompletableResultCode.ofSuccess()); emitLog(sdkLoggerProvider, LOG_MESSAGE_2); exported.await(); diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorTest.java index bfbb14ce414..977a7590076 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorTest.java @@ -77,10 +77,9 @@ void onEmit_ExporterError() { @SuppressLogger(SimpleLogRecordProcessor.class) void onEmit_ExporterThrowsCheckedException() { when(logRecordExporter.export(any())) - .thenAnswer( - invocation -> { - throw new Exception("Exporter error!"); - }); + .thenAnswer(invocation -> { + throw new Exception("Exporter error!"); + }); assertThatCode(() -> logRecordProcessor.onEmit(Context.current(), readWriteLogRecord)) .doesNotThrowAnyException(); diff --git a/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ExtendedLoggerBuilderTest.java b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ExtendedLoggerBuilderTest.java index 3c800bf71a9..79885f853b5 100644 --- a/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ExtendedLoggerBuilderTest.java +++ b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ExtendedLoggerBuilderTest.java @@ -32,17 +32,16 @@ void setException_DefaultResolver() { logger.logRecordBuilder().setException(new Exception("error")).emit(); assertThat(exporter.getFinishedLogRecordItems()) - .satisfiesExactly( - logRecord -> - assertThat(logRecord) - .hasAttributesSatisfyingExactly( - equalTo(EXCEPTION_TYPE, "java.lang.Exception"), - equalTo(EXCEPTION_MESSAGE, "error"), - satisfies( - EXCEPTION_STACKTRACE, - stacktrace -> - stacktrace.startsWith( - "java.lang.Exception: error" + System.lineSeparator())))); + .satisfiesExactly(logRecord -> + assertThat(logRecord) + .hasAttributesSatisfyingExactly( + equalTo(EXCEPTION_TYPE, "java.lang.Exception"), + equalTo(EXCEPTION_MESSAGE, "error"), + satisfies( + EXCEPTION_STACKTRACE, + stacktrace -> + stacktrace.startsWith( + "java.lang.Exception: error" + System.lineSeparator())))); } @Test @@ -64,12 +63,10 @@ public void setExceptionAttributes( logger.logRecordBuilder().setException(new Exception("error")).emit(); assertThat(exporter.getFinishedLogRecordItems()) - .satisfiesExactly( - logRecord -> - assertThat(logRecord) - .hasAttributesSatisfyingExactly( - equalTo(EXCEPTION_TYPE, "type"), - equalTo(EXCEPTION_STACKTRACE, "stacktrace"))); + .satisfiesExactly(logRecord -> + assertThat(logRecord) + .hasAttributesSatisfyingExactly( + equalTo(EXCEPTION_TYPE, "type"), equalTo(EXCEPTION_STACKTRACE, "stacktrace"))); } @Test @@ -83,16 +80,15 @@ void setException_UserAttributesTakePrecedence() { .emit(); assertThat(exporter.getFinishedLogRecordItems()) - .satisfiesExactly( - logRecord -> - assertThat(logRecord) - .hasAttributesSatisfyingExactly( - equalTo(EXCEPTION_TYPE, "java.lang.Exception"), - equalTo(EXCEPTION_MESSAGE, "custom message"), - satisfies( - EXCEPTION_STACKTRACE, - stacktrace -> - stacktrace.startsWith( - "java.lang.Exception: error" + System.lineSeparator())))); + .satisfiesExactly(logRecord -> + assertThat(logRecord) + .hasAttributesSatisfyingExactly( + equalTo(EXCEPTION_TYPE, "java.lang.Exception"), + equalTo(EXCEPTION_MESSAGE, "custom message"), + satisfies( + EXCEPTION_STACKTRACE, + stacktrace -> + stacktrace.startsWith( + "java.lang.Exception: error" + System.lineSeparator())))); } } diff --git a/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/LoggerConfigTest.java b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/LoggerConfigTest.java index b0665c29917..b2b24b25efe 100644 --- a/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/LoggerConfigTest.java +++ b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/LoggerConfigTest.java @@ -77,15 +77,14 @@ void disableScopes() { // Only logs from loggerA and loggerC should be seen assertThat(exporter.getFinishedLogRecordItems()) - .satisfies( - metrics -> { - Map> logsByScope = - metrics.stream() - .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); - assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerA"))).hasSize(1); - assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerB"))).isNull(); - assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerC"))).hasSize(1); - }); + .satisfies(metrics -> { + Map> logsByScope = + metrics.stream() + .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); + assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerA"))).hasSize(1); + assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerB"))).isNull(); + assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerC"))).hasSize(1); + }); // loggerA and loggerC are enabled, loggerB is disabled. assertThat(((ExtendedLogger) loggerA).isEnabled(Severity.INFO)).isTrue(); assertThat(((ExtendedLogger) loggerB).isEnabled(Severity.INFO)).isFalse(); diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmarkTest.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmarkTest.java index e06a5941c42..dda107b41ae 100644 --- a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmarkTest.java +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmarkTest.java @@ -91,41 +91,39 @@ public void normalizedAllocationRateTest() throws RunnerException { } } - testInstrumentTypeResultsMap.forEach( - (testInstrumentTypeString, testInstrumentTypeResults) -> { - Map> resultMap = - testInstrumentTypeResults.aggregationTemporalityToMemoryModeResult; - assertThat(resultMap).hasSameSizeAs(AggregationTemporality.values()); - - // Asserts that reusable data GC allocation rate is a tiny fraction of immutable data - // GC allocation rate - resultMap.forEach( - (aggregationTemporality, memoryModeToAllocRateMap) -> { - Double immutableDataAllocRate = - memoryModeToAllocRateMap.get(MemoryMode.IMMUTABLE_DATA.toString()); - Double reusableDataAllocRate = - memoryModeToAllocRateMap.get(MemoryMode.REUSABLE_DATA.toString()); - - assertThat(immutableDataAllocRate).isNotNull().isNotZero(); - assertThat(reusableDataAllocRate).isNotNull().isNotZero(); - - TestInstrumentType testInstrumentType = - TestInstrumentType.valueOf(testInstrumentTypeString); - float dataAllocRateReductionPercentage = - testInstrumentType.getDataAllocRateReductionPercentage(); - double allowedOffset = testInstrumentType.getAllowedPercentOffset(); - - // If this test suddenly fails for you this means you have changed the code in a way - // that allocates more memory than before. You can find out where, by running - // ProfileBenchmark class and looking at the flame graph. Make sure to - // set the parameters according to where it failed for. - assertThat(100 - (reusableDataAllocRate / immutableDataAllocRate) * 100) - .describedAs( - "Aggregation temporality = %s, testInstrumentType = %s", - aggregationTemporality, testInstrumentTypeString) - .isCloseTo(dataAllocRateReductionPercentage, Offset.offset(allowedOffset)); - }); - }); + testInstrumentTypeResultsMap.forEach((testInstrumentTypeString, testInstrumentTypeResults) -> { + Map> resultMap = + testInstrumentTypeResults.aggregationTemporalityToMemoryModeResult; + assertThat(resultMap).hasSameSizeAs(AggregationTemporality.values()); + + // Asserts that reusable data GC allocation rate is a tiny fraction of immutable data + // GC allocation rate + resultMap.forEach((aggregationTemporality, memoryModeToAllocRateMap) -> { + Double immutableDataAllocRate = + memoryModeToAllocRateMap.get(MemoryMode.IMMUTABLE_DATA.toString()); + Double reusableDataAllocRate = + memoryModeToAllocRateMap.get(MemoryMode.REUSABLE_DATA.toString()); + + assertThat(immutableDataAllocRate).isNotNull().isNotZero(); + assertThat(reusableDataAllocRate).isNotNull().isNotZero(); + + TestInstrumentType testInstrumentType = + TestInstrumentType.valueOf(testInstrumentTypeString); + float dataAllocRateReductionPercentage = + testInstrumentType.getDataAllocRateReductionPercentage(); + double allowedOffset = testInstrumentType.getAllowedPercentOffset(); + + // If this test suddenly fails for you this means you have changed the code in a way + // that allocates more memory than before. You can find out where, by running + // ProfileBenchmark class and looking at the flame graph. Make sure to + // set the parameters according to where it failed for. + assertThat(100 - (reusableDataAllocRate / immutableDataAllocRate) * 100) + .describedAs( + "Aggregation temporality = %s, testInstrumentType = %s", + aggregationTemporality, testInstrumentTypeString) + .isCloseTo(dataAllocRateReductionPercentage, Offset.offset(allowedOffset)); + }); + }); } static class TestInstrumentTypeResults { diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/AsyncCounterTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/AsyncCounterTester.java index f926fb343b6..4cc5b1bb4bb 100644 --- a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/AsyncCounterTester.java +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/AsyncCounterTester.java @@ -30,13 +30,12 @@ public TestInstrumentType.TestInstrumentsState buildInstruments( sdkMeterProvider .get("meter") .counterBuilder("counter" + i) - .buildWithCallback( - observableLongMeasurement -> { - for (int j = 0; j < attributesList.size(); j++) { - Attributes attributes = attributesList.get(j); - observableLongMeasurement.record(random.nextInt(10_000), attributes); - } - }); + .buildWithCallback(observableLongMeasurement -> { + for (int j = 0; j < attributesList.size(); j++) { + Attributes attributes = attributesList.get(j); + observableLongMeasurement.record(random.nextInt(10_000), attributes); + } + }); } return new EmptyInstrumentsState(); } diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleLastValueTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleLastValueTester.java index c9144ad2c1a..ad23b9cc826 100644 --- a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleLastValueTester.java +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleLastValueTester.java @@ -30,12 +30,11 @@ public TestInstrumentType.TestInstrumentsState buildInstruments( Meter meter = sdkMeterProvider.meterBuilder("meter").build(); meter .gaugeBuilder("test.double.last.value") - .buildWithCallback( - observableDoubleMeasurement -> { - for (int j = 0; j < attributesList.size(); j++) { - observableDoubleMeasurement.record(1.2f, attributesList.get(j)); - } - }); + .buildWithCallback(observableDoubleMeasurement -> { + for (int j = 0; j < attributesList.size(); j++) { + observableDoubleMeasurement.record(1.2f, attributesList.get(j)); + } + }); return new TestInstrumentType.EmptyInstrumentsState(); } diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongLastValueTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongLastValueTester.java index c766f74e290..0838f7612b3 100644 --- a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongLastValueTester.java +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongLastValueTester.java @@ -31,12 +31,11 @@ public TestInstrumentType.TestInstrumentsState buildInstruments( meter .gaugeBuilder("test.long.last.value") .ofLongs() - .buildWithCallback( - observableLongMeasurement -> { - for (int j = 0; j < attributesList.size(); j++) { - observableLongMeasurement.record(1, attributesList.get(j)); - } - }); + .buildWithCallback(observableLongMeasurement -> { + for (int j = 0; j < attributesList.size(); j++) { + observableLongMeasurement.record(1, attributesList.get(j)); + } + }); return new TestInstrumentType.EmptyInstrumentsState(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java index 3851fbe4ed8..c0a3b1a69ef 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java @@ -78,22 +78,20 @@ public static SdkMeterProviderBuilder builder() { this.registeredViews = registeredViews; this.registeredReaders = metricReaders.entrySet().stream() - .map( - entry -> - RegisteredReader.create( - entry.getKey(), - ViewRegistry.create(entry.getKey(), entry.getValue(), registeredViews))) + .map(entry -> + RegisteredReader.create( + entry.getKey(), + ViewRegistry.create(entry.getKey(), entry.getValue(), registeredViews))) .collect(toList()); this.metricProducers = metricProducers; this.sharedState = MeterProviderSharedState.create(clock, resourceProvider, exemplarFilter); this.registry = - new ComponentRegistry<>( - instrumentationLibraryInfo -> - new SdkMeter( - sharedState, - instrumentationLibraryInfo, - registeredReaders, - getMeterConfig(instrumentationLibraryInfo))); + new ComponentRegistry<>(instrumentationLibraryInfo -> + new SdkMeter( + sharedState, + instrumentationLibraryInfo, + registeredReaders, + getMeterConfig(instrumentationLibraryInfo))); this.meterConfigurator = meterConfigurator; for (RegisteredReader registeredReader : registeredReaders) { List readerMetricProducers = new ArrayList<>(metricProducers); @@ -126,9 +124,8 @@ void setMeterConfigurator(ScopeConfigurator meterConfigurator) { this.meterConfigurator = meterConfigurator; this.registry .getComponents() - .forEach( - sdkMeter -> - sdkMeter.updateMeterConfig(getMeterConfig(sdkMeter.getInstrumentationScopeInfo()))); + .forEach(sdkMeter -> + sdkMeter.updateMeterConfig(getMeterConfig(sdkMeter.getInstrumentationScopeInfo()))); } @Override diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java index 373c54fee5b..eb8668db984 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java @@ -132,18 +132,16 @@ public CompletableResultCode forceFlush() { CompletableResultCode collectExport = new CompletableResultCode(); signals.offer(Signal.flush(collectExport)); CompletableResultCode result = new CompletableResultCode(); - collectExport.whenComplete( - () -> { - CompletableResultCode flushResult = exporter.flush(); - flushResult.whenComplete( - () -> { - if (collectExport.isSuccess() && flushResult.isSuccess()) { - result.succeed(); - } else { - result.fail(); - } - }); - }); + collectExport.whenComplete(() -> { + CompletableResultCode flushResult = exporter.flush(); + flushResult.whenComplete(() -> { + if (collectExport.isSuccess() && flushResult.isSuccess()) { + result.succeed(); + } else { + result.fail(); + } + }); + }); return result; } @@ -181,14 +179,13 @@ public CompletableResultCode shutdown() { CompletableResultCode result = new CompletableResultCode(); CompletableResultCode exporterShutdown = exporter.shutdown(); - exporterShutdown.whenComplete( - () -> { - if (finalFlush.isSuccess() && exporterShutdown.isSuccess()) { - result.succeed(); - } else { - result.fail(); - } - }); + exporterShutdown.whenComplete(() -> { + if (finalFlush.isSuccess() && exporterShutdown.isSuccess()) { + result.succeed(); + } else { + result.fail(); + } + }); return result; } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java index 2aa28cb8ade..1b28be543f1 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java @@ -279,50 +279,48 @@ Collection doCollect(long epochNanos) { long startEpochNanos = registeredReader.getLastCollectEpochNanosOrDefault(instrumentCreationEpochNanos); - aggregatorHandles.forEach( - (attributes, handle) -> { - T point = - handle.aggregateThenMaybeReset( - startEpochNanos, epochNanos, attributes, /* reset= */ true); - - T pointForCurrentPoints; - if (memoryMode == REUSABLE_DATA) { - // AggregatorHandle is going to modify the point eventually, but we must persist its - // value to used it at the next collection (within lastPoints). Thus, we make a copy. - pointForCurrentPoints = reusablePointsPool.borrowObject(); - aggregator.copyPoint(point, pointForCurrentPoints); - } else { - pointForCurrentPoints = point; - } - currentPoints.put(attributes, pointForCurrentPoints); - }); + aggregatorHandles.forEach((attributes, handle) -> { + T point = + handle.aggregateThenMaybeReset( + startEpochNanos, epochNanos, attributes, /* reset= */ true); + + T pointForCurrentPoints; + if (memoryMode == REUSABLE_DATA) { + // AggregatorHandle is going to modify the point eventually, but we must persist its + // value to used it at the next collection (within lastPoints). Thus, we make a copy. + pointForCurrentPoints = reusablePointsPool.borrowObject(); + aggregator.copyPoint(point, pointForCurrentPoints); + } else { + pointForCurrentPoints = point; + } + currentPoints.put(attributes, pointForCurrentPoints); + }); List deltaPoints = memoryMode == REUSABLE_DATA ? reusablePointsList : new ArrayList<>(); - currentPoints.forEach( - (attributes, currentPoint) -> { - T lastPoint = lastPoints.remove(attributes); - - T deltaPoint; - if (lastPoint == null) { - if (memoryMode == REUSABLE_DATA) { - // All deltaPoints are released at the end of the collection. Thus, we need a copy - // to make sure currentPoint can still be used within lastPoints during the next - // collection. - deltaPoint = reusablePointsPool.borrowObject(); - aggregator.copyPoint(currentPoint, deltaPoint); - } else { - deltaPoint = currentPoint; - } - } else { - if (memoryMode == REUSABLE_DATA) { - aggregator.diffInPlace(lastPoint, currentPoint); - deltaPoint = lastPoint; - } else { - deltaPoint = aggregator.diff(lastPoint, currentPoint); - } - } - deltaPoints.add(deltaPoint); - }); + currentPoints.forEach((attributes, currentPoint) -> { + T lastPoint = lastPoints.remove(attributes); + + T deltaPoint; + if (lastPoint == null) { + if (memoryMode == REUSABLE_DATA) { + // All deltaPoints are released at the end of the collection. Thus, we need a copy + // to make sure currentPoint can still be used within lastPoints during the next + // collection. + deltaPoint = reusablePointsPool.borrowObject(); + aggregator.copyPoint(currentPoint, deltaPoint); + } else { + deltaPoint = currentPoint; + } + } else { + if (memoryMode == REUSABLE_DATA) { + aggregator.diffInPlace(lastPoint, currentPoint); + deltaPoint = lastPoint; + } else { + deltaPoint = aggregator.diff(lastPoint, currentPoint); + } + } + deltaPoints.add(deltaPoint); + }); if (memoryMode == REUSABLE_DATA) { // - If the point was used to compute a delta, it's now in deltaPoints (and thus in @@ -394,17 +392,16 @@ Collection doCollect(long epochNanos) { // cycle // - Otherwise, the preceding collection interval's timestamp // This logic is handled in AggregatorHandle creation via #createAggregatorHandle() - aggregatorHandles.forEach( - (attributes, handle) -> { - if (!handle.hasRecordedValues()) { - aggregatorHandles.remove(attributes); - return; - } - T value = - handle.aggregateThenMaybeReset( - handle.getCreationEpochNanos(), epochNanos, attributes, /* reset= */ true); - currentPoints.add(value); - }); + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.hasRecordedValues()) { + aggregatorHandles.remove(attributes); + return; + } + T value = + handle.aggregateThenMaybeReset( + handle.getCreationEpochNanos(), epochNanos, attributes, /* reset= */ true); + currentPoints.add(value); + }); return currentPoints; } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CumulativeSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CumulativeSynchronousMetricStorage.java index 26fe09fac40..8b843633f99 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CumulativeSynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CumulativeSynchronousMetricStorage.java @@ -132,21 +132,20 @@ public MetricData collect( } // Grab aggregated points. - aggregatorHandles.forEach( - (attributes, handle) -> { - if (!handle.hasRecordedValues()) { - return; - } - // Start time for cumulative synchronous instruments is the time the first series - // measurement was recorded. I.e. the time the AggregatorHandle was created. - T point = - handle.aggregateThenMaybeReset( - handle.getCreationEpochNanos(), epochNanos, attributes, /* reset= */ false); - - if (point != null) { - points.add(point); - } - }); + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.hasRecordedValues()) { + return; + } + // Start time for cumulative synchronous instruments is the time the first series + // measurement was recorded. I.e. the time the AggregatorHandle was created. + T point = + handle.aggregateThenMaybeReset( + handle.getCreationEpochNanos(), epochNanos, attributes, /* reset= */ false); + + if (point != null) { + points.add(point); + } + }); if (points.isEmpty() || !enabled) { return EmptyMetricData.getInstance(); diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java index 51edfe0321d..102bad92258 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java @@ -235,12 +235,11 @@ public MetricData collect( (memoryMode == REUSABLE_DATA) ? previousCollectionAggregatorHandles : new ConcurrentHashMap<>(); - holder.aggregatorHandles.forEach( - (attributes, handle) -> { - if (handle.bound) { - newHolderHandles.put(attributes, handle); - } - }); + holder.aggregatorHandles.forEach((attributes, handle) -> { + if (handle.bound) { + newHolderHandles.put(attributes, handle); + } + }); this.aggregatorHolder = new AggregatorHolder<>(newHolderHandles); ConcurrentHashMap> aggregatorHandles = @@ -249,18 +248,16 @@ public MetricData collect( // Lock and drain unbound handles (unchanged from the unbound-only path). Bound handles are // handled separately below with a tight per-handle lock window so that recording to a bound // series never blocks for the duration of the whole collection. - aggregatorHandles.forEach( - (attributes, handle) -> { - if (!handle.bound) { - handle.lockForCollect(); - } - }); - aggregatorHandles.forEach( - (attributes, handle) -> { - if (!handle.bound) { - handle.awaitRecordersAndUnlock(); - } - }); + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.bound) { + handle.lockForCollect(); + } + }); + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.bound) { + handle.awaitRecordersAndUnlock(); + } + }); List points; if (memoryMode == REUSABLE_DATA) { @@ -286,12 +283,11 @@ public MetricData collect( // Bound handles are kept unconditionally since their bound instruments hold direct references. if (memoryMode == REUSABLE_DATA) { if (aggregatorHandles.size() >= maxCardinality) { - aggregatorHandles.forEach( - (attribute, handle) -> { - if (!handle.bound && !handle.handle.hasRecordedValues()) { - aggregatorHandles.remove(attribute); - } - }); + aggregatorHandles.forEach((attribute, handle) -> { + if (!handle.bound && !handle.handle.hasRecordedValues()) { + aggregatorHandles.remove(attribute); + } + }); } } @@ -301,30 +297,29 @@ public MetricData collect( registeredReader.getLastCollectEpochNanosOrDefault(instrumentCreationEpochNanos); // Grab aggregated points. - aggregatorHandles.forEach( - (attributes, handle) -> { - if (handle.bound) { - collectBound(handle, attributes, startEpochNanos, epochNanos, points); - return; - } - if (!handle.handle.hasRecordedValues()) { - return; - } - T point = - handle.handle.aggregateThenMaybeReset( - startEpochNanos, epochNanos, attributes, /* reset= */ true); - - if (memoryMode == IMMUTABLE_DATA) { - // Return the handle to the pool. - // Only in IMMUTABLE_DATA memory mode: in REUSABLE_DATA we avoid using the pool - // since ConcurrentLinkedQueue.offer() allocates memory internally. - aggregatorHandlePool.offer(handle); - } + aggregatorHandles.forEach((attributes, handle) -> { + if (handle.bound) { + collectBound(handle, attributes, startEpochNanos, epochNanos, points); + return; + } + if (!handle.handle.hasRecordedValues()) { + return; + } + T point = + handle.handle.aggregateThenMaybeReset( + startEpochNanos, epochNanos, attributes, /* reset= */ true); + + if (memoryMode == IMMUTABLE_DATA) { + // Return the handle to the pool. + // Only in IMMUTABLE_DATA memory mode: in REUSABLE_DATA we avoid using the pool + // since ConcurrentLinkedQueue.offer() allocates memory internally. + aggregatorHandlePool.offer(handle); + } - if (point != null) { - points.add(point); - } - }); + if (point != null) { + points.add(point); + } + }); if (memoryMode == REUSABLE_DATA) { previousCollectionAggregatorHandles = aggregatorHandles; diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java index fd5e90aa3f6..d6a6de929f4 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java @@ -70,28 +70,25 @@ void staleMetricsDropped_synchronousInstrument() { // DELTA reader only has latest assertThat(deltaReader.collectAllMetrics()) .as("Delta collection " + i) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); // Make sure we preserve previous cumulatives int currentSize = i; assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection " + i) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(currentSize)))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(currentSize)))); } // Now punch the limit and ONLY metrics we just recorded stay, due to simplistic GC. for (int i = DEFAULT_MAX_CARDINALITY + 1; i <= DEFAULT_MAX_CARDINALITY + 10; i++) { @@ -99,33 +96,28 @@ void staleMetricsDropped_synchronousInstrument() { } assertThat(deltaReader.collectAllMetrics()) .as("Delta collection - post limit @ 10") - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(10)))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()).isEqualTo(10)))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection - post limit @ 10") - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY)))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); } /** @@ -139,28 +131,25 @@ void staleMetricsDropped_asynchronousInstrument() { meter .counterBuilder("async-counter") - .buildWithCallback( - measurement -> - measurement.record( - 1, Attributes.builder().put("key", "num_" + count.incrementAndGet()).build())); + .buildWithCallback(measurement -> + measurement.record( + 1, Attributes.builder().put("key", "num_" + count.incrementAndGet()).build())); for (int i = 1; i <= 5; i++) { assertThat(deltaReader.collectAllMetrics()) .as("Delta collection " + i) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasName("async-counter") - .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("async-counter") + .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection " + i) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasName("async-counter") - .hasLongSumSatisfying( - sum -> sum.isCumulative().hasPointsSatisfying(point -> {}))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("async-counter") + .hasLongSumSatisfying( + sum -> sum.isCumulative().hasPointsSatisfying(point -> {}))); } } @@ -183,25 +172,23 @@ void defaultCardinalityLimits_synchronousInstrument() { metricData -> assertThat(metricData) .hasName("sync-counter1") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("sync-counter2") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY)))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection") @@ -209,25 +196,23 @@ void defaultCardinalityLimits_synchronousInstrument() { metricData -> assertThat(metricData) .hasName("sync-counter1") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("sync-counter2") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY)))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); } /** @@ -251,25 +236,23 @@ void defaultCardinalityLimits_asynchronousInstrument() { metricData -> assertThat(metricData) .hasName("async-counter1") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("async-counter2") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY)))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection") @@ -277,25 +260,23 @@ void defaultCardinalityLimits_asynchronousInstrument() { metricData -> assertThat(metricData) .hasName("async-counter1") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("async-counter2") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(DEFAULT_MAX_CARDINALITY)))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); } /** @@ -339,13 +320,12 @@ void readerAndViewCardinalityConfiguration() { LongHistogram histogram = meter.histogramBuilder("histogram").ofLongs().build(); meter .counterBuilder("asyncCounter") - .buildWithCallback( - observableMeasurement -> { - // Record enough measurements to exceed cardinality threshold - for (int i = 0; i < DEFAULT_MAX_CARDINALITY; i++) { - observableMeasurement.record(1, Attributes.builder().put("key", i).build()); - } - }); + .buildWithCallback(observableMeasurement -> { + // Record enough measurements to exceed cardinality threshold + for (int i = 0; i < DEFAULT_MAX_CARDINALITY; i++) { + observableMeasurement.record(1, Attributes.builder().put("key", i).build()); + } + }); // Record enough measurements to exceed cardinality threshold for (int i = 0; i < DEFAULT_MAX_CARDINALITY; i++) { @@ -364,128 +344,112 @@ void readerAndViewCardinalityConfiguration() { metricData -> assertThat(metricData) .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - data -> - pointsAssert( - data, - counterLimit, - 0, - counterLimit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + 0, + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), metricData -> assertThat(metricData) .hasName("counter2") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - data -> - pointsAssert( - data, - counter2Limit, - 0, - counter2Limit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + 0, + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), metricData -> assertThat(metricData) .hasName("histogram") - .hasHistogramSatisfying( - histogramMetric -> - histogramMetric - .isDelta() - .satisfies( - data -> - pointsAssert( - data, - generalLimit, - 0, - generalLimit, - HistogramPointData::getCount, - DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isDelta() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + 0, + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), metricData -> assertThat(metricData) .hasName("asyncCounter") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - data -> - pointsAssert( - data, - asyncCounterLimit, - 0, - asyncCounterLimit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); assertThat(cumulativeReader.collectAllMetrics()) .as("cumulative collection") .satisfiesExactlyInAnyOrder( metricData -> assertThat(metricData) .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - data -> - pointsAssert( - data, - counterLimit, - 0, - counterLimit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + 0, + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), metricData -> assertThat(metricData) .hasName("counter2") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - data -> - pointsAssert( - data, - counter2Limit, - 0, - counter2Limit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + 0, + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), metricData -> assertThat(metricData) .hasName("histogram") - .hasHistogramSatisfying( - histogramMetric -> - histogramMetric - .isCumulative() - .satisfies( - data -> - pointsAssert( - data, - generalLimit, - 0, - generalLimit, - HistogramPointData::getCount, - DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isCumulative() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + 0, + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), metricData -> assertThat(metricData) .hasName("asyncCounter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - data -> - pointsAssert( - data, - asyncCounterLimit, - 0, - asyncCounterLimit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); // Record another round of measurements, again exceeding cardinality limits for (int i = DEFAULT_MAX_CARDINALITY; i < DEFAULT_MAX_CARDINALITY * 2; i++) { @@ -502,64 +466,56 @@ void readerAndViewCardinalityConfiguration() { metricData -> assertThat(metricData) .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - data -> - pointsAssert( - data, - counterLimit, - DEFAULT_MAX_CARDINALITY, - DEFAULT_MAX_CARDINALITY + counterLimit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + DEFAULT_MAX_CARDINALITY, + DEFAULT_MAX_CARDINALITY + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), metricData -> assertThat(metricData) .hasName("counter2") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - data -> - pointsAssert( - data, - counter2Limit, - DEFAULT_MAX_CARDINALITY, - DEFAULT_MAX_CARDINALITY + counter2Limit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + DEFAULT_MAX_CARDINALITY, + DEFAULT_MAX_CARDINALITY + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), metricData -> assertThat(metricData) .hasName("histogram") - .hasHistogramSatisfying( - histogramMetric -> - histogramMetric - .isDelta() - .satisfies( - data -> - pointsAssert( - data, - generalLimit, - DEFAULT_MAX_CARDINALITY, - DEFAULT_MAX_CARDINALITY + generalLimit, - HistogramPointData::getCount, - DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isDelta() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + DEFAULT_MAX_CARDINALITY, + DEFAULT_MAX_CARDINALITY + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), metricData -> assertThat(metricData) .hasName("asyncCounter") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - data -> - pointsAssert( - data, - asyncCounterLimit, - 0, - asyncCounterLimit, - LongPointData::getValue, - 0)))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + 0)))); // Cumulative reader should retain old points, dropping the new measurements assertThat(cumulativeReader.collectAllMetrics()) @@ -568,64 +524,56 @@ void readerAndViewCardinalityConfiguration() { metricData -> assertThat(metricData) .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - data -> - pointsAssert( - data, - counterLimit, - 0, - counterLimit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY * 2 - (counterLimit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + 0, + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY * 2 - (counterLimit - 1)))), metricData -> assertThat(metricData) .hasName("counter2") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - data -> - pointsAssert( - data, - counter2Limit, - 0, - counter2Limit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY * 2 - (counter2Limit - 1)))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + 0, + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY * 2 - (counter2Limit - 1)))), metricData -> assertThat(metricData) .hasName("histogram") - .hasHistogramSatisfying( - histogramMetric -> - histogramMetric - .isCumulative() - .satisfies( - data -> - pointsAssert( - data, - generalLimit, - 0, - generalLimit, - HistogramPointData::getCount, - DEFAULT_MAX_CARDINALITY * 2 - (generalLimit - 1)))), + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isCumulative() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + 0, + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY * 2 - (generalLimit - 1)))), metricData -> assertThat(metricData) .hasName("asyncCounter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - data -> - pointsAssert( - data, - asyncCounterLimit, - 0, - asyncCounterLimit, - LongPointData::getValue, - DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); } /** @@ -644,21 +592,20 @@ private static void pointsAssert( long expectedOverflowValue) { assertThat(data.getPoints()) .hasSize(expectedNumPoints) - .allSatisfy( - point -> { - boolean isOverflowSeries = - point.getAttributes().equals(MetricStorage.CARDINALITY_OVERFLOW); - Long keyValue = point.getAttributes().get(AttributeKey.longKey("key")); - boolean isKeySeries = keyValue != null; - assertThat(isOverflowSeries || isKeySeries).isTrue(); - if (isOverflowSeries) { - assertThat(overflowValueProvider.apply(point)).isEqualTo(expectedOverflowValue); - } - if (isKeySeries) { - assertThat(keyValue) - .isGreaterThanOrEqualTo(minAttributeValueInclusive) - .isLessThan(maxAttributeValueExclusive); - } - }); + .allSatisfy(point -> { + boolean isOverflowSeries = + point.getAttributes().equals(MetricStorage.CARDINALITY_OVERFLOW); + Long keyValue = point.getAttributes().get(AttributeKey.longKey("key")); + boolean isKeySeries = keyValue != null; + assertThat(isOverflowSeries || isKeySeries).isTrue(); + if (isOverflowSeries) { + assertThat(overflowValueProvider.apply(point)).isEqualTo(expectedOverflowValue); + } + if (isKeySeries) { + assertThat(keyValue) + .isGreaterThanOrEqualTo(minAttributeValueInclusive) + .isLessThan(maxAttributeValueExclusive); + } + }); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ExplicitBucketBoundariesAdviceTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ExplicitBucketBoundariesAdviceTest.java index 5a6c68bd229..cfe1d05d089 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ExplicitBucketBoundariesAdviceTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ExplicitBucketBoundariesAdviceTest.java @@ -54,19 +54,15 @@ void histogramWithoutAdvice(Function> histogram // Should use default bucket bounds assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasBucketCounts( - 0, 1, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasBucketBoundaries( - 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, - 1_000d, 2_500d, 5_000d, 7_500d, 10_000d)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(0, 1, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries( + 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, 2_500d, + 5_000d, 7_500d, 10_000d)))); assertThat(logCapturer.getEvents()).isEmpty(); } @@ -85,17 +81,12 @@ void histogramWithAdvice(Function> histogramBui // Bucket bounds from advice should be used assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("histogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasBucketCounts(1, 1, 1, 1) - .hasBucketBoundaries(10.0, 20.0, 30.0)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point.hasBucketCounts(1, 1, 1, 1).hasBucketBoundaries(10.0, 20.0, 30.0)))); assertThat(logCapturer.getEvents()).isEmpty(); } @@ -126,14 +117,12 @@ void histogramWithAdviceAndViews(Function> hist // View should take priority over bucket bounds from advice assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("histogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> point.hasBucketCounts(4, 0).hasBucketBoundaries(50.0)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> point.hasBucketCounts(4, 0).hasBucketBoundaries(50.0)))); assertThat(logCapturer.getEvents()).isEmpty(); } @@ -162,14 +151,12 @@ void histogramWithAdviceAndReaderAggregationPreference( // Reader aggregation preference should take priority over bucket bounds from advice assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("histogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> point.hasBucketCounts(4, 0).hasBucketBoundaries(50.0)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> point.hasBucketCounts(4, 0).hasBucketBoundaries(50.0)))); assertThat(logCapturer.getEvents()).isEmpty(); } @@ -191,19 +178,15 @@ void histogramWithInvalidAdvice( // Should use default bucket bounds assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasBucketCounts( - 0, 1, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasBucketBoundaries( - 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, - 1_000d, 2_500d, 5_000d, 7_500d, 10_000d)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(0, 1, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries( + 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, 2_500d, + 5_000d, 7_500d, 10_000d)))); logCapturer.assertContains(expectedErrorMessage); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java index cf230236915..00cb18f6dc3 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java @@ -50,25 +50,22 @@ void sameMeterSameInstrumentNoViews() { meterProvider.get("meter1").counterBuilder("counter1").build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter1")) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); meterProvider.get("meter2").counterBuilder("counter2").ofDoubles().build().add(10); meterProvider.get("meter2").counterBuilder("counter2").ofDoubles().build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter2")) - .hasName("counter2") - .hasDoubleSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter2")) + .hasName("counter2") + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); meterProvider .get("meter3") @@ -84,27 +81,23 @@ void sameMeterSameInstrumentNoViews() { .add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter3")) - .hasName("counter3") - .hasDescription("description3") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter3")) + .hasName("counter3") + .hasDescription("description3") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); meterProvider.get("meter4").counterBuilder("counter4").setUnit("unit4").build().add(10); meterProvider.get("meter4").counterBuilder("counter4").setUnit("unit4").build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter4")) - .hasName("counter4") - .hasUnit("unit4") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter4")) + .hasName("counter4") + .hasUnit("unit4") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); } @@ -142,13 +135,11 @@ void sameMeterDifferentInstrumentNameCaseNoViews() { meterProvider.get("meter1").counterBuilder("counter1").build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter1")) - .hasName("Counter1") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("Counter1") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); } @@ -207,14 +198,12 @@ void sameMeterSameInstrumentNameDifferentIdentifyingFieldsNoViews() { assertThat(metricData) .hasInstrumentationScope(forMeter("meter1")) .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic().hasPointsSatisfying(point -> point.hasValue(10)))); + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic().hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(4); } @@ -246,27 +235,22 @@ void sameMeterSameInstrumentNameDifferentNonIdentifyingFieldsNoViews() { assertThat(metricData) .hasInstrumentationScope(forMeter("meter1")) .hasName("histogram1") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasBucketCounts( - 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasBucketBoundaries( - 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, - 1_000d, 2_500d, 5_000d, 7_500d, 10_000d))), + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries( + 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, + 2_500d, 5_000d, 7_500d, 10_000d))), metricData -> assertThat(metricData) .hasInstrumentationScope(forMeter("meter1")) .hasName("histogram2") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasBucketCounts(2, 0, 0, 0) - .hasBucketBoundaries(10.0, 20.0, 30.0)))); + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(2, 0, 0, 0) + .hasBucketBoundaries(10.0, 20.0, 30.0)))); assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); } @@ -391,9 +375,8 @@ void sameMeterConflictingInstrumentDescriptionNoViews() { }); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -424,9 +407,8 @@ void sameMeterConflictingInstrumentUnitNoViews() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -445,9 +427,8 @@ void sameMeterConflictingInstrumentTypeNoViews() { assertThat(metricData) .hasInstrumentationScope(forMeter("meter1")) .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), metricData -> assertThat(metricData) .hasInstrumentationScope(forMeter("meter1")) @@ -456,9 +437,8 @@ void sameMeterConflictingInstrumentTypeNoViews() { sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -487,9 +467,8 @@ void sameMeterConflictingInstrumentValueTypeNoViews() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -506,14 +485,12 @@ void sameMeterSameInstrumentSingleView() { meterProvider.get("meter1").counterBuilder("counter1").build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter1")) - .hasName("counter1") - .hasDescription("description1") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasDescription("description1") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); } @@ -855,9 +832,8 @@ void sameMeterSameInstrumentConflictingViewDescriptions() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -895,9 +871,8 @@ void sameMeterSameInstrumentConflictingViewAggregations() { histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(20)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); assertThat(viewRegistryLogs.getEvents()).hasSize(0); } @@ -933,9 +908,8 @@ void sameMeterDifferentInstrumentConflictingViewName() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -1087,11 +1061,10 @@ void sameMeterDifferentInstrumentIncompatibleViewAggregation() { assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); assertThat(viewRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()) - .contains( - "View aggregation explicit_bucket_histogram is incompatible with instrument counter1 of type OBSERVABLE_COUNTER")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()) + .contains( + "View aggregation explicit_bucket_histogram is incompatible with instrument counter1 of type OBSERVABLE_COUNTER")) .hasSize(1); } @@ -1112,13 +1085,11 @@ void viewNameNotValidated() { assertThat(counter.isEnabled()).isTrue(); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter1")) - .hasName("1invalid-name") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("1invalid-name") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); assertThat(viewRegistryLogs.getEvents()).hasSize(0); @@ -1137,10 +1108,9 @@ void instrumentWithInvalidName() { assertThat(counter.isEnabled()).isFalse(); assertThat(reader.collectAllMetrics()).isEmpty(); assertThat(sdkMeterLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()) - .contains("Instrument name \"1invalid-name\" is invalid")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()) + .contains("Instrument name \"1invalid-name\" is invalid")) .hasSize(1); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java index 29c68e239fd..dffeaea887e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java @@ -84,77 +84,53 @@ void collectAllMetrics() { .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("longCounter") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("key", "val1")))), + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(1).hasAttributes(attributeEntry("key", "val1")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("doubleCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1.1) - .hasAttributes(attributeEntry("key", "val2")))), + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(1.1).hasAttributes(attributeEntry("key", "val2")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("longUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(2) - .hasAttributes(attributeEntry("key", "val3")))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(2).hasAttributes(attributeEntry("key", "val3")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("doubleUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(2.2) - .hasAttributes(attributeEntry("key", "val4")))), + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(2.2).hasAttributes(attributeEntry("key", "val4")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("longGauge") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(3) - .hasAttributes(attributeEntry("key", "val5")))), + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasValue(3).hasAttributes(attributeEntry("key", "val5")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("doubleGauge") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(3.3) - .hasAttributes(attributeEntry("key", "val6"))))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasValue(3.3).hasAttributes(attributeEntry("key", "val6"))))); // Should not be called after closed batchCallback.close(); @@ -175,14 +151,13 @@ void collectAllMetrics_RecordToUnregisteredInstrument() { // counter2 is not registered and measurements should be ignored assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); observableMeasurementLogs.assertContains( "Measurement recorded for instrument counter2 outside callback registered to instrument. Dropping measurement."); @@ -199,20 +174,15 @@ void collectAllMetrics_RecordOutsideCallback() { () -> counter1.record(1, Attributes.builder().put("key", "value2").build()), counter1); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("key", "value2"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(1).hasAttributes(attributeEntry("key", "value2"))))); observableMeasurementLogs.assertContains( "Measurement recorded for instrument counter1 outside callback registered to instrument. Dropping measurement."); @@ -235,14 +205,13 @@ void collectAllMetrics_InstrumentFromAnotherMeter() { // counter2 belongs to another meter and measurements should be ignored assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); sdkMeterLogs.assertContains( "batchCallback called with instruments that belong to a different Meter."); @@ -271,14 +240,13 @@ public void record(long value, Attributes attributes) {} // counter2 was not obtained from the sdk and its measurements should be ignored. assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); sdkMeterLogs.assertContains( "batchCallback called with instruments that were not created by the SDK."); diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java index 5f421a1c3b0..1f738e59285 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java @@ -71,25 +71,22 @@ void collectMetrics_WithEmptyAttributes() { doubleCounter.add(12d); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasDescription("description") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasDescription("description") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test @@ -104,57 +101,53 @@ void collectMetrics_WithMultipleCollects() { doubleCounter.add(321.5d, Attributes.builder().put("K", "V").build()); doubleCounter.add(111.1d, Attributes.builder().put("K", "V").build()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasDescription("") - .hasUnit("") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(555.9) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasDescription("") + .hasUnit("") + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(555.9) + .hasAttributes(attributeEntry("K", "V"))))); // Repeat to prove we keep previous values. testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleCounter.add(222d, Attributes.builder().put("K", "V").build()); doubleCounter.add(11d, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(777.9) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(777.9) + .hasAttributes(attributeEntry("K", "V"))))); } @Test diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeTest.java index 85b4d6d1267..d3f9e40e0d0 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeTest.java @@ -72,12 +72,11 @@ void observable_RemoveCallback() { sdkMeter.gaugeBuilder("testGauge").buildWithCallback(measurement -> measurement.record(10)); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasDoubleGaugeSatisfying( - doubleGauge -> doubleGauge.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasDoubleGaugeSatisfying( + doubleGauge -> doubleGauge.hasPointsSatisfying(point -> {}))); gauge.close(); @@ -108,23 +107,20 @@ void collectMetrics_WithEmptyAttributes() { doubleGauge.set(13d); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("description") - .hasUnit("K") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(13d)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(13d)))); } @Test @@ -155,28 +151,22 @@ void collectMetrics_WithExemplars() { } assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("description") - .hasUnit("K") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12d) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasValue(12d) - .hasFilteredAttributes( - Attributes.builder() - .put("key", "value") - .build()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12d) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(12d) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } @Test @@ -196,14 +186,11 @@ void observable_CollectMetrics_DefaultExemplarFilter_NoExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasValue(12d).hasExemplars()))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasValue(12d).hasExemplars()))); } @Test @@ -224,18 +211,14 @@ void observable_CollectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12d) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(12d))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12d) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12d))))); } @Test @@ -250,90 +233,81 @@ void collectMetrics_WithMultipleCollects() { doubleGauge.set(321.5d, Attributes.builder().put("K", "V").build()); doubleGauge.set(111.1d, Attributes.builder().put("K", "V").build()); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("") - .hasUnit("") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(21.4d), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(111.1d) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21.4d), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111.1d) + .hasAttributes(attributeEntry("K", "V"))))); assertThat(deltaReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("") - .hasUnit("") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(21.4d), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(111.1d) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21.4d), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111.1d) + .hasAttributes(attributeEntry("K", "V"))))); // Repeat to prove we keep previous values. testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleGauge.set(222d, Attributes.builder().put("K", "V").build()); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(21.4d), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(222d) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21.4d), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(222d) + .hasAttributes(attributeEntry("K", "V"))))); // Delta reader should only have point for {K=V} series, since the {} did not have any // measurements assertThat(deltaReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime + SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(222d) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(startTime + SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(222d) + .hasAttributes(attributeEntry("K", "V"))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java index 80c27b24d73..7058ae02210 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java @@ -79,31 +79,27 @@ void collectMetrics_WithEmptyAttributes() { doubleHistogram.record(12d); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(24) - .hasBucketBoundaries( - 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, - 2_500, 5_000, 7_500, 10_000) - .hasBucketCounts( - 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("ms") + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(24) + .hasBucketBoundaries( + 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, 5_000, + 7_500, 10_000) + .hasBucketCounts(0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); } @Test @@ -118,66 +114,58 @@ void collectMetrics_WithMultipleCollects() { doubleHistogram.record(321.5d, Attributes.builder().put("K", "V").build()); doubleHistogram.record(121.5d, Attributes.builder().put("K", "V").build()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(566.3d) - .hasBucketCounts( - 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(2) - .hasSum(22.2d) - .hasBucketCounts( - 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(566.3d) + .hasBucketCounts(0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(2) + .hasSum(22.2d) + .hasBucketCounts(0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); // Histograms are cumulative by default. testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleHistogram.record(222d, Attributes.builder().put("K", "V").build()); doubleHistogram.record(17d, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(4) - .hasSum(788.3) - .hasBucketCounts( - 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(39.2) - .hasBucketCounts( - 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(4) + .hasSum(788.3) + .hasBucketCounts(0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(39.2) + .hasBucketCounts(0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); } @Test @@ -212,63 +200,51 @@ void collectMetrics_ExponentialHistogramAggregation() { doubleHistogram.record(13d); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("ms") - .hasExponentialHistogramSatisfying( - expHistogram -> - expHistogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(25) - .hasMin(12) - .hasMax(13) - .hasScale(5) - .hasZeroCount(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(114) - .hasCounts( - Arrays.asList(1L, 0L, 0L, 0L, 1L))) - .hasNegativeBucketsSatisfying( - buckets -> - buckets - .hasOffset(0) - .hasCounts(Collections.emptyList())), - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes( - Attributes.builder().put("key", "value").build()) - .hasCount(1) - .hasSum(12) - .hasMin(12) - .hasMax(12) - .hasScale(20) - .hasZeroCount(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(3759105) - .hasCounts(Collections.singletonList(1L))) - .hasNegativeBucketsSatisfying( - buckets -> - buckets - .hasOffset(0) - .hasCounts(Collections.emptyList()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("ms") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(25) + .hasMin(12) + .hasMax(13) + .hasScale(5) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(114) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList())), + point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.builder().put("key", "value").build()) + .hasCount(1) + .hasSum(12) + .hasMin(12) + .hasMax(12) + .hasScale(20) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(3759105) + .hasCounts(Collections.singletonList(1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList()))))); } @Test @@ -319,24 +295,18 @@ void collectMetrics_ExemplarsWithExponentialHistogram() { } assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasExponentialHistogramSatisfying( - exponentialHistogram -> - exponentialHistogram.hasPointsSatisfying( - point -> - point - .hasSum(10.0) - .hasAttributes(Attributes.empty()) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasValue(10.0) - .hasFilteredAttributes( - Attributes.builder() - .put("key", "value") - .build()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasExponentialHistogramSatisfying(exponentialHistogram -> + exponentialHistogram.hasPointsSatisfying(point -> + point + .hasSum(10.0) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } @Test @@ -366,23 +336,17 @@ void collectMetrics_ExemplarsWithExplicitBucketHistogram() { } assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasHistogramSatisfying( - explicitHistogram -> - explicitHistogram.hasPointsSatisfying( - point -> - point - .hasSum(10) - .hasAttributes(Attributes.empty()) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasValue(10.0) - .hasFilteredAttributes( - Attributes.builder() - .put("key", "value") - .build()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(explicitHistogram -> + explicitHistogram.hasPointsSatisfying(point -> + point + .hasSum(10) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java index 244d3d3c5e2..45d559adc0f 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java @@ -39,13 +39,8 @@ class SdkDoubleUpDownCounterTest { @Test void add_PreventNullAttributes() { - assertThatThrownBy( - () -> - sdkMeter - .upDownCounterBuilder("testUpDownCounter") - .ofDoubles() - .build() - .add(1.0, null)) + assertThatThrownBy(() -> + sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build().add(1.0, null)) .isInstanceOf(NullPointerException.class) .hasMessage("attributes"); } @@ -70,25 +65,22 @@ void collectMetrics_WithEmptyAttributes() { doubleUpDownCounter.add(12d); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDescription("description") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDescription("description") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test @@ -104,58 +96,54 @@ void collectMetrics_WithMultipleCollects() { doubleUpDownCounter.add(321.5d, Attributes.builder().put("K", "V").build()); doubleUpDownCounter.add(111.1d, Attributes.builder().put("K", "V").build()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(555.9) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(555.9) + .hasAttributes(attributeEntry("K", "V"))))); // Repeat to prove we keep previous values. testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleUpDownCounter.add(222d, Attributes.builder().put("K", "V").build()); doubleUpDownCounter.add(11d, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(777.9)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(777.9)))); } @Test diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java index fbfe9fb1803..02f3f43b4ce 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java @@ -64,26 +64,23 @@ void collectMetrics_WithEmptyAttributes() { longCounter.add(12); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasDescription("description") - .hasUnit("By") - .hasLongSumSatisfying( - longSum -> - longSum - .isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasDescription("description") + .hasUnit("By") + .hasLongSumSatisfying(longSum -> + longSum + .isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test @@ -98,60 +95,56 @@ void collectMetrics_WithMultipleCollects() { longCounter.add(321, Attributes.builder().put("K", "V").build()); longCounter.add(111, Attributes.builder().put("K", "V").build()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasLongSumSatisfying( - longSum -> - longSum - .isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(555)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasLongSumSatisfying(longSum -> + longSum + .isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(555)))); // Repeat to prove we keep previous values. testClock.advance(Duration.ofNanos(SECOND_NANOS)); longCounter.add(222, Attributes.builder().put("K", "V").build()); longCounter.add(11, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasLongSumSatisfying( - longSum -> - longSum - .isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(777)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasLongSumSatisfying(longSum -> + longSum + .isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(777)))); } @Test diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeTest.java index 489c57d784d..ee1054400e1 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeTest.java @@ -65,12 +65,10 @@ void observable_RemoveCallback() { .buildWithCallback(measurement -> measurement.record(10)); Assertions.assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasLongGaugeSatisfying( - longGauge -> longGauge.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasLongGaugeSatisfying(longGauge -> longGauge.hasPointsSatisfying(point -> {}))); gauge.close(); @@ -97,23 +95,20 @@ void collectMetrics_WithEmptyAttributes() { longGauge.set(13); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("description") - .hasUnit("K") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(13)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(13)))); } @Test @@ -149,28 +144,22 @@ void collectMetrics_WithExemplars() { } assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("description") - .hasUnit("K") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12L) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasValue(12L) - .hasFilteredAttributes( - Attributes.builder() - .put("key", "value") - .build()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12L) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(12L) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } @Test @@ -191,13 +180,11 @@ void observable_CollectMetrics_DefaultExemplarFilter_NoExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); } @Test @@ -219,18 +206,14 @@ void observable_CollectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(12))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12))))); } @Test @@ -245,90 +228,81 @@ void collectMetrics_WithMultipleCollects() { longGauge.set(321, Attributes.builder().put("K", "V").build()); longGauge.set(111, Attributes.builder().put("K", "V").build()); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("") - .hasUnit("") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(21), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(111) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111) + .hasAttributes(attributeEntry("K", "V"))))); assertThat(deltaReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testGauge") - .hasDescription("") - .hasUnit("") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(21), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(111) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111) + .hasAttributes(attributeEntry("K", "V"))))); // Repeat to prove we keep previous values. testClock.advance(Duration.ofNanos(SECOND_NANOS)); longGauge.set(222, Attributes.builder().put("K", "V").build()); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(21), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(222) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(222) + .hasAttributes(attributeEntry("K", "V"))))); // Delta reader should only have point for {K=V} series, since the {} did not have any // measurements assertThat(deltaReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime + SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(222) - .hasAttributes(attributeEntry("K", "V"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(startTime + SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(222) + .hasAttributes(attributeEntry("K", "V"))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java index 891ce85d01e..36e8e16f832 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java @@ -79,31 +79,27 @@ void collectMetrics_WithEmptyAttributes() { longHistogram.record(12); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("By") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(24) - .hasBucketBoundaries( - 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, - 2_500, 5_000, 7_500, 10_000) - .hasBucketCounts( - 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("By") + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(24) + .hasBucketBoundaries( + 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, 5_000, + 7_500, 10_000) + .hasBucketCounts(0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); } @Test @@ -118,66 +114,58 @@ void collectMetrics_WithMultipleCollects() { longHistogram.record(321, Attributes.builder().put("K", "V").build()); longHistogram.record(1, Attributes.builder().put("K", "V").build()); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(445) - .hasBucketCounts( - 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(2) - .hasSum(23) - .hasBucketCounts( - 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(445) + .hasBucketCounts(0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(2) + .hasSum(23) + .hasBucketCounts(0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); // Histograms are cumulative by default. testClock.advance(Duration.ofNanos(SECOND_NANOS)); longHistogram.record(222, Attributes.builder().put("K", "V").build()); longHistogram.record(17, Attributes.empty()); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(4) - .hasSum(667) - .hasBucketCounts( - 0, 1, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(40) - .hasBucketCounts( - 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(4) + .hasSum(667) + .hasBucketCounts(0, 1, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(40) + .hasBucketCounts(0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); } /** @@ -220,65 +208,53 @@ void collectMetrics_ExponentialHistogramScaleResets() { // Both deltaReader and cumulativeReader should read out the same values, with the attributes1 // point having a scale that accommodates the range of measurements. assertThat(deltaReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("histogram") - .hasExponentialHistogramSatisfying( - expHistogram -> - expHistogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasAttributes(attributes1) - .hasScale(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts( - Arrays.asList(1L, 0L, 0L, 0L, 1L))), - point -> - point - .hasAttributes(attributes2) - .hasScale(20) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts( - Collections.singletonList(1L)))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isDelta() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(20) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Collections.singletonList(1L)))))); assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("histogram") - .hasExponentialHistogramSatisfying( - expHistogram -> - expHistogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasAttributes(attributes1) - .hasScale(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts( - Arrays.asList(1L, 0L, 0L, 0L, 1L))), - point -> - point - .hasAttributes(attributes2) - .hasScale(20) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts( - Collections.singletonList(1L)))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(20) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Collections.singletonList(1L)))))); // Record 1 measurement to attributes1 such that scale doesn't change, 2 measurement to // attributes2 such that scale changes. @@ -290,66 +266,55 @@ void collectMetrics_ExponentialHistogramScaleResets() { // now has scale 20, the attributes2 point now has scale 0 to accommodate the range of // measurements. assertThat(deltaReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("histogram") - .hasExponentialHistogramSatisfying( - expHistogram -> - expHistogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasAttributes(attributes1) - .hasScale(20) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts(Collections.singletonList(1L))), - point -> - point - .hasAttributes(attributes2) - .hasScale(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts( - Arrays.asList(1L, 0L, 0L, 0L, 1L)))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isDelta() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(20) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Collections.singletonList(1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L)))))); // The cumulativeReader does not reset after collection, so both attributes1 and attributes2 // points should now have scale 0. assertThat(cumulativeReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("histogram") - .hasExponentialHistogramSatisfying( - expHistogram -> - expHistogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasAttributes(attributes1) - .hasScale(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts( - Arrays.asList(2L, 0L, 0L, 0L, 1L))), - point -> - point - .hasAttributes(attributes2) - .hasScale(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(-1) - .hasCounts( - Arrays.asList(2L, 0L, 0L, 0L, 1L)))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(2L, 0L, 0L, 0L, 1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(2L, 0L, 0L, 0L, 1L)))))); } @Test @@ -385,63 +350,51 @@ void collectMetrics_ExponentialHistogramAggregation() { longHistogram.record(13L); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("ms") - .hasExponentialHistogramSatisfying( - expHistogram -> - expHistogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(25) - .hasMin(12) - .hasMax(13) - .hasScale(5) - .hasZeroCount(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(114) - .hasCounts( - Arrays.asList(1L, 0L, 0L, 0L, 1L))) - .hasNegativeBucketsSatisfying( - buckets -> - buckets - .hasOffset(0) - .hasCounts(Collections.emptyList())), - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes( - Attributes.builder().put("key", "value").build()) - .hasCount(1) - .hasSum(12) - .hasMin(12) - .hasMax(12) - .hasScale(20) - .hasZeroCount(0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(3759105) - .hasCounts(Collections.singletonList(1L))) - .hasNegativeBucketsSatisfying( - buckets -> - buckets - .hasOffset(0) - .hasCounts(Collections.emptyList()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("ms") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(25) + .hasMin(12) + .hasMax(13) + .hasScale(5) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(114) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList())), + point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.builder().put("key", "value").build()) + .hasCount(1) + .hasSum(12) + .hasMin(12) + .hasMax(12) + .hasScale(20) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(3759105) + .hasCounts(Collections.singletonList(1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList()))))); } @Test @@ -484,24 +437,18 @@ void collectMetrics_ExemplarsWithExponentialHistogram() { } assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasExponentialHistogramSatisfying( - exponentialHistogram -> - exponentialHistogram.hasPointsSatisfying( - point -> - point - .hasSum(10.0) - .hasAttributes(Attributes.empty()) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasValue(10.0) - .hasFilteredAttributes( - Attributes.builder() - .put("key", "value") - .build()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasExponentialHistogramSatisfying(exponentialHistogram -> + exponentialHistogram.hasPointsSatisfying(point -> + point + .hasSum(10.0) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } @Test @@ -531,23 +478,17 @@ void collectMetrics_ExemplarsWithExplicitBucketHistogram() { } assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasHistogramSatisfying( - explicitHistogram -> - explicitHistogram.hasPointsSatisfying( - point -> - point - .hasSum(10) - .hasAttributes(Attributes.empty()) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasValue(10.0) - .hasFilteredAttributes( - Attributes.builder() - .put("key", "value") - .build()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(explicitHistogram -> + explicitHistogram.hasPointsSatisfying(point -> + point + .hasSum(10) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java index 63bb43a1468..64b486934a4 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java @@ -63,25 +63,22 @@ void collectMetrics_WithEmptyAttributes() { longUpDownCounter.add(12); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDescription("description") - .hasUnit("By") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDescription("description") + .hasUnit("By") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test @@ -97,57 +94,53 @@ void collectMetrics_WithMultipleCollects() { longUpDownCounter.add(321, Attributes.builder().put("K", "V").build()); longUpDownCounter.add(111, Attributes.builder().put("K", "V").build()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(555)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(555)))); // Repeat to prove we keep previous values. testClock.advance(Duration.ofNanos(SECOND_NANOS)); longUpDownCounter.add(222, Attributes.builder().put("K", "V").build()); longUpDownCounter.add(11, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(777)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(777)))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderMetricsTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderMetricsTest.java index 8c3f006d1e2..f7f4efb32e7 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderMetricsTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderMetricsTest.java @@ -48,18 +48,16 @@ void simple() { m -> { assertThat(m) .hasName("otel.sdk.metric_reader.collection.duration") - .hasHistogramSatisfying( - h -> - h.hasPointsSatisfying( - p -> - p.hasCount(1) - .hasAttributesSatisfying( - equalTo( - SemConvConstants.OTEL_COMPONENT_TYPE, - "periodic_metric_reader"), - equalTo( - SemConvConstants.OTEL_COMPONENT_NAME, - "periodic_metric_reader/0")))); + .hasHistogramSatisfying(h -> + h.hasPointsSatisfying(p -> + p.hasCount(1) + .hasAttributesSatisfying( + equalTo( + SemConvConstants.OTEL_COMPONENT_TYPE, + "periodic_metric_reader"), + equalTo( + SemConvConstants.OTEL_COMPONENT_NAME, + "periodic_metric_reader/0")))); }); } } @@ -90,18 +88,15 @@ void collectionFailureIsRecordedWithErrorType() { meterProvider.forceFlush().join(10, TimeUnit.SECONDS); assertThat(metricExporter.getFinishedMetricItems()) - .anySatisfy( - m -> - assertThat(m) - .hasName("otel.sdk.metric_reader.collection.duration") - .hasHistogramSatisfying( - h -> - h.hasPointsSatisfying( - p -> - p.hasAttributesSatisfying( - equalTo( - SemConvConstants.ERROR_TYPE, - "java.lang.IllegalStateException"))))); + .anySatisfy(m -> + assertThat(m) + .hasName("otel.sdk.metric_reader.collection.duration") + .hasHistogramSatisfying(h -> + h.hasPointsSatisfying(p -> + p.hasAttributesSatisfying( + equalTo( + SemConvConstants.ERROR_TYPE, + "java.lang.IllegalStateException"))))); } } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java index d6e3c1621dc..e71204f4bd0 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java @@ -112,100 +112,85 @@ void collectAllSyncInstruments() { doubleValueRecorder.record(10.1, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("")) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("")) .satisfiesExactlyInAnyOrder( metric -> assertThat(metric) .hasName("testDoubleHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(1) - .hasSum(10.1) - .hasBucketCounts( - 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(1) + .hasSum(10.1) + .hasBucketCounts(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), metric -> assertThat(metric) .hasName("testDoubleCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10.1))), + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10.1))), metric -> assertThat(metric) .hasName("testLongHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(1) - .hasSum(10) - .hasBucketCounts( - 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(1) + .hasSum(10) + .hasBucketCounts(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), metric -> assertThat(metric) .hasName("testLongUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10))), metric -> assertThat(metric) .hasName("testLongCounter") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10))), + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10))), metric -> assertThat(metric) .hasName("testDoubleUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10.1)))); + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10.1)))); } @Test @@ -229,44 +214,38 @@ void collectAllSyncInstruments_OverwriteTemporality() { testClock.advance(Duration.ofSeconds(1)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testLongCounter") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testLongCounter") + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))); longCounter.add(10, Attributes.empty()); testClock.advance(Duration.ofSeconds(1)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))); } @Test @@ -293,24 +272,21 @@ void collectAllSyncInstruments_DeltaHistogram() { testClock.advance(Duration.ofSeconds(1)); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("") + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))) .extracting(MetricData::getName) .containsExactlyInAnyOrder( "testLongCounter", "testDoubleCounter", "testLongHistogram", "testDoubleHistogram"); @@ -323,24 +299,21 @@ void collectAllSyncInstruments_DeltaHistogram() { doubleHistogram.record(10, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("") + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))) .extracting(MetricData::getName) .containsExactlyInAnyOrder( "testLongCounter", "testDoubleCounter", "testLongHistogram", "testDoubleHistogram"); @@ -376,94 +349,81 @@ void collectAllAsyncInstruments() { .buildWithCallback(doubleResult -> doubleResult.record(10.1, Attributes.empty())); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("")) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("")) .satisfiesExactlyInAnyOrder( metric -> assertThat(metric) .hasName("testLongSumObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10))), + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10))), metric -> assertThat(metric) .hasName("testDoubleSumObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10.1))), + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10.1))), metric -> assertThat(metric) .hasName("testLongUpDownSumObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10))), metric -> assertThat(metric) .hasName("testDoubleUpDownSumObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10.1))), + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10.1))), metric -> assertThat(metric) .hasName("testLongValueObserver") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10))), + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10))), metric -> assertThat(metric) .hasName("testDoubleValueObserver") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10.1)))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10.1)))); } @Test @@ -475,38 +435,32 @@ void removeAsyncInstrument() { ObservableLongCounter observableCounter1 = meter .counterBuilder("foo") - .buildWithCallback( - measurement -> - measurement.record(10, Attributes.builder().put("callback", "one").build())); + .buildWithCallback(measurement -> + measurement.record(10, Attributes.builder().put("callback", "one").build())); ObservableLongCounter observableCounter2 = meter .counterBuilder("foo") - .buildWithCallback( - measurement -> - measurement.record(10, Attributes.builder().put("callback", "two").build())); + .buildWithCallback(measurement -> + measurement.record(10, Attributes.builder().put("callback", "two").build())); assertThat(reader.collectAllMetrics()) .hasSize(1) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> point.hasAttributes(attributeEntry("callback", "one")), - point -> point.hasAttributes(attributeEntry("callback", "two"))))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasAttributes(attributeEntry("callback", "one")), + point -> point.hasAttributes(attributeEntry("callback", "two"))))); observableCounter1.close(); assertThat(reader.collectAllMetrics()) .hasSize(1) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> point.hasAttributes(attributeEntry("callback", "two"))))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasAttributes(attributeEntry("callback", "two"))))); observableCounter2.close(); assertThat(reader.collectAllMetrics()).hasSize(0); @@ -550,12 +504,11 @@ void collectAllMetrics_NoConcurrentCalls() // If callback is in invoked concurrently, only one metric data will be reported assertThat(allMetricData) .hasSize(4) - .allSatisfy( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(InstrumentationScopeInfo.create("meter")) - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .allSatisfy(metricData -> + assertThat(metricData) + .hasInstrumentationScope(InstrumentationScopeInfo.create("meter")) + .hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } finally { executorService.shutdown(); } @@ -576,19 +529,15 @@ void viewSdk_filterAttributes() { .gaugeBuilder("test") .setDescription("desc") .setUnit("unit") - .buildWithCallback( - o -> - o.record( - 1, - Attributes.builder().put("allowed", "bear").put("not allowed", "dog").build())); + .buildWithCallback(o -> + o.record( + 1, Attributes.builder().put("allowed", "bear").put("not allowed", "dog").build())); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(attributeEntry("allowed", "bear"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(attributeEntry("allowed", "bear"))))); } @Test @@ -612,13 +561,12 @@ void viewSdk_AllowRenames() { .setUnit("unit") .buildWithCallback(o -> o.record(1)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("not_test") - .hasDescription("not_desc") - .hasUnit("unit") - .hasDoubleGaugeSatisfying(gauge -> {})); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("not_test") + .hasDescription("not_desc") + .hasUnit("unit") + .hasDoubleGaugeSatisfying(gauge -> {})); } @Test @@ -727,78 +675,72 @@ void sdkMeterProvider_supportsMultipleReadersCumulative() { testClock.advance(Duration.ofSeconds(1)); assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); counter.add(1L); testClock.advance(Duration.ofSeconds(1)); // Reader 2 should see the measurements of Reader 1 plus the additional measurement assertThat(reader2.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(2) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(2) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); // Reader 1 should see updated cumulative values assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(2) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(2) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); } @Test @@ -817,27 +759,25 @@ void sdkMeterProvider_supportsMultipleReadersDelta() { testClock.advance(Duration.ofSeconds(1)); assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); long collectorOneTimeOne = testClock.now(); counter.add(1L); @@ -845,44 +785,39 @@ void sdkMeterProvider_supportsMultipleReadersDelta() { // Reader 2 should see the measurements of Reader 1 plus the additional measurement assertThat(reader2.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(2) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(2) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); // Reader 1 should only see diff since its last collect assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(collectorOneTimeOne) - .hasEpochNanos(testClock.now()) - .hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(collectorOneTimeOne) + .hasEpochNanos(testClock.now()) + .hasValue(1)))); } @Test @@ -919,20 +854,16 @@ void collectAll_AsyncInstrumentAlwaysOnExemplars() { .buildWithCallback(measurement -> measurement.record(1, Attributes.empty())); assertThat(collector.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("async-counter") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(Attributes.empty()) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(1))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("async-counter") + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(1) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(1))))); } @Test diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java index 49a92aa3a3b..2c4c1ccdb4b 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java @@ -115,20 +115,17 @@ void metricProducer_GetAllMetrics() { longCounter2.add(10, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasName("testLongCounter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(10) - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now())))) + .allSatisfy(metric -> + assertThat(metric) + .hasName("testLongCounter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasValue(10) + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now())))) .extracting(MetricData::getInstrumentationScopeInfo) .containsExactlyInAnyOrder( ((SdkMeter) sdkMeter1).getInstrumentationScopeInfo(), diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java index 93fa99a5942..67bd6abb66a 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java @@ -45,11 +45,10 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); @@ -100,44 +99,38 @@ void collectMetrics_WithOneRecord() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleSumObserver") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDescription("My own DoubleSumObserver") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -160,47 +153,40 @@ void collectMetrics_DeltaSumAggregator() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleSumObserver") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes( - Attributes.builder().put("k", "v").build())))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDescription("My own DoubleSumObserver") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(Attributes.builder().put("k", "v").build())))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleSumObserver") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDescription("My own DoubleSumObserver") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -216,14 +202,11 @@ void collectMetrics_DefaultExemplarFilter_NoExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> point.hasValue(12.1d).hasExemplars()))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12.1d).hasExemplars()))); } @Test @@ -242,17 +225,13 @@ void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(12.1d) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(12.1d))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12.1d) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12.1d))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java index 6ae2b8e9763..457c5e943a1 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java @@ -47,11 +47,10 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); @@ -100,42 +99,36 @@ void collectMetrics_WithOneRecord() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -158,42 +151,36 @@ void collectMetrics_DeltaSumAggregator() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -216,14 +203,11 @@ void collectMetrics_DefaultExemplarFilter_NoExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> point.hasValue(12.1d).hasExemplars()))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12.1d).hasExemplars()))); } @Test @@ -242,17 +226,13 @@ void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(12.1d) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(12.1d))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12.1d) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12.1d))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java index 4ff6e09e546..78afd4c4f1b 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java @@ -41,11 +41,10 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); @@ -77,42 +76,36 @@ void collectMetrics_WithOneRecord() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -131,42 +124,36 @@ void collectMetrics_DeltaSumAggregator() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -181,13 +168,11 @@ void collectMetrics_DefaultExemplarFilter_NoExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); } @Test @@ -205,17 +190,13 @@ void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(12) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(12))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java index b316bc8c6e0..3f1efcbad09 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java @@ -41,11 +41,10 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); @@ -77,42 +76,36 @@ void collectMetrics_WithOneRecord() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -133,42 +126,36 @@ void collectMetrics_DeltaSumAggregator() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -183,13 +170,11 @@ void collectMetrics_DefaultExemplarFilter_NoExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); } @Test @@ -207,17 +192,13 @@ void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(12) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(12))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java index c41f23233e9..b0690c2ffa2 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java @@ -198,47 +198,44 @@ void metricData_HistogramPoints() { AggregationTemporality.DELTA, Collections.singleton(HISTOGRAM_POINT))); assertThat(metricData.getHistogramData().getPoints()).containsExactly(HISTOGRAM_POINT); - assertThatThrownBy( - () -> - ImmutableHistogramPointData.create( - 0, - 0, - Attributes.empty(), - 0.0, - /* hasMin= */ false, - 0.0, - /* hasMax= */ false, - 0.0, - ImmutableList.of(), - ImmutableList.of())) + assertThatThrownBy(() -> + ImmutableHistogramPointData.create( + 0, + 0, + Attributes.empty(), + 0.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + ImmutableList.of(), + ImmutableList.of())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - ImmutableHistogramPointData.create( - 0, - 0, - Attributes.empty(), - 0.0, - /* hasMin= */ false, - 0.0, - /* hasMax= */ false, - 0.0, - ImmutableList.of(1.0, 1.0), - ImmutableList.of(0L, 0L, 0L))) + assertThatThrownBy(() -> + ImmutableHistogramPointData.create( + 0, + 0, + Attributes.empty(), + 0.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + ImmutableList.of(1.0, 1.0), + ImmutableList.of(0L, 0L, 0L))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - ImmutableHistogramPointData.create( - 0, - 0, - Attributes.empty(), - 0.0, - /* hasMin= */ false, - 0.0, - /* hasMax= */ false, - 0.0, - ImmutableList.of(Double.NEGATIVE_INFINITY), - ImmutableList.of(0L, 0L))) + assertThatThrownBy(() -> + ImmutableHistogramPointData.create( + 0, + 0, + Attributes.empty(), + 0.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + ImmutableList.of(Double.NEGATIVE_INFINITY), + ImmutableList.of(0L, 0L))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java index 0021192a235..4b99e18e7b7 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java @@ -425,11 +425,10 @@ public CompletableResultCode shutdown() { // Shutdown in background — should block waiting for in-flight export CountDownLatch shutdownDone = new CountDownLatch(1); Thread shutdownThread = - new Thread( - () -> { - reader.shutdown(); - shutdownDone.countDown(); - }); + new Thread(() -> { + reader.shutdown(); + shutdownDone.countDown(); + }); shutdownThread.setDaemon(true); shutdownThread.start(); @@ -461,9 +460,8 @@ void invalidConfig() { assertThatThrownBy(() -> PeriodicMetricReader.builder(metricExporter).setInterval(1, null)) .isInstanceOf(NullPointerException.class) .hasMessage("unit"); - assertThatThrownBy( - () -> - PeriodicMetricReader.builder(metricExporter).setInterval(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + PeriodicMetricReader.builder(metricExporter).setInterval(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("interval must be positive"); assertThatThrownBy(() -> PeriodicMetricReader.builder(metricExporter).setInterval(null)) @@ -705,10 +703,8 @@ public CompletableResultCode shutdown() { @Test void setExporterTimeout_negativeThrows() { - assertThatThrownBy( - () -> - PeriodicMetricReader.builder(metricExporter) - .setExporterTimeout(Duration.ofSeconds(-1))) + assertThatThrownBy(() -> + PeriodicMetricReader.builder(metricExporter).setExporterTimeout(Duration.ofSeconds(-1))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("timeout must be non-negative"); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregatorTest.java index 42a55878297..2100f3dccb6 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregatorTest.java @@ -375,31 +375,25 @@ void testToMetricData(MemoryMode memoryMode) { // Assertions run twice to verify immutability; recordings shouldn't modify the metric data for (int i = 0; i < 2; i++) { assertThat(metricDataCumulative) - .hasExponentialHistogramSatisfying( - expHistogram -> - expHistogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasSum(123.456) - .hasScale(20) - .hasZeroCount(2) - .hasCount(3) - .hasMin(0) - .hasMax(123.456) - .hasExemplars(exemplar) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasCounts(Collections.singletonList(1L)) - .hasOffset(valueToIndex(20, 123.456)) - .hasTotalCount(1)) - .hasNegativeBucketsSatisfying( - buckets -> - buckets - .hasTotalCount(0) - .hasCounts(Collections.emptyList())))); + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasSum(123.456) + .hasScale(20) + .hasZeroCount(2) + .hasCount(3) + .hasMin(0) + .hasMax(123.456) + .hasExemplars(exemplar) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasCounts(Collections.singletonList(1L)) + .hasOffset(valueToIndex(20, 123.456)) + .hasTotalCount(1)) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasTotalCount(0).hasCounts(Collections.emptyList())))); aggregatorHandle.recordDouble(1, Attributes.empty(), Context.current()); aggregatorHandle.recordDouble(-1, Attributes.empty(), Context.current()); aggregatorHandle.recordDouble(0, Attributes.empty(), Context.current()); @@ -431,18 +425,16 @@ void testMultithreadedUpdates(MemoryMode memoryMode) throws InterruptedException executor.invokeAll( updates.stream() - .map( - v -> - Executors.callable( - () -> { - for (int j = 0; j < numberOfUpdates; j++) { - aggregatorHandle.recordDouble(v, Attributes.empty(), Context.current()); - if (ThreadLocalRandom.current().nextInt(10) == 0) { - aggregatorHandle.aggregateThenMaybeReset( - 0, 1, Attributes.empty(), /* reset= */ false); - } - } - })) + .map(v -> + Executors.callable(() -> { + for (int j = 0; j < numberOfUpdates; j++) { + aggregatorHandle.recordDouble(v, Attributes.empty(), Context.current()); + if (ThreadLocalRandom.current().nextInt(10) == 0) { + aggregatorHandle.aggregateThenMaybeReset( + 0, 1, Attributes.empty(), /* reset= */ false); + } + } + })) .collect(Collectors.toList())); ExponentialHistogramPointData point = diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java index 0d12083f306..e3676182e3e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java @@ -240,17 +240,15 @@ void toMetricDataWithExemplars(MemoryMode memoryMode) { METRIC_DESCRIPTOR, Collections.singletonList(histPoint), AggregationTemporality.CUMULATIVE)) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(2) - .hasMin(2) - .hasMax(2) - .hasBucketCounts(1, 0, 0, 0) - .hasCount(1) - .hasExemplars(exemplar))); + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasSum(2) + .hasMin(2) + .hasMax(2) + .hasBucketCounts(1, 0, 0, 0) + .hasCount(1) + .hasExemplars(exemplar))); } @ParameterizedTest diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java index 2a110096444..0485ca2669a 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java @@ -243,15 +243,13 @@ void toMetricData(MemoryMode memoryMode) { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasAttributes(Attributes.empty()) - .hasStartEpochNanos(10) - .hasEpochNanos(100) - .hasValue(10))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasAttributes(Attributes.empty()) + .hasStartEpochNanos(10) + .hasEpochNanos(100) + .hasValue(10))); } @Test diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java index 1e4353b21fc..04b92566f9d 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java @@ -331,17 +331,15 @@ void toMetricData(MemoryMode memoryMode) { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(100) - .hasAttributes(Attributes.empty()) - .hasValue(10))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(0) + .hasEpochNanos(100) + .hasAttributes(Attributes.empty()) + .hasValue(10))); } @ParameterizedTest diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java index b984731190c..c0fc8ec2e2d 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java @@ -329,17 +329,15 @@ void toMetricData(MemoryMode memoryMode) { .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(100) - .hasAttributes(Attributes.empty()) - .hasValue(10))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(0) + .hasEpochNanos(100) + .hasAttributes(Attributes.empty()) + .hasValue(10))); } @ParameterizedTest diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointDataTest.java index 514c5c84411..961651b687e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointDataTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointDataTest.java @@ -106,38 +106,36 @@ void testSanity() { @Test void testBoundaries() { MutableHistogramPointData pointData = new MutableHistogramPointData(10); - assertThatThrownBy( - () -> - pointData.set( - /* startEpochNanos= */ 10, - /* epochNanos= */ 20, - Attributes.of(AttributeKey.stringKey("foo"), "bar"), - /* sum= */ 2, - /* hasMin= */ true, - /* min= */ 100, - /* hasMax= */ true, - /* max= */ 1000, - /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0), - /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, - Collections.emptyList())) + assertThatThrownBy(() -> + pointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, + Collections.emptyList())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid boundaries: size should be 9 but was 4"); - assertThatThrownBy( - () -> - pointData.set( - /* startEpochNanos= */ 10, - /* epochNanos= */ 20, - Attributes.of(AttributeKey.stringKey("foo"), "bar"), - /* sum= */ 2, - /* hasMin= */ true, - /* min= */ 100, - /* hasMax= */ true, - /* max= */ 1000, - /* boundaries= */ Arrays.asList( - 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, Double.POSITIVE_INFINITY), - /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, - Collections.emptyList())) + assertThatThrownBy(() -> + pointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList( + 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, Double.POSITIVE_INFINITY), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, + Collections.emptyList())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid boundaries: contains explicit +/-Inf"); } @@ -145,20 +143,19 @@ void testBoundaries() { @Test void testCounts() { MutableHistogramPointData pointData = new MutableHistogramPointData(10); - assertThatThrownBy( - () -> - pointData.set( - /* startEpochNanos= */ 10, - /* epochNanos= */ 20, - Attributes.of(AttributeKey.stringKey("foo"), "bar"), - /* sum= */ 2, - /* hasMin= */ true, - /* min= */ 100, - /* hasMax= */ true, - /* max= */ 1000, - /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), - /* counts= */ new long[] {10, 20, 30, 40, 50, 60}, - Collections.emptyList())) + assertThatThrownBy(() -> + pointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60}, + Collections.emptyList())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid counts: size should be 10 but was 6"); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java index dc336673a78..cfe7a3080dd 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java @@ -40,35 +40,32 @@ void oneBucket_samplesEverything() { reservoir.offerDoubleMeasurement(1.1, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getValue()).isEqualTo(1.1); - assertThat(exemplar.getFilteredAttributes()).isEmpty(); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1.1); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); // Measurement count is reset, we should sample a new measurement (and only one) clock.advance(Duration.ofSeconds(1)); reservoir.offerDoubleMeasurement(2, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getValue()).isEqualTo(2); - assertThat(exemplar.getFilteredAttributes()).isEmpty(); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(2); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); // only latest measurement is kept per-bucket clock.advance(Duration.ofSeconds(1)); reservoir.offerDoubleMeasurement(3, Attributes.empty(), Context.root()); reservoir.offerDoubleMeasurement(4, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getValue()).isEqualTo(4); - assertThat(exemplar.getFilteredAttributes()).isEmpty(); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(4); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); } @Test @@ -85,11 +82,10 @@ void oneBucket_overwriteWithoutSpan_clearsSpanContext() { reservoir.offerDoubleMeasurement(1, Attributes.empty(), context); reservoir.offerDoubleMeasurement(2, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getValue()).isEqualTo(2); - assertThat(exemplar.getSpanContext()).isEqualTo(SpanContext.getInvalid()); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getValue()).isEqualTo(2); + assertThat(exemplar.getSpanContext()).isEqualTo(SpanContext.getInvalid()); + }); } @Test @@ -131,22 +127,20 @@ void longMeasurement_CastsToDouble() { reservoir.offerLongMeasurement(1L, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getValue()).isEqualTo(1); - assertThat(exemplar.getFilteredAttributes()).isEmpty(); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); // Measurement count is reset, we should sample a new measurement (and only one) clock.advance(Duration.ofSeconds(1)); reservoir.offerLongMeasurement(2, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getValue()).isEqualTo(2); - assertThat(exemplar.getFilteredAttributes()).isEmpty(); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(2); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoirTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoirTest.java index 07ac044acda..6439967c359 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoirTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoirTest.java @@ -40,24 +40,22 @@ public void oneMeasurement_alwaysSamplesFirstMeasurement() { reservoir.offerDoubleMeasurement(1.1, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getFilteredAttributes()).isEmpty(); - assertThat(exemplar.getValue()).isEqualTo(1.1); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + assertThat(exemplar.getValue()).isEqualTo(1.1); + }); // Measurement count is reset, we should sample a new measurement (and only one) clock.advance(Duration.ofSeconds(1)); reservoir.offerDoubleMeasurement(2, Attributes.empty(), Context.root()); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getFilteredAttributes()).isEmpty(); - assertThat(exemplar.getValue()).isEqualTo(2); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + assertThat(exemplar.getValue()).isEqualTo(2); + }); } @Test @@ -71,12 +69,11 @@ public void oneMeasurement_filtersAttributes() { RandomFixedSizeExemplarReservoir.create(clock, 1, RandomSupplier.platformDefault()); reservoir.offerDoubleMeasurement(1.1, all, Context.root()); assertThat(reservoir.collectAndResetDoubles(partial)) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getValue()).isEqualTo(1.1); - assertThat(exemplar.getFilteredAttributes()).isEqualTo(remaining); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1.1); + assertThat(exemplar.getFilteredAttributes()).isEqualTo(remaining); + }); } @Test @@ -94,14 +91,13 @@ public void oneMeasurement_includesTraceAndSpanIds() { RandomFixedSizeExemplarReservoir.create(clock, 1, RandomSupplier.platformDefault()); reservoir.offerDoubleMeasurement(1, all, context); assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) - .satisfiesExactly( - exemplar -> { - assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); - assertThat(exemplar.getValue()).isEqualTo(1); - assertThat(exemplar.getFilteredAttributes()).isEqualTo(all); - assertThat(exemplar.getSpanContext().getTraceId()).isEqualTo(TRACE_ID); - assertThat(exemplar.getSpanContext().getSpanId()).isEqualTo(SPAN_ID); - }); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1); + assertThat(exemplar.getFilteredAttributes()).isEqualTo(all); + assertThat(exemplar.getSpanContext().getTraceId()).isEqualTo(TRACE_ID); + assertThat(exemplar.getSpanContext().getSpanId()).isEqualTo(SPAN_ID); + }); } @Test diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java index f1dd1a13d13..6133bbdff02 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java @@ -134,18 +134,13 @@ void recordLong(MemoryMode memoryMode) { longCounterStorage.record(Attributes.builder().put("key", "c").build(), 3); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .satisfies( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(1).hasAttributes(attributeEntry("key", "a")), - point -> - point.hasValue(2).hasAttributes(attributeEntry("key", "b")), - point -> - point.hasValue(3).hasAttributes(attributeEntry("key", "c"))))); + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(1).hasAttributes(attributeEntry("key", "a")), + point -> point.hasValue(2).hasAttributes(attributeEntry("key", "b")), + point -> point.hasValue(3).hasAttributes(attributeEntry("key", "c"))))); assertThat(logs.size()).isEqualTo(0); } @@ -159,20 +154,13 @@ void recordDouble(MemoryMode memoryMode) { doubleCounterStorage.record(Attributes.builder().put("key", "c").build(), 3.3); assertThat(doubleCounterStorage.collect(resource, scope, testClock.now())) - .satisfies( - metricData -> - assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(1.1).hasAttributes(attributeEntry("key", "a")), - point -> - point.hasValue(2.2).hasAttributes(attributeEntry("key", "b")), - point -> - point - .hasValue(3.3) - .hasAttributes(attributeEntry("key", "c"))))); + .satisfies(metricData -> + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(1.1).hasAttributes(attributeEntry("key", "a")), + point -> point.hasValue(2.2).hasAttributes(attributeEntry("key", "b")), + point -> point.hasValue(3.3).hasAttributes(attributeEntry("key", "c"))))); assertThat(logs.size()).isEqualTo(0); } @@ -204,14 +192,11 @@ void record_ProcessesAttributes(MemoryMode memoryMode) { storage.record(Attributes.builder().put("key1", "a").put("key2", "b").build(), 1); assertThat(storage.collect(resource, scope, testClock.now())) - .satisfies( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(1).hasAttributes(attributeEntry("key1", "a"))))); + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(1).hasAttributes(attributeEntry("key1", "a"))))); assertThat(logs.size()).isEqualTo(0); } @@ -225,9 +210,8 @@ void record_MaxCardinality(MemoryMode memoryMode) { } assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .satisfies( - metricData -> - assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT)); + .satisfies(metricData -> + assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT)); logs.assertContains("Instrument long-counter has exceeded the maximum allowed cardinality"); } @@ -241,9 +225,8 @@ void record_DeltaHandlesSpotsAreReleasedAfterCollection(MemoryMode memoryMode) { } assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .satisfies( - metricData -> - assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT - 1)); + .satisfies(metricData -> + assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT - 1)); logs.assertDoesNotContain( "Instrument long-counter has exceeded the maximum allowed cardinality"); @@ -253,9 +236,8 @@ void record_DeltaHandlesSpotsAreReleasedAfterCollection(MemoryMode memoryMode) { } assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .satisfies( - metricData -> - assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT - 1)); + .satisfies(metricData -> + assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT - 1)); logs.assertDoesNotContain( "Instrument long-counter has exceeded the maximum allowed cardinality"); } @@ -269,14 +251,11 @@ void record_DuplicateAttributes(MemoryMode memoryMode) { longCounterStorage.record(Attributes.builder().put("key1", "a").build(), 2); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .satisfies( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(3).hasAttributes(attributeEntry("key1", "a"))))); + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(3).hasAttributes(attributeEntry("key1", "a"))))); } @ParameterizedTest @@ -288,16 +267,14 @@ void collect_CumulativeReportsCumulativeObservations(MemoryMode memoryMode) { testClock.advance(Duration.ofSeconds(10)); longCounterStorage.record(Attributes.empty(), 3); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(START_SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(3) - .hasAttributes(Attributes.empty()))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(3) + .hasAttributes(Attributes.empty()))); registeredReader.setLastCollectEpochNanos(testClock.now()); // Record measurements and collect at time START_SECONDS + 30s @@ -305,23 +282,21 @@ void collect_CumulativeReportsCumulativeObservations(MemoryMode memoryMode) { longCounterStorage.record(Attributes.empty(), 3); longCounterStorage.record(Attributes.builder().put("key", "value1").build(), 6); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(START_SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(3) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos( - testClock.now() - Duration.ofSeconds(20).toNanos()) - .hasEpochNanos(testClock.now()) - .hasValue(6) - .hasAttributes(Attributes.builder().put("key", "value1").build()))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(3) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(testClock.now() - Duration.ofSeconds(20).toNanos()) + .hasEpochNanos(testClock.now()) + .hasValue(6) + .hasAttributes(Attributes.builder().put("key", "value1").build()))); registeredReader.setLastCollectEpochNanos(testClock.now()); // Record measurement and collect at time START_SECONDS + 35s @@ -329,23 +304,21 @@ void collect_CumulativeReportsCumulativeObservations(MemoryMode memoryMode) { longCounterStorage.record(Attributes.empty(), 4); longCounterStorage.record(Attributes.builder().put("key", "value2").build(), 5); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(START_SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(4) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos( - testClock.now() - Duration.ofSeconds(5).toNanos()) - .hasEpochNanos(testClock.now()) - .hasValue(5) - .hasAttributes(Attributes.builder().put("key", "value2").build()))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(4) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(testClock.now() - Duration.ofSeconds(5).toNanos()) + .hasEpochNanos(testClock.now()) + .hasValue(5) + .hasAttributes(Attributes.builder().put("key", "value2").build()))); } @ParameterizedTest @@ -362,35 +335,29 @@ void collect_CumulativeSeriesDisappearsAndReappears(MemoryMode memoryMode) { longCounterStorage.record(attrA, 1); longCounterStorage.record(attrB, 2); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(START_SECOND_NANOS) - .hasAttributes(attrA) - .hasValue(1), - point -> - point - .hasStartEpochNanos(START_SECOND_NANOS) - .hasAttributes(attrB) - .hasValue(2))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasAttributes(attrA) + .hasValue(1), + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasAttributes(attrB) + .hasValue(2))); registeredReader.setLastCollectEpochNanos(testClock.now()); // Collection 2: only attrA reported; attrB disappears and its handle is removed. testClock.advance(Duration.ofSeconds(10)); longCounterStorage.record(attrA, 3); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(START_SECOND_NANOS) - .hasAttributes(attrA) - .hasValue(3))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(START_SECOND_NANOS).hasAttributes(attrA).hasValue(3))); registeredReader.setLastCollectEpochNanos(testClock.now()); long collectTime2 = testClock.now(); @@ -400,20 +367,16 @@ void collect_CumulativeSeriesDisappearsAndReappears(MemoryMode memoryMode) { longCounterStorage.record(attrA, 5); longCounterStorage.record(attrB, 7); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(START_SECOND_NANOS) - .hasAttributes(attrA) - .hasValue(5), - point -> - point - .hasStartEpochNanos(collectTime2) - .hasAttributes(attrB) - .hasValue(7))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasAttributes(attrA) + .hasValue(5), + point -> + point.hasStartEpochNanos(collectTime2).hasAttributes(attrB).hasValue(7))); } @ParameterizedTest @@ -476,60 +439,56 @@ void collect_DeltaComputesDiff(MemoryMode memoryMode) { // Record measurement and collect at time 10 longCounterStorage.record(Attributes.empty(), 3); assertThat(longCounterStorage.collect(resource, scope, 10)) - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(10) - .hasValue(3) - .hasAttributes(Attributes.empty()))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(10) + .hasValue(3) + .hasAttributes(Attributes.empty()))); registeredReader.setLastCollectEpochNanos(10); // Record measurement and collect at time 30 longCounterStorage.record(Attributes.empty(), 3); longCounterStorage.record(Attributes.builder().put("key", "value1").build(), 6); assertThat(longCounterStorage.collect(resource, scope, 30)) - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(10) - .hasEpochNanos(30) - .hasValue(0) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(10) - .hasEpochNanos(30) - .hasValue(6) - .hasAttributes(Attributes.builder().put("key", "value1").build()))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(10) + .hasEpochNanos(30) + .hasValue(0) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(10) + .hasEpochNanos(30) + .hasValue(6) + .hasAttributes(Attributes.builder().put("key", "value1").build()))); registeredReader.setLastCollectEpochNanos(30); // Record measurement and collect at time 35 longCounterStorage.record(Attributes.empty(), 4); longCounterStorage.record(Attributes.builder().put("key", "value2").build(), 5); assertThat(longCounterStorage.collect(resource, scope, 35)) - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(30) - .hasEpochNanos(35) - .hasValue(1) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(30) - .hasEpochNanos(35) - .hasValue(5) - .hasAttributes(Attributes.builder().put("key", "value2").build()))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(30) + .hasEpochNanos(35) + .hasValue(1) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(30) + .hasEpochNanos(35) + .hasValue(5) + .hasAttributes(Attributes.builder().put("key", "value2").build()))); } @ParameterizedTest @@ -540,14 +499,12 @@ void recordLong_AlwaysOnCollectsExemplars(MemoryMode memoryMode) { longCounterStorage.record(Attributes.empty(), 3); assertThat(longCounterStorage.collect(resource, scope, testClock.now())) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(3) - .hasAttributes(Attributes.empty()) - .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(3)))); + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(3) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(3)))); } @Test @@ -561,27 +518,25 @@ void collect_reusableData_reusedObjectsAreReturnedOnSecondCall() { MetricData firstCollectMetricData = longCounterStorage.collect(resource, scope, testClock.now()); assertThat(firstCollectMetricData) - .satisfies( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("key", "a")) - .isInstanceOf(MutableLongPointData.class), - point -> - point - .hasValue(2) - .hasAttributes(attributeEntry("key", "b")) - .isInstanceOf(MutableLongPointData.class), - point -> - point - .hasValue(3) - .hasAttributes(attributeEntry("key", "c")) - .isInstanceOf(MutableLongPointData.class)))); + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> + point + .hasValue(1) + .hasAttributes(attributeEntry("key", "a")) + .isInstanceOf(MutableLongPointData.class), + point -> + point + .hasValue(2) + .hasAttributes(attributeEntry("key", "b")) + .isInstanceOf(MutableLongPointData.class), + point -> + point + .hasValue(3) + .hasAttributes(attributeEntry("key", "c")) + .isInstanceOf(MutableLongPointData.class)))); MetricData secondCollectMetricData = longCounterStorage.collect(resource, scope, testClock.now()); diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMapTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMapTest.java index 8c68988a44a..800894a651b 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMapTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMapTest.java @@ -86,13 +86,12 @@ void forEachAllowsRemovalOfCurrentEntry() { collidingMap.put(second, 2); Map visited = new HashMap<>(); - collidingMap.forEach( - (key, value) -> { - visited.put(key, value); - if (visited.size() == 1) { - collidingMap.remove(key); // drop the first one we see - } - }); + collidingMap.forEach((key, value) -> { + visited.put(key, value); + if (visited.size() == 1) { + collidingMap.remove(key); // drop the first one we see + } + }); assertThat(visited).containsOnlyKeys(first, second).containsValues(1, 2); assertThat(collidingMap.size()).isEqualTo(1); diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java index d5d382d4809..4e8102c33c7 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java @@ -140,9 +140,8 @@ void attributeFilter_applied(MemoryMode memoryMode) { storage.recordDouble(1, attributes, Context.root()); MetricData md = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, testClock.now()); assertThat(md) - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying(point -> point.hasAttributes(attributeEntry("keep", "V")))); + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> point.hasAttributes(attributeEntry("keep", "V")))); } @ParameterizedTest @@ -164,45 +163,30 @@ void recordAndCollect_CumulativeDoesNotReset(MemoryMode memoryMode) { storage.recordDouble(3, Attributes.empty(), Context.current()); verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(10) - .hasValue(3))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(10).hasValue(3))); cumulativeReader.setLastCollectEpochNanos(10); // Record measurement and collect at time 30 storage.recordDouble(3, Attributes.empty(), Context.current()); verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(30) - .hasValue(6))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(30).hasValue(6))); cumulativeReader.setLastCollectEpochNanos(30); // Record measurement and collect at time 35 storage.recordDouble(2, Attributes.empty(), Context.current()); verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 35)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(35) - .hasValue(8))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(35).hasValue(8))); } @ParameterizedTest @@ -224,16 +208,14 @@ void recordAndCollect_CumulativeNewSeriesAfterFirstCollection(MemoryMode memoryM storage.recordDouble(3, Attributes.builder().put("series", "A").build(), Context.current()); long seriesACreationTime = testClock.now(); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(seriesACreationTime) - .hasEpochNanos(10) - .hasValue(3) - .hasAttributes(Attributes.builder().put("series", "A").build()))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(seriesACreationTime) + .hasEpochNanos(10) + .hasValue(3) + .hasAttributes(Attributes.builder().put("series", "A").build()))); cumulativeReader.setLastCollectEpochNanos(10); // Advance clock and record for both series A and a new series B @@ -244,22 +226,21 @@ void recordAndCollect_CumulativeNewSeriesAfterFirstCollection(MemoryMode memoryM // Series B's start time must be clock.now() at its first measurement, NOT instrument // creation time or last collection time. assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(seriesACreationTime) - .hasEpochNanos(30) - .hasValue(8) - .hasAttributes(Attributes.builder().put("series", "A").build()), - point -> - point - .hasStartEpochNanos(seriesBCreationTime) - .hasEpochNanos(30) - .hasValue(7) - .hasAttributes(Attributes.builder().put("series", "B").build()))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(seriesACreationTime) + .hasEpochNanos(30) + .hasValue(8) + .hasAttributes(Attributes.builder().put("series", "A").build()), + point -> + point + .hasStartEpochNanos(seriesBCreationTime) + .hasEpochNanos(30) + .hasValue(7) + .hasAttributes(Attributes.builder().put("series", "B").build()))); } @Test @@ -281,15 +262,10 @@ void recordAndCollect_DeltaResets_ImmutableData() { verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(10) - .hasValue(3))); + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(10).hasValue(3))); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(1); deltaReader.setLastCollectEpochNanos(10); @@ -300,11 +276,10 @@ void recordAndCollect_DeltaResets_ImmutableData() { verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(3))); + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(3))); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(1); deltaReader.setLastCollectEpochNanos(30); @@ -313,11 +288,10 @@ void recordAndCollect_DeltaResets_ImmutableData() { verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 35)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(30).hasEpochNanos(35).hasValue(2))); + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> point.hasStartEpochNanos(30).hasEpochNanos(35).hasValue(2))); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(1); } @@ -340,15 +314,10 @@ void recordAndCollect_DeltaResets_ReusableData() { verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(10) - .hasValue(3))); + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(10).hasValue(3))); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); deltaReader.setLastCollectEpochNanos(10); @@ -360,11 +329,10 @@ void recordAndCollect_DeltaResets_ReusableData() { verify(aggregator, times(2)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(3))); + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(3))); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); deltaReader.setLastCollectEpochNanos(30); @@ -382,28 +350,23 @@ void recordAndCollect_DeltaResets_ReusableData() { MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 35); assertThat(metricData).hasDoubleSumSatisfying(DoubleSumAssert::isDelta); assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(2) - .anySatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(30); - assertThat(point.getEpochNanos()).isEqualTo(35); - assertThat(point.getValue()).isEqualTo(2); - assertThat(point.getAttributes()).isEqualTo(Attributes.empty()); - }) - .anySatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(30); - assertThat(point.getEpochNanos()).isEqualTo(35); - assertThat(point.getValue()).isEqualTo(4); - assertThat(point.getAttributes()) - .isEqualTo( - Attributes.of(AttributeKey.stringKey("foo"), "bar")); - }))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(2) + .anySatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(30); + assertThat(point.getEpochNanos()).isEqualTo(35); + assertThat(point.getValue()).isEqualTo(2); + assertThat(point.getAttributes()).isEqualTo(Attributes.empty()); + }) + .anySatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(30); + assertThat(point.getEpochNanos()).isEqualTo(35); + assertThat(point.getValue()).isEqualTo(4); + assertThat(point.getAttributes()) + .isEqualTo(Attributes.of(AttributeKey.stringKey("foo"), "bar")); + }))); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); @@ -411,21 +374,17 @@ void recordAndCollect_DeltaResets_ReusableData() { storage.recordDouble(6, Attributes.of(AttributeKey.stringKey("foo"), "bar"), Context.current()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 45)) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(1) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(40); - assertThat(point.getEpochNanos()).isEqualTo(45); - assertThat(point.getValue()).isEqualTo(6); - assertThat(point.getAttributes()) - .isEqualTo( - Attributes.of(AttributeKey.stringKey("foo"), "bar")); - }))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(40); + assertThat(point.getEpochNanos()).isEqualTo(45); + assertThat(point.getValue()).isEqualTo(6); + assertThat(point.getAttributes()) + .isEqualTo(Attributes.of(AttributeKey.stringKey("foo"), "bar")); + }))); } @ParameterizedTest @@ -451,18 +410,15 @@ void recordAndCollect_CumulativeAtLimit(MemoryMode memoryMode) { } verify(aggregator, times(CARDINALITY_LIMIT - 1)).createHandle(testClock.now()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(CARDINALITY_LIMIT - 1) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); - assertThat(point.getEpochNanos()).isEqualTo(10); - assertThat(point.getValue()).isEqualTo(3); - }))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT - 1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + assertThat(point.getEpochNanos()).isEqualTo(10); + assertThat(point.getValue()).isEqualTo(3); + }))); assertThat(logs.getEvents()).isEmpty(); cumulativeReader.setLastCollectEpochNanos(10); @@ -472,29 +428,21 @@ void recordAndCollect_CumulativeAtLimit(MemoryMode memoryMode) { // Should not create an additional handles for the overflow series verify(aggregator, times(CARDINALITY_LIMIT)).createHandle(testClock.now()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(CARDINALITY_LIMIT) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); - assertThat(point.getEpochNanos()).isEqualTo(20); - assertThat(point.getValue()).isEqualTo(3); - }) - .noneMatch( - point -> - ("value" + CARDINALITY_LIMIT + 1) - .equals( - point - .getAttributes() - .get(AttributeKey.stringKey("key")))) - .satisfiesOnlyOnce( - point -> - assertThat(point.getAttributes()) - .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + assertThat(point.getEpochNanos()).isEqualTo(20); + assertThat(point.getValue()).isEqualTo(3); + }) + .noneMatch(point -> + ("value" + CARDINALITY_LIMIT + 1) + .equals(point.getAttributes().get(AttributeKey.stringKey("key")))) + .satisfiesOnlyOnce(point -> + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); logs.assertContains("Instrument name has exceeded the maximum allowed cardinality"); } @@ -521,18 +469,15 @@ void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { verify(aggregator, times(CARDINALITY_LIMIT - 1)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(CARDINALITY_LIMIT - 1) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); - assertThat(point.getEpochNanos()).isEqualTo(10); - assertThat(point.getValue()).isEqualTo(3); - }))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT - 1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + assertThat(point.getEpochNanos()).isEqualTo(10); + assertThat(point.getValue()).isEqualTo(3); + }))); assertThat(storage) .extracting("aggregatorHandlePool", as(collection(Object.class))) .hasSize(CARDINALITY_LIMIT - 1); @@ -549,19 +494,15 @@ void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { .extracting("aggregatorHandlePool", as(collection(Object.class))) .hasSize(CARDINALITY_LIMIT - 2); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(10) - .hasEpochNanos(20) - .hasValue(3) - .hasAttributes( - Attributes.builder() - .put("key", "value" + CARDINALITY_LIMIT) - .build()))); + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(10) + .hasEpochNanos(20) + .hasValue(3) + .hasAttributes( + Attributes.builder().put("key", "value" + CARDINALITY_LIMIT).build()))); assertThat(storage) .extracting("aggregatorHandlePool", as(collection(Object.class))) .hasSize(CARDINALITY_LIMIT - 1); @@ -578,29 +519,21 @@ void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { verify(aggregator, times(CARDINALITY_LIMIT)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(CARDINALITY_LIMIT) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(20); - assertThat(point.getEpochNanos()).isEqualTo(30); - assertThat(point.getValue()).isEqualTo(3); - }) - .noneMatch( - point -> - ("value" + CARDINALITY_LIMIT + 1) - .equals( - point - .getAttributes() - .get(AttributeKey.stringKey("key")))) - .satisfiesOnlyOnce( - point -> - assertThat(point.getAttributes()) - .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(20); + assertThat(point.getEpochNanos()).isEqualTo(30); + assertThat(point.getValue()).isEqualTo(3); + }) + .noneMatch(point -> + ("value" + CARDINALITY_LIMIT + 1) + .equals(point.getAttributes().get(AttributeKey.stringKey("key")))) + .satisfiesOnlyOnce(point -> + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); assertThat(storage) .extracting("aggregatorHandlePool", as(collection(Object.class))) @@ -634,19 +567,15 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode() { MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10); assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - Assertions.assertThat(sumData.getPoints()) - .hasSize(CARDINALITY_LIMIT - 1) - .allSatisfy( - point -> { - Assertions.assertThat(point.getStartEpochNanos()) - .isEqualTo(testClock.now()); - Assertions.assertThat(point.getEpochNanos()).isEqualTo(10); - Assertions.assertThat(point.getValue()).isEqualTo(3); - }))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + Assertions.assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT - 1) + .allSatisfy(point -> { + Assertions.assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + Assertions.assertThat(point.getEpochNanos()).isEqualTo(10); + Assertions.assertThat(point.getValue()).isEqualTo(3); + }))); assertThat(logs.getEvents()).isEmpty(); @@ -668,29 +597,21 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode() { metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20); assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(CARDINALITY_LIMIT) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(10); - assertThat(point.getEpochNanos()).isEqualTo(20); - assertThat(point.getValue()).isEqualTo(3); - }) - .noneMatch( - point -> - ("value" + CARDINALITY_LIMIT) - .equals( - point - .getAttributes() - .get(AttributeKey.stringKey("key")))) - .satisfiesOnlyOnce( - point -> - assertThat(point.getAttributes()) - .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(10); + assertThat(point.getEpochNanos()).isEqualTo(20); + assertThat(point.getValue()).isEqualTo(3); + }) + .noneMatch(point -> + ("value" + CARDINALITY_LIMIT) + .equals(point.getAttributes().get(AttributeKey.stringKey("key")))) + .satisfiesOnlyOnce(point -> + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).isEmpty(); @@ -789,57 +710,45 @@ private static void assertOnlyOverflowWasRecorded( MetricData metricData, long startTime, long endTime, double value) { assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(1) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(startTime); - assertThat(point.getEpochNanos()).isEqualTo(endTime); - assertThat(point.getValue()).isEqualTo(value); - assertThat(point.getAttributes()) - .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW); - }))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(startTime); + assertThat(point.getEpochNanos()).isEqualTo(endTime); + assertThat(point.getValue()).isEqualTo(value); + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW); + }))); } private static void assertNumberOfPoints(MetricData metricData, int numberOfPoints) { assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies(sumData -> assertThat(sumData.getPoints()).hasSize(numberOfPoints))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> assertThat(sumData.getPoints()).hasSize(numberOfPoints))); } private static void assertAllPointsWithValue( MetricData metricData, long startTime, long endTime, double value) { assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(startTime); - assertThat(point.getEpochNanos()).isEqualTo(endTime); - assertThat(point.getValue()).isEqualTo(value); - }))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(startTime); + assertThat(point.getEpochNanos()).isEqualTo(endTime); + assertThat(point.getValue()).isEqualTo(value); + }))); } private static void assertOverflowDoesNotExists(MetricData metricData) { assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.satisfies( - sumData -> - assertThat(sumData.getPoints()) - .noneMatch( - point -> - point - .getAttributes() - .equals(MetricStorage.CARDINALITY_OVERFLOW)))); + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .noneMatch(point -> + point.getAttributes().equals(MetricStorage.CARDINALITY_OVERFLOW)))); } @ParameterizedTest diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java index 9299babeb9f..b2cbb924321 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java @@ -24,36 +24,32 @@ void goodConfig() { @Test void badBuckets_throwArgumentException() { - assertThatThrownBy( - () -> - Aggregation.explicitBucketHistogram( - ExplicitBucketHistogramOptions.builder() - .setBucketBoundaries(Collections.singletonList(Double.NEGATIVE_INFINITY)) - .build())) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.singletonList(Double.NEGATIVE_INFINITY)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid bucket boundary: -Inf"); - assertThatThrownBy( - () -> - Aggregation.explicitBucketHistogram( - ExplicitBucketHistogramOptions.builder() - .setBucketBoundaries(Arrays.asList(1.0, Double.POSITIVE_INFINITY)) - .build())) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, Double.POSITIVE_INFINITY)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid bucket boundary: +Inf"); - assertThatThrownBy( - () -> - Aggregation.explicitBucketHistogram( - ExplicitBucketHistogramOptions.builder() - .setBucketBoundaries(Arrays.asList(1.0, Double.NaN)) - .build())) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, Double.NaN)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid bucket boundary: NaN"); - assertThatThrownBy( - () -> - Aggregation.explicitBucketHistogram( - ExplicitBucketHistogramOptions.builder() - .setBucketBoundaries(Arrays.asList(2.0, 1.0, 3.0)) - .build())) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(2.0, 1.0, 3.0)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Bucket boundaries must be in increasing order: 2.0 >= 1.0"); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributesTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributesTest.java index ebbcb744460..b2c5b7ff946 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributesTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributesTest.java @@ -139,12 +139,11 @@ void largeAttributes() { Set> allKeys = new HashSet<>(); AttributesBuilder allAttributesBuilder = Attributes.builder(); IntStream.range(0, 100) - .forEach( - i -> { - AttributeKey key = stringKey("key" + i); - allKeys.add(key); - allAttributesBuilder.put(key, "value" + i); - }); + .forEach(i -> { + AttributeKey key = stringKey("key" + i); + allKeys.add(key); + allAttributesBuilder.put(key, "value" + i); + }); Attributes allAttributes = allAttributesBuilder.build(); Attributes empty = FilteredAttributes.create(allAttributes, Collections.emptySet()); @@ -156,28 +155,26 @@ void largeAttributes() { assertThat(one.size()).isEqualTo(1); assertThat(one.isEmpty()).isFalse(); allKeys.stream() - .forEach( - key -> { - if (oneKey.contains(key)) { - assertThat(one.get(key)).isNotNull(); - } else { - assertThat(one.get(key)).isNull(); - } - }); + .forEach(key -> { + if (oneKey.contains(key)) { + assertThat(one.get(key)).isNotNull(); + } else { + assertThat(one.get(key)).isNull(); + } + }); Set> tenKeys = allKeys.stream().limit(10).collect(Collectors.toSet()); Attributes ten = FilteredAttributes.create(allAttributes, tenKeys); assertThat(ten.size()).isEqualTo(10); assertThat(ten.isEmpty()).isFalse(); allKeys.stream() - .forEach( - key -> { - if (tenKeys.contains(key)) { - assertThat(ten.get(key)).isNotNull(); - } else { - assertThat(ten.get(key)).isNull(); - } - }); + .forEach(key -> { + if (tenKeys.contains(key)) { + assertThat(ten.get(key)).isNotNull(); + } else { + assertThat(ten.get(key)).isNull(); + } + }); } @Test diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/AttributesAdviceTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/AttributesAdviceTest.java index e231a84d364..ddfff8d611a 100644 --- a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/AttributesAdviceTest.java +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/AttributesAdviceTest.java @@ -82,10 +82,9 @@ void instrumentWithoutAdvice( instrument.record(1, ATTRIBUTES); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - pointsAssert.hasPointSatisfying( - assertThat(metric), point -> point.hasAttributes(ATTRIBUTES))); + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), point -> point.hasAttributes(ATTRIBUTES))); } @ParameterizedTest @@ -101,13 +100,12 @@ void instrumentWithAdvice( instrument.record(1, ATTRIBUTES); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - pointsAssert.hasPointSatisfying( - assertThat(metric), - point -> - point.hasAttributesSatisfyingExactly( - equalTo(stringKey("key1"), "1"), equalTo(stringKey("key2"), "2")))); + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), + point -> + point.hasAttributesSatisfyingExactly( + equalTo(stringKey("key1"), "1"), equalTo(stringKey("key2"), "2")))); } @ParameterizedTest @@ -131,13 +129,12 @@ void instrumentWithAdviceAndViews( instrument.record(1, ATTRIBUTES); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - pointsAssert.hasPointSatisfying( - assertThat(metric), - point -> - point.hasAttributesSatisfyingExactly( - equalTo(stringKey("key2"), "2"), equalTo(stringKey("key3"), "3")))); + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), + point -> + point.hasAttributesSatisfyingExactly( + equalTo(stringKey("key2"), "2"), equalTo(stringKey("key3"), "3")))); } @ParameterizedTest @@ -161,15 +158,14 @@ void instrumentWithAdviceAndDescriptionViews( instrument.record(1, ATTRIBUTES); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - pointsAssert.hasPointSatisfying( - assertThat(metric), - point -> - point.hasAttributesSatisfyingExactly( - equalTo(stringKey("key1"), "1"), - equalTo(stringKey("key2"), "2"), - equalTo(stringKey("key3"), "3")))); + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), + point -> + point.hasAttributesSatisfyingExactly( + equalTo(stringKey("key1"), "1"), + equalTo(stringKey("key2"), "2"), + equalTo(stringKey("key3"), "3")))); } static final class InstrumentsProvider implements ArgumentsProvider { diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/BoundInstrumentExemplarTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/BoundInstrumentExemplarTest.java index 5a8fc0b3338..3d77fd6e99b 100644 --- a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/BoundInstrumentExemplarTest.java +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/BoundInstrumentExemplarTest.java @@ -48,25 +48,18 @@ void delta_collapsingBindings_keepPerBindExemplarAttributes() { boundFirst.add(1); assertThat(deltaReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes( - Attributes.builder().put("keep", "k").build()) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasValue(1) - .hasFilteredAttributes( - Attributes.builder() - .put("drop", "first") - .build()))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasValue(1) + .hasAttributes(Attributes.builder().put("keep", "k").build()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(1) + .hasFilteredAttributes( + Attributes.builder().put("drop", "first").build()))))); } } diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/MeterConfigTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/MeterConfigTest.java index ba264081799..bd77a48e337 100644 --- a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/MeterConfigTest.java +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/MeterConfigTest.java @@ -71,15 +71,14 @@ void disableScopes() { // Only metrics from meterA and meterC should be seen assertThat(reader.collectAllMetrics()) - .satisfies( - metrics -> { - Map> metricsByScope = - metrics.stream().collect(groupingBy(MetricData::getInstrumentationScopeInfo)); - assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterA"))).hasSize(14); - assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterB"))).isNull(); - assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterC"))).hasSize(14); - assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterD"))).isNull(); - }); + .satisfies(metrics -> { + Map> metricsByScope = + metrics.stream().collect(groupingBy(MetricData::getInstrumentationScopeInfo)); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterA"))).hasSize(14); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterB"))).isNull(); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterC"))).hasSize(14); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterD"))).isNull(); + }); // Only async callbacks from meterA and meterC should be invoked assertThat(meterAInvocations.get()).isPositive(); assertThat(meterBInvocations.get()).isZero(); @@ -97,55 +96,49 @@ private static void recordToMeterInstruments(Meter meter, AtomicLong asyncInvoca meter.counterBuilder("doubleCounter").ofDoubles().build().add(1); meter .counterBuilder("asyncLongCounter") - .buildWithCallback( - observable -> { - asyncInvocationsCount.incrementAndGet(); - observable.record(1); - }); + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); meter .counterBuilder("asyncDoubleCounter") .ofDoubles() - .buildWithCallback( - observable -> { - asyncInvocationsCount.incrementAndGet(); - observable.record(1); - }); + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); meter.upDownCounterBuilder("longUpDownCounter").build().add(1); meter.upDownCounterBuilder("doubleUpDownCounter").ofDoubles().build().add(1); meter .upDownCounterBuilder("asyncLongUpDownCounter") - .buildWithCallback( - observable -> { - asyncInvocationsCount.incrementAndGet(); - observable.record(1); - }); + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); meter .upDownCounterBuilder("asyncDoubleUpDownCounter") .ofDoubles() - .buildWithCallback( - observable -> { - asyncInvocationsCount.incrementAndGet(); - observable.record(1); - }); + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); meter.histogramBuilder("doubleHistogram").build().record(1.0); meter.histogramBuilder("longHistogram").ofLongs().build().record(1); meter.gaugeBuilder("doubleGauge").build().set(1); meter.gaugeBuilder("longGauge").ofLongs().build().set(1); meter .gaugeBuilder("asyncDoubleGauge") - .buildWithCallback( - observable -> { - asyncInvocationsCount.incrementAndGet(); - observable.record(1.0); - }); + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1.0); + }); meter .gaugeBuilder("asyncLongGauge") .ofLongs() - .buildWithCallback( - observable -> { - asyncInvocationsCount.incrementAndGet(); - observable.record(1); - }); + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); } private static void assertMeterInstrumentsEnabled(Meter meter, boolean expectedEnabled) { diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/SynchronousInstrumentStressTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/SynchronousInstrumentStressTest.java index 3e29aac7598..c1babd7f59d 100644 --- a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/SynchronousInstrumentStressTest.java +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/SynchronousInstrumentStressTest.java @@ -161,21 +161,20 @@ private void stressTestOnce( AtomicLong zeroCount = new AtomicLong(0); LongStream.range(0, threadCount) .flatMap(i -> measurements.stream().mapToLong(l -> l)) - .forEach( - measurement -> { - lastValue.set(measurement); - sum.addAndGet(measurement); - min.updateAndGet(v -> Math.min(v, measurement)); - max.updateAndGet(v -> Math.max(v, measurement)); - totalCount.incrementAndGet(); - int bucketIndex = - ExplicitBucketHistogramUtils.findBucketIndex( - BUCKET_BOUNDARIES_ARR, (double) measurement); - bucketCounts.set(bucketIndex, bucketCounts.get(bucketIndex) + 1); - if (measurement == 0) { - zeroCount.incrementAndGet(); - } - }); + .forEach(measurement -> { + lastValue.set(measurement); + sum.addAndGet(measurement); + min.updateAndGet(v -> Math.min(v, measurement)); + max.updateAndGet(v -> Math.max(v, measurement)); + totalCount.incrementAndGet(); + int bucketIndex = + ExplicitBucketHistogramUtils.findBucketIndex( + BUCKET_BOUNDARIES_ARR, (double) measurement); + bucketCounts.set(bucketIndex, bucketCounts.get(bucketIndex) + 1); + if (measurement == 0) { + zeroCount.incrementAndGet(); + } + }); boolean isCumulative = aggregationTemporality == AggregationTemporality.CUMULATIVE; List points = @@ -185,72 +184,65 @@ private void stressTestOnce( if (aggregation == Aggregation.sum()) { if (instrumentValueType == InstrumentValueType.DOUBLE) { assertThat(points) - .allSatisfy( - point -> - assertThat(point) - .isInstanceOfSatisfying( - DoublePointData.class, - p -> assertThat(p.getValue()).isEqualTo((double) sum.get()))); + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + DoublePointData.class, + p -> assertThat(p.getValue()).isEqualTo((double) sum.get()))); } else { assertThat(points) - .allSatisfy( - point -> - assertThat(point) - .isInstanceOfSatisfying( - LongPointData.class, - p -> assertThat(p.getValue()).isEqualTo(sum.get()))); + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + LongPointData.class, p -> assertThat(p.getValue()).isEqualTo(sum.get()))); } } else if (aggregation == Aggregation.lastValue()) { if (instrumentValueType == InstrumentValueType.DOUBLE) { assertThat(points) - .allSatisfy( - point -> - assertThat(point) - .isInstanceOfSatisfying( - DoublePointData.class, - p -> assertThat(p.getValue()).isEqualTo((double) lastValue.get()))); + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + DoublePointData.class, + p -> assertThat(p.getValue()).isEqualTo((double) lastValue.get()))); } else { assertThat(points) - .allSatisfy( - point -> - assertThat(point) - .isInstanceOfSatisfying( - LongPointData.class, - p -> assertThat(p.getValue()).isEqualTo(lastValue.get()))); + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + LongPointData.class, + p -> assertThat(p.getValue()).isEqualTo(lastValue.get()))); } } else if (aggregation == Aggregation.explicitBucketHistogram()) { assertThat(points) - .allSatisfy( - point -> - assertThat(point) - .isInstanceOfSatisfying( - HistogramPointData.class, - p -> { - assertThat(p.getSum()).isEqualTo((double) sum.get()); - assertThat(p.getMin()).isEqualTo((double) min.get()); - assertThat(p.getMax()).isEqualTo((double) max.get()); - assertThat(p.getCount()) - .isEqualTo(bucketCounts.stream().reduce(0L, Long::sum)); - assertThat(p.getCounts()).isEqualTo(bucketCounts); - })); + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + HistogramPointData.class, + p -> { + assertThat(p.getSum()).isEqualTo((double) sum.get()); + assertThat(p.getMin()).isEqualTo((double) min.get()); + assertThat(p.getMax()).isEqualTo((double) max.get()); + assertThat(p.getCount()) + .isEqualTo(bucketCounts.stream().reduce(0L, Long::sum)); + assertThat(p.getCounts()).isEqualTo(bucketCounts); + })); } else if (aggregation == Aggregation.base2ExponentialBucketHistogram()) { assertThat(points) - .allSatisfy( - point -> - assertThat(point) - .isInstanceOfSatisfying( - ExponentialHistogramPointData.class, - p -> { - assertThat(p.getSum()).isEqualTo((double) sum.get()); - assertThat(p.getMin()).isEqualTo((double) min.get()); - assertThat(p.getMax()).isEqualTo((double) max.get()); - assertThat(p.getZeroCount()).isEqualTo(zeroCount.get()); - assertThat( - p.getPositiveBuckets().getBucketCounts().stream() - .reduce(0L, Long::sum)) - .isEqualTo(totalCount.get() - zeroCount.get()); - })); + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + ExponentialHistogramPointData.class, + p -> { + assertThat(p.getSum()).isEqualTo((double) sum.get()); + assertThat(p.getMin()).isEqualTo((double) min.get()); + assertThat(p.getMax()).isEqualTo((double) max.get()); + assertThat(p.getZeroCount()).isEqualTo(zeroCount.get()); + assertThat( + p.getPositiveBuckets().getBucketCounts().stream() + .reduce(0L, Long::sum)) + .isEqualTo(totalCount.get() - zeroCount.get()); + })); } else { throw new IllegalArgumentException(); } @@ -321,54 +313,49 @@ private void partialWriteStressTestOnce( if (aggregation == Aggregation.explicitBucketHistogram()) { collectedMetrics.stream() .flatMap(m -> m.getHistogramData().getPoints().stream()) - .forEach( - p -> { - long bucketSum = p.getCounts().stream().reduce(0L, Long::sum); - assertThat(p.getCount()).as("count == sum of bucket counts").isEqualTo(bucketSum); - assertThat(p.getSum()) - .as("sum == count (uniform value=1)") - .isEqualTo((double) p.getCount()); - if (p.getCount() > 0) { - assertThat(p.hasMin()).isTrue(); - assertThat(p.getMin()).as("min == 1 (uniform value)").isEqualTo(1.0); - assertThat(p.hasMax()).isTrue(); - assertThat(p.getMax()).as("max == 1 (uniform value)").isEqualTo(1.0); - } - }); + .forEach(p -> { + long bucketSum = p.getCounts().stream().reduce(0L, Long::sum); + assertThat(p.getCount()).as("count == sum of bucket counts").isEqualTo(bucketSum); + assertThat(p.getSum()) + .as("sum == count (uniform value=1)") + .isEqualTo((double) p.getCount()); + if (p.getCount() > 0) { + assertThat(p.hasMin()).isTrue(); + assertThat(p.getMin()).as("min == 1 (uniform value)").isEqualTo(1.0); + assertThat(p.hasMax()).isTrue(); + assertThat(p.getMax()).as("max == 1 (uniform value)").isEqualTo(1.0); + } + }); } else if (aggregation == Aggregation.base2ExponentialBucketHistogram()) { collectedMetrics.stream() .flatMap(m -> m.getExponentialHistogramData().getPoints().stream()) - .forEach( - p -> { - long positiveBucketSum = - p.getPositiveBuckets().getBucketCounts().stream().reduce(0L, Long::sum); - long negativeBucketSum = - p.getNegativeBuckets().getBucketCounts().stream().reduce(0L, Long::sum); - assertThat(p.getCount()) - .as("count == pos + neg + zero bucket counts") - .isEqualTo(positiveBucketSum + negativeBucketSum + p.getZeroCount()); - assertThat(p.getSum()) - .as("sum == count (uniform value=1)") - .isEqualTo((double) p.getCount()); - if (p.getCount() > 0) { - assertThat(p.hasMin()).isTrue(); - assertThat(p.getMin()).as("min == 1 (uniform value)").isEqualTo(1.0); - assertThat(p.hasMax()).isTrue(); - assertThat(p.getMax()).as("max == 1 (uniform value)").isEqualTo(1.0); - } - }); + .forEach(p -> { + long positiveBucketSum = + p.getPositiveBuckets().getBucketCounts().stream().reduce(0L, Long::sum); + long negativeBucketSum = + p.getNegativeBuckets().getBucketCounts().stream().reduce(0L, Long::sum); + assertThat(p.getCount()) + .as("count == pos + neg + zero bucket counts") + .isEqualTo(positiveBucketSum + negativeBucketSum + p.getZeroCount()); + assertThat(p.getSum()) + .as("sum == count (uniform value=1)") + .isEqualTo((double) p.getCount()); + if (p.getCount() > 0) { + assertThat(p.hasMin()).isTrue(); + assertThat(p.getMin()).as("min == 1 (uniform value)").isEqualTo(1.0); + assertThat(p.hasMax()).isTrue(); + assertThat(p.getMax()).as("max == 1 (uniform value)").isEqualTo(1.0); + } + }); } else if (aggregation == Aggregation.sum()) { // Uniform value=1 adds only. Sum should be a non-negative whole number. if (instrumentValueType == InstrumentValueType.DOUBLE) { collectedMetrics.stream() .flatMap(m -> m.getDoubleSumData().getPoints().stream()) - .forEach( - p -> { - assertThat(p.getValue()).as("sum non-negative").isGreaterThanOrEqualTo(0.0); - assertThat(p.getValue()) - .as("sum is integral") - .isEqualTo(Math.floor(p.getValue())); - }); + .forEach(p -> { + assertThat(p.getValue()).as("sum non-negative").isGreaterThanOrEqualTo(0.0); + assertThat(p.getValue()).as("sum is integral").isEqualTo(Math.floor(p.getValue())); + }); } else { collectedMetrics.stream() .flatMap(m -> m.getLongSumData().getPoints().stream()) @@ -439,45 +426,43 @@ private List runStressLoop( CountDownLatch startSignal = new CountDownLatch(1); for (int i = 0; i < threadCount; i++) { recordThreads.add( - new Thread( - () -> { - Uninterruptibles.awaitUninterruptibly(startSignal); - if (bound) { - for (Long measurement : measurements) { - for (BoundInstrument boundInstrument : boundInstruments) { - boundInstrument.record(measurement); - } - Thread.yield(); - } - } else { - for (Long measurement : measurements) { - for (Attributes attr : attributes) { - instrument.record(measurement, attr); - } - Thread.yield(); - } + new Thread(() -> { + Uninterruptibles.awaitUninterruptibly(startSignal); + if (bound) { + for (Long measurement : measurements) { + for (BoundInstrument boundInstrument : boundInstruments) { + boundInstrument.record(measurement); } - latch.countDown(); - })); + Thread.yield(); + } + } else { + for (Long measurement : measurements) { + for (Attributes attr : attributes) { + instrument.record(measurement, attr); + } + Thread.yield(); + } + } + latch.countDown(); + })); } List collectedMetrics = new ArrayList<>(); Thread collectThread = - new Thread( - () -> { - Uninterruptibles.awaitUninterruptibly(startSignal); - while (latch.getCount() != 0) { - Thread.yield(); - collectedMetrics.addAll( - reader.collectAllMetrics().stream() - .map(SynchronousInstrumentStressTest::copy) - .collect(toList())); - } - collectedMetrics.addAll( - reader.collectAllMetrics().stream() - .map(SynchronousInstrumentStressTest::copy) - .collect(toList())); - }); + new Thread(() -> { + Uninterruptibles.awaitUninterruptibly(startSignal); + while (latch.getCount() != 0) { + Thread.yield(); + collectedMetrics.addAll( + reader.collectAllMetrics().stream() + .map(SynchronousInstrumentStressTest::copy) + .collect(toList())); + } + collectedMetrics.addAll( + reader.collectAllMetrics().stream() + .map(SynchronousInstrumentStressTest::copy) + .collect(toList())); + }); // Start all the threads, then release the start signal so they begin simultaneously collectThread.start(); @@ -635,14 +620,13 @@ private static MetricData copy(MetricData m) { m.getUnit(), ImmutableGaugeData.create( m.getLongGaugeData().getPoints().stream() - .map( - p -> - ImmutableLongPointData.create( - p.getStartEpochNanos(), - p.getEpochNanos(), - p.getAttributes(), - p.getValue(), - p.getExemplars())) + .map(p -> + ImmutableLongPointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) .collect(toList()))); case DOUBLE_GAUGE: return ImmutableMetricData.createDoubleGauge( @@ -653,14 +637,13 @@ private static MetricData copy(MetricData m) { m.getUnit(), ImmutableGaugeData.create( m.getDoubleGaugeData().getPoints().stream() - .map( - p -> - ImmutableDoublePointData.create( - p.getStartEpochNanos(), - p.getEpochNanos(), - p.getAttributes(), - p.getValue(), - p.getExemplars())) + .map(p -> + ImmutableDoublePointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) .collect(toList()))); case LONG_SUM: return ImmutableMetricData.createLongSum( @@ -673,14 +656,13 @@ private static MetricData copy(MetricData m) { m.getLongSumData().isMonotonic(), m.getLongSumData().getAggregationTemporality(), m.getLongSumData().getPoints().stream() - .map( - p -> - ImmutableLongPointData.create( - p.getStartEpochNanos(), - p.getEpochNanos(), - p.getAttributes(), - p.getValue(), - p.getExemplars())) + .map(p -> + ImmutableLongPointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) .collect(toList()))); case DOUBLE_SUM: return ImmutableMetricData.createDoubleSum( @@ -693,14 +675,13 @@ private static MetricData copy(MetricData m) { m.getDoubleSumData().isMonotonic(), m.getDoubleSumData().getAggregationTemporality(), m.getDoubleSumData().getPoints().stream() - .map( - p -> - ImmutableDoublePointData.create( - p.getStartEpochNanos(), - p.getEpochNanos(), - p.getAttributes(), - p.getValue(), - p.getExemplars())) + .map(p -> + ImmutableDoublePointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) .collect(toList()))); case HISTOGRAM: return ImmutableMetricData.createDoubleHistogram( @@ -712,20 +693,19 @@ private static MetricData copy(MetricData m) { ImmutableHistogramData.create( m.getHistogramData().getAggregationTemporality(), m.getHistogramData().getPoints().stream() - .map( - p -> - ImmutableHistogramPointData.create( - p.getStartEpochNanos(), - p.getEpochNanos(), - p.getAttributes(), - p.getSum(), - p.hasMin(), - p.getMin(), - p.hasMax(), - p.getMax(), - p.getBoundaries(), - new ArrayList<>(p.getCounts()), - p.getExemplars())) + .map(p -> + ImmutableHistogramPointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getSum(), + p.hasMin(), + p.getMin(), + p.hasMax(), + p.getMax(), + p.getBoundaries(), + new ArrayList<>(p.getCounts()), + p.getExemplars())) .collect(toList()))); case EXPONENTIAL_HISTOGRAM: return ImmutableMetricData.createExponentialHistogram( @@ -737,28 +717,27 @@ private static MetricData copy(MetricData m) { ImmutableExponentialHistogramData.create( m.getExponentialHistogramData().getAggregationTemporality(), m.getExponentialHistogramData().getPoints().stream() - .map( - p -> - ImmutableExponentialHistogramPointData.create( - p.getScale(), - p.getSum(), - p.getZeroCount(), - p.hasMin(), - p.getMin(), - p.hasMax(), - p.getMax(), - ExponentialHistogramBuckets.create( - p.getPositiveBuckets().getScale(), - p.getPositiveBuckets().getOffset(), - new ArrayList<>(p.getPositiveBuckets().getBucketCounts())), - ExponentialHistogramBuckets.create( - p.getNegativeBuckets().getScale(), - p.getNegativeBuckets().getOffset(), - new ArrayList<>(p.getNegativeBuckets().getBucketCounts())), - p.getStartEpochNanos(), - p.getEpochNanos(), - p.getAttributes(), - p.getExemplars())) + .map(p -> + ImmutableExponentialHistogramPointData.create( + p.getScale(), + p.getSum(), + p.getZeroCount(), + p.hasMin(), + p.getMin(), + p.hasMax(), + p.getMax(), + ExponentialHistogramBuckets.create( + p.getPositiveBuckets().getScale(), + p.getPositiveBuckets().getOffset(), + new ArrayList<>(p.getPositiveBuckets().getBucketCounts())), + ExponentialHistogramBuckets.create( + p.getNegativeBuckets().getScale(), + p.getNegativeBuckets().getOffset(), + new ArrayList<>(p.getNegativeBuckets().getBucketCounts())), + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getExemplars())) .collect(toList()))); case SUMMARY: } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java index df0f6038cf7..e8d38b15c09 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java @@ -29,18 +29,17 @@ public final class TracesAssert /** Compare spans by start time, placing parents before their children as a tiebreaker. */ static final Comparator SPAN_DATA_COMPARATOR = Comparator.comparingLong(SpanData::getStartEpochNanos) - .thenComparing( - (span1, span2) -> { - SpanContext parent1 = span1.getParentSpanContext(); - if (parent1.isValid() && parent1.getSpanId().equals(span2.getSpanId())) { - return 1; - } - SpanContext parent2 = span2.getParentSpanContext(); - if (parent2.isValid() && parent2.getSpanId().equals(span1.getSpanId())) { - return -1; - } - return 0; - }); + .thenComparing((span1, span2) -> { + SpanContext parent1 = span1.getParentSpanContext(); + if (parent1.isValid() && parent1.getSpanId().equals(span2.getSpanId())) { + return 1; + } + SpanContext parent2 = span2.getParentSpanContext(); + if (parent2.isValid() && parent2.getSpanId().equals(span1.getSpanId())) { + return -1; + } + return 0; + }); /** * Returns an assertion for a list of traces. The provided spans will be grouped into traces by diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertionTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertionTest.java index 44c09e39af2..e64fb2382bf 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertionTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertionTest.java @@ -17,11 +17,10 @@ class AttributeAssertionTest { void nullAttr_errorMessageContainsAttrName() { AttributeKey key = AttributeKey.stringKey("flib"); - assertThatThrownBy( - () -> - AttributeAssertion.create(key, AbstractAssert::isNotNull) - .getAssertion() - .accept(AttributeAssertion.attributeValueAssertion(key, null))) + assertThatThrownBy(() -> + AttributeAssertion.create(key, AbstractAssert::isNotNull) + .getAssertion() + .accept(AttributeAssertion.attributeValueAssertion(key, null))) .isInstanceOf(AssertionError.class) .hasMessage( "[STRING attribute 'flib'] " diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java index 78fd216123e..2df7107f865 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java @@ -77,36 +77,30 @@ public class LogAssertionsTest { void passing() { assertThat(LOG_DATA) .hasResource(RESOURCE) - .hasResourceSatisfying( - resource -> - resource - .hasSchemaUrl(null) - .hasAttribute(DOG, "bark") - .hasAttributes( - Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) - .hasAttributes( - attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasSize(2) - .containsEntry(stringKey("dog"), "bark") - .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) - .hasEntrySatisfying( - AttributeKey.booleanKey("dog is cute"), - value -> assertThat(value).isTrue()))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - satisfies(DOG, val -> val.startsWith("bar")), - satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) + .hasResourceSatisfying(resource -> + resource + .hasSchemaUrl(null) + .hasAttribute(DOG, "bark") + .hasAttributes( + Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) + .hasAttributes(attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(2) + .containsEntry(stringKey("dog"), "bark") + .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) + .hasEntrySatisfying( + AttributeKey.booleanKey("dog is cute"), + value -> assertThat(value).isTrue()))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.startsWith("bar")), + satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasEventName("event name") .hasTimestamp(100) @@ -127,39 +121,38 @@ void passing() { attributeEntry("scores", 0L, 1L), attributeEntry("coins", 0.01, 0.05, 0.1), attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .hasSize(9) - .containsEntry(stringKey("bear"), "mya") - .hasEntrySatisfying(stringKey("bear"), value -> assertThat(value).hasSize(3)) - .containsEntry("bear", "mya") - .containsEntry("warm", true) - .containsEntry("temperature", 30) - .containsEntry(longKey("temperature"), 30L) - .containsEntry(longKey("temperature"), 30) - .containsEntry("length", 1.2) - .containsEntry("colors", "red", "blue") - .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) - .containsEntry("conditions", false, true) - .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) - .containsEntry("scores", 0L, 1L) - .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) - .containsEntry("coins", 0.01, 0.05, 0.1) - .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) - .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) - .containsKey(stringKey("bear")) - .containsKey("bear") - .containsOnly( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1), - attributeEntry("bytes", Value.of(new byte[] {1, 2, 3})))) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes) + .hasSize(9) + .containsEntry(stringKey("bear"), "mya") + .hasEntrySatisfying(stringKey("bear"), value -> assertThat(value).hasSize(3)) + .containsEntry("bear", "mya") + .containsEntry("warm", true) + .containsEntry("temperature", 30) + .containsEntry(longKey("temperature"), 30L) + .containsEntry(longKey("temperature"), 30) + .containsEntry("length", 1.2) + .containsEntry("colors", "red", "blue") + .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) + .containsEntry("conditions", false, true) + .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) + .containsEntry("scores", 0L, 1L) + .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsKey(stringKey("bear")) + .containsKey("bear") + .containsOnly( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3})))) .hasAttributesSatisfying( equalTo(stringKey("bear"), "mya"), equalTo(AttributeKey.booleanArrayKey("conditions"), Arrays.asList(false, true))) @@ -179,35 +172,29 @@ void passing() { @Test void failure() { assertThatThrownBy(() -> assertThat(LOG_DATA).hasResource(Resource.empty())); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasResourceSatisfying( - resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying( + resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasResourceSatisfying( - resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying( + resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - attributes -> assertThat(attributes).hasSize(1)))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying( + attributes -> assertThat(attributes).hasSize(1)))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(LOG_DATA).hasInstrumentationScope(InstrumentationScopeInfo.empty())); @@ -231,61 +218,48 @@ void failure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(LOG_DATA).hasAttributes(attributeEntry("food", "burger"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .containsEntry("cat", "bark"))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes).containsEntry("cat", "bark"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .containsKey(stringKey("cat")))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes).containsKey(stringKey("cat")))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes).containsKey("cat"))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes).containsKey("cat"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> OpenTelemetryAssertions.assertThat(attributes).isEmpty())) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying( + attributes -> OpenTelemetryAssertions.assertThat(attributes).isEmpty())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> OpenTelemetryAssertions.assertThat(attributes).hasSize(33))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying( + attributes -> OpenTelemetryAssertions.assertThat(attributes).hasSize(33))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .hasEntrySatisfying( - stringKey("bear"), value -> assertThat(value).hasSize(2)))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes) + .hasEntrySatisfying( + stringKey("bear"), value -> assertThat(value).hasSize(2)))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(LOG_DATA).hasAttributesSatisfying(equalTo(stringKey("bear"), "moo"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfyingExactly( - equalTo(stringKey("bear"), "mya"), - equalTo(AttributeKey.booleanKey("warm"), true), - equalTo(longKey("temperature"), 30L), - equalTo(AttributeKey.doubleKey("length"), 1.2))) + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfyingExactly( + equalTo(stringKey("bear"), "mya"), + equalTo(AttributeKey.booleanKey("warm"), true), + equalTo(longKey("temperature"), 30L), + equalTo(AttributeKey.doubleKey("length"), 1.2))) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(LOG_DATA).hasTotalAttributeCount(11)) .isInstanceOf(AssertionError.class); diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java index b0a1ac3e240..9108b5260f1 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java @@ -309,182 +309,170 @@ class MetricAssertionsTest { void doubleGauge() { assertThat(DOUBLE_GAUGE_METRIC) .hasResource(RESOURCE) - .hasResourceSatisfying( - resource -> - resource - .hasSchemaUrl(null) - .hasAttribute(DOG, "bark") - .hasAttributes( - Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) - .hasAttributes( - attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasSize(2) - .containsEntry(stringKey("dog"), "bark") - .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) - .hasEntrySatisfying( - AttributeKey.booleanKey("dog is cute"), - value -> assertThat(value).isTrue()))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - satisfies(DOG, val -> val.startsWith("bar")), - satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) + .hasResourceSatisfying(resource -> + resource + .hasSchemaUrl(null) + .hasAttribute(DOG, "bark") + .hasAttributes( + Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) + .hasAttributes(attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(2) + .containsEntry(stringKey("dog"), "bark") + .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) + .hasEntrySatisfying( + AttributeKey.booleanKey("dog is cute"), + value -> assertThat(value).isTrue()))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.startsWith("bar")), + satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("gauge") .hasDescription("a gauge") .hasUnit("1") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(3) - .hasEpochNanos(4) - .hasAttributes(Attributes.empty()) - .hasValue(3.0) - .hasValueSatisfying(val -> val.isEqualTo(3.0)) - .hasExemplars(DOUBLE_EXEMPLAR2, DOUBLE_EXEMPLAR1) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasEpochNanos(2) - .hasTraceId(TRACE_ID) - .hasSpanId(SPAN_ID2) - .hasValue(2.0) - .hasFilteredAttributes(Attributes.empty()), - exemplar -> - exemplar - .hasEpochNanos(0) - .hasTraceId(TRACE_ID) - .hasSpanId(SPAN_ID1) - .hasValue(1.0) - .hasFilteredAttribute(BEAR, "mya") - .hasFilteredAttribute(equalTo(BEAR, "mya")) - .hasFilteredAttributes(ATTRIBUTES) - .hasFilteredAttributes( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1), - attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) - .hasFilteredAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30), - equalTo(LENGTH, 1.2)) - .hasFilteredAttributesSatisfying( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(WARM, val -> val.isTrue()), - satisfies( - TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies( - COLORS, val -> val.containsExactly("red", "blue")), - satisfies( - CONDITIONS, - val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies( - COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies( - BYTES, - val -> - val.isEqualTo(Value.of(new byte[] {1, 2, 3})))) - // Demonstrates common usage of many exact matches and one - // needing a loose one. - .hasFilteredAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(COLORS, Arrays.asList("red", "blue")), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) - .hasFilteredAttributesSatisfyingExactly( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30L), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), - equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), - satisfies( - LENGTH, val -> val.isCloseTo(1, offset(0.3))))), - point -> - point - .hasStartEpochNanos(1) - .hasEpochNanos(2) - .hasValue(3.0) - .hasAttribute(BEAR, "mya") - .hasAttribute(equalTo(BEAR, "mya")) - .hasAttributes(ATTRIBUTES) - .hasAttributes( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1), - attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) - .hasAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30), - equalTo(LENGTH, 1.2), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), - equalTo(BYTES, Value.of(new byte[] {1, 2, 3}))) - .hasAttributesSatisfying( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies( - BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))) - // Demonstrates common usage of many exact matches and one needing a - // loose one. - .hasAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30L), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), - equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasSize(9) - .containsEntry(stringKey("bear"), "mya") - .containsEntry("warm", true) - .containsEntry("temperature", 30L) - .containsEntry("colors", "red", "blue") - .containsEntry("conditions", false, true) - .containsEntry("scores", 0L, 1L) - .containsEntry("coins", 0.01, 0.05, 0.1) - .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) - .containsEntry("length", 1.2)))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(3) + .hasEpochNanos(4) + .hasAttributes(Attributes.empty()) + .hasValue(3.0) + .hasValueSatisfying(val -> val.isEqualTo(3.0)) + .hasExemplars(DOUBLE_EXEMPLAR2, DOUBLE_EXEMPLAR1) + .hasExemplarsSatisfying( + exemplar -> + exemplar + .hasEpochNanos(2) + .hasTraceId(TRACE_ID) + .hasSpanId(SPAN_ID2) + .hasValue(2.0) + .hasFilteredAttributes(Attributes.empty()), + exemplar -> + exemplar + .hasEpochNanos(0) + .hasTraceId(TRACE_ID) + .hasSpanId(SPAN_ID1) + .hasValue(1.0) + .hasFilteredAttribute(BEAR, "mya") + .hasFilteredAttribute(equalTo(BEAR, "mya")) + .hasFilteredAttributes(ATTRIBUTES) + .hasFilteredAttributes( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) + .hasFilteredAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30), + equalTo(LENGTH, 1.2)) + .hasFilteredAttributesSatisfying( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(WARM, val -> val.isTrue()), + satisfies( + TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies( + COLORS, val -> val.containsExactly("red", "blue")), + satisfies( + CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies( + COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))) + // Demonstrates common usage of many exact matches and one + // needing a loose one. + .hasFilteredAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(COLORS, Arrays.asList("red", "blue")), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) + .hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))))), + point -> + point + .hasStartEpochNanos(1) + .hasEpochNanos(2) + .hasValue(3.0) + .hasAttribute(BEAR, "mya") + .hasAttribute(equalTo(BEAR, "mya")) + .hasAttributes(ATTRIBUTES) + .hasAttributes( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) + .hasAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30), + equalTo(LENGTH, 1.2), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3}))) + .hasAttributesSatisfying( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))) + // Demonstrates common usage of many exact matches and one needing a + // loose one. + .hasAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(9) + .containsEntry(stringKey("bear"), "mya") + .containsEntry("warm", true) + .containsEntry("temperature", 30L) + .containsEntry("colors", "red", "blue") + .containsEntry("conditions", false, true) + .containsEntry("scores", 0L, 1L) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsEntry("length", 1.2)))); } @Test @@ -492,83 +480,62 @@ void doubleGauge() { void doubleGaugeFailure() { assertThatThrownBy(() -> assertThat(DOUBLE_GAUGE_METRIC).hasResource(Resource.empty())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - attributes -> assertThat(attributes).hasSize(1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .containsEntry(stringKey("dog"), "meow")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .containsEntry( - AttributeKey.booleanKey("dog is cute"), false)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - satisfies(DOG, val -> val.isEqualTo("meow"))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> resource.hasAttributesSatisfyingExactly(equalTo(DOG, "bark")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - satisfies(DOG, val -> val.isEqualTo("bark"))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasInstrumentationScope(InstrumentationScopeInfo.empty())) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying( + resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying( + resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying( + attributes -> assertThat(attributes).hasSize(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes).containsEntry(stringKey("dog"), "meow")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes) + .containsEntry(AttributeKey.booleanKey("dog is cute"), false)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("meow"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying( + resource -> resource.hasAttributesSatisfyingExactly(equalTo(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.isEqualTo("bark"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasInstrumentationScope(InstrumentationScopeInfo.empty())) .isInstanceOf(AssertionError.class) .hasMessage( "Expected MetricData to have instrumentation scope <" @@ -584,228 +551,109 @@ void doubleGaugeFailure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(DOUBLE_GAUGE_METRIC).hasLongGaugeSatisfying(gauge -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - // Not enough points - gauge -> gauge.hasPointsSatisfying(point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasStartEpochNanos(100), point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasEpochNanos(100), point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying(point -> point.hasValue(100), point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - // Not enough exemplars - point -> point.hasExemplarsSatisfying(exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - // Not enough exemplars - point -> point.hasExemplars(DOUBLE_EXEMPLAR1), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasEpochNanos(100), exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasTraceId("trace"), exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasSpanId("span"), exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(100.0), exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasFilteredAttribute(CAT, "garfield"), - exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> - exemplar.hasFilteredAttributes( - Attributes.of(CAT, "garfield")), - exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> - // Extra CAT - exemplar.hasFilteredAttributesSatisfying( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(CAT, val -> val.startsWith("nya")), - satisfies(WARM, val -> val.isTrue()), - satisfies( - TEMPERATURE, - val -> val.isGreaterThanOrEqualTo(30)), - satisfies( - LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies( - COLORS, - val -> val.containsExactly("red", "blue")), - satisfies( - CONDITIONS, - val -> val.containsExactly(false, true)), - satisfies( - SCORES, val -> val.containsExactly(0L, 1L)), - satisfies( - COINS, - val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies( - BYTES, - val -> - val.isEqualTo( - Value.of(new byte[] {1, 2, 3})))), - exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> - // Extra CAT - exemplar.hasFilteredAttributesSatisfyingExactly( - satisfies(WARM, val -> val.isTrue()), - satisfies( - TEMPERATURE, - val -> val.isGreaterThanOrEqualTo(30)), - satisfies( - LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies( - COLORS, - val -> val.containsExactly("red", "blue")), - satisfies( - CONDITIONS, - val -> val.containsExactly(false, true)), - satisfies( - SCORES, val -> val.containsExactly(0L, 1L)), - satisfies( - COINS, - val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies( - BYTES, - val -> - val.isEqualTo( - Value.of(new byte[] {1, 2, 3})))), - exemplar -> {}), - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(Attributes.empty()), - point -> point.hasAttribute(CAT, "garfield")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(Attributes.empty()), - point -> point.hasAttributes(Attributes.of(CAT, "garfield"))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(Attributes.empty()), - // Extra CAT - point -> - point.hasAttributesSatisfying( + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying( + // Not enough points + gauge -> gauge.hasPointsSatisfying(point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasStartEpochNanos(100), point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasEpochNanos(100), point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying( + gauge -> gauge.hasPointsSatisfying(point -> point.hasValue(100), point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + // Not enough exemplars + point -> point.hasExemplarsSatisfying(exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + // Not enough exemplars + point -> point.hasExemplars(DOUBLE_EXEMPLAR1), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasEpochNanos(100), exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasTraceId("trace"), exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasSpanId("span"), exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(100.0), exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasFilteredAttribute(CAT, "garfield"), + exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> + exemplar.hasFilteredAttributes(Attributes.of(CAT, "garfield")), + exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> + // Extra CAT + exemplar.hasFilteredAttributesSatisfying( satisfies(BEAR, val -> val.startsWith("mya")), satisfies(CAT, val -> val.startsWith("nya")), satisfies(WARM, val -> val.isTrue()), @@ -821,33 +669,89 @@ void doubleGaugeFailure() { COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), satisfies( BYTES, - val -> - val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))))) + val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))), + exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> + // Extra CAT + exemplar.hasFilteredAttributesSatisfyingExactly( + satisfies(WARM, val -> val.isTrue()), + satisfies( + TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies( + COLORS, val -> val.containsExactly("red", "blue")), + satisfies( + CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies( + COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))), + exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + point -> point.hasAttribute(CAT, "garfield")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + point -> point.hasAttributes(Attributes.of(CAT, "garfield"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + // Extra CAT + point -> + point.hasAttributesSatisfying( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(CAT, val -> val.startsWith("nya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(Attributes.empty()), - point -> - point.hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasSize(9) - .containsEntry( - stringKey("bear"), - "WRONG BEAR NAME") // Failed here - .containsEntry("warm", true) - .containsEntry("temperature", 30L) - .containsEntry("colors", "red", "blue") - .containsEntry("conditions", false, true) - .containsEntry("scores", 0L, 1L) - .containsEntry("coins", 0.01, 0.05, 0.1) - .containsEntry( - "bytes", Value.of(new byte[] {1, 2, 3})) - .containsEntry("length", 1.2))))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + point -> + point.hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(9) + .containsEntry( + stringKey("bear"), "WRONG BEAR NAME") // Failed here + .containsEntry("warm", true) + .containsEntry("temperature", 30L) + .containsEntry("colors", "red", "blue") + .containsEntry("conditions", false, true) + .containsEntry("scores", 0L, 1L) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsEntry("length", 1.2))))) .isInstanceOf(AssertionError.class); } @@ -858,135 +762,110 @@ void doubleGaugeFailure() { @Test void longGauge() { assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(Long.MAX_VALUE) - .hasValueSatisfying(val -> val.isEqualTo(Long.MAX_VALUE)) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(2), - exemplar -> - exemplar - .hasValue(1) - .hasFilteredAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30L), - equalTo(COLORS, Arrays.asList("red", "blue")), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) - .hasFilteredAttributesSatisfyingExactly( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30L), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), - equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), - satisfies( - LENGTH, val -> val.isCloseTo(1, offset(0.3))))), - point -> point.hasValue(1))); + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasValue(Long.MAX_VALUE) + .hasValueSatisfying(val -> val.isEqualTo(Long.MAX_VALUE)) + .hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(2), + exemplar -> + exemplar + .hasValue(1) + .hasFilteredAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) + .hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))))), + point -> point.hasValue(1))); } @Test void longGaugeFailure() { assertThatThrownBy(() -> assertThat(LONG_GAUGE_METRIC).hasDoubleGaugeSatisfying(gauge -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - // Not enough points - point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasValue(2), point -> point.hasValue(1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasValueSatisfying(val -> val.isNegative()), - point -> point.hasValueSatisfying(val -> val.isNegative())))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasExemplars(LONG_EXEMPLAR2), - point -> point.hasValue(1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(100), exemplar -> {}), - point -> point.hasValue(1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> - exemplar.hasFilteredAttributesSatisfying( - equalTo(CAT, "mya"), equalTo(WARM, true)))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> - exemplar.hasFilteredAttributesSatisfyingExactly( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - satisfies( - LENGTH, - val -> val.isCloseTo(1, offset(0.3)))))))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + // Not enough points + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasValue(2), point -> point.hasValue(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasValueSatisfying(val -> val.isNegative()), + point -> point.hasValueSatisfying(val -> val.isNegative())))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasExemplars(LONG_EXEMPLAR2), point -> point.hasValue(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(100), exemplar -> {}), + point -> point.hasValue(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasExemplarsSatisfying(exemplar -> + exemplar.hasFilteredAttributesSatisfying( + equalTo(CAT, "mya"), equalTo(WARM, true)))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasExemplarsSatisfying(exemplar -> + exemplar.hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))))))) .isInstanceOf(AssertionError.class); // hasFilteredAttributesSatisfyingExactly must reject extra filtered attributes. The exemplar // has nine filtered attributes but only one is asserted, so the exact assertion must fail. - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(Long.MAX_VALUE) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(2), - exemplar -> - exemplar - .hasValue(1) - .hasFilteredAttributesSatisfyingExactly( - equalTo(BEAR, "mya"))), - point -> point.hasValue(1)))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasValue(Long.MAX_VALUE) + .hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(2), + exemplar -> + exemplar + .hasValue(1) + .hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"))), + point -> point.hasValue(1)))) .isInstanceOf(AssertionError.class); } @@ -1005,14 +884,12 @@ void doubleSum() { void doubleSumFailure() { assertThatThrownBy(() -> assertThat(DOUBLE_SUM_METRIC).hasLongSumSatisfying(sum -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_SUM_METRIC) - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - // Not enough points - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_SUM_METRIC) + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying( + // Not enough points + point -> {}))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(DOUBLE_SUM_METRIC).hasDoubleSumSatisfying(sum -> sum.isNotMonotonic())) @@ -1020,15 +897,13 @@ void doubleSumFailure() { assertThatThrownBy( () -> assertThat(DOUBLE_SUM_METRIC).hasDoubleSumSatisfying(sum -> sum.isDelta())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) - .hasDoubleSumSatisfying(sum -> sum.isMonotonic())) + assertThatThrownBy(() -> + assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) + .hasDoubleSumSatisfying(sum -> sum.isMonotonic())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) - .hasDoubleSumSatisfying(sum -> sum.isCumulative())) + assertThatThrownBy(() -> + assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) + .hasDoubleSumSatisfying(sum -> sum.isCumulative())) .isInstanceOf(AssertionError.class); } @@ -1047,49 +922,43 @@ void longSum() { void longSumFailure() { assertThatThrownBy(() -> assertThat(LONG_SUM_METRIC).hasDoubleSumSatisfying(sum -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_SUM_METRIC) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - // Not enough points - point -> {}))) + assertThatThrownBy(() -> + assertThat(LONG_SUM_METRIC) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + // Not enough points + point -> {}))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(LONG_SUM_METRIC).hasLongSumSatisfying(sum -> sum.isNotMonotonic())) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(LONG_SUM_METRIC).hasLongSumSatisfying(sum -> sum.isDelta())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) - .hasLongSumSatisfying(sum -> sum.isMonotonic())) + assertThatThrownBy(() -> + assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) + .hasLongSumSatisfying(sum -> sum.isMonotonic())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) - .hasLongSumSatisfying(sum -> sum.isCumulative())) + assertThatThrownBy(() -> + assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) + .hasLongSumSatisfying(sum -> sum.isCumulative())) .isInstanceOf(AssertionError.class); } @Test void histogram() { assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasSum(15.0) - .hasSumGreaterThan(10.1) - .hasMax(7.0) - .hasMin(4.0) - .hasCount(3) - .hasBucketBoundaries(10.0) - .hasBucketBoundaries(new double[] {10.1}, within(0.1)))); + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasSum(15.0) + .hasSumGreaterThan(10.1) + .hasMax(7.0) + .hasMin(4.0) + .hasCount(3) + .hasBucketBoundaries(10.0) + .hasBucketBoundaries(new double[] {10.1}, within(0.1)))); assertThat(HISTOGRAM_METRIC_DELTA).hasHistogramSatisfying(histogram -> histogram.isDelta()); } @@ -1097,107 +966,84 @@ void histogram() { void histogram_failure() { assertThatThrownBy(() -> assertThat(HISTOGRAM_METRIC).hasDoubleGaugeSatisfying(gauge -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying(histogram -> histogram.isDelta())) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC).hasHistogramSatisfying(histogram -> histogram.isDelta())) .isInstanceOf(AssertionError.class) .hasMessage("Expected Histogram to have delta aggregation but found "); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC_DELTA) - .hasHistogramSatisfying(histogram -> histogram.isCumulative())) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC_DELTA) + .hasHistogramSatisfying(histogram -> histogram.isCumulative())) .isInstanceOf(AssertionError.class) .hasMessage("Expected Histogram to have cumulative aggregation but found "); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> {}, point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(14.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying(point -> point.hasSumGreaterThan(16.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasMax(8.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasMin(5.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasCount(4)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> point.hasBucketBoundaries(11.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point.hasBucketBoundaries(new double[] {11.0}, within(0.1))))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> {}, point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(14.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> point.hasSumGreaterThan(16.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMax(8.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMin(5.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasCount(4)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> point.hasBucketBoundaries(11.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> point.hasBucketBoundaries(new double[] {11.0}, within(0.1))))) .isInstanceOf(AssertionError.class); } @Test void exponentialHistogram() { assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasScale(1) - .hasSum(10.0) - .hasZeroCount(1) - .hasCount(4) - .hasMin(2.0) - .hasMax(4.0) - .hasPositiveBucketsSatisfying( - buckets -> - buckets - .hasOffset(10) - .hasCounts(Arrays.asList(1L, 2L)) - .hasTotalCount(3)) - .hasNegativeBucketsSatisfying( - buckets -> - buckets - .hasOffset(0) - .hasCounts(Collections.emptyList()) - .hasTotalCount(0)) - .hasStartEpochNanos(1) - .hasEpochNanos(2) - .hasAttributes(Attributes.empty()) - .hasExemplars(DOUBLE_EXEMPLAR1, DOUBLE_EXEMPLAR2) - .hasExemplarsSatisfying(exemplar -> {}, exemplar -> {}))); + .hasExponentialHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasScale(1) + .hasSum(10.0) + .hasZeroCount(1) + .hasCount(4) + .hasMin(2.0) + .hasMax(4.0) + .hasPositiveBucketsSatisfying(buckets -> + buckets.hasOffset(10).hasCounts(Arrays.asList(1L, 2L)).hasTotalCount(3)) + .hasNegativeBucketsSatisfying(buckets -> + buckets + .hasOffset(0) + .hasCounts(Collections.emptyList()) + .hasTotalCount(0)) + .hasStartEpochNanos(1) + .hasEpochNanos(2) + .hasAttributes(Attributes.empty()) + .hasExemplars(DOUBLE_EXEMPLAR1, DOUBLE_EXEMPLAR2) + .hasExemplarsSatisfying(exemplar -> {}, exemplar -> {}))); assertThat(EXPONENTIAL_HISTOGRAM_DELTA_METRIC) .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isDelta); } @@ -1207,125 +1053,101 @@ void exponentialHistogram_failure() { assertThatThrownBy( () -> assertThat(EXPONENTIAL_HISTOGRAM_METRIC).hasDoubleGaugeSatisfying(gauge -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isDelta)) + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isDelta)) .isInstanceOf(AssertionError.class) .hasMessage("Expected Histogram to have delta aggregation but found "); - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_DELTA_METRIC) - .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isCumulative)) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> {}, point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(14.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasMax(8.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasMin(5.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasCount(4)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point.hasPositiveBucketsSatisfying( - buckets -> - buckets.hasCounts(Collections.singletonList(1L)))))) + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_DELTA_METRIC) + .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isCumulative)) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> {}, point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(14.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMax(8.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMin(5.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasCount(4)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point.hasPositiveBucketsSatisfying( + buckets -> buckets.hasCounts(Collections.singletonList(1L)))))) .isInstanceOf(AssertionError.class); } @Test void summary() { assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> - point - .hasSum(2.0) - .hasCount(1) - .hasValuesSatisfying(value -> value.hasQuantile(0.0).hasValue(1.0)))); + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying(point -> + point + .hasSum(2.0) + .hasCount(1) + .hasValuesSatisfying(value -> value.hasQuantile(0.0).hasValue(1.0)))); } @Test void summary_failure() { assertThatThrownBy(() -> assertThat(SUMMARY_METRIC).hasHistogramSatisfying(histogram -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasSummarySatisfying( - summary -> summary.hasPointsSatisfying(point -> {}, point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> summary.hasPointsSatisfying(point -> {}, point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> summary.hasPointsSatisfying(point -> point.hasSum(1.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> summary.hasPointsSatisfying(point -> point.hasCount(2)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> point.hasValuesSatisfying(value -> {}, value -> {})))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> - point.hasValuesSatisfying(value -> value.hasQuantile(1.0))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> point.hasValuesSatisfying(value -> value.hasValue(3.0))))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> {}, point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> {}, point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> point.hasSum(1.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> point.hasCount(2)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying( + point -> point.hasValuesSatisfying(value -> {}, value -> {})))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying( + point -> point.hasValuesSatisfying(value -> value.hasQuantile(1.0))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying( + point -> point.hasValuesSatisfying(value -> value.hasValue(3.0))))) .isInstanceOf(AssertionError.class); } @@ -1335,10 +1157,9 @@ void containsPointsSatisfying() { .hasDoubleGaugeSatisfying( gauge -> gauge.containsPointsSatisfying(point -> point.hasValue(3.0))); assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.containsPointsSatisfying( - point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(1))); + .hasLongGaugeSatisfying(gauge -> + gauge.containsPointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(1))); assertThat(DOUBLE_SUM_METRIC) .hasDoubleSumSatisfying(sum -> sum.containsPointsSatisfying(point -> point.hasValue(3.0))); assertThat(LONG_SUM_METRIC) @@ -1358,40 +1179,32 @@ void containsPointsSatisfying() { @Test void containsPointsSatisfyingFailure() { // single assertion that matches no point - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> gauge.containsPointsSatisfying(point -> point.hasValue(42.0)))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying( + gauge -> gauge.containsPointsSatisfying(point -> point.hasValue(42.0)))) .isInstanceOf(AssertionError.class); // one of multiple assertions unmatched - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.containsPointsSatisfying( - point -> point.hasValue(Long.MAX_VALUE), - point -> point.hasValue(42)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.containsPointsSatisfying(point -> point.hasSum(42)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasExponentialHistogramSatisfying( - histogram -> - histogram.containsPointsSatisfying(point -> point.hasSum(42.0)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> summary.containsPointsSatisfying(point -> point.hasSum(42.0)))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.containsPointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(42)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.containsPointsSatisfying(point -> point.hasSum(42)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.containsPointsSatisfying(point -> point.hasSum(42.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.containsPointsSatisfying(point -> point.hasSum(42.0)))) .isInstanceOf(AssertionError.class); } } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java index 55e65ea0e50..a93a6e27f98 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java @@ -147,36 +147,30 @@ void passing() { .hasTraceState(TRACE_STATE) .hasParentSpanId(SPAN_ID2) .hasResource(RESOURCE) - .hasResourceSatisfying( - resource -> - resource - .hasSchemaUrl(null) - .hasAttribute(DOG, "bark") - .hasAttributes( - Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) - .hasAttributes( - attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasSize(2) - .containsEntry(stringKey("dog"), "bark") - .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) - .hasEntrySatisfying( - AttributeKey.booleanKey("dog is cute"), - value -> assertThat(value).isTrue()))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - satisfies(DOG, val -> val.startsWith("bar")), - satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) + .hasResourceSatisfying(resource -> + resource + .hasSchemaUrl(null) + .hasAttribute(DOG, "bark") + .hasAttributes( + Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) + .hasAttributes(attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(2) + .containsEntry(stringKey("dog"), "bark") + .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) + .hasEntrySatisfying( + AttributeKey.booleanKey("dog is cute"), + value -> assertThat(value).isTrue()))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.startsWith("bar")), + satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) .hasInstrumentationScopeInfo(INSTRUMENTATION_SCOPE_INFO) .hasName("span") .hasKind(SpanKind.CLIENT) @@ -229,63 +223,61 @@ void passing() { equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasSize(9) - .containsEntry(stringKey("bear"), "mya") - .hasEntrySatisfying(stringKey("bear"), value -> assertThat(value).hasSize(3)) - .containsEntry("bear", "mya") - .containsEntry("warm", true) - .containsEntry("temperature", 30) - .containsEntry(AttributeKey.longKey("temperature"), 30L) - .containsEntry(AttributeKey.longKey("temperature"), 30) - .containsEntry("length", 1.2) - .containsEntry("colors", "red", "blue") - .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) - .containsEntry("conditions", false, true) - .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) - .containsEntry("scores", 0L, 1L) - .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) - .containsEntry("coins", 0.01, 0.05, 0.1) - .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) - .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) - .containsKey(stringKey("bear")) - .containsKey("bear") - .doesNotContainKey(stringKey("cat")) - .doesNotContainKey("cat") - .containsOnly( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1), - attributeEntry("bytes", Value.of(new byte[] {1, 2, 3})))) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(9) + .containsEntry(stringKey("bear"), "mya") + .hasEntrySatisfying(stringKey("bear"), value -> assertThat(value).hasSize(3)) + .containsEntry("bear", "mya") + .containsEntry("warm", true) + .containsEntry("temperature", 30) + .containsEntry(AttributeKey.longKey("temperature"), 30L) + .containsEntry(AttributeKey.longKey("temperature"), 30) + .containsEntry("length", 1.2) + .containsEntry("colors", "red", "blue") + .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) + .containsEntry("conditions", false, true) + .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) + .containsEntry("scores", 0L, 1L) + .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsKey(stringKey("bear")) + .containsKey("bear") + .doesNotContainKey(stringKey("cat")) + .doesNotContainKey("cat") + .containsOnly( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3})))) .hasEvents(EVENTS) .hasEvents(EVENTS.toArray(new EventData[0])) - .hasEventsSatisfying( - events -> { - assertThat(events).hasSize(EVENTS.size()); - assertThat(events.get(0)) - .hasName("event") - .hasTimestamp(10) - .hasTimestamp(10, TimeUnit.NANOSECONDS) - .hasTimestamp(Instant.ofEpochSecond(0, 10)) - .hasAttributes(Attributes.empty()) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).isEqualTo(Attributes.empty())) - .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty()); - assertThat(events.get(2)) - .hasAttributesSatisfying( - equalTo(stringKey("exception.type"), "java.lang.IllegalArgumentException")) - .hasAttributesSatisfyingExactly( - equalTo(stringKey("exception.type"), "java.lang.IllegalArgumentException"), - equalTo(stringKey("exception.message"), "bad argument"), - equalTo(stringKey("exception.stacktrace"), "some obfuscated stack")); - }) + .hasEventsSatisfying(events -> { + assertThat(events).hasSize(EVENTS.size()); + assertThat(events.get(0)) + .hasName("event") + .hasTimestamp(10) + .hasTimestamp(10, TimeUnit.NANOSECONDS) + .hasTimestamp(Instant.ofEpochSecond(0, 10)) + .hasAttributes(Attributes.empty()) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).isEqualTo(Attributes.empty())) + .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty()); + assertThat(events.get(2)) + .hasAttributesSatisfying( + equalTo(stringKey("exception.type"), "java.lang.IllegalArgumentException")) + .hasAttributesSatisfyingExactly( + equalTo(stringKey("exception.type"), "java.lang.IllegalArgumentException"), + equalTo(stringKey("exception.message"), "bad argument"), + equalTo(stringKey("exception.stacktrace"), "some obfuscated stack")); + }) .hasEventsSatisfyingExactly( event -> event.hasName("event"), event -> event.hasName("event2"), @@ -295,13 +287,8 @@ void passing() { .hasLinks(LINKS.toArray(new LinkData[0])) .hasLinksSatisfying(links -> assertThat(links).hasSize(LINKS.size())) .hasStatus(StatusData.ok()) - .hasStatusSatisfying( - status -> - status - .isOk() - .hasCode(StatusCode.OK) - .hasDescription("") - .hasDescriptionMatching("^$")) + .hasStatusSatisfying(status -> + status.isOk().hasCode(StatusCode.OK).hasDescription("").hasDescriptionMatching("^$")) .endsAt(200) .endsAt(200, TimeUnit.NANOSECONDS) .endsAt(Instant.ofEpochSecond(0, 200)) @@ -330,78 +317,57 @@ void failure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasResource(Resource.empty())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - attributes -> assertThat(attributes).hasSize(1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .containsEntry(stringKey("dog"), "meow")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .containsEntry( - AttributeKey.booleanKey("dog is cute"), false)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfying( - satisfies(DOG, val -> val.isEqualTo("meow"))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> resource.hasAttributesSatisfyingExactly(equalTo(DOG, "bark")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasResourceSatisfying( - resource -> - resource.hasAttributesSatisfyingExactly( - satisfies(DOG, val -> val.isEqualTo("bark"))))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1).hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying( + resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying( + resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying( + attributes -> assertThat(attributes).hasSize(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes).containsEntry(stringKey("dog"), "meow")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes) + .containsEntry(AttributeKey.booleanKey("dog is cute"), false)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("meow"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying( + resource -> resource.hasAttributesSatisfyingExactly(equalTo(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.isEqualTo("bark"))))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasInstrumentationScopeInfo(InstrumentationScopeInfo.empty())) @@ -420,159 +386,133 @@ void failure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasAttributes(attributeEntry("food", "burger"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfyingExactly( - // Failed - satisfies(BEAR, val -> val.doesNotContain("mya")), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - // Missing BEAR - .hasAttributesSatisfyingExactly( - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - // Extra CAT - .hasAttributesSatisfyingExactly( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(CAT, val -> val.startsWith("nya")), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).containsEntry("cat", "bark"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).containsKey(stringKey("cat")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).containsKey("cat"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).doesNotContainKey(stringKey("bear")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).doesNotContainKey("bear"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty())) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying(attributes -> assertThat(attributes).hasSize(33))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasEntrySatisfying( - stringKey("bear"), value -> assertThat(value).hasSize(2)))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfyingExactly( + // Failed + satisfies(BEAR, val -> val.doesNotContain("mya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + // Missing BEAR + .hasAttributesSatisfyingExactly( + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + // Extra CAT + .hasAttributesSatisfyingExactly( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(CAT, val -> val.startsWith("nya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).containsEntry("cat", "bark"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).containsKey(stringKey("cat")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> assertThat(attributes).containsKey("cat"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).doesNotContainKey(stringKey("bear")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).doesNotContainKey("bear"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty())) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> assertThat(attributes).hasSize(33))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasEntrySatisfying( + stringKey("bear"), value -> assertThat(value).hasSize(2)))) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasEvents()).isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasEvents(Collections.emptyList())) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasEventsSatisfying(events -> assertThat(events).isEmpty())); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying(events -> assertThat(events.get(0)).hasName("notevent"))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> assertThat(events.get(0)).hasName("notevent"))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasEventsSatisfyingExactly(event -> event.hasName("notevent"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying(events -> assertThat(events.get(0)).hasTimestamp(1))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> assertThat(events.get(0)).hasTimestamp(1, TimeUnit.NANOSECONDS))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> - assertThat(events.get(0)).hasTimestamp(Instant.ofEpochSecond(0, 1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> - assertThat(events.get(0)).hasAttributes(RESOURCE.getAttributes()))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> - assertThat(events.get(0)) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes).containsEntry("dogs", "meow")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> - assertThat(events.get(2)) - .hasAttributesSatisfyingExactly( - equalTo( - stringKey("exception.type"), - "java.lang.IllegalArgumentException"), - equalTo(stringKey("exception.message"), "bad argument")))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> assertThat(events.get(0)).hasTimestamp(1))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying( + events -> assertThat(events.get(0)).hasTimestamp(1, TimeUnit.NANOSECONDS))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying( + events -> assertThat(events.get(0)).hasTimestamp(Instant.ofEpochSecond(0, 1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying( + events -> assertThat(events.get(0)).hasAttributes(RESOURCE.getAttributes()))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> + assertThat(events.get(0)) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).containsEntry("dogs", "meow")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> + assertThat(events.get(2)) + .hasAttributesSatisfyingExactly( + equalTo( + stringKey("exception.type"), "java.lang.IllegalArgumentException"), + equalTo(stringKey("exception.message"), "bad argument")))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasException(new IllegalStateException("bad argument"))) @@ -595,10 +535,8 @@ void failure() { assertThatThrownBy( () -> assertThat(SPAN1).hasStatusSatisfying(status -> status.hasCode(StatusCode.ERROR))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasStatusSatisfying(status -> status.hasDescriptionMatching("test"))) + assertThatThrownBy(() -> + assertThat(SPAN1).hasStatusSatisfying(status -> status.hasDescriptionMatching("test"))) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).endsAt(10)).isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).endsAt(10, TimeUnit.NANOSECONDS)) @@ -616,14 +554,12 @@ void failure() { assertThatThrownBy(() -> assertThat(SPAN2).isSampled()).isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN2).hasEnded()).isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(RESOURCE.getAttributes()) - .containsOnly(entry(stringKey("dog"), "bark"), entry(stringKey("cat"), "meow"))) + assertThatThrownBy(() -> + assertThat(RESOURCE.getAttributes()) + .containsOnly(entry(stringKey("dog"), "bark"), entry(stringKey("cat"), "meow"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(RESOURCE.getAttributes()).containsOnly(entry(stringKey("cat"), "meow"))) + assertThatThrownBy(() -> + assertThat(RESOURCE.getAttributes()).containsOnly(entry(stringKey("cat"), "meow"))) .isInstanceOf(AssertionError.class); } @@ -656,29 +592,28 @@ void optionalAttributes() { val -> val.extracting(v -> ((ByteBuffer) v.getValue()).get(0)).isEqualTo((byte) 1))); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfyingExactly( - // Yes null - satisfies( - UNSET, - val -> - val.satisfiesAnyOf( - v -> assertThat(v).isNull(), - v -> assertThat(v).isEqualTo("objection"))), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), - satisfies( - BYTES, - val -> - val.extracting(v -> ((ByteBuffer) v.getValue()).get(0)) - .isEqualTo((byte) 1)))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfyingExactly( + // Yes null + satisfies( + UNSET, + val -> + val.satisfiesAnyOf( + v -> assertThat(v).isNull(), + v -> assertThat(v).isEqualTo("objection"))), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> + val.extracting(v -> ((ByteBuffer) v.getValue()).get(0)) + .isEqualTo((byte) 1)))) .isInstanceOf(AssertionError.class); } @@ -703,53 +638,43 @@ void hasSpansSatisfyingExactly() { // test asserting spans in exact oder TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactly( - span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactly( + span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); // wrong number of spans - assertThatThrownBy( - () -> - TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> trace.hasSpansSatisfyingExactly(span -> span.hasSpanId(SPAN_ID1)))) + assertThatThrownBy(() -> + TracesAssert.assertThat(traces) + .hasTracesSatisfyingExactly( + trace -> trace.hasSpansSatisfyingExactly(span -> span.hasSpanId(SPAN_ID1)))) .isInstanceOf(AssertionError.class) .hasMessageStartingWith( "[Trace 0] " + System.lineSeparator() + "Expected size: 1 but was: 2"); // test asserting spans in wrong oder - assertThatThrownBy( - () -> - TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactly( - span -> span.hasSpanId(SPAN_ID2), - span -> span.hasSpanId(SPAN_ID1)))) + assertThatThrownBy(() -> + TracesAssert.assertThat(traces) + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactly( + span -> span.hasSpanId(SPAN_ID2), span -> span.hasSpanId(SPAN_ID1)))) .isInstanceOf(AssertionError.class) .hasMessage( "[Span 0] Expected span [span1] to have span ID <0000000000000004> but was <0000000000000003>"); // test asserting spans in any order TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactlyInAnyOrder( - span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactlyInAnyOrder( + span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactlyInAnyOrder( - span -> span.hasSpanId(SPAN_ID2), span -> span.hasSpanId(SPAN_ID1))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactlyInAnyOrder( + span -> span.hasSpanId(SPAN_ID2), span -> span.hasSpanId(SPAN_ID1))); // test not asserting all spans - assertThatThrownBy( - () -> - TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactlyInAnyOrder( - span -> span.hasSpanId(SPAN_ID1), - span -> span.hasSpanId(SPAN_ID1)))) + assertThatThrownBy(() -> + TracesAssert.assertThat(traces) + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactlyInAnyOrder( + span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID1)))) .isInstanceOf(AssertionError.class); } } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java index c37cc996f5d..244b5fb4b0c 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java @@ -73,12 +73,10 @@ public void getMetrics() { counter.add(1); OpenTelemetryAssertions.assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - OpenTelemetryAssertions.assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactlyInAnyOrder(metricData -> + OpenTelemetryAssertions.assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } // We have two tests to verify metrics get cleared up between tests. @@ -88,12 +86,10 @@ public void getMetricsAgain() { counter.add(1); OpenTelemetryAssertions.assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - OpenTelemetryAssertions.assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactlyInAnyOrder(metricData -> + OpenTelemetryAssertions.assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } @Test diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java index 2c41bfab153..e6bc5251532 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java @@ -139,11 +139,8 @@ public void assertTraces() { s -> s.hasName("testb2"), s -> s.hasName("testexception"))))); - assertThatThrownBy( - () -> - otelTesting - .assertTraces() - .hasTracesSatisfyingExactly(trace -> trace.hasTraceId("foo"))) + assertThatThrownBy(() -> + otelTesting.assertTraces().hasTracesSatisfyingExactly(trace -> trace.hasTraceId("foo"))) .isInstanceOf(AssertionError.class); otelTesting @@ -153,10 +150,8 @@ public void assertTraces() { otelTesting .assertTraces() .filteredOn(trace -> trace.size() == 2) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactly( - s -> s.hasName("testa1"), s -> s.hasName("testa2"))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactly(s -> s.hasName("testa1"), s -> s.hasName("testa2"))); } @Test @@ -165,12 +160,10 @@ void getMetrics() { counter.add(1); assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } // We have two tests to verify metrics get cleared up between tests. @@ -180,12 +173,10 @@ void getMetricsAgain() { counter.add(1); assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } @Test diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java index 9d2107669da..cb0db4dc941 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java @@ -59,11 +59,10 @@ private long getMetric(boolean dropped) { .filter(metricData -> !metricData.isEmpty()) .map(metricData -> metricData.getLongSumData().getPoints()) .flatMap(Collection::stream) - .filter( - point -> { - Boolean attrDropped = point.getAttributes().get(booleanKey("dropped")); - return attrDropped != null && attrDropped == dropped; - }) + .filter(point -> { + Boolean attrDropped = point.getAttributes().get(booleanKey("dropped")); + return attrDropped != null && attrDropped == dropped; + }) .mapToLong(LongPointData::getValue) .findFirst(); return value.isPresent() ? value.getAsLong() : 0; diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java index 6e2e57b43db..6f1ccb9e744 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java @@ -71,12 +71,9 @@ public static SdkTracerProviderBuilder builder() { exceptionAttributeResolver, new SdkTracerInstrumentation(meterProvider)); this.tracerSdkComponentRegistry = - new ComponentRegistry<>( - instrumentationScopeInfo -> - SdkTracer.create( - sharedState, - instrumentationScopeInfo, - getTracerConfig(instrumentationScopeInfo))); + new ComponentRegistry<>(instrumentationScopeInfo -> + SdkTracer.create( + sharedState, instrumentationScopeInfo, getTracerConfig(instrumentationScopeInfo))); this.tracerConfigurator = tracerConfigurator; } @@ -143,10 +140,8 @@ void setTracerConfigurator(ScopeConfigurator tracerConfigurator) { this.tracerConfigurator = tracerConfigurator; this.tracerSdkComponentRegistry .getComponents() - .forEach( - sdkTracer -> - sdkTracer.updateTracerConfig( - getTracerConfig(sdkTracer.getInstrumentationScopeInfo()))); + .forEach(sdkTracer -> + sdkTracer.updateTracerConfig(getTracerConfig(sdkTracer.getInstrumentationScopeInfo()))); } /** diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java index a471a53901f..422c9a576c1 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java @@ -305,19 +305,17 @@ private CompletableResultCode shutdown() { CompletableResultCode result = new CompletableResultCode(); CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - continueWork = false; - CompletableResultCode shutdownResult = spanExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); + flushResult.whenComplete(() -> { + continueWork = false; + CompletableResultCode shutdownResult = spanExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); return result; } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LegacySpanProcessorInstrumentation.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LegacySpanProcessorInstrumentation.java index b8e81b6c250..368d66f7413 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LegacySpanProcessorInstrumentation.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LegacySpanProcessorInstrumentation.java @@ -75,11 +75,10 @@ public void buildQueueMetricsOnce(long unusedCapacity, LongCallable getSize) { .ofLongs() .setDescription("The number of items queued") .setUnit("1") - .buildWithCallback( - result -> - result.record( - getSize.get(), - Attributes.of(SPAN_PROCESSOR_TYPE_LABEL, SPAN_PROCESSOR_TYPE_VALUE))); + .buildWithCallback(result -> + result.record( + getSize.get(), + Attributes.of(SPAN_PROCESSOR_TYPE_LABEL, SPAN_PROCESSOR_TYPE_VALUE))); // No capacity metric when legacy. } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java index c0aabdcd836..80a14438d11 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java @@ -117,13 +117,12 @@ public void onEnd(ReadableSpan span) { } pendingExports.add(result); - result.whenComplete( - () -> { - pendingExports.remove(result); - if (!result.isSuccess()) { - logger.log(Level.FINE, "Exporter failed"); - } - }); + result.whenComplete(() -> { + pendingExports.remove(result); + if (!result.isSuccess()) { + logger.log(Level.FINE, "Exporter failed"); + } + }); } catch (Throwable t) { ThrowableUtil.propagateIfFatal(t); logger.log(Level.WARNING, "Exporter threw an Exception", t); @@ -144,18 +143,16 @@ public CompletableResultCode shutdown() { CompletableResultCode result = new CompletableResultCode(); CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - CompletableResultCode shutdownResult = spanExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); + flushResult.whenComplete(() -> { + CompletableResultCode shutdownResult = spanExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); return result; } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java index 93d11865044..d42cc3f88a7 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java @@ -208,10 +208,9 @@ void onEnding_concurrentModificationsPrevented() { ReadWriteSpan sp = invocation.getArgument(0, ReadWriteSpan.class); Thread concurrent = - new Thread( - () -> { - sp.setAttribute(concurrentAttrib, "concurrent_bar"); - }); + new Thread(() -> { + sp.setAttribute(concurrentAttrib, "concurrent_bar"); + }); concurrent.start(); concurrent.join(); @@ -818,50 +817,43 @@ void addEvent() { List events = span.toSpanData().getEvents(); assertThat(events).hasSize(6); assertThat(events.get(0)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event1"); - assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); - assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event1"); + assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); + }); assertThat(events.get(1)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event2"); - assertThat(event.getAttributes()) - .isEqualTo(Attributes.of(stringKey("e1key"), "e1Value")); - assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event2"); + assertThat(event.getAttributes()).isEqualTo(Attributes.of(stringKey("e1key"), "e1Value")); + assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); + }); assertThat(events.get(2)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event3"); - assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(10)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event3"); + assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(10)); + }); assertThat(events.get(3)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event4"); - assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(20)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event4"); + assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(20)); + }); assertThat(events.get(4)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event5"); - assertThat(event.getAttributes()) - .isEqualTo(Attributes.builder().put("foo", "bar").build()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(30)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event5"); + assertThat(event.getAttributes()) + .isEqualTo(Attributes.builder().put("foo", "bar").build()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(30)); + }); assertThat(events.get(5)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event6"); - assertThat(event.getAttributes()) - .isEqualTo(Attributes.builder().put("foo", "bar").build()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(1000)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event6"); + assertThat(event.getAttributes()) + .isEqualTo(Attributes.builder().put("foo", "bar").build()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(1000)); + }); } @Test @@ -1185,10 +1177,9 @@ void addLink_FaultIn() { SpanData spanData = span.toSpanData(); assertThat(spanData.getTotalRecordedLinks()).isEqualTo(1); assertThat(spanData.getLinks()) - .satisfiesExactly( - link -> { - assertThat(link.getSpanContext()).isEqualTo(linkedSpan.getSpanContext()); - }); + .satisfiesExactly(link -> { + assertThat(link.getSpanContext()).isEqualTo(linkedSpan.getSpanContext()); + }); } @Test @@ -1591,19 +1582,17 @@ private static Stream setStatusArgs() { StatusData.ok()), Arguments.argumentSet( "setStatus OK after end ignored", - spanConsumer( - span -> { - span.end(); - span.setStatus(StatusCode.OK); - }), + spanConsumer(span -> { + span.end(); + span.setStatus(StatusCode.OK); + }), StatusData.unset()), Arguments.argumentSet( "setStatus ERROR after end ignored", - spanConsumer( - span -> { - span.end(); - span.setStatus(StatusCode.ERROR); - }), + spanConsumer(span -> { + span.end(); + span.setStatus(StatusCode.ERROR); + }), StatusData.unset())); } @@ -1815,12 +1804,11 @@ void testConcurrentModification() throws ExecutionException, InterruptedExceptio SdkSpan span = createTestSpan(SpanKind.INTERNAL); ExecutorService es = Executors.newSingleThreadExecutor(); Future modifierFuture = - es.submit( - () -> { - for (int i = 0; i < 5096 * 5; ++i) { - span.setAttribute("hey" + i, ""); - } - }); + es.submit(() -> { + for (int i = 0; i < 5096 * 5; ++i) { + span.setAttribute("hey" + i, ""); + } + }); try { for (int i = 0; i < 5096 * 5; ++i) { span.toSpanData(); diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderMetricsTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderMetricsTest.java index 504c54a4b19..dc5e34c2ef0 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderMetricsTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderMetricsTest.java @@ -76,28 +76,24 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); span.end(); assertThat(metricReader.collectAllMetrics()) .satisfiesExactlyInAnyOrder( @@ -105,42 +101,36 @@ void simple() { assertThat(m) .hasName("otel.sdk.processor.span.processed") .hasUnit("{span}") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); setSamplingDecision(SamplingDecision.RECORD_ONLY); span = tracer.spanBuilder("span").startSpan(); @@ -149,110 +139,100 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); span.end(); assertThat(metricReader.collectAllMetrics()) .satisfiesExactlyInAnyOrder( m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); setSamplingDecision(SamplingDecision.DROP); span = tracer.spanBuilder("span").startSpan(); @@ -261,126 +241,116 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); span.end(); assertThat(metricReader.collectAllMetrics()) .satisfiesExactlyInAnyOrder( m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); span = tracer @@ -400,142 +370,132 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "local", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); span.end(); assertThat(metricReader.collectAllMetrics()) .satisfiesExactlyInAnyOrder( m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "local", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); setSamplingDecision(SamplingDecision.RECORD_AND_SAMPLE); span = @@ -556,158 +516,148 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "remote", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "local", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); span.end(); assertThat(metricReader.collectAllMetrics()) .satisfiesExactlyInAnyOrder( m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "remote", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "local", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); // Spans rejected after the call to shutdown, regardless of completion so no join. processor.shutdown(); @@ -718,89 +668,85 @@ void simple() { m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor", - ERROR_TYPE, - "already_shutdown")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor", + ERROR_TYPE, + "already_shutdown")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "remote", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_ONLY")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "local", - OTEL_SPAN_SAMPLING_RESULT, - "DROP")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); } @Test @@ -847,82 +793,73 @@ void batch() throws Exception { assertThat(m) .hasName("otel.sdk.processor.span.queue.capacity") .hasUnit("{span}") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.span.queue.size") .hasUnit("{span}") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") .hasUnit("{span}") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor", - ERROR_TYPE, - "queue_full")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "queue_full")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(3) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(3) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); result1.succeed(); result2.fail(); @@ -933,80 +870,71 @@ void batch() throws Exception { m -> assertThat(m) .hasName("otel.sdk.processor.span.queue.capacity") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.span.queue.size") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor", - ERROR_TYPE, - "queue_full")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "queue_full")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(3) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(3) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); lenient().when(mockExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); // Spans rejected after the call to shutdown, regardless of completion so no join. @@ -1018,90 +946,81 @@ void batch() throws Exception { m -> assertThat(m) .hasName("otel.sdk.processor.span.queue.capacity") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.span.queue.size") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(2) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor", - ERROR_TYPE, - "already_shutdown")), - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "batching_span_processor/0", - OTEL_COMPONENT_TYPE, - "batching_span_processor", - ERROR_TYPE, - "queue_full")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "already_shutdown")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "queue_full")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(4) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(4) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); } @Test @@ -1131,42 +1050,36 @@ void simpleExportError() { m -> assertThat(m) .hasName("otel.sdk.processor.span.processed") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_COMPONENT_NAME, - "simple_span_processor/0", - OTEL_COMPONENT_TYPE, - "simple_span_processor")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), m -> assertThat(m) .hasName("otel.sdk.span.started") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(1) - .hasAttributes( - Attributes.of( - OTEL_SPAN_PARENT_ORIGIN, - "none", - OTEL_SPAN_SAMPLING_RESULT, - "RECORD_AND_SAMPLE")))), + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), m -> assertThat(m) .hasName("otel.sdk.span.live") - .hasLongSumSatisfying( - s -> - s.hasPointsSatisfying( - p -> - p.hasValue(0) - .hasAttributes( - Attributes.of( - OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); } private void setSamplingDecision(SamplingDecision decision) { diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java index 61152ff487b..d1e852f2bb9 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java @@ -31,15 +31,14 @@ final void run() { List operationThreads = new ArrayList<>(numThreads); for (Operation operation : operations) { operationThreads.add( - new Thread( - () -> { - for (int i = 0; i < operation.getNumOperations(); i++) { - operation.getUpdater().update(); - Uninterruptibles.sleepUninterruptibly( - Duration.ofMillis(operation.getOperationDelayMs())); - } - countDownLatch.countDown(); - })); + new Thread(() -> { + for (int i = 0; i < operation.getNumOperations(); i++) { + operation.getUpdater().update(); + Uninterruptibles.sleepUninterruptibly( + Duration.ofMillis(operation.getOperationDelayMs())); + } + countDownLatch.countDown(); + })); } for (Thread thread : operationThreads) { diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java index 5e9bc38ff78..2f1b3d005e4 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java @@ -123,10 +123,9 @@ void createNull() { @Test void builderInvalidConfig() { - assertThatThrownBy( - () -> - BatchSpanProcessor.builder(mockSpanExporter) - .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + BatchSpanProcessor.builder(mockSpanExporter) + .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("delay must be non-negative"); assertThatThrownBy(() -> BatchSpanProcessor.builder(mockSpanExporter).setScheduleDelay(1, null)) @@ -135,10 +134,9 @@ void builderInvalidConfig() { assertThatThrownBy(() -> BatchSpanProcessor.builder(mockSpanExporter).setScheduleDelay(null)) .isInstanceOf(NullPointerException.class) .hasMessage("delay"); - assertThatThrownBy( - () -> - BatchSpanProcessor.builder(mockSpanExporter) - .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + BatchSpanProcessor.builder(mockSpanExporter) + .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("timeout must be non-negative"); assertThatThrownBy( @@ -244,16 +242,15 @@ void exportMoreSpansThanTheBufferSize() { spanExporter.succeed(); await() - .untilAsserted( - () -> - assertThat(spanExporter.getExported()) - .containsExactly( - span1.toSpanData(), - span2.toSpanData(), - span3.toSpanData(), - span4.toSpanData(), - span5.toSpanData(), - span6.toSpanData())); + .untilAsserted(() -> + assertThat(spanExporter.getExported()) + .containsExactly( + span1.toSpanData(), + span2.toSpanData(), + span3.toSpanData(), + span4.toSpanData(), + span5.toSpanData(), + span6.toSpanData())); } @Test @@ -525,13 +522,12 @@ public void continuesIfExporterTimesOut() throws InterruptedException { CountDownLatch exported = new CountDownLatch(1); // We return a result we never complete, meaning it will timeout. when(mockSpanExporter.export( - argThat( - spans -> { - assertThat(spans) - .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_1)); - exported.countDown(); - return true; - }))) + argThat(spans -> { + assertThat(spans) + .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_1)); + exported.countDown(); + return true; + }))) .thenReturn(new CompletableResultCode()); createEndedSpan(SPAN_NAME_1); exported.await(); @@ -543,13 +539,12 @@ public void continuesIfExporterTimesOut() throws InterruptedException { reset(mockSpanExporter); when(mockSpanExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); when(mockSpanExporter.export( - argThat( - spans -> { - assertThat(spans) - .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_2)); - exportedAgain.countDown(); - return true; - }))) + argThat(spans -> { + assertThat(spans) + .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_2)); + exportedAgain.countDown(); + return true; + }))) .thenReturn(CompletableResultCode.ofSuccess()); createEndedSpan(SPAN_NAME_2); exported.await(); @@ -718,10 +713,9 @@ void stringRepresentation() { @SuppressLogger(BatchSpanProcessor.class) void exporterThrowsNonRuntimeException() { when(mockSpanExporter.export(anyList())) - .thenAnswer( - invocation -> { - throw new Exception("No export for you."); - }); + .thenAnswer(invocation -> { + throw new Exception("No export for you."); + }); BatchSpanProcessor batchSpanProcessor = BatchSpanProcessor.builder(mockSpanExporter) .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java index fa8831d4d4c..15e3c2d6a4b 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java @@ -93,10 +93,9 @@ void onEndSync_ExporterThrowsCheckedException() { when(readableSpan.getSpanContext()).thenReturn(SAMPLED_SPAN_CONTEXT); when(readableSpan.toSpanData()).thenReturn(spanData); when(spanExporter.export(anyCollection())) - .thenAnswer( - invocation -> { - throw new Exception("No export for you."); - }); + .thenAnswer(invocation -> { + throw new Exception("No export for you."); + }); assertThatCode(() -> simpleSampledSpansProcessor.onEnd(readableSpan)) .doesNotThrowAnyException(); diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessorUsageTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessorUsageTest.java index 3185aa9a1df..0174c949675 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessorUsageTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessorUsageTest.java @@ -74,12 +74,11 @@ void extendedSpanProcessorUsage() { assertThat(exporter.getFinishedSpanItems()) .hasSize(1) .first() - .satisfies( - spanData -> { - assertThat(spanData.getAttributes()) - .containsEntry(FOO_KEY, "Hello!") - .containsEntry(BAR_KEY, "Hello!"); - }); + .satisfies(spanData -> { + assertThat(spanData.getAttributes()) + .containsEntry(FOO_KEY, "Hello!") + .containsEntry(BAR_KEY, "Hello!"); + }); } } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java index 3e9103dd6cc..a91211d89b6 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java @@ -66,30 +66,29 @@ void test() { private void submitAnotherTask(Span initialSpan) { - executor.submit( - () -> { - // Create a new Span for this task - Span taskSpan = tracer.spanBuilder("task").startSpan(); - try (Scope scope = taskSpan.makeCurrent()) { - - // Simulate work strictly related to the initial Span - // and finish it. - try (Scope initialScope = initialSpan.makeCurrent()) { - sleep(50); - } finally { - initialSpan.end(); - } - - // Restore the span for this task and create a subspan - Span subTaskSpan = tracer.spanBuilder("subtask").startSpan(); - try (Scope subTaskScope = subTaskSpan.makeCurrent()) { - sleep(50); - } finally { - subTaskSpan.end(); - } - } finally { - taskSpan.end(); - } - }); + executor.submit(() -> { + // Create a new Span for this task + Span taskSpan = tracer.spanBuilder("task").startSpan(); + try (Scope scope = taskSpan.makeCurrent()) { + + // Simulate work strictly related to the initial Span + // and finish it. + try (Scope initialScope = initialSpan.makeCurrent()) { + sleep(50); + } finally { + initialSpan.end(); + } + + // Restore the span for this task and create a subspan + Span subTaskSpan = tracer.spanBuilder("subtask").startSpan(); + try (Scope subTaskScope = subTaskSpan.makeCurrent()) { + sleep(50); + } finally { + subTaskSpan.end(); + } + } finally { + taskSpan.end(); + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java index 73b6e4ca171..6a0a44eb44f 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java @@ -36,47 +36,45 @@ public void close() { Future tell(String message) { Context parent = Context.current(); phaser.register(); - return executor.submit( - () -> { - Span child = - tracer - .spanBuilder("received") - .setParent(parent) - .setSpanKind(SpanKind.CONSUMER) - .startSpan(); - try (Scope ignored = child.makeCurrent()) { - phaser.arriveAndAwaitAdvance(); // child tracer started - child.addEvent("received " + message); - phaser.arriveAndAwaitAdvance(); // assert size - } finally { - child.end(); - } + return executor.submit(() -> { + Span child = + tracer + .spanBuilder("received") + .setParent(parent) + .setSpanKind(SpanKind.CONSUMER) + .startSpan(); + try (Scope ignored = child.makeCurrent()) { + phaser.arriveAndAwaitAdvance(); // child tracer started + child.addEvent("received " + message); + phaser.arriveAndAwaitAdvance(); // assert size + } finally { + child.end(); + } - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size - }); + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + }); } Future ask(String message) { Context parent = Context.current(); phaser.register(); - return executor.submit( - () -> { - Span span = - tracer - .spanBuilder("received") - .setParent(parent) - .setSpanKind(SpanKind.CONSUMER) - .startSpan(); - try { - phaser.arriveAndAwaitAdvance(); // child tracer started - phaser.arriveAndAwaitAdvance(); // assert size - return "received " + message; - } finally { - span.end(); - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size - } - }); + return executor.submit(() -> { + Span span = + tracer + .spanBuilder("received") + .setParent(parent) + .setSpanKind(SpanKind.CONSUMER) + .startSpan(); + try { + phaser.arriveAndAwaitAdvance(); // child tracer started + phaser.arriveAndAwaitAdvance(); // assert size + return "received " + message; + } finally { + span.end(); + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java index fae1666de87..8d66f8db610 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java @@ -21,26 +21,23 @@ public Client(RequestHandler requestHandler) { public Future send(Object message) { RequestHandlerContext requestHandlerContext = new RequestHandlerContext(); - return executor.submit( - () -> { - TestUtils.sleep(); - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.beforeRequest(message, requestHandlerContext); - }) - .get(); - - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.afterResponse(message, requestHandlerContext); - }) - .get(); - - return message + ":response"; - }); + return executor.submit(() -> { + TestUtils.sleep(); + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.beforeRequest(message, requestHandlerContext); + }) + .get(); + + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.afterResponse(message, requestHandlerContext); + }) + .get(); + + return message + ":response"; + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java index 9c2681ca2b2..f306d7df0f6 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java @@ -57,16 +57,15 @@ void testSimpleError() { @Test void testCallbackError() { Span span = tracer.spanBuilder("one").startSpan(); - executor.submit( - () -> { - try (Scope ignored = span.makeCurrent()) { - throw new RuntimeException("Invalid state"); - } catch (RuntimeException exc) { - span.setStatus(StatusCode.ERROR); - } finally { - span.end(); - } - }); + executor.submit(() -> { + try (Scope ignored = span.makeCurrent()) { + throw new RuntimeException("Invalid state"); + } catch (RuntimeException exc) { + span.setStatus(StatusCode.ERROR); + } finally { + span.end(); + } + }); await() .atMost(Duration.ofSeconds(5)) @@ -115,16 +114,15 @@ void testInstrumentationLayer() { Span span = tracer.spanBuilder("one").startSpan(); try (Scope ignored = span.makeCurrent()) { executor.submit( - new ScopedRunnable( - () -> { - try { - throw new RuntimeException("Invalid state"); - } catch (RuntimeException exc) { - Span.current().setStatus(StatusCode.ERROR); - } finally { - Span.current().end(); - } - })); + new ScopedRunnable(() -> { + try { + throw new RuntimeException("Invalid state"); + } catch (RuntimeException exc) { + Span.current().setStatus(StatusCode.ERROR); + } finally { + Span.current().end(); + } + })); } await() diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java index dee45a33ec3..37debb0144c 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java @@ -60,30 +60,28 @@ void test() throws Exception { */ private void submitTasks(Span parentSpan) { - executor.submit( - () -> { - /* Alternative to calling activate() is to pass it manually to asChildOf() for each - * created Span. */ - try (Scope scope = parentSpan.makeCurrent()) { - Span childSpan = tracer.spanBuilder("task1").startSpan(); - try (Scope childScope = childSpan.makeCurrent()) { - TestUtils.sleep(55); - } finally { - childSpan.end(); - } - } - }); + executor.submit(() -> { + /* Alternative to calling activate() is to pass it manually to asChildOf() for each + * created Span. */ + try (Scope scope = parentSpan.makeCurrent()) { + Span childSpan = tracer.spanBuilder("task1").startSpan(); + try (Scope childScope = childSpan.makeCurrent()) { + TestUtils.sleep(55); + } finally { + childSpan.end(); + } + } + }); - executor.submit( - () -> { - try (Scope scope = parentSpan.makeCurrent()) { - Span childSpan = tracer.spanBuilder("task2").startSpan(); - try (Scope childScope = childSpan.makeCurrent()) { - TestUtils.sleep(85); - } finally { - childSpan.end(); - } - } - }); + executor.submit(() -> { + try (Scope scope = parentSpan.makeCurrent()) { + Span childSpan = tracer.spanBuilder("task2").startSpan(); + try (Scope childScope = childSpan.makeCurrent()) { + TestUtils.sleep(85); + } finally { + childSpan.end(); + } + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java index fb5e8515702..d2e0e5b8ab5 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java @@ -22,13 +22,12 @@ public Client(Tracer tracer) { /** Async execution. */ private Future execute(Object message, ResponseListener responseListener) { - return executor.submit( - () -> { - // send via wire and get response - Object response = message + ":response"; - responseListener.onResponse(response); - return response; - }); + return executor.submit(() -> { + // send via wire and get response + Object response = message + ":response"; + responseListener.onResponse(response); + return response; + }); } public Future send(Object message) { diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java index e54fdbe351e..f4f16389dae 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java @@ -27,17 +27,16 @@ public Client(Tracer tracer, CountDownLatch parentDoneLatch) { public Future send(Object message) { Context parent = Context.current(); - return executor.submit( - () -> { - Span span = tracer.spanBuilder("subtask").setParent(parent).startSpan(); - try (Scope subtaskScope = span.makeCurrent()) { - // Simulate work - make sure we finish *after* the parent Span. - parentDoneLatch.await(); - } finally { - span.end(); - } + return executor.submit(() -> { + Span span = tracer.spanBuilder("subtask").setParent(parent).startSpan(); + try (Scope subtaskScope = span.makeCurrent()) { + // Simulate work - make sure we finish *after* the parent Span. + parentDoneLatch.await(); + } finally { + span.end(); + } - return message + "::response"; - }); + return message + "::response"; + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java index 7a3e87fe439..61f4395ca73 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java @@ -58,27 +58,24 @@ void test() { private void submitCallbacks(Span span) { - executor.submit( - () -> { - try (Scope ignored = span.makeCurrent()) { - span.setAttribute("key1", "1"); + executor.submit(() -> { + try (Scope ignored = span.makeCurrent()) { + span.setAttribute("key1", "1"); - executor.submit( - () -> { - try (Scope ignored12 = span.makeCurrent()) { - span.setAttribute("key2", "2"); + executor.submit(() -> { + try (Scope ignored12 = span.makeCurrent()) { + span.setAttribute("key2", "2"); - executor.submit( - () -> { - try (Scope ignored1 = span.makeCurrent()) { - span.setAttribute("key3", "3"); - } finally { - span.end(); - } - }); - } - }); + executor.submit(() -> { + try (Scope ignored1 = span.makeCurrent()) { + span.setAttribute("key3", "3"); + } finally { + span.end(); + } + }); } }); + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java index 80c5d2dddaf..559062ac27e 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java @@ -39,34 +39,32 @@ void onError(ErrorCallback errorCallback) { @SuppressWarnings("FutureReturnValueIgnored") void success(T result) { for (SuccessCallback callback : successCallbacks) { - context.submit( - () -> { - Span childSpan = tracer.spanBuilder("success").setParent(parent).startSpan(); - childSpan.setAttribute("component", "success"); - try (Scope ignored = childSpan.makeCurrent()) { - callback.accept(result); - } finally { - childSpan.end(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = tracer.spanBuilder("success").setParent(parent).startSpan(); + childSpan.setAttribute("component", "success"); + try (Scope ignored = childSpan.makeCurrent()) { + callback.accept(result); + } finally { + childSpan.end(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } @SuppressWarnings("FutureReturnValueIgnored") void error(Throwable error) { for (ErrorCallback callback : errorCallbacks) { - context.submit( - () -> { - Span childSpan = tracer.spanBuilder("error").setParent(parent).startSpan(); - childSpan.setAttribute("component", "error"); - try (Scope ignored = childSpan.makeCurrent()) { - callback.accept(error); - } finally { - childSpan.end(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = tracer.spanBuilder("error").setParent(parent).startSpan(); + childSpan.setAttribute("component", "error"); + try (Scope ignored = childSpan.makeCurrent()) { + callback.accept(error); + } finally { + childSpan.end(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java index 19b896d5436..7325f3e7795 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java @@ -58,26 +58,23 @@ void testPromiseCallback() { try (Scope ignored = parentSpan.makeCurrent()) { Promise successPromise = new Promise<>(context, tracer); - successPromise.onSuccess( - s -> { - Span.current().addEvent("Promised 1 " + s); - successResult1.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); - successPromise.onSuccess( - s -> { - Span.current().addEvent("Promised 2 " + s); - successResult2.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); + successPromise.onSuccess(s -> { + Span.current().addEvent("Promised 1 " + s); + successResult1.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); + successPromise.onSuccess(s -> { + Span.current().addEvent("Promised 2 " + s); + successResult2.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); Promise errorPromise = new Promise<>(context, tracer); - errorPromise.onError( - t -> { - errorResult.set(t); - phaser.arriveAndAwaitAdvance(); // result set - }); + errorPromise.onError(t -> { + errorResult.set(t); + phaser.arriveAndAwaitAdvance(); // result set + }); assertThat(otelTesting.getSpans().size()).isEqualTo(0); successPromise.success("success!"); diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java index aef5423d5f2..48ab85f8a86 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java @@ -22,15 +22,14 @@ public Client(RequestHandler requestHandler) { /** Send a request....... */ public Future send(Object message) { - return executor.submit( - () -> { - TestUtils.sleep(); - requestHandler.beforeRequest(message); + return executor.submit(() -> { + TestUtils.sleep(); + requestHandler.beforeRequest(message); - TestUtils.sleep(); - requestHandler.afterResponse(message); + TestUtils.sleep(); + requestHandler.afterResponse(message); - return message + ":response"; - }); + return message + ":response"; + }); } } From 0e82d8071f4cf4614fa54af22c011b5d1bd2344d Mon Sep 17 00:00:00 2001 From: Jack Berg <34418638+jack-berg@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:48:07 -0600 Subject: [PATCH 3/4] More formatting --- .../otlp/internal/GrpcExporterTest.java | 128 ++++++++---------- .../testing/assertj/MetricAssertionsTest.java | 69 ++++------ .../exporter/InMemoryMetricExporterTest.java | 13 +- 3 files changed, 93 insertions(+), 117 deletions(-) diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java index 2cc3b4bfb96..2587d6101ed 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java @@ -149,75 +149,65 @@ public int getContentLength() { assertThat(inMemoryMetrics.collectAllMetrics()) .hasSize(3) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName(signalMetricPrefix + "inflight") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName(signalMetricPrefix + "exported") - .hasUnit(expectedUnit) - .hasLongSumSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> pa.hasAttributes(expectedAttributes).hasValue(42), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "" + UNAVAILABLE.getValue()) - .build()) - .hasValue(15), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "java.io.IOException") - .build()) - .hasValue(7)))) - .anySatisfy( - metric -> - OpenTelemetryAssertions.assertThat(metric) - .hasName("otel.sdk.exporter.operation.duration") - .hasUnit("s") - .hasHistogramSatisfying( - ma -> - ma.hasPointsSatisfying( - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.RPC_RESPONSE_STATUS_CODE, - GrpcStatusCode.OK.name()) - .build()) - .hasBucketCounts(1), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "" + UNAVAILABLE.getValue()) - .put( - SemConvConstants.RPC_RESPONSE_STATUS_CODE, - UNAVAILABLE.name()) - .build()) - .hasBucketCounts(1), - pa -> - pa.hasAttributes( - expectedAttributes.toBuilder() - .put( - SemConvConstants.ERROR_TYPE, - "java.io.IOException") - .build()) - .hasBucketCounts(1)))); + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "exported") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.ERROR_TYPE, + "" + UNAVAILABLE.getValue()) + .build()) + .hasValue(15), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasValue(7)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasUnit("s") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.RPC_RESPONSE_STATUS_CODE, + GrpcStatusCode.OK.name()) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.ERROR_TYPE, + "" + UNAVAILABLE.getValue()) + .put( + SemConvConstants.RPC_RESPONSE_STATUS_CODE, + UNAVAILABLE.name()) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasBucketCounts(1)))); } } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java index f021c17e495..846d5340f27 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java @@ -483,63 +483,52 @@ static Stream pointShortcuts() { @Test void pointShortcutsRejectMismatchedPoints() { - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramPointsSatisfying(point -> point.hasCount(42))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC).hasHistogramPointsSatisfying(point -> point.hasCount(42))) .isInstanceOf(AssertionError.class); } @Test void pointShortcutsRequireExactMatching() { - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugePointsSatisfying(point -> point.hasValue(1))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC).hasLongGaugePointsSatisfying(point -> point.hasValue(1))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugePointsSatisfying( - point -> point.hasValue(Long.MAX_VALUE), - point -> point.hasValue(1), - point -> point.hasValue(1))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugePointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), + point -> point.hasValue(1), + point -> point.hasValue(1))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugePointsSatisfying( - point -> point.hasValue(1), point -> point.hasValue(1))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugePointsSatisfying( + point -> point.hasValue(1), point -> point.hasValue(1))) .isInstanceOf(AssertionError.class); } @Test @SuppressWarnings("NullAway") void pointShortcutsNullAssertions() { - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramPointsSatisfying((Consumer[]) null)) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramPointsSatisfying((Consumer[]) null)) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramPointsSatisfying((Iterable>) null)) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramPointsSatisfying((Iterable>) null)) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramPointsSatisfying((Consumer) null)) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramPointsSatisfying((Consumer) null)) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasHistogramPointsSatisfying((Consumer[]) null)) + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasHistogramPointsSatisfying((Consumer[]) null)) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat((MetricData) null) - .hasHistogramPointsSatisfying((Consumer[]) null)) + assertThatThrownBy(() -> + assertThat((MetricData) null) + .hasHistogramPointsSatisfying((Consumer[]) null)) .isInstanceOf(AssertionError.class); } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java index 6ae31491b40..45a03c281b3 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java @@ -137,17 +137,14 @@ void export_deltaPreferred() { metric -> assertThat(metric) .hasName("counter") - .hasLongSumSatisfying( - sum -> - sum.isDelta().hasPointsSatisfying(point -> point.hasValue(value))), + .hasLongSumSatisfying(sum -> + sum.isDelta().hasPointsSatisfying(point -> point.hasValue(value))), metric -> assertThat(metric) .hasName("upDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> point.hasValue(value == 1 ? 1 : 0)))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> point.hasValue(value == 1 ? 1 : 0)))); deltaExporter.reset(); } } From e2815b3cf2878e86ff3df2aa7bb355937349eb35 Mon Sep 17 00:00:00 2001 From: Jack Berg <34418638+jack-berg@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:56:14 -0600 Subject: [PATCH 4/4] Fix build --- .../exporter/otlp/internal/GrpcExporterTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java index 2587d6101ed..60bd32ee181 100644 --- a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java @@ -187,7 +187,7 @@ public int getContentLength() { pa.hasAttributes( expectedAttributes.toBuilder() .put( - SemConvConstants.RPC_RESPONSE_STATUS_CODE, + SemConvConstants.RPC_STATUS_CODE, GrpcStatusCode.OK.name()) .build()) .hasBucketCounts(1), @@ -197,9 +197,7 @@ public int getContentLength() { .put( SemConvConstants.ERROR_TYPE, "" + UNAVAILABLE.getValue()) - .put( - SemConvConstants.RPC_RESPONSE_STATUS_CODE, - UNAVAILABLE.name()) + .put(SemConvConstants.RPC_STATUS_CODE, UNAVAILABLE.name()) .build()) .hasBucketCounts(1), pa ->