Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Exporter.OTLP - Tests] Nullable #5720

Merged
merged 1 commit into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class OtlpExporterOptions : IOtlpExporterOptions

internal static readonly KeyValuePair<string, string>[] StandardHeaders = new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("User-Agent", GetUserAgentString()),
new("User-Agent", GetUserAgentString()),
};

internal readonly Func<HttpClient> DefaultHttpClientFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public void NewOtlpHttpTraceExportClient_OtlpExporterOptions_ExporterHasCorrectP
public void SendExportRequest_ExportTraceServiceRequest_SendsCorrectHttpRequest(bool includeServiceNameInResource)
{
// Arrange
var evenTags = new[] { new KeyValuePair<string, object>("k0", "v0") };
var oddTags = new[] { new KeyValuePair<string, object>("k1", "v1") };
var evenTags = new[] { new KeyValuePair<string, object?>("k0", "v0") };
var oddTags = new[] { new KeyValuePair<string, object?>("k1", "v1") };
var sources = new[]
{
new ActivitySource("even", "2.4.6"),
Expand Down Expand Up @@ -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);
}

Expand All @@ -141,6 +142,7 @@ void RunTest(Batch<Activity> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -61,7 +61,7 @@ public void TraceExportResultIsSuccess(OtlpExportProtocol protocol, string endpo
},
};

DelegatingExporter<Activity> delegatingExporter = null;
DelegatingExporter<Activity>? delegatingExporter = null;
var exportResults = new List<ExportResult>();

var activitySourceName = "otlp.collector.test";
Expand Down Expand Up @@ -140,7 +140,7 @@ public void MetricExportResultIsSuccess(OtlpExportProtocol protocol, string endp
Protocol = protocol,
};

DelegatingExporter<Metric> delegatingExporter = null;
DelegatingExporter<Metric>? delegatingExporter = null;
var exportResults = new List<ExportResult>();

var meterName = "otlp.collector.test";
Expand Down Expand Up @@ -220,7 +220,7 @@ public void LogExportResultIsSuccess(OtlpExportProtocol protocol, string endpoin
Protocol = protocol,
};

DelegatingExporter<LogRecord> delegatingExporter = null;
DelegatingExporter<LogRecord> delegatingExporter;
var exportResults = new List<ExportResult>();
var processorOptions = new LogRecordExportProcessorOptions
{
Expand Down Expand Up @@ -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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#if !NETFRAMEWORK
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Google.Protobuf;
using Grpc.Core;
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -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<string, string> { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null })
.AddInMemoryCollection(new Dictionary<string, string?> { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null })
.Build();

var otlpExporter = new OtlpTraceExporter(exporterOptions, new SdkLimitOptions(), new ExperimentalOptions(configuration));
Expand All @@ -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>([activity], 1);

Expand Down Expand Up @@ -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<string, string> { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null })
.AddInMemoryCollection(new Dictionary<string, string?> { [ExperimentalOptions.OtlpRetryEnvVar] = useRetryTransmissionHandler ? "in_memory" : null })
.Build();

var otlpExporter = new OtlpTraceExporter(exporterOptions, new SdkLimitOptions(), new ExperimentalOptions(configuration));
Expand All @@ -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>([activity], 1);

Expand Down Expand Up @@ -348,7 +351,7 @@ public async Task HttpPersistentStorageRetryTests(bool usePersistentStorageTrans

// TODO: update this to configure via experimental environment variable.
OtlpExporterTransmissionHandler<ExportTraceServiceRequest> transmissionHandler;
MockFileProvider mockProvider = null;
MockFileProvider? mockProvider = null;
if (usePersistentStorageTransmissionHandler)
{
mockProvider = new MockFileProvider();
Expand Down Expand Up @@ -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>([activity], 1);

Expand All @@ -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<ExportTraceServiceRequest>).InitiateAndWaitForRetryProcess(-1));
Assert.True((transmissionHandler as OtlpExporterPersistentStorageTransmissionHandler<ExportTraceServiceRequest>)!.InitiateAndWaitForRetryProcess(-1));

Assert.False(mockProvider.TryGetBlob(out _));
}
Expand Down Expand Up @@ -485,7 +490,7 @@ public async Task GrpcPersistentStorageRetryTests(bool usePersistentStorageTrans

// TODO: update this to configure via experimental environment variable.
OtlpExporterTransmissionHandler<ExportTraceServiceRequest> transmissionHandler;
MockFileProvider mockProvider = null;
MockFileProvider? mockProvider = null;
if (usePersistentStorageTransmissionHandler)
{
mockProvider = new MockFileProvider();
Expand Down Expand Up @@ -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>([activity], 1);

Expand All @@ -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<ExportTraceServiceRequest>).InitiateAndWaitForRetryProcess(-1));
Assert.True((transmissionHandler as OtlpExporterPersistentStorageTransmissionHandler<ExportTraceServiceRequest>)!.InitiateAndWaitForRetryProcess(-1));

Assert.False(mockProvider.TryGetBlob(out _));
}
Expand Down Expand Up @@ -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();

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

<PropertyGroup>
<TargetFrameworks>$(TargetFrameworksForTests)</TargetFrameworks>
<!-- this is temporary. will remove in future PR. -->
<Nullable>disable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -13,19 +14,19 @@ public class OtlpAttributeTests
[Fact]
public void NullValueAttribute()
{
var kvp = new KeyValuePair<string, object>("key", null);
Assert.False(TryTransformTag(kvp, out var _));
var kvp = new KeyValuePair<string, object?>("key", null);
Assert.False(TryTransformTag(kvp, out _));
}

[Fact]
public void EmptyArrays()
{
var kvp = new KeyValuePair<string, object>("key", Array.Empty<int>());
var kvp = new KeyValuePair<string, object?>("key", Array.Empty<int>());
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<string, object>("key", Array.Empty<object>());
kvp = new KeyValuePair<string, object?>("key", Array.Empty<object>());
Assert.True(TryTransformTag(kvp, out attribute));
Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase);
Assert.Empty(attribute.Value.ArrayValue.Values);
Expand All @@ -48,7 +49,7 @@ public void EmptyArrays()
[InlineData(new long[] { 1, 2, 3 })]
public void IntegralTypesSupported(object value)
{
var kvp = new KeyValuePair<string, object>("key", value);
var kvp = new KeyValuePair<string, object?>("key", value);
Assert.True(TryTransformTag(kvp, out var attribute));

switch (value)
Expand Down Expand Up @@ -77,7 +78,7 @@ public void IntegralTypesSupported(object value)
[InlineData(new double[] { 1, 2, 3 })]
public void FloatingPointTypesSupported(object value)
{
var kvp = new KeyValuePair<string, object>("key", value);
var kvp = new KeyValuePair<string, object?>("key", value);
Assert.True(TryTransformTag(kvp, out var attribute));

switch (value)
Expand All @@ -104,7 +105,7 @@ public void FloatingPointTypesSupported(object value)
[InlineData(new bool[] { true, false, true })]
public void BooleanTypeSupported(object value)
{
var kvp = new KeyValuePair<string, object>("key", value);
var kvp = new KeyValuePair<string, object?>("key", value);
Assert.True(TryTransformTag(kvp, out var attribute));

switch (value)
Expand All @@ -131,7 +132,7 @@ public void BooleanTypeSupported(object value)
[InlineData("string")]
public void StringTypesSupported(object value)
{
var kvp = new KeyValuePair<string, object>("key", value);
var kvp = new KeyValuePair<string, object?>("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);
Expand All @@ -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<string, object>("key", objectArray);
var kvp = new KeyValuePair<string, object?>("key", objectArray);

Assert.True(TryTransformTag(kvp, out var attribute));
Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase);
Expand Down Expand Up @@ -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<string, object>("key", charArray);
var kvp = new KeyValuePair<string, object?>("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<string, object>("key", stringArray);
kvp = new KeyValuePair<string, object?>("key", stringArray);
Assert.True(TryTransformTag(kvp, out attribute));
Assert.Equal(OtlpCommon.AnyValue.ValueOneofCase.ArrayValue, attribute.Value.ValueCase);

Expand Down Expand Up @@ -221,24 +222,25 @@ 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<string, object>("key", value);
var kvp = new KeyValuePair<string, object?>("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);
}

foreach (var value in testArrayValues)
{
var kvp = new KeyValuePair<string, object>("key", value);
var kvp = new KeyValuePair<string, object?>("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();
Expand All @@ -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);
}
}
}
Expand All @@ -258,14 +260,14 @@ public void ToStringIsCalledForAllOtherTypes()
[Fact]
public void ExceptionInToStringIsCaught()
{
var kvp = new KeyValuePair<string, object>("key", new MyToStringMethodThrowsAnException());
Assert.False(TryTransformTag(kvp, out var _));
var kvp = new KeyValuePair<string, object?>("key", new MyToStringMethodThrowsAnException());
Assert.False(TryTransformTag(kvp, out _));

kvp = new KeyValuePair<string, object>("key", new object[] { 1, false, new MyToStringMethodThrowsAnException() });
Assert.False(TryTransformTag(kvp, out var _));
kvp = new KeyValuePair<string, object?>("key", new object[] { 1, false, new MyToStringMethodThrowsAnException() });
Assert.False(TryTransformTag(kvp, out _));
}

private static bool TryTransformTag(KeyValuePair<string, object> tag, out OtlpCommon.KeyValue attribute)
private static bool TryTransformTag(KeyValuePair<string, object?> tag, [NotNullWhen(true)] out OtlpCommon.KeyValue? attribute)
{
var destination = new RepeatedField<OtlpCommon.KeyValue>();

Expand Down
Loading