diff --git a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs index 59088ce0877..355ab376743 100644 --- a/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs +++ b/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpExporterOptions.cs @@ -30,7 +30,7 @@ public class OtlpExporterOptions : IOtlpExporterOptions internal static readonly KeyValuePair[] StandardHeaders = new KeyValuePair[] { - new KeyValuePair("User-Agent", GetUserAgentString()), + new("User-Agent", GetUserAgentString()), }; internal readonly Func DefaultHttpClientFactory; diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/BaseOtlpHttpExportClientTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/BaseOtlpHttpExportClientTests.cs index a846af33a4e..36d534df9a1 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/BaseOtlpHttpExportClientTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/BaseOtlpHttpExportClientTests.cs @@ -17,7 +17,7 @@ public class BaseOtlpHttpExportClientTests [InlineData("https://custom.host", null, "https://custom.host")] [InlineData("http://custom.host:44318/custom/path", null, "http://custom.host:44318/custom/path")] [InlineData("https://custom.host", "http://from.otel.exporter.env.var", "https://custom.host")] - public void ValidateOtlpHttpExportClientEndpoint(string optionEndpoint, string endpointEnvVar, string expectedExporterEndpoint) + public void ValidateOtlpHttpExportClientEndpoint(string? optionEndpoint, string? endpointEnvVar, string expectedExporterEndpoint) { try { diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/Implementation/ExportClient/OtlpHttpTraceExportClientTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/Implementation/ExportClient/OtlpHttpTraceExportClientTests.cs index d796e36ef5a..0b932f87d39 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/Implementation/ExportClient/OtlpHttpTraceExportClientTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/Implementation/ExportClient/OtlpHttpTraceExportClientTests.cs @@ -63,8 +63,8 @@ public void NewOtlpHttpTraceExportClient_OtlpExporterOptions_ExporterHasCorrectP public void SendExportRequest_ExportTraceServiceRequest_SendsCorrectHttpRequest(bool includeServiceNameInResource) { // Arrange - var evenTags = new[] { new KeyValuePair("k0", "v0") }; - var oddTags = new[] { new KeyValuePair("k1", "v1") }; + var evenTags = new[] { new KeyValuePair("k0", "v0") }; + var oddTags = new[] { new KeyValuePair("k1", "v1") }; var sources = new[] { new ActivitySource("even", "2.4.6"), @@ -116,7 +116,8 @@ public void SendExportRequest_ExportTraceServiceRequest_SendsCorrectHttpRequest( var activityKind = isEven ? ActivityKind.Client : ActivityKind.Server; var activityTags = isEven ? evenTags : oddTags; - using Activity activity = source.StartActivity($"span-{i}", activityKind, parentContext: default, activityTags); + using Activity? activity = source.StartActivity($"span-{i}", activityKind, parentContext: default, activityTags); + Assert.NotNull(activity); processor.OnEnd(activity); } @@ -141,6 +142,7 @@ void RunTest(Batch batch) Assert.True(result.Success); Assert.NotNull(httpRequest); Assert.Equal(HttpMethod.Post, httpRequest.Method); + Assert.NotNull(httpRequest.RequestUri); Assert.Equal("http://localhost:4317/", httpRequest.RequestUri.AbsoluteUri); Assert.Equal(OtlpExporterOptions.StandardHeaders.Length + 2, httpRequest.Headers.Count()); Assert.Contains(httpRequest.Headers, h => h.Key == header1.Name && h.Value.First() == header1.Value); diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/IntegrationTest/IntegrationTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/IntegrationTest/IntegrationTests.cs index 14b73571e35..3e40b9c6d9f 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/IntegrationTest/IntegrationTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/IntegrationTest/IntegrationTests.cs @@ -21,7 +21,7 @@ public sealed class IntegrationTests : IDisposable private const int ExportIntervalMilliseconds = 10000; private static readonly SdkLimitOptions DefaultSdkLimitOptions = new(); private static readonly ExperimentalOptions DefaultExperimentalOptions = new(); - private static readonly string CollectorHostname = SkipUnlessEnvVarFoundTheoryAttribute.GetEnvironmentVariable(CollectorHostnameEnvVarName); + private static readonly string? CollectorHostname = SkipUnlessEnvVarFoundTheoryAttribute.GetEnvironmentVariable(CollectorHostnameEnvVarName); private readonly OpenTelemetryEventListener openTelemetryEventListener; public IntegrationTests(ITestOutputHelper outputHelper) @@ -61,7 +61,7 @@ public void TraceExportResultIsSuccess(OtlpExportProtocol protocol, string endpo }, }; - DelegatingExporter delegatingExporter = null; + DelegatingExporter? delegatingExporter = null; var exportResults = new List(); var activitySourceName = "otlp.collector.test"; @@ -140,7 +140,7 @@ public void MetricExportResultIsSuccess(OtlpExportProtocol protocol, string endp Protocol = protocol, }; - DelegatingExporter delegatingExporter = null; + DelegatingExporter? delegatingExporter = null; var exportResults = new List(); var meterName = "otlp.collector.test"; @@ -220,7 +220,7 @@ public void LogExportResultIsSuccess(OtlpExportProtocol protocol, string endpoin Protocol = protocol, }; - DelegatingExporter delegatingExporter = null; + DelegatingExporter delegatingExporter; var exportResults = new List(); var processorOptions = new LogRecordExportProcessorOptions { @@ -298,8 +298,8 @@ protected override void OnEventSourceCreated(EventSource eventSource) protected override void OnEventWritten(EventWrittenEventArgs eventData) { - string message; - if (eventData.Message != null && (eventData.Payload?.Count ?? 0) > 0) + string? message; + if (eventData.Message != null && eventData.Payload != null && eventData.Payload.Count > 0) { message = string.Format(eventData.Message, eventData.Payload.ToArray()); } diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/MockCollectorIntegrationTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/MockCollectorIntegrationTests.cs index a5ce7a0a279..e72a6773b81 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/MockCollectorIntegrationTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/MockCollectorIntegrationTests.cs @@ -3,6 +3,7 @@ #if !NETFRAMEWORK using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Net; using Google.Protobuf; using Grpc.Core; @@ -94,12 +95,12 @@ public async Task TestRecoveryAfterFailedExport() using var source = new ActivitySource(activitySourceName); - source.StartActivity().Stop(); + source.StartActivity()?.Stop(); Assert.Single(exportResults); Assert.Equal(ExportResult.Failure, exportResults[0]); - source.StartActivity().Stop(); + source.StartActivity()?.Stop(); Assert.Equal(2, exportResults.Count); Assert.Equal(ExportResult.Success, exportResults[1]); @@ -179,7 +180,7 @@ public async Task GrpcRetryTests(bool useRetryTransmissionHandler, ExportResult var exporterOptions = new OtlpExporterOptions() { Endpoint = endpoint, TimeoutMilliseconds = 20000, Protocol = OtlpExportProtocol.Grpc }; var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null }) + .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null }) .Build(); var otlpExporter = new OtlpTraceExporter(exporterOptions, new SdkLimitOptions(), new ExperimentalOptions(configuration)); @@ -192,6 +193,7 @@ public async Task GrpcRetryTests(bool useRetryTransmissionHandler, ExportResult .Build(); using var activity = source.StartActivity("GrpcRetryTest"); + Assert.NotNull(activity); activity.Stop(); using var batch = new Batch([activity], 1); @@ -263,7 +265,7 @@ public async Task HttpRetryTests(bool useRetryTransmissionHandler, ExportResult var exporterOptions = new OtlpExporterOptions() { Endpoint = endpoint, TimeoutMilliseconds = 20000, Protocol = OtlpExportProtocol.HttpProtobuf }; var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null }) + .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null }) .Build(); var otlpExporter = new OtlpTraceExporter(exporterOptions, new SdkLimitOptions(), new ExperimentalOptions(configuration)); @@ -276,6 +278,7 @@ public async Task HttpRetryTests(bool useRetryTransmissionHandler, ExportResult .Build(); using var activity = source.StartActivity("HttpRetryTest"); + Assert.NotNull(activity); activity.Stop(); using var batch = new Batch([activity], 1); @@ -348,7 +351,7 @@ public async Task HttpPersistentStorageRetryTests(bool usePersistentStorageTrans // TODO: update this to configure via experimental environment variable. OtlpExporterTransmissionHandler transmissionHandler; - MockFileProvider mockProvider = null; + MockFileProvider? mockProvider = null; if (usePersistentStorageTransmissionHandler) { mockProvider = new MockFileProvider(); @@ -378,6 +381,7 @@ public async Task HttpPersistentStorageRetryTests(bool usePersistentStorageTrans .Build(); using var activity = source.StartActivity("HttpPersistentStorageRetryTest"); + Assert.NotNull(activity); activity.Stop(); using var batch = new Batch([activity], 1); @@ -387,12 +391,13 @@ public async Task HttpPersistentStorageRetryTests(bool usePersistentStorageTrans if (usePersistentStorageTransmissionHandler) { + Assert.NotNull(mockProvider); if (exportResult == ExportResult.Success) { - Assert.Single(mockProvider.TryGetBlobs()); + Assert.Single(mockProvider!.TryGetBlobs()); // Force Retry - Assert.True((transmissionHandler as OtlpExporterPersistentStorageTransmissionHandler).InitiateAndWaitForRetryProcess(-1)); + Assert.True((transmissionHandler as OtlpExporterPersistentStorageTransmissionHandler)!.InitiateAndWaitForRetryProcess(-1)); Assert.False(mockProvider.TryGetBlob(out _)); } @@ -485,7 +490,7 @@ public async Task GrpcPersistentStorageRetryTests(bool usePersistentStorageTrans // TODO: update this to configure via experimental environment variable. OtlpExporterTransmissionHandler transmissionHandler; - MockFileProvider mockProvider = null; + MockFileProvider? mockProvider = null; if (usePersistentStorageTransmissionHandler) { mockProvider = new MockFileProvider(); @@ -515,6 +520,7 @@ public async Task GrpcPersistentStorageRetryTests(bool usePersistentStorageTrans .Build(); using var activity = source.StartActivity("GrpcPersistentStorageRetryTest"); + Assert.NotNull(activity); activity.Stop(); using var batch = new Batch([activity], 1); @@ -524,12 +530,13 @@ public async Task GrpcPersistentStorageRetryTests(bool usePersistentStorageTrans if (usePersistentStorageTransmissionHandler) { + Assert.NotNull(mockProvider); if (exportResult == ExportResult.Success) { Assert.Single(mockProvider.TryGetBlobs()); // Force Retry - Assert.True((transmissionHandler as OtlpExporterPersistentStorageTransmissionHandler).InitiateAndWaitForRetryProcess(-1)); + Assert.True((transmissionHandler as OtlpExporterPersistentStorageTransmissionHandler)!.InitiateAndWaitForRetryProcess(-1)); Assert.False(mockProvider.TryGetBlob(out _)); } @@ -630,7 +637,7 @@ protected override bool OnTryCreateBlob(byte[] buffer, out PersistentBlob blob) return blob.TryWrite(buffer); } - protected override bool OnTryGetBlob(out PersistentBlob blob) + protected override bool OnTryGetBlob([NotNullWhen(true)] out PersistentBlob? blob) { blob = this.GetBlobs().FirstOrDefault(); diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests.csproj b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests.csproj index ad60a2385a2..21b320de546 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests.csproj +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests.csproj @@ -2,8 +2,6 @@ $(TargetFrameworksForTests) - - disable diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpAttributeTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpAttributeTests.cs index af31f32c795..a325874fb30 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpAttributeTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpAttributeTests.cs @@ -1,6 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +using System.Diagnostics.CodeAnalysis; using Google.Protobuf.Collections; using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation; using Xunit; @@ -13,19 +14,19 @@ public class OtlpAttributeTests [Fact] public void NullValueAttribute() { - var kvp = new KeyValuePair("key", null); - Assert.False(TryTransformTag(kvp, out var _)); + var kvp = new KeyValuePair("key", null); + Assert.False(TryTransformTag(kvp, out _)); } [Fact] public void EmptyArrays() { - var kvp = new KeyValuePair("key", Array.Empty()); + var kvp = new KeyValuePair("key", Array.Empty()); Assert.True(TryTransformTag(kvp, out var attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase); Assert.Empty(attribute.Value.ArrayValue.Values); - kvp = new KeyValuePair("key", Array.Empty()); + kvp = new KeyValuePair("key", Array.Empty()); Assert.True(TryTransformTag(kvp, out attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase); Assert.Empty(attribute.Value.ArrayValue.Values); @@ -48,7 +49,7 @@ public void EmptyArrays() [InlineData(new long[] { 1, 2, 3 })] public void IntegralTypesSupported(object value) { - var kvp = new KeyValuePair("key", value); + var kvp = new KeyValuePair("key", value); Assert.True(TryTransformTag(kvp, out var attribute)); switch (value) @@ -77,7 +78,7 @@ public void IntegralTypesSupported(object value) [InlineData(new double[] { 1, 2, 3 })] public void FloatingPointTypesSupported(object value) { - var kvp = new KeyValuePair("key", value); + var kvp = new KeyValuePair("key", value); Assert.True(TryTransformTag(kvp, out var attribute)); switch (value) @@ -104,7 +105,7 @@ public void FloatingPointTypesSupported(object value) [InlineData(new bool[] { true, false, true })] public void BooleanTypeSupported(object value) { - var kvp = new KeyValuePair("key", value); + var kvp = new KeyValuePair("key", value); Assert.True(TryTransformTag(kvp, out var attribute)); switch (value) @@ -131,7 +132,7 @@ public void BooleanTypeSupported(object value) [InlineData("string")] public void StringTypesSupported(object value) { - var kvp = new KeyValuePair("key", value); + var kvp = new KeyValuePair("key", value); Assert.True(TryTransformTag(kvp, out var attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.StringValue, attribute.Value.ValueCase); Assert.Equal(Convert.ToString(value), attribute.Value.StringValue); @@ -141,9 +142,9 @@ public void StringTypesSupported(object value) public void ObjectArrayTypesSupported() { var obj = new object(); - var objectArray = new object[] { null, "a", 'b', true, int.MaxValue, long.MaxValue, float.MaxValue, double.MaxValue, obj }; + var objectArray = new object?[] { null, "a", 'b', true, int.MaxValue, long.MaxValue, float.MaxValue, double.MaxValue, obj }; - var kvp = new KeyValuePair("key", objectArray); + var kvp = new KeyValuePair("key", objectArray); Assert.True(TryTransformTag(kvp, out var attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase); @@ -179,14 +180,14 @@ public void ObjectArrayTypesSupported() public void StringArrayTypesSupported() { var charArray = new char[] { 'a', 'b', 'c' }; - var stringArray = new string[] { "a", "b", "c", string.Empty, null }; + var stringArray = new string?[] { "a", "b", "c", string.Empty, null }; - var kvp = new KeyValuePair("key", charArray); + var kvp = new KeyValuePair("key", charArray); Assert.True(TryTransformTag(kvp, out var attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase); Assert.Equal(charArray.Select(x => x.ToString()), attribute.Value.ArrayValue.Values.Select(x => x.StringValue)); - kvp = new KeyValuePair("key", stringArray); + kvp = new KeyValuePair("key", stringArray); Assert.True(TryTransformTag(kvp, out attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase); @@ -221,12 +222,12 @@ public void ToStringIsCalledForAllOtherTypes() new nint[] { 1, 2, 3 }, new nuint[] { 1, 2, 3 }, new decimal[] { 1, 2, 3 }, - new object[] { new object[3], new object(), null }, + new object?[] { new object[3], new object(), null }, }; foreach (var value in testValues) { - var kvp = new KeyValuePair("key", value); + var kvp = new KeyValuePair("key", value); Assert.True(TryTransformTag(kvp, out var attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.StringValue, attribute.Value.ValueCase); Assert.Equal(value.ToString(), attribute.Value.StringValue); @@ -234,11 +235,12 @@ public void ToStringIsCalledForAllOtherTypes() foreach (var value in testArrayValues) { - var kvp = new KeyValuePair("key", value); + var kvp = new KeyValuePair("key", value); Assert.True(TryTransformTag(kvp, out var attribute)); Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase); var array = value as Array; + Assert.NotNull(array); for (var i = 0; i < attribute.Value.ArrayValue.Values.Count; ++i) { var expectedValue = array.GetValue(i)?.ToString(); @@ -249,7 +251,7 @@ public void ToStringIsCalledForAllOtherTypes() Assert.Equal(expectedValueCase, attribute.Value.ArrayValue.Values[i].ValueCase); if (expectedValueCase != OtlpCommon.AnyValue.ValueOneofCase.None) { - Assert.Equal(array.GetValue(i).ToString(), attribute.Value.ArrayValue.Values[i].StringValue); + Assert.Equal(array.GetValue(i)!.ToString(), attribute.Value.ArrayValue.Values[i].StringValue); } } } @@ -258,14 +260,14 @@ public void ToStringIsCalledForAllOtherTypes() [Fact] public void ExceptionInToStringIsCaught() { - var kvp = new KeyValuePair("key", new MyToStringMethodThrowsAnException()); - Assert.False(TryTransformTag(kvp, out var _)); + var kvp = new KeyValuePair("key", new MyToStringMethodThrowsAnException()); + Assert.False(TryTransformTag(kvp, out _)); - kvp = new KeyValuePair("key", new object[] { 1, false, new MyToStringMethodThrowsAnException() }); - Assert.False(TryTransformTag(kvp, out var _)); + kvp = new KeyValuePair("key", new object[] { 1, false, new MyToStringMethodThrowsAnException() }); + Assert.False(TryTransformTag(kvp, out _)); } - private static bool TryTransformTag(KeyValuePair tag, out OtlpCommon.KeyValue attribute) + private static bool TryTransformTag(KeyValuePair tag, [NotNullWhen(true)] out OtlpCommon.KeyValue? attribute) { var destination = new RepeatedField(); diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs index 2b7810dfadf..4018998b890 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsExtensionsTests.cs @@ -73,7 +73,7 @@ public void GetMetadataFromHeadersThrowsExceptionOnInvalidFormat(string headers) [Theory] [InlineData("")] [InlineData(null)] - public void GetHeaders_NoOptionHeaders_ReturnsStandardHeaders(string optionHeaders) + public void GetHeaders_NoOptionHeaders_ReturnsStandardHeaders(string? optionHeaders) { var options = new OtlpExporterOptions { @@ -158,19 +158,19 @@ public void AppendPathIfNotPresent_TracesPath_AppendsCorrectly(string inputUri, [InlineData(OtlpExportProtocol.Grpc, typeof(OtlpGrpcLogExportClient), false, 10000, "disk")] [InlineData(OtlpExportProtocol.HttpProtobuf, typeof(OtlpHttpLogExportClient), false, 10000, "disk")] [InlineData(OtlpExportProtocol.HttpProtobuf, typeof(OtlpHttpLogExportClient), true, 8000, "disk")] - public void GetTransmissionHandler_InitializesCorrectHandlerExportClientAndTimeoutValue(OtlpExportProtocol protocol, Type exportClientType, bool customHttpClient, int expectedTimeoutMilliseconds, string retryStrategy) + public void GetTransmissionHandler_InitializesCorrectHandlerExportClientAndTimeoutValue(OtlpExportProtocol protocol, Type exportClientType, bool customHttpClient, int expectedTimeoutMilliseconds, string? retryStrategy) { var exporterOptions = new OtlpExporterOptions() { Protocol = protocol }; if (customHttpClient) { exporterOptions.HttpClientFactory = () => { - return new HttpClient() { Timeout = TimeSpan.FromMilliseconds(expectedTimeoutMilliseconds) }; + return new HttpClient { Timeout = TimeSpan.FromMilliseconds(expectedTimeoutMilliseconds) }; }; } var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.OtlpRetryEnvVar] = retryStrategy }) + .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.OtlpRetryEnvVar] = retryStrategy }) .Build(); if (exportClientType == typeof(OtlpGrpcTraceExportClient) || exportClientType == typeof(OtlpHttpTraceExportClient)) @@ -193,7 +193,7 @@ public void GetTransmissionHandler_InitializesCorrectHandlerExportClientAndTimeo } } - private static void AssertTransmissionHandler(OtlpExporterTransmissionHandler transmissionHandler, Type exportClientType, int expectedTimeoutMilliseconds, string retryStrategy) + private static void AssertTransmissionHandler(OtlpExporterTransmissionHandler transmissionHandler, Type exportClientType, int expectedTimeoutMilliseconds, string? retryStrategy) { if (retryStrategy == "in_memory") { diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs index dc79c95c07b..c22f0e14863 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpExporterOptionsTests.cs @@ -74,7 +74,7 @@ public void OtlpExporterOptions_UsingIConfiguration(object testDataObject) [Fact] public void OtlpExporterOptions_InvalidEnvironmentVariableOverride() { - var values = new Dictionary() + var values = new Dictionary { ["EndpointWithInvalidValue"] = "invalid", ["TimeoutWithInvalidValue"] = "invalid", @@ -104,7 +104,7 @@ public void OtlpExporterOptions_InvalidEnvironmentVariableOverride() [Fact] public void OtlpExporterOptions_SetterOverridesEnvironmentVariable() { - var values = new Dictionary() + var values = new Dictionary { ["Endpoint"] = "http://test:8888", ["Timeout"] = "2000", @@ -169,7 +169,7 @@ public void OtlpExporterOptions_SettingEndpointToNullResetsAppendSignalPathToEnd { var options = new OtlpExporterOptions(OtlpExporterOptionsConfigurationType.Default); - Assert.Throws(() => options.Endpoint = null); + Assert.Throws(() => options.Endpoint = null!); } [Fact] @@ -177,7 +177,7 @@ public void OtlpExporterOptions_HttpClientFactoryThrowsWhenSetToNull() { var options = new OtlpExporterOptions(OtlpExporterOptionsConfigurationType.Default); - Assert.Throws(() => options.HttpClientFactory = null); + Assert.Throws(() => options.HttpClientFactory = null!); } [Fact] diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs index f494a2683c6..c47fa7b5a5d 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpLogExporterTests.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation; using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.Transmission; using OpenTelemetry.Internal; @@ -100,7 +99,7 @@ public void UserHttpFactoryCalledWhenUsingHttpProtobuf() Assert.Equal(2, invocations); } - options.HttpClientFactory = () => null; + options.HttpClientFactory = () => null!; Assert.Throws(() => { using var exporter = new OtlpLogExporter(options); @@ -218,6 +217,7 @@ public void AddOtlpLogExporterParseStateValueCanBeTurnedOffHosting(bool parseSta var host = hostBuilder.Build(); var loggerFactory = host.Services.GetService(); + Assert.NotNull(loggerFactory); var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); logger.Log(LogLevel.Information, default, new { propertyA = "valueA" }, null, (s, e) => "Custom state log message"); Assert.Single(logRecords); @@ -290,7 +290,7 @@ public void OtlpLogRecordTestWhenStateValuesArePopulated() [InlineData("true")] [InlineData("false")] [InlineData(null)] - public void CheckToOtlpLogRecordEventId(string emitLogEventAttributes) + public void CheckToOtlpLogRecordEventId(string? emitLogEventAttributes) { var logRecords = new List(); using var loggerFactory = LoggerFactory.Create(builder => @@ -309,7 +309,7 @@ public void CheckToOtlpLogRecordEventId(string emitLogEventAttributes) Assert.Single(logRecords); var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.EmitLogEventEnvVar] = emitLogEventAttributes }) + .AddInMemoryCollection(new Dictionary { [ExperimentalOptions.EmitLogEventEnvVar] = emitLogEventAttributes }) .Build(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new(configuration)); @@ -375,6 +375,7 @@ public void CheckToOtlpLogRecordTimestamps() var logRecord = logRecords[0]; var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.True(otlpLogRecord.TimeUnixNano > 0); Assert.True(otlpLogRecord.ObservedTimeUnixNano > 0); } @@ -397,9 +398,10 @@ public void CheckToOtlpLogRecordTraceIdSpanIdFlagWithNoActivity() var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); Assert.Null(Activity.Current); + Assert.NotNull(otlpLogRecord); Assert.True(otlpLogRecord.TraceId.IsEmpty); Assert.True(otlpLogRecord.SpanId.IsEmpty); - Assert.True(otlpLogRecord.Flags == 0); + Assert.Equal(0u, otlpLogRecord.Flags); } [Fact] @@ -428,6 +430,7 @@ public void CheckToOtlpLogRecordSpanIdTraceIdAndFlag() var logRecord = logRecords[0]; var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Equal(expectedTraceId.ToString(), ActivityTraceId.CreateFromBytes(otlpLogRecord.TraceId.ToByteArray()).ToString()); Assert.Equal(expectedSpanId.ToString(), ActivitySpanId.CreateFromBytes(otlpLogRecord.SpanId.ToByteArray()).ToString()); Assert.Equal((uint)logRecord.TraceFlags, otlpLogRecord.Flags); @@ -465,6 +468,7 @@ public void CheckToOtlpLogRecordSeverityLevelAndText(LogLevel logLevel) #pragma warning disable CS0618 // Type or member is obsolete Assert.Equal(logRecord.LogLevel.ToString(), otlpLogRecord.SeverityText); #pragma warning restore CS0618 // Type or member is obsolete + Assert.NotNull(logRecord.Severity); Assert.Equal((int)logRecord.Severity, (int)otlpLogRecord.SeverityNumber); switch (logLevel) { @@ -546,7 +550,7 @@ public void CheckToOtlpLogRecordBodyIsPopulated(bool includeFormattedMessage) // Scenario 3 - Using the raw ILogger.Log Method, but with null // formatter. - logger.Log(LogLevel.Information, default, "state", exception: null, formatter: null); + logger.Log(LogLevel.Information, default, "state", exception: null, formatter: null!); Assert.Single(logRecords); logRecord = logRecords[0]; @@ -590,6 +594,7 @@ public void LogRecordBodyIsExportedWhenUsingBridgeApi(bool isBodySet) var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecords[0]); + Assert.NotNull(otlpLogRecord); if (isBodySet) { Assert.Equal("Hello world", otlpLogRecord.Body?.StringValue); @@ -601,6 +606,7 @@ public void LogRecordBodyIsExportedWhenUsingBridgeApi(bool isBodySet) otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecords[1]); + Assert.NotNull(otlpLogRecord); Assert.Equal(2, otlpLogRecord.Attributes.Count); var index = 0; @@ -638,6 +644,7 @@ public void CheckToOtlpLogRecordExceptionAttributes() var otlpLogRecordAttributes = otlpLogRecord.Attributes.ToString(); Assert.Contains(SemanticConventions.AttributeExceptionType, otlpLogRecordAttributes); + Assert.NotNull(logRecord.Exception); Assert.Contains(logRecord.Exception.GetType().Name, otlpLogRecordAttributes); Assert.Contains(SemanticConventions.AttributeExceptionMessage, otlpLogRecordAttributes); @@ -785,6 +792,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsFalse_DoesNotContainScopeAttribu var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); var actualScope = TryGetAttribute(otlpLogRecord, expectedScopeKey); Assert.Null(actualScope); } @@ -819,6 +827,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeStrin var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Single(otlpLogRecord.Attributes); var actualScope = TryGetAttribute(otlpLogRecord, scopeKey); Assert.NotNull(actualScope); @@ -857,6 +866,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeBoolV var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Single(otlpLogRecord.Attributes); var actualScope = TryGetAttribute(otlpLogRecord, scopeKey); Assert.NotNull(actualScope); @@ -907,6 +917,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeIntVa var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Single(otlpLogRecord.Attributes); var actualScope = TryGetAttribute(otlpLogRecord, scopeKey); Assert.NotNull(actualScope); @@ -935,7 +946,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeDoubl // Act. using (logger.BeginScope(new List> { - new KeyValuePair(scopeKey, scopeValue), + new(scopeKey, scopeValue), })) { logger.LogInformation("Some log information message."); @@ -945,6 +956,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeDoubl var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Single(otlpLogRecord.Attributes); var actualScope = TryGetAttribute(otlpLogRecord, scopeKey); Assert.NotNull(actualScope); @@ -973,7 +985,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeDoubl // Act. using (logger.BeginScope(new List> { - new KeyValuePair(scopeKey, scopeValue), + new(scopeKey, scopeValue), })) { logger.LogInformation("Some log information message."); @@ -983,6 +995,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeDoubl var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Single(otlpLogRecord.Attributes); var actualScope = TryGetAttribute(otlpLogRecord, scopeKey); Assert.NotNull(actualScope); @@ -1038,6 +1051,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_AndScopeStateIsOfPrimitiveT var logger = loggerFactory.CreateLogger(nameof(OtlpLogExporterTests)); var scopeState = Activator.CreateInstance(typeOfScopeState); + Assert.NotNull(scopeState); // Act. using (logger.BeginScope(scopeState)) @@ -1080,6 +1094,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_AndScopeStateIsOfDictionary var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Single(otlpLogRecord.Attributes); var actualScope = TryGetAttribute(otlpLogRecord, scopeKey); Assert.NotNull(actualScope); @@ -1105,10 +1120,11 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_AndScopeStateIsOfEnumerable const string scopeKey = "Some scope key"; const string scopeValue = "Some scope value"; - var scopeValues = new List> { new KeyValuePair(scopeKey, scopeValue) }; + var scopeValues = new List> { new(scopeKey, scopeValue) }; var scopeState = Activator.CreateInstance(typeOfScopeState, scopeValues) as ICollection>; // Act. + Assert.NotNull(scopeState); using (logger.BeginScope(scopeState)) { logger.LogInformation("Some log information message."); @@ -1118,6 +1134,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_AndScopeStateIsOfEnumerable var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); Assert.Single(otlpLogRecord.Attributes); var actualScope = TryGetAttribute(otlpLogRecord, scopeKey); Assert.NotNull(actualScope); @@ -1157,6 +1174,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_AndMultipleScopesAreAdded_C var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); var allScopeValues = otlpLogRecord.Attributes .Where(_ => _.Key == scopeKey1 || _.Key == scopeKey2) .Select(_ => _.Value.StringValue); @@ -1197,6 +1215,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_AndMultipleScopeLevelsAreAd var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); var allScopeValues = otlpLogRecord.Attributes .Where(_ => _.Key == scopeKey1 || _.Key == scopeKey2) .Select(_ => _.Value.StringValue); @@ -1242,6 +1261,7 @@ public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_AndScopeIsUsedInLogMethod_C var logRecord = logRecords.Single(); var otlpLogRecordTransformer = new OtlpLogRecordTransformer(DefaultSdkLimitOptions, new()); var otlpLogRecord = otlpLogRecordTransformer.ToOtlpLog(logRecord); + Assert.NotNull(otlpLogRecord); var allScopeValues = otlpLogRecord.Attributes .Where(_ => _.Key == scopeKey1 || _.Key == scopeKey2) .Select(_ => _.Value.StringValue); @@ -1314,9 +1334,9 @@ public void AddOtlpLogExporterLogRecordProcessorOptionsTest(ExportProcessorType } else { - var simpleProcesor = processor as SimpleLogRecordExportProcessor; + var simpleProcessor = processor as SimpleLogRecordExportProcessor; - Assert.NotNull(simpleProcesor); + Assert.NotNull(simpleProcessor); } } @@ -1381,7 +1401,7 @@ public void ValidateInstrumentationScope() [InlineData("logging", false)] [InlineData(null, true)] [InlineData("logging", true)] - public void VerifyEnvironmentVariablesTakenFromIConfigurationWhenUsingLoggerFactoryCreate(string optionsName, bool callUseOpenTelemetry) + public void VerifyEnvironmentVariablesTakenFromIConfigurationWhenUsingLoggerFactoryCreate(string? optionsName, bool callUseOpenTelemetry) { RunVerifyEnvironmentVariablesTakenFromIConfigurationTest( optionsName, @@ -1406,7 +1426,7 @@ public void VerifyEnvironmentVariablesTakenFromIConfigurationWhenUsingLoggerFact [InlineData("logging", false)] [InlineData(null, true)] [InlineData("logging", true)] - public void VerifyEnvironmentVariablesTakenFromIConfigurationWhenUsingLoggingBuilder(string optionsName, bool callUseOpenTelemetry) + public void VerifyEnvironmentVariablesTakenFromIConfigurationWhenUsingLoggingBuilder(string? optionsName, bool callUseOpenTelemetry) { RunVerifyEnvironmentVariablesTakenFromIConfigurationTest( optionsName, @@ -1433,7 +1453,7 @@ public void VerifyEnvironmentVariablesTakenFromIConfigurationWhenUsingLoggingBui [Theory] [InlineData("my_instrumentation_scope_name", "my_instrumentation_scope_name")] [InlineData(null, "")] - public void LogRecordLoggerNameIsExportedWhenUsingBridgeApi(string loggerName, string expectedScopeName) + public void LogRecordLoggerNameIsExportedWhenUsingBridgeApi(string? loggerName, string expectedScopeName) { LogRecordAttributeList attributes = default; attributes.Add("name", "tomato"); @@ -1469,10 +1489,10 @@ public void LogRecordLoggerNameIsExportedWhenUsingBridgeApi(string loggerName, s } private static void RunVerifyEnvironmentVariablesTakenFromIConfigurationTest( - string optionsName, + string? optionsName, Func, (IDisposable Container, ILoggerFactory LoggerFactory)> createLoggerFactoryFunc) { - var values = new Dictionary() + var values = new Dictionary { [OtlpSpecConfigDefinitions.DefaultEndpointEnvVarName] = "http://test:8888", }; @@ -1542,7 +1562,7 @@ private static void RunVerifyEnvironmentVariablesTakenFromIConfigurationTest( Assert.True(allConfigureDelegateCalled); } - private static OtlpCommon.KeyValue TryGetAttribute(OtlpLogs.LogRecord record, string key) + private static OtlpCommon.KeyValue? TryGetAttribute(OtlpLogs.LogRecord record, string key) { return record.Attributes.FirstOrDefault(att => att.Key == key); } @@ -1550,11 +1570,11 @@ private static OtlpCommon.KeyValue TryGetAttribute(OtlpLogs.LogRecord record, st private static void ConfigureOtlpExporter( ILoggingBuilder builder, bool callUseOpenTelemetry, - string name = null, - Action configureExporter = null, - Action configureExporterAndProcessor = null, - Action configureOptions = null, - List logRecords = null) + string? name = null, + Action? configureExporter = null, + Action? configureExporterAndProcessor = null, + Action? configureOptions = null, + List? logRecords = null) { if (callUseOpenTelemetry) { @@ -1604,23 +1624,4 @@ private static void ConfigureOtlpExporter( #pragma warning restore CS0618 // Type or member is obsolete } } - - private sealed class TestOptionsMonitor : IOptionsMonitor - { - private readonly T instance; - - public TestOptionsMonitor(T instance) - { - this.instance = instance; - } - - public T CurrentValue => this.instance; - - public T Get(string name) => this.instance; - - public IDisposable OnChange(Action listener) - { - throw new NotImplementedException(); - } - } } diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpMetricsExporterTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpMetricsExporterTests.cs index 07124e63a85..d92f33ee6a9 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpMetricsExporterTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpMetricsExporterTests.cs @@ -21,10 +21,10 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests; [Collection("EnvVars")] public class OtlpMetricsExporterTests : IDisposable { - private static readonly KeyValuePair[] KeyValues = new KeyValuePair[] + private static readonly KeyValuePair[] KeyValues = new KeyValuePair[] { - new KeyValuePair("key1", "value1"), - new KeyValuePair("key2", 123), + new("key1", "value1"), + new("key2", 123), }; public OtlpMetricsExporterTests() @@ -57,14 +57,14 @@ void CheckMetricReaderDefaults() var metricReader = typeof(MetricReader) .Assembly - .GetType("OpenTelemetry.Metrics.MeterProviderSdk") - .GetField("reader", bindingFlags) + .GetType("OpenTelemetry.Metrics.MeterProviderSdk")? + .GetField("reader", bindingFlags)? .GetValue(meterProvider) as PeriodicExportingMetricReader; Assert.NotNull(metricReader); - var exportIntervalMilliseconds = (int)typeof(PeriodicExportingMetricReader) - .GetField("ExportIntervalMilliseconds", bindingFlags) + var exportIntervalMilliseconds = (int?)typeof(PeriodicExportingMetricReader)? + .GetField("ExportIntervalMilliseconds", bindingFlags)? .GetValue(metricReader); Assert.Equal(60000, exportIntervalMilliseconds); @@ -129,8 +129,8 @@ public void UserHttpFactoryCalled() Assert.Equal(2, invocations); } - options.HttpClientFactory = () => null; - Assert.Throws(() => + options.HttpClientFactory = () => throw new NotSupportedException(); + Assert.Throws(() => { using var exporter = new OtlpMetricExporter(options); }); @@ -219,7 +219,7 @@ public void ToOtlpResourceMetricsTest(bool includeServiceNameInResource) [InlineData("test_gauge", null, null, 123L, null, true)] [InlineData("test_gauge", null, null, null, 123.45, true)] [InlineData("test_gauge", "description", "unit", 123L, null)] - public void TestGaugeToOtlpMetric(string name, string description, string unit, long? longValue, double? doubleValue, bool enableExemplars = false) + public void TestGaugeToOtlpMetric(string name, string? description, string? unit, long? longValue, double? doubleValue, bool enableExemplars = false) { var metrics = new List(); @@ -236,7 +236,7 @@ public void TestGaugeToOtlpMetric(string name, string description, string unit, } else { - meter.CreateObservableGauge(name, () => doubleValue.Value, unit, description); + meter.CreateObservableGauge(name, () => doubleValue!.Value, unit, description); } provider.ForceFlush(); @@ -294,7 +294,7 @@ public void TestGaugeToOtlpMetric(string name, string description, string unit, [InlineData("test_counter", null, null, null, 123.45, MetricReaderTemporalityPreference.Delta, false, true)] [InlineData("test_counter", "description", "unit", 123L, null, MetricReaderTemporalityPreference.Cumulative)] [InlineData("test_counter", null, null, 123L, null, MetricReaderTemporalityPreference.Delta, true)] - public void TestCounterToOtlpMetric(string name, string description, string unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) + public void TestCounterToOtlpMetric(string name, string? description, string? unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) { var metrics = new List(); @@ -308,7 +308,7 @@ public void TestCounterToOtlpMetric(string name, string description, string unit }) .Build(); - var attributes = enableKeyValues ? KeyValues : Array.Empty>(); + var attributes = enableKeyValues ? KeyValues : Array.Empty>(); if (longValue.HasValue) { var counter = meter.CreateCounter(name, unit, description); @@ -317,7 +317,7 @@ public void TestCounterToOtlpMetric(string name, string description, string unit else { var counter = meter.CreateCounter(name, unit, description); - counter.Add(doubleValue.Value, attributes); + counter.Add(doubleValue!.Value, attributes); } provider.ForceFlush(); @@ -391,7 +391,7 @@ public void TestCounterToOtlpMetric(string name, string description, string unit [InlineData("test_counter", null, null, null, -123.45, MetricReaderTemporalityPreference.Delta, false, true)] [InlineData("test_counter", "description", "unit", 123L, null, MetricReaderTemporalityPreference.Cumulative)] [InlineData("test_counter", null, null, 123L, null, MetricReaderTemporalityPreference.Delta, true)] - public void TestUpDownCounterToOtlpMetric(string name, string description, string unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) + public void TestUpDownCounterToOtlpMetric(string name, string? description, string? unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) { var metrics = new List(); @@ -405,7 +405,7 @@ public void TestUpDownCounterToOtlpMetric(string name, string description, strin }) .Build(); - var attributes = enableKeyValues ? KeyValues : Array.Empty>(); + var attributes = enableKeyValues ? KeyValues : Array.Empty>(); if (longValue.HasValue) { var counter = meter.CreateUpDownCounter(name, unit, description); @@ -414,7 +414,7 @@ public void TestUpDownCounterToOtlpMetric(string name, string description, strin else { var counter = meter.CreateUpDownCounter(name, unit, description); - counter.Add(doubleValue.Value, attributes); + counter.Add(doubleValue!.Value, attributes); } provider.ForceFlush(); @@ -488,7 +488,7 @@ public void TestUpDownCounterToOtlpMetric(string name, string description, strin [InlineData("test_histogram", null, null, null, 123.45, MetricReaderTemporalityPreference.Delta, false, true)] [InlineData("test_histogram", "description", "unit", 123L, null, MetricReaderTemporalityPreference.Cumulative)] [InlineData("test_histogram", null, null, 123L, null, MetricReaderTemporalityPreference.Delta, true)] - public void TestExponentialHistogramToOtlpMetric(string name, string description, string unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) + public void TestExponentialHistogramToOtlpMetric(string name, string? description, string? unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) { var metrics = new List(); @@ -506,7 +506,7 @@ public void TestExponentialHistogramToOtlpMetric(string name, string description }) .Build(); - var attributes = enableKeyValues ? KeyValues : Array.Empty>(); + var attributes = enableKeyValues ? KeyValues : Array.Empty>(); if (longValue.HasValue) { var histogram = meter.CreateHistogram(name, unit, description); @@ -516,7 +516,7 @@ public void TestExponentialHistogramToOtlpMetric(string name, string description else { var histogram = meter.CreateHistogram(name, unit, description); - histogram.Record(doubleValue.Value, attributes); + histogram.Record(doubleValue!.Value, attributes); histogram.Record(0, attributes); } @@ -577,7 +577,7 @@ public void TestExponentialHistogramToOtlpMetric(string name, string description { Assert.Equal(0, dataPoint.Sum); Assert.Null(dataPoint.Negative); - Assert.True(dataPoint.Positive.Offset == 0); + Assert.Equal(0, dataPoint.Positive.Offset); Assert.Empty(dataPoint.Positive.BucketCounts); } } @@ -594,7 +594,7 @@ public void TestExponentialHistogramToOtlpMetric(string name, string description { Assert.Equal(0, dataPoint.Sum); Assert.Null(dataPoint.Negative); - Assert.True(dataPoint.Positive.Offset == 0); + Assert.Equal(0, dataPoint.Positive.Offset); Assert.Empty(dataPoint.Positive.BucketCounts); } } @@ -628,7 +628,7 @@ public void TestExponentialHistogramToOtlpMetric(string name, string description [InlineData("test_histogram", null, null, null, 123.45, MetricReaderTemporalityPreference.Delta, false, true)] [InlineData("test_histogram", "description", "unit", 123L, null, MetricReaderTemporalityPreference.Cumulative)] [InlineData("test_histogram", null, null, 123L, null, MetricReaderTemporalityPreference.Delta, true)] - public void TestHistogramToOtlpMetric(string name, string description, string unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) + public void TestHistogramToOtlpMetric(string name, string? description, string? unit, long? longValue, double? doubleValue, MetricReaderTemporalityPreference aggregationTemporality, bool enableKeyValues = false, bool enableExemplars = false) { var metrics = new List(); @@ -642,7 +642,7 @@ public void TestHistogramToOtlpMetric(string name, string description, string un }) .Build(); - var attributes = enableKeyValues ? KeyValues : Array.Empty>(); + var attributes = enableKeyValues ? KeyValues : Array.Empty>(); if (longValue.HasValue) { var histogram = meter.CreateHistogram(name, unit, description); @@ -651,7 +651,7 @@ public void TestHistogramToOtlpMetric(string name, string description, string un else { var histogram = meter.CreateHistogram(name, unit, description); - histogram.Record(doubleValue.Value, attributes); + histogram.Record(doubleValue!.Value, attributes); } provider.ForceFlush(); @@ -732,7 +732,7 @@ public void TestTemporalityPreferenceUsingConfiguration(string configValue, Metr { var testExecuted = false; - var configData = new Dictionary { [OtlpSpecConfigDefinitionTests.MetricsData.TemporalityKeyName] = configValue }; + var configData = new Dictionary { [OtlpSpecConfigDefinitionTests.MetricsData.TemporalityKeyName] = configValue }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(configData) .Build(); @@ -786,9 +786,9 @@ public void TestTemporalityPreferenceUsingEnvVar(string configValue, MetricReade [InlineData(true, true)] public void ToOtlpExemplarTests(bool enableTagFiltering, bool enableTracing) { - ActivitySource activitySource = null; - Activity activity = null; - TracerProvider tracerProvider = null; + ActivitySource? activitySource = null; + Activity? activity = null; + TracerProvider? tracerProvider = null; using var meter = new Meter(Utils.GetCurrentMethodName()); @@ -823,8 +823,8 @@ public void ToOtlpExemplarTests(bool enableTagFiltering, bool enableTracing) var counterDouble = meter.CreateCounter("testCounterDouble"); var counterLong = meter.CreateCounter("testCounterLong"); - counterDouble.Add(1.18D, new KeyValuePair("key1", "value1")); - counterLong.Add(18L, new KeyValuePair("key1", "value1")); + counterDouble.Add(1.18D, new KeyValuePair("key1", "value1")); + counterLong.Add(18L, new KeyValuePair("key1", "value1")); meterProvider.ForceFlush(); @@ -869,6 +869,7 @@ void AssertExemplars(T value, Metric metric) else { byte[] traceIdBytes = new byte[16]; + Assert.NotNull(activity); activity.TraceId.CopyTo(traceIdBytes); byte[] spanIdBytes = new byte[8]; @@ -914,7 +915,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private static void VerifyExemplars(long? longValue, double? doubleValue, bool enableExemplars, Func getExemplarFunc, T state) + private static void VerifyExemplars(long? longValue, double? doubleValue, bool enableExemplars, Func getExemplarFunc, T state) { var exemplar = getExemplarFunc(state); @@ -928,6 +929,7 @@ private static void VerifyExemplars(long? longValue, double? doubleValue, boo } else { + Assert.NotNull(doubleValue); Assert.Equal(doubleValue.Value, exemplar.AsDouble); } } diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTestHelpers.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTestHelpers.cs index ec9dbbe4312..7cc6b10336e 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTestHelpers.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTestHelpers.cs @@ -11,7 +11,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests; internal static class OtlpTestHelpers { public static void AssertOtlpAttributes( - IEnumerable> expected, + IEnumerable> expected, RepeatedField actual) { var expectedAttributes = expected.ToList(); @@ -20,6 +20,7 @@ public static void AssertOtlpAttributes( { var current = expectedAttributes[i].Value; Assert.Equal(expectedAttributes[i].Key, actual[i].Key); + Assert.NotNull(current); if (current.GetType().IsArray) { @@ -91,7 +92,7 @@ public static void AssertOtlpAttributes( Assert.Equal(expectedSize, actual.Count); } - private static void AssertOtlpAttributeValue(object expected, OtlpCommon.AnyValue actual) + private static void AssertOtlpAttributeValue(object? expected, OtlpCommon.AnyValue actual) { switch (expected) { diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTraceExporterTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTraceExporterTests.cs index 18434043bc7..84d3076500a 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTraceExporterTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/OtlpTraceExporterTests.cs @@ -63,8 +63,8 @@ public void AddOtlpTraceExporterNamedOptionsSupported() [Fact] public void OtlpExporter_BadArgs() { - TracerProviderBuilder builder = null; - Assert.Throws(() => builder.AddOtlpExporter()); + TracerProviderBuilder? builder = null; + Assert.Throws(() => builder!.AddOtlpExporter()); } [Fact] @@ -98,7 +98,7 @@ public void UserHttpFactoryCalled() Assert.Equal(2, invocations); } - options.HttpClientFactory = () => null; + options.HttpClientFactory = () => null!; Assert.Throws(() => { using var exporter = new OtlpTraceExporter(options); @@ -131,8 +131,8 @@ public void ServiceProviderHttpClientFactoryInvoked() [InlineData(false)] public void ToOtlpResourceSpansTest(bool includeServiceNameInResource) { - var evenTags = new[] { new KeyValuePair("k0", "v0") }; - var oddTags = new[] { new KeyValuePair("k1", "v1") }; + var evenTags = new[] { new KeyValuePair("k0", "v0") }; + var oddTags = new[] { new KeyValuePair("k1", "v1") }; var sources = new[] { new ActivitySource("even", "2.4.6"), @@ -163,7 +163,7 @@ public void ToOtlpResourceSpansTest(bool includeServiceNameInResource) var activityKind = isEven ? ActivityKind.Client : ActivityKind.Server; var activityTags = isEven ? evenTags : oddTags; - using Activity activity = source.StartActivity($"span-{i}", activityKind, parentContext: default, activityTags); + using Activity? activity = source.StartActivity($"span-{i}", activityKind, parentContext: default, activityTags); } Assert.Equal(10, exportedItems.Count); @@ -232,12 +232,12 @@ public void SpanLimitsTest() SpanLinkCountLimit = 1, }; - var tags = new ActivityTagsCollection() + var tags = new ActivityTagsCollection { - new KeyValuePair("TruncatedTag", "12345"), - new KeyValuePair("TruncatedStringArray", new string[] { "12345", "1234", string.Empty, null }), - new KeyValuePair("TruncatedObjectTag", new object()), - new KeyValuePair("OneTagTooMany", 1), + new("TruncatedTag", "12345"), + new("TruncatedStringArray", new string?[] { "12345", "1234", string.Empty, null }), + new("TruncatedObjectTag", new object()), + new("OneTagTooMany", 1), }; var links = new[] @@ -249,6 +249,8 @@ public void SpanLimitsTest() using var activitySource = new ActivitySource(nameof(this.SpanLimitsTest)); using var activity = activitySource.StartActivity("root", ActivityKind.Server, default(ActivityContext), tags, links); + Assert.NotNull(activity); + var event1 = new ActivityEvent("Event", DateTime.UtcNow, tags); var event2 = new ActivityEvent("OneEventTooMany", DateTime.Now, tags); @@ -262,7 +264,7 @@ public void SpanLimitsTest() Assert.Equal(1u, otlpSpan.DroppedAttributesCount); Assert.Equal("1234", otlpSpan.Attributes[0].Value.StringValue); ArrayValueAsserts(otlpSpan.Attributes[1].Value.ArrayValue.Values); - Assert.Equal(new object().ToString().Substring(0, 4), otlpSpan.Attributes[2].Value.StringValue); + Assert.Equal(new object().ToString()!.Substring(0, 4), otlpSpan.Attributes[2].Value.StringValue); Assert.Single(otlpSpan.Events); Assert.Equal(1u, otlpSpan.DroppedEventsCount); @@ -270,7 +272,7 @@ public void SpanLimitsTest() Assert.Equal(1u, otlpSpan.Events[0].DroppedAttributesCount); Assert.Equal("1234", otlpSpan.Events[0].Attributes[0].Value.StringValue); ArrayValueAsserts(otlpSpan.Events[0].Attributes[1].Value.ArrayValue.Values); - Assert.Equal(new object().ToString().Substring(0, 4), otlpSpan.Events[0].Attributes[2].Value.StringValue); + Assert.Equal(new object().ToString()!.Substring(0, 4), otlpSpan.Events[0].Attributes[2].Value.StringValue); Assert.Single(otlpSpan.Links); Assert.Equal(1u, otlpSpan.DroppedLinksCount); @@ -278,11 +280,11 @@ public void SpanLimitsTest() Assert.Equal(1u, otlpSpan.Links[0].DroppedAttributesCount); Assert.Equal("1234", otlpSpan.Links[0].Attributes[0].Value.StringValue); ArrayValueAsserts(otlpSpan.Links[0].Attributes[1].Value.ArrayValue.Values); - Assert.Equal(new object().ToString().Substring(0, 4), otlpSpan.Links[0].Attributes[2].Value.StringValue); + Assert.Equal(new object().ToString()!.Substring(0, 4), otlpSpan.Links[0].Attributes[2].Value.StringValue); void ArrayValueAsserts(RepeatedField values) { - var expectedStringArray = new string[] { "1234", "1234", string.Empty, null }; + var expectedStringArray = new string?[] { "1234", "1234", string.Empty, null }; for (var i = 0; i < expectedStringArray.Length; ++i) { var expectedValue = expectedStringArray[i]; @@ -307,21 +309,22 @@ public void ToOtlpSpanTest() using var rootActivity = activitySource.StartActivity("root", ActivityKind.Producer); - var attributes = new List> - { - new KeyValuePair("bool", true), - new KeyValuePair("long", 1L), - new KeyValuePair("string", "text"), - new KeyValuePair("double", 3.14), - new KeyValuePair("int", 1), - new KeyValuePair("datetime", DateTime.UtcNow), - new KeyValuePair("bool_array", new bool[] { true, false }), - new KeyValuePair("int_array", new int[] { 1, 2 }), - new KeyValuePair("double_array", new double[] { 1.0, 2.09 }), - new KeyValuePair("string_array", new string[] { "a", "b" }), - new KeyValuePair("datetime_array", new DateTime[] { DateTime.UtcNow, DateTime.Now }), + var attributes = new List> + { + new("bool", true), + new("long", 1L), + new("string", "text"), + new("double", 3.14), + new("int", 1), + new("datetime", DateTime.UtcNow), + new("bool_array", new bool[] { true, false }), + new("int_array", new int[] { 1, 2 }), + new("double_array", new double[] { 1.0, 2.09 }), + new("string_array", new string[] { "a", "b" }), + new("datetime_array", new DateTime[] { DateTime.UtcNow, DateTime.Now }), }; + Assert.NotNull(rootActivity); foreach (var kvp in attributes) { rootActivity.SetTag(kvp.Key, kvp.Value); @@ -359,16 +362,17 @@ public void ToOtlpSpanTest() var expectedEndTimeUnixNano = expectedStartTimeUnixNano + (duration.TotalMilliseconds * 1_000_000); Assert.Equal(expectedEndTimeUnixNano, otlpSpan.EndTimeUnixNano); - var childLinks = new List { new ActivityLink(rootActivity.Context, new ActivityTagsCollection(attributes)) }; + var childLinks = new List { new(rootActivity.Context, new ActivityTagsCollection(attributes)) }; var childActivity = activitySource.StartActivity( "child", ActivityKind.Client, rootActivity.Context, links: childLinks); + Assert.NotNull(childActivity); childActivity.SetStatus(Status.Error); - var childEvents = new List { new ActivityEvent("e0"), new ActivityEvent("e1", default, new ActivityTagsCollection(attributes)) }; + var childEvents = new List { new("e0"), new("e1", default, new ActivityTagsCollection(attributes)) }; childActivity.AddEvent(childEvents[0]); childActivity.AddEvent(childEvents[1]); @@ -400,7 +404,9 @@ public void ToOtlpSpanTest() Assert.Equal(childLinks.Count, otlpSpan.Links.Count); for (var i = 0; i < childLinks.Count; i++) { - OtlpTestHelpers.AssertOtlpAttributes(childLinks[i].Tags.ToList(), otlpSpan.Links[i].Attributes); + var tags = childLinks[i].Tags; + Assert.NotNull(tags); + OtlpTestHelpers.AssertOtlpAttributes(tags, otlpSpan.Links[i].Attributes); } var flags = (OtlpTrace.SpanFlags)otlpSpan.Flags; @@ -416,7 +422,7 @@ public void ToOtlpSpanActivitiesWithNullArrayTest() using var rootActivity = activitySource.StartActivity("root", ActivityKind.Client); Assert.NotNull(rootActivity); - var stringArr = new string[] { "test", string.Empty, null }; + var stringArr = new string?[] { "test", string.Empty, null }; rootActivity.SetTag("stringArray", stringArr); var otlpSpan = rootActivity.ToOtlpSpan(DefaultSdkLimitOptions); @@ -439,10 +445,11 @@ public void ToOtlpSpanNativeActivityStatusTest(ActivityStatusCode expectedStatus { using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest)); using var activity = activitySource.StartActivity("Name"); + Assert.NotNull(activity); activity.SetStatus(expectedStatusCode, statusDescription); var otlpSpan = activity.ToOtlpSpan(DefaultSdkLimitOptions); - + Assert.NotNull(otlpSpan); if (expectedStatusCode == ActivityStatusCode.Unset) { Assert.Null(otlpSpan.Status); @@ -471,11 +478,13 @@ public void ToOtlpSpanStatusTagTest(StatusCode expectedStatusCode, string status { using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest)); using var activity = activitySource.StartActivity("Name"); + Assert.NotNull(activity); activity.SetTag(SpanAttributeConstants.StatusCodeKey, statusCodeTagValue); activity.SetTag(SpanAttributeConstants.StatusDescriptionKey, statusDescription); var otlpSpan = activity.ToOtlpSpan(DefaultSdkLimitOptions); + Assert.NotNull(otlpSpan); Assert.NotNull(otlpSpan.Status); Assert.Equal((int)expectedStatusCode, (int)otlpSpan.Status.Code); @@ -497,10 +506,12 @@ public void ToOtlpSpanStatusTagIsCaseInsensitiveTest(StatusCode expectedStatusCo { using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest)); using var activity = activitySource.StartActivity("Name"); + Assert.NotNull(activity); activity.SetTag(SpanAttributeConstants.StatusCodeKey, statusCodeTagValue); var otlpSpan = activity.ToOtlpSpan(DefaultSdkLimitOptions); + Assert.NotNull(otlpSpan); Assert.NotNull(otlpSpan.Status); Assert.Equal((int)expectedStatusCode, (int)otlpSpan.Status.Code); } @@ -510,13 +521,15 @@ public void ToOtlpSpanActivityStatusTakesPrecedenceOverStatusTagsWhenActivitySta { using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest)); using var activity = activitySource.StartActivity("Name"); - const string TagDescriptionOnError = "Description when TagStatusCode is Error."; + const string tagDescriptionOnError = "Description when TagStatusCode is Error."; + Assert.NotNull(activity); activity.SetStatus(ActivityStatusCode.Ok); activity.SetTag(SpanAttributeConstants.StatusCodeKey, "ERROR"); - activity.SetTag(SpanAttributeConstants.StatusDescriptionKey, TagDescriptionOnError); + activity.SetTag(SpanAttributeConstants.StatusDescriptionKey, tagDescriptionOnError); var otlpSpan = activity.ToOtlpSpan(DefaultSdkLimitOptions); + Assert.NotNull(otlpSpan); Assert.NotNull(otlpSpan.Status); Assert.Equal((int)ActivityStatusCode.Ok, (int)otlpSpan.Status.Code); Assert.Empty(otlpSpan.Status.Message); @@ -527,15 +540,17 @@ public void ToOtlpSpanActivityStatusTakesPrecedenceOverStatusTagsWhenActivitySta { using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest)); using var activity = activitySource.StartActivity("Name"); - const string StatusDescriptionOnError = "Description when ActivityStatusCode is Error."; - activity.SetStatus(ActivityStatusCode.Error, StatusDescriptionOnError); + const string statusDescriptionOnError = "Description when ActivityStatusCode is Error."; + Assert.NotNull(activity); + activity.SetStatus(ActivityStatusCode.Error, statusDescriptionOnError); activity.SetTag(SpanAttributeConstants.StatusCodeKey, "OK"); var otlpSpan = activity.ToOtlpSpan(DefaultSdkLimitOptions); + Assert.NotNull(otlpSpan); Assert.NotNull(otlpSpan.Status); Assert.Equal((int)ActivityStatusCode.Error, (int)otlpSpan.Status.Code); - Assert.Equal(StatusDescriptionOnError, otlpSpan.Status.Message); + Assert.Equal(statusDescriptionOnError, otlpSpan.Status.Message); } [Theory] @@ -545,6 +560,7 @@ public void ToOtlpSpanTraceStateTest(bool traceStateWasSet) { using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest)); using var activity = activitySource.StartActivity("Name"); + Assert.NotNull(activity); string tracestate = "a=b;c=d"; if (traceStateWasSet) { @@ -552,6 +568,7 @@ public void ToOtlpSpanTraceStateTest(bool traceStateWasSet) } var otlpSpan = activity.ToOtlpSpan(DefaultSdkLimitOptions); + Assert.NotNull(otlpSpan); if (traceStateWasSet) { @@ -571,6 +588,7 @@ public void ToOtlpSpanPeerServiceTest() using var rootActivity = activitySource.StartActivity("root", ActivityKind.Client); + Assert.NotNull(rootActivity); rootActivity.SetTag(SemanticConventions.AttributeHttpHost, "opentelemetry.io"); var otlpSpan = rootActivity.ToOtlpSpan(DefaultSdkLimitOptions); @@ -641,7 +659,7 @@ public void Null_BatchExportProcessorOptions_SupportedTest() { o.Protocol = OtlpExportProtocol.HttpProtobuf; o.ExportProcessorType = ExportProcessorType.Batch; - o.BatchExportProcessorOptions = null; + o.BatchExportProcessorOptions = null!; }); } @@ -650,8 +668,8 @@ public void NonnamedOptionsMutateSharedInstanceTest() { var testOptionsInstance = new OtlpExporterOptions(); - OtlpExporterOptions tracerOptions = null; - OtlpExporterOptions meterOptions = null; + OtlpExporterOptions? tracerOptions = null; + OtlpExporterOptions? meterOptions = null; var services = new ServiceCollection(); @@ -695,8 +713,8 @@ public void NonnamedOptionsMutateSharedInstanceTest() [Fact] public void NamedOptionsMutateSeparateInstancesTest() { - OtlpExporterOptions tracerOptions = null; - OtlpExporterOptions meterOptions = null; + OtlpExporterOptions? tracerOptions = null; + OtlpExporterOptions? meterOptions = null; var services = new ServiceCollection(); @@ -753,9 +771,11 @@ public void SpanFlagsTest(bool isRecorded, bool isRemote) isRemote: isRemote); using var rootActivity = activitySource.StartActivity("root", ActivityKind.Server, ctx); + Assert.NotNull(rootActivity); var otlpSpan = rootActivity.ToOtlpSpan(DefaultSdkLimitOptions); + Assert.NotNull(otlpSpan); var flags = (OtlpTrace.SpanFlags)otlpSpan.Flags; ActivityTraceFlags traceFlags = (ActivityTraceFlags)(flags & OtlpTrace.SpanFlags.TraceFlagsMask); @@ -802,9 +822,11 @@ public void SpanLinkFlagsTest(bool isRecorded, bool isRemote) }; using var rootActivity = activitySource.StartActivity("root", ActivityKind.Server, default(ActivityContext), links: links); + Assert.NotNull(rootActivity); var otlpSpan = rootActivity.ToOtlpSpan(DefaultSdkLimitOptions); + Assert.NotNull(otlpSpan); var spanLink = Assert.Single(otlpSpan.Links); var flags = (OtlpTrace.SpanFlags)spanLink.Flags; diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/SdkLimitOptionsTests.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/SdkLimitOptionsTests.cs index dc36def4665..0a737ff1438 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/SdkLimitOptionsTests.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/SdkLimitOptionsTests.cs @@ -135,7 +135,7 @@ public void SpanAttributeCountLimitFallback() [Fact] public void SdkLimitOptionsUsingIConfiguration() { - var values = new Dictionary + var values = new Dictionary { ["OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT"] = "23", ["OTEL_ATTRIBUTE_COUNT_LIMIT"] = "24", diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestExportClient.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestExportClient.cs index eab9178db49..bbecfa2fa37 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestExportClient.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestExportClient.cs @@ -32,7 +32,7 @@ public bool Shutdown(int timeoutMilliseconds) private class TestExportClientResponse : ExportClientResponse { - public TestExportClientResponse(bool success, DateTime deadline, Exception exception) + public TestExportClientResponse(bool success, DateTime deadline, Exception? exception) : base(success, deadline, exception) { } diff --git a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestHttpMessageHandler.cs b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestHttpMessageHandler.cs index cf62af4e994..2e5d6ede2b0 100644 --- a/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestHttpMessageHandler.cs +++ b/test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/TestHttpMessageHandler.cs @@ -9,14 +9,14 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests; internal class TestHttpMessageHandler : HttpMessageHandler { - public HttpRequestMessage HttpRequestMessage { get; private set; } + public HttpRequestMessage? HttpRequestMessage { get; private set; } - public byte[] HttpRequestContent { get; private set; } + public byte[]? HttpRequestContent { get; private set; } public virtual HttpResponseMessage InternalSend(HttpRequestMessage request, CancellationToken cancellationToken) { this.HttpRequestMessage = request; - this.HttpRequestContent = request.Content.ReadAsByteArrayAsync().Result; + this.HttpRequestContent = request.Content!.ReadAsByteArrayAsync().Result; return new HttpResponseMessage(); } diff --git a/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs b/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs index c0f5055d490..26d82bb6a0b 100644 --- a/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs +++ b/test/OpenTelemetry.Tests/Shared/EventSourceTestHelper.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + using System.Diagnostics.Tracing; using System.Globalization; using System.Reflection; @@ -26,7 +28,7 @@ private static void VerifyMethodImplementation(EventSource eventSource, MethodIn object[] eventArguments = GenerateEventArguments(eventMethod); eventMethod.Invoke(eventSource, eventArguments); - EventWrittenEventArgs actualEvent = listener.Messages.FirstOrDefault(x => x.EventName == eventMethod.Name); + EventWrittenEventArgs? actualEvent = listener.Messages.FirstOrDefault(x => x.EventName == eventMethod.Name); if (actualEvent == null) { @@ -47,7 +49,7 @@ private static void VerifyMethodImplementation(EventSource eventSource, MethodIn } catch (Exception e) { - var name = eventMethod.DeclaringType.Name + "." + eventMethod.Name; + var name = eventMethod.DeclaringType?.Name + "." + eventMethod.Name; throw new Exception("Method '" + name + "' is implemented incorrectly.", e); } @@ -78,7 +80,7 @@ private static object GenerateArgument(ParameterInfo parameter) if (parameter.ParameterType.IsValueType) { - return Activator.CreateInstance(parameter.ParameterType); + return Activator.CreateInstance(parameter.ParameterType)!; } throw new NotSupportedException("Complex types are not supported"); @@ -99,13 +101,14 @@ private static void VerifyEventLevel(MethodInfo eventMethod, EventWrittenEventAr private static void VerifyEventMessage(MethodInfo eventMethod, EventWrittenEventArgs actualEvent, object[] eventArguments) { string expectedMessage = eventArguments.Length == 0 - ? GetEventAttribute(eventMethod).Message - : string.Format(CultureInfo.InvariantCulture, GetEventAttribute(eventMethod).Message, eventArguments); - string actualMessage = string.Format(CultureInfo.InvariantCulture, actualEvent.Message, actualEvent.Payload.ToArray()); + ? GetEventAttribute(eventMethod).Message! + : string.Format(CultureInfo.InvariantCulture, GetEventAttribute(eventMethod).Message!, eventArguments)!; + string actualMessage = string.Format(CultureInfo.InvariantCulture, actualEvent.Message!, actualEvent.Payload!.ToArray()); AssertEqual(nameof(VerifyEventMessage), expectedMessage, actualMessage); } private static void AssertEqual(string methodName, T expected, T actual) + where T : notnull { if (!expected.Equals(actual)) { diff --git a/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundFactAttribute.cs b/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundFactAttribute.cs index adfebcaf184..0fb748ba2c2 100644 --- a/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundFactAttribute.cs +++ b/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundFactAttribute.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + using Xunit; namespace OpenTelemetry.Tests; @@ -15,9 +17,9 @@ public SkipUnlessEnvVarFoundFactAttribute(string environmentVariable) } } - public static string GetEnvironmentVariable(string environmentVariableName) + public static string? GetEnvironmentVariable(string environmentVariableName) { - string environmentVariableValue = Environment.GetEnvironmentVariable(environmentVariableName, EnvironmentVariableTarget.Process); + string? environmentVariableValue = Environment.GetEnvironmentVariable(environmentVariableName, EnvironmentVariableTarget.Process); if (string.IsNullOrEmpty(environmentVariableValue)) { diff --git a/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs b/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs index dc5ce2ca66f..056c37036dc 100644 --- a/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs +++ b/test/OpenTelemetry.Tests/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + using Xunit; namespace OpenTelemetry.Tests; @@ -15,9 +17,9 @@ public SkipUnlessEnvVarFoundTheoryAttribute(string environmentVariable) } } - public static string GetEnvironmentVariable(string environmentVariableName) + public static string? GetEnvironmentVariable(string environmentVariableName) { - string environmentVariableValue = Environment.GetEnvironmentVariable(environmentVariableName, EnvironmentVariableTarget.Process); + string? environmentVariableValue = Environment.GetEnvironmentVariable(environmentVariableName, EnvironmentVariableTarget.Process); if (string.IsNullOrEmpty(environmentVariableValue)) { diff --git a/test/OpenTelemetry.Tests/Shared/TestActivityProcessor.cs b/test/OpenTelemetry.Tests/Shared/TestActivityProcessor.cs index 36d47b7b8fa..a386b67c8d3 100644 --- a/test/OpenTelemetry.Tests/Shared/TestActivityProcessor.cs +++ b/test/OpenTelemetry.Tests/Shared/TestActivityProcessor.cs @@ -1,14 +1,16 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + using System.Diagnostics; namespace OpenTelemetry.Tests; internal class TestActivityProcessor : BaseProcessor { - public Action StartAction; - public Action EndAction; + public Action? StartAction; + public Action? EndAction; public TestActivityProcessor() { diff --git a/test/OpenTelemetry.Tests/Shared/TestEventListener.cs b/test/OpenTelemetry.Tests/Shared/TestEventListener.cs index b0cf1d0b120..4e9d79c4735 100644 --- a/test/OpenTelemetry.Tests/Shared/TestEventListener.cs +++ b/test/OpenTelemetry.Tests/Shared/TestEventListener.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + using System.Diagnostics.Tracing; namespace OpenTelemetry.Tests; @@ -39,7 +41,7 @@ public TestEventListener() } /// Gets or sets the handler for event source creation. - public Action OnOnEventSourceCreated { get; set; } + public Action? OnOnEventSourceCreated { get; set; } /// Gets or sets the handler for event source writes. public Action OnOnEventWritten { get; set; } @@ -81,7 +83,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) protected override void OnEventSourceCreated(EventSource eventSource) { // Check for null because this method is called by the base class constructor before we can initialize it - Action callback = this.OnOnEventSourceCreated; + Action? callback = this.OnOnEventSourceCreated; callback?.Invoke(eventSource); } }