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

[AzureMonitorExporter] fix nullables in more tests #34454

Merged
merged 4 commits into from
Feb 22, 2023
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 @@ -14,7 +14,7 @@ internal partial class TelemetryExceptionDetails
/// <summary>
/// Creates a new instance of ExceptionDetails from a System.Exception and a parent ExceptionDetails.
/// </summary>
internal TelemetryExceptionDetails(Exception exception, string message, TelemetryExceptionDetails parentExceptionDetails)
internal TelemetryExceptionDetails(Exception exception, string message, TelemetryExceptionDetails? parentExceptionDetails)
{
if (exception == null)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

using OpenTelemetry.Trace;
using System;
using System.Reflection;
Expand All @@ -24,7 +22,7 @@ public void VerifyConnectionString_CorrectlySetsEndpoint()

var exporter = new AzureMonitorTraceExporter(new AzureMonitorExporterOptions { ConnectionString = $"InstrumentationKey={testIkey};IngestionEndpoint={testEndpoint}" });

GetInternalFields(exporter, out string ikey, out string endpoint);
GetInternalFields(exporter, out string? ikey, out string? endpoint);
Assert.Equal(testIkey, ikey);
Assert.Equal(testEndpoint, endpoint);
}
Expand All @@ -36,7 +34,7 @@ public void VerifyConnectionString_CorrectlySetsDefaultEndpoint()

var exporter = new AzureMonitorTraceExporter(new AzureMonitorExporterOptions { ConnectionString = $"InstrumentationKey={testIkey};" });

GetInternalFields(exporter, out string ikey, out string endpoint);
GetInternalFields(exporter, out string? ikey, out string? endpoint);
Assert.Equal(testIkey, ikey);
Assert.Equal(Constants.DefaultIngestionEndpoint, endpoint);
}
Expand All @@ -58,33 +56,35 @@ public void VerifyConnectionString_ThrowsExceptionWhenMissingInstrumentationKey(
[Fact]
public void AzureMonitorExporter_BadArgs()
{
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
TracerProviderBuilder builder = null;
Assert.Throws<ArgumentNullException>(() => builder.AddAzureMonitorTraceExporter());
Assert.Throws<ArgumentNullException>(() => builder!.AddAzureMonitorTraceExporter());
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
}

private void GetInternalFields(AzureMonitorTraceExporter exporter, out string ikey, out string endpoint)
private void GetInternalFields(AzureMonitorTraceExporter exporter, out string? ikey, out string? endpoint)
{
// TODO: NEED A BETTER APPROACH FOR TESTING. WE DECIDED AGAINST MAKING FIELDS "internal".
// instrumentationKey: AzureMonitorTraceExporter.AzureMonitorTransmitter.instrumentationKey
// endpoint: AzureMonitorTraceExporter.AzureMonitorTransmitter.ServiceRestClient.endpoint

ikey = typeof(AzureMonitorTraceExporter)
.GetField("_instrumentationKey", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(exporter)
.ToString();
?.GetValue(exporter)
?.ToString();

var transmitter = typeof(AzureMonitorTraceExporter)
.GetField("_transmitter", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(exporter);
?.GetValue(exporter);

var serviceRestClient = typeof(AzureMonitorTransmitter)
.GetField("_applicationInsightsRestClient", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(transmitter);
?.GetValue(transmitter);

endpoint = typeof(ApplicationInsightsRestClient)
.GetField("_host", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(serviceRestClient)
.ToString();
?.GetValue(serviceRestClient)
?.ToString();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -59,6 +57,7 @@ public void Success200()
transmitter.TrackAsync(telemetryItems, false, CancellationToken.None).EnsureCompleted();

//Assert
Assert.NotNull(transmitter._fileBlobProvider);
Assert.Empty(transmitter._fileBlobProvider.GetBlobs());
}

Expand All @@ -76,6 +75,7 @@ public void FailureResponseCode500()
transmitter.TrackAsync(telemetryItems, false, CancellationToken.None).EnsureCompleted();

//Assert
Assert.NotNull(transmitter._fileBlobProvider);
Assert.Single(transmitter._fileBlobProvider.GetBlobs());
}

Expand All @@ -95,6 +95,7 @@ public void FailureResponseCode429()
transmitter.TrackAsync(telemetryItems, false, CancellationToken.None).EnsureCompleted();

//Assert
Assert.NotNull(transmitter._fileBlobProvider);
Assert.Single(transmitter._fileBlobProvider.GetBlobs());
}

Expand All @@ -120,8 +121,9 @@ public void FailureResponseCode206()
transmitter.TrackAsync(telemetryItems, false, CancellationToken.None).EnsureCompleted();

//Assert
Assert.NotNull(transmitter._fileBlobProvider);
Assert.Single(transmitter._fileBlobProvider.GetBlobs());
transmitter._fileBlobProvider.TryGetBlob(out var blob);
Assert.True(transmitter._fileBlobProvider.TryGetBlob(out var blob));
blob.TryRead(out var content);

Assert.NotNull(content);
Expand Down Expand Up @@ -190,13 +192,14 @@ private static Activity CreateActivity(string activityName)
parentContext: default,
startTime: DateTime.UtcNow);

Assert.NotNull(activity);
return activity;
}

private static TelemetryItem CreateTelemetryItem(Activity activity)
{
var monitorTags = TraceHelper.EnumerateActivityTags(activity);
return new TelemetryItem(activity, ref monitorTags, null, null);
return new TelemetryItem(activity, ref monitorTags, null, string.Empty);
}

private class MockFileProvider : PersistentBlobProvider
Expand Down Expand Up @@ -224,15 +227,15 @@ protected override bool OnTryCreateBlob(byte[] buffer, out PersistentBlob blob)

protected override bool OnTryGetBlob(out PersistentBlob blob)
{
blob = this.GetBlobs().FirstOrDefault();
blob = this.GetBlobs().First();

return true;
}
}

private class MockFileBlob : PersistentBlob
{
private byte[] _buffer;
private byte[] _buffer = Array.Empty<byte>();

private readonly List<PersistentBlob> _mockStorage;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
Expand Down Expand Up @@ -52,8 +50,9 @@ public void ValidateSampleRateForEventException(object SampleRate)
ActivityKind.Client,
parentContext: default,
startTime: DateTime.UtcNow,
tags: new Dictionary<string, object>() { ["sampleRate"] = SampleRate });
tags: new Dictionary<string, object?>() { ["sampleRate"] = SampleRate });

Assert.NotNull(activity);
var monitorTags = TraceHelper.EnumerateActivityTags(activity);
var telemetryItem = new TelemetryItem(activity, ref monitorTags, null, "00000000-0000-0000-0000-000000000000");
var expTelemetryItem = new TelemetryItem("Exception", telemetryItem, default, default, default);
Expand Down Expand Up @@ -83,8 +82,9 @@ public void ValidateSampleRateInTelemetry(object SampleRate)
ActivityKind.Client,
parentContext: default,
startTime: DateTime.UtcNow,
tags: new Dictionary<string, object>() { ["sampleRate"] = SampleRate });
tags: new Dictionary<string, object?>() { ["sampleRate"] = SampleRate });

Assert.NotNull(activity);
var monitorTags = TraceHelper.EnumerateActivityTags(activity);
var telemetryItem = new TelemetryItem(activity, ref monitorTags, null, "00000000-0000-0000-0000-000000000000");

Expand Down Expand Up @@ -112,10 +112,10 @@ public void SampleRateE2ETest()
{
}

tracerProvider.ForceFlush();
tracerProvider?.ForceFlush();

Assert.NotEmpty(telemetryItems);
Assert.Equal(100F, telemetryItems.FirstOrDefault().SampleRate);
Assert.Equal(100F, telemetryItems.First().SampleRate);
}

[Fact]
Expand All @@ -132,7 +132,7 @@ public void NoTelemetryCreatedOnZeroSampleRate()
{
}

tracerProvider.ForceFlush();
tracerProvider?.ForceFlush();

Assert.Empty(telemetryItems);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -47,7 +45,9 @@ public void ValidateProblemIdForExceptionWithStackTrace()
[Fact]
public void CallingConvertToExceptionDetailsWithNullExceptionThrowsArgumentNullException()
{
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
Assert.Throws<ArgumentNullException>(() => new TelemetryExceptionDetails(null, "Exception Message", null));
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
}

[Fact]
Expand Down Expand Up @@ -92,7 +92,11 @@ public void FirstAndLastStackPointsAreCollectedForLongStack()
public void TestNullMethodInfoInStack()
{
var frameMock = new Mock<System.Diagnostics.StackFrame>(null, 0, 0);
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
frameMock.Setup(x => x.GetMethod()).Returns((MethodBase)null);
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.

Models.StackFrame stackFrame = new Models.StackFrame(frameMock.Object, 0);

Expand All @@ -109,8 +113,8 @@ public void CheckThatFileNameAndLineAreCorrectIfAvailable()

StackTrace st = new StackTrace(exception, true);
var frame = st.GetFrame(0);
var line = frame.GetFileLineNumber();
var fileName = frame.GetFileName();
var line = frame?.GetFileLineNumber();
var fileName = frame?.GetFileName();

var exceptionDetails = new TelemetryExceptionDetails(exception, exception.Message, null);
var stack = exceptionDetails.ParsedStack;
Expand Down Expand Up @@ -357,7 +361,7 @@ public void ValidateTelemetryExceptionData(LogLevel logLevel)
[MethodImpl(MethodImplOptions.NoInlining)]
private Exception CreateException(int stackDepth)
{
Exception exception = null;
Exception? exception = null;

try
{
Expand All @@ -368,7 +372,7 @@ private Exception CreateException(int stackDepth)
exception = exp;
}

return exception;
return exception!;
}

[MethodImpl(MethodImplOptions.NoInlining)]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

#if !NETCOREAPP3_1
namespace Azure.Monitor.OpenTelemetry.Exporter.E2E.Tests
{
Expand Down Expand Up @@ -56,16 +54,15 @@ public async Task VerifyTraceExporter()
}

// Export
tracerProvider.ForceFlush();
tracerProvider?.ForceFlush();

// Query
var client = CreateClient();

string query = $"AppDependencies | where AppRoleName == '{nameof(VerifyTraceExporter)}' | top 1 by TimeGenerated";

LogsTable table = await CheckForRecord(client, query);

var rowCount = table.Rows.Count();
LogsTable? table = await CheckForRecord(client, query);
var rowCount = table?.Rows.Count();

// Assert

Expand All @@ -76,13 +73,13 @@ public async Task VerifyTraceExporter()
}
else
{
Assert.True(table.Rows.Count() == 1);
Assert.True(table?.Rows.Count() == 1);
}
}

private async Task<LogsTable> CheckForRecord(LogsQueryClient client, string query)
private async Task<LogsTable?> CheckForRecord(LogsQueryClient client, string query)
{
LogsTable table = null;
LogsTable? table = null;
int count = 0;

// Try every 30 secs for total of 5 minutes.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

using System.Net;

using Microsoft.AspNetCore.Mvc;
Expand All @@ -24,7 +22,7 @@ public class HomeController : ControllerBase
/// <param name="id">Set this value to a random value and use this value to distinguish requests in any unit tests.</param>
/// <returns></returns>
[HttpGet("{id?}")]
public ActionResult<string> Get(string id = null) => StatusCode((int)HttpStatusCode.OK);
public ActionResult<string> Get(string? id = null) => StatusCode((int)HttpStatusCode.OK);

/// <summary>
/// This URI will return the <see cref="HttpStatusCode"/> matching the provided value.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

using System;
using System.Net;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Microsoft.AspNetCore.Mvc.Testing;

using Xunit;
Expand All @@ -32,7 +29,7 @@ public async Task VerifyRequest(HttpStatusCode httpStatusCode)
{
// Arrange
var client = this.factory.CreateClient();
var request = new Uri(client.BaseAddress, $"api/home/statuscode/{(int)httpStatusCode}");
var request = new Uri(client.BaseAddress!, $"api/home/statuscode/{(int)httpStatusCode}");

// Act
var response = await client.GetAsync(request);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#nullable disable // TODO: remove and fix errors

using System;
using System.Collections.Concurrent;
using System.Linq;
Expand All @@ -15,7 +13,6 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry;
using OpenTelemetry.Trace;

using Xunit;
Expand All @@ -39,7 +36,7 @@ public async Task VerifyRequestTelemetry()
{
string testValue = Guid.NewGuid().ToString();

ConcurrentBag<TelemetryItem> telemetryItems = null;
ConcurrentBag<TelemetryItem>? telemetryItems = null;

// Arrange
var client = this.factory
Expand All @@ -54,11 +51,12 @@ public async Task VerifyRequestTelemetry()
.CreateClient();

// Act
var request = new Uri(client.BaseAddress, $"api/home/{testValue}");
var request = new Uri(client.BaseAddress!, $"api/home/{testValue}");
var response = await client.GetAsync(request);

// Shutdown
response.EnsureSuccessStatusCode();
Assert.NotNull(telemetryItems);
this.WaitForActivityExport(telemetryItems);

// Assert
Expand Down