From 19e1663c1e9485948d522d4f6d77ab652d6033bc Mon Sep 17 00:00:00 2001 From: Yevhenii Solomchenko Date: Tue, 1 Oct 2024 23:16:32 +0200 Subject: [PATCH] [Extensions.Hosting.Tests] Nullable (#5862) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Piotr Kiełkowicz Co-authored-by: Mikel Blanchard --- ...nTelemetry.Extensions.Hosting.Tests.csproj | 2 - .../OpenTelemetryServicesExtensionsTests.cs | 12 +- .../Metrics/AggregatorTestsBase.cs | 33 ++-- .../Metrics/MetricApiTestsBase.cs | 176 +++++++++--------- .../Metrics/MetricTestsBase.cs | 30 +-- .../Metrics/MetricViewTests.cs | 24 +-- .../Shared/SkipUnlessTrueTheoryAttribute.cs | 2 +- 7 files changed, 145 insertions(+), 134 deletions(-) diff --git a/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetry.Extensions.Hosting.Tests.csproj b/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetry.Extensions.Hosting.Tests.csproj index 7dec47d546..73299e92b0 100644 --- a/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetry.Extensions.Hosting.Tests.csproj +++ b/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetry.Extensions.Hosting.Tests.csproj @@ -2,8 +2,6 @@ Unit test project for OpenTelemetry .NET Core hosting library $(TargetFrameworksForTests) - - disable $(DefineConstants);BUILDING_HOSTING_TESTS diff --git a/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetryServicesExtensionsTests.cs b/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetryServicesExtensionsTests.cs index 0753220b6c..16ee08af2c 100644 --- a/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetryServicesExtensionsTests.cs +++ b/test/OpenTelemetry.Extensions.Hosting.Tests/OpenTelemetryServicesExtensionsTests.cs @@ -129,7 +129,7 @@ public async Task AddOpenTelemetry_WithTracing_HostConfigurationHonoredTest() var builder = new HostBuilder() .ConfigureAppConfiguration(builder => { - builder.AddInMemoryCollection(new Dictionary + builder.AddInMemoryCollection(new Dictionary { ["TEST_KEY"] = "TEST_KEY_VALUE", }); @@ -147,7 +147,7 @@ public async Task AddOpenTelemetry_WithTracing_HostConfigurationHonoredTest() var configuration = sp.GetRequiredService(); - var testKeyValue = configuration.GetValue("TEST_KEY", null); + var testKeyValue = configuration.GetValue("TEST_KEY", null); Assert.Equal("TEST_KEY_VALUE", testKeyValue); }); @@ -252,7 +252,7 @@ public async Task AddOpenTelemetry_WithMetrics_HostConfigurationHonoredTest() var builder = new HostBuilder() .ConfigureAppConfiguration(builder => { - builder.AddInMemoryCollection(new Dictionary + builder.AddInMemoryCollection(new Dictionary { ["TEST_KEY"] = "TEST_KEY_VALUE", }); @@ -270,7 +270,7 @@ public async Task AddOpenTelemetry_WithMetrics_HostConfigurationHonoredTest() var configuration = sp.GetRequiredService(); - var testKeyValue = configuration.GetValue("TEST_KEY", null); + var testKeyValue = configuration.GetValue("TEST_KEY", null); Assert.Equal("TEST_KEY_VALUE", testKeyValue); }); @@ -375,7 +375,7 @@ public void AddOpenTelemetry_WithLogging_HostConfigurationHonoredTest() var builder = new HostBuilder() .ConfigureAppConfiguration(builder => { - builder.AddInMemoryCollection(new Dictionary + builder.AddInMemoryCollection(new Dictionary { ["TEST_KEY"] = "TEST_KEY_VALUE", }); @@ -393,7 +393,7 @@ public void AddOpenTelemetry_WithLogging_HostConfigurationHonoredTest() var configuration = sp.GetRequiredService(); - var testKeyValue = configuration.GetValue("TEST_KEY", null); + var testKeyValue = configuration.GetValue("TEST_KEY", null); Assert.Equal("TEST_KEY_VALUE", testKeyValue); }); diff --git a/test/OpenTelemetry.Tests/Metrics/AggregatorTestsBase.cs b/test/OpenTelemetry.Tests/Metrics/AggregatorTestsBase.cs index 6bd96046d3..dd7b21c6cc 100644 --- a/test/OpenTelemetry.Tests/Metrics/AggregatorTestsBase.cs +++ b/test/OpenTelemetry.Tests/Metrics/AggregatorTestsBase.cs @@ -1,6 +1,9 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + +using System.Diagnostics; using System.Diagnostics.Metrics; using Xunit; @@ -193,11 +196,7 @@ public void MultiThreadedHistogramUpdateAndSnapShotTest() { var boundaries = Array.Empty(); var histogramPoint = new MetricPoint(this.aggregatorStore, AggregationType.Histogram, null, boundaries, Metric.DefaultExponentialHistogramMaxBuckets, Metric.DefaultExponentialHistogramMaxScale); - var argsToThread = new ThreadArguments - { - HistogramPoint = histogramPoint, - MreToEnsureAllThreadsStart = new ManualResetEvent(false), - }; + var argsToThread = new ThreadArguments(histogramPoint, new ManualResetEvent(false)); var numberOfThreads = 2; var snapshotThread = new Thread(HistogramSnapshotThread); @@ -243,7 +242,7 @@ public void MultiThreadedHistogramUpdateAndSnapShotTest() [InlineData("System.Net.Http", "http.client.request.time_in_queue", "s", KnownHistogramBuckets.DefaultShortSeconds)] [InlineData("System.Net.NameResolution", "dns.lookup.duration", "s", KnownHistogramBuckets.DefaultShortSeconds)] [InlineData("General.App", "simple.alternative.counter", "s", KnownHistogramBuckets.Default)] - public void HistogramBucketsDefaultUpdatesForSecondsTest(string meterName, string instrumentName, string unit, KnownHistogramBuckets expectedHistogramBuckets) + public void HistogramBucketsDefaultUpdatesForSecondsTest(string meterName, string instrumentName, string? unit, KnownHistogramBuckets expectedHistogramBuckets) { using var meter = new Meter(meterName); @@ -341,7 +340,7 @@ internal void ExponentialHistogramTests(AggregationType aggregationType, Aggrega foreach (var value in valuesToRecord) { - aggregatorStore.Update(value, Array.Empty>()); + aggregatorStore.Update(value, Array.Empty>()); if (value >= 0) { @@ -446,7 +445,7 @@ internal void ExponentialMaxScaleConfigWorks(int? maxScale) this.emitOverflowAttribute, this.shouldReclaimUnusedMetricPoints); - aggregatorStore.Update(10, Array.Empty>()); + aggregatorStore.Update(10, Array.Empty>()); aggregatorStore.Snapshot(); @@ -466,10 +465,11 @@ internal void ExponentialMaxScaleConfigWorks(int? maxScale) Assert.Equal(expectedScale, metricPoint.GetExponentialHistogramData().Scale); } - private static void HistogramSnapshotThread(object obj) + private static void HistogramSnapshotThread(object? obj) { var args = obj as ThreadArguments; - var mreToEnsureAllThreadsStart = args.MreToEnsureAllThreadsStart; + Debug.Assert(args != null, "args was null"); + var mreToEnsureAllThreadsStart = args!.MreToEnsureAllThreadsStart; if (Interlocked.Increment(ref args.ThreadStartedCount) == 3) { @@ -487,10 +487,11 @@ private static void HistogramSnapshotThread(object obj) } } - private static void HistogramUpdateThread(object obj) + private static void HistogramUpdateThread(object? obj) { var args = obj as ThreadArguments; - var mreToEnsureAllThreadsStart = args.MreToEnsureAllThreadsStart; + Debug.Assert(args != null, "args was null"); + var mreToEnsureAllThreadsStart = args!.MreToEnsureAllThreadsStart; if (Interlocked.Increment(ref args.ThreadStartedCount) == 3) { @@ -509,11 +510,17 @@ private static void HistogramUpdateThread(object obj) private class ThreadArguments { + public readonly ManualResetEvent MreToEnsureAllThreadsStart; public MetricPoint HistogramPoint; - public ManualResetEvent MreToEnsureAllThreadsStart; public int ThreadStartedCount; public long ThreadsFinishedAllUpdatesCount; public double SumOfDelta; + + public ThreadArguments(MetricPoint histogramPoint, ManualResetEvent mreToEnsureAllThreadsStart) + { + this.HistogramPoint = histogramPoint; + this.MreToEnsureAllThreadsStart = mreToEnsureAllThreadsStart; + } } } diff --git a/test/OpenTelemetry.Tests/Metrics/MetricApiTestsBase.cs b/test/OpenTelemetry.Tests/Metrics/MetricApiTestsBase.cs index d4088bb0d1..2dfa737333 100644 --- a/test/OpenTelemetry.Tests/Metrics/MetricApiTestsBase.cs +++ b/test/OpenTelemetry.Tests/Metrics/MetricApiTestsBase.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + using System.Diagnostics; using System.Diagnostics.Metrics; using Microsoft.Extensions.Configuration; @@ -40,7 +42,7 @@ public void MeasurementWithNullValuedTag() .AddInMemoryExporter(exportedItems)); var counter = meter.CreateCounter("myCounter"); - counter.Add(100, new KeyValuePair("tagWithNullValue", null)); + counter.Add(100, new KeyValuePair("tagWithNullValue", null)); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); @@ -125,7 +127,7 @@ public void ObserverCallbackExceptionTest() [InlineData("unit")] [InlineData("")] [InlineData(null)] - public void MetricUnitIsExportedCorrectly(string unit) + public void MetricUnitIsExportedCorrectly(string? unit) { var exportedItems = new List(); @@ -147,7 +149,7 @@ public void MetricUnitIsExportedCorrectly(string unit) [InlineData("description")] [InlineData("")] [InlineData(null)] - public void MetricDescriptionIsExportedCorrectly(string description) + public void MetricDescriptionIsExportedCorrectly(string? description) { var exportedItems = new List(); @@ -171,7 +173,7 @@ public void MetricInstrumentationScopeIsExportedCorrectly() var exportedItems = new List(); var meterName = Utils.GetCurrentMethodName(); var meterVersion = "1.0"; - var meterTags = new List> + var meterTags = new List> { new( "MeterTagKey", @@ -190,6 +192,8 @@ public void MetricInstrumentationScopeIsExportedCorrectly() Assert.Equal(meterName, metric.MeterName); Assert.Equal(meterVersion, metric.MeterVersion); + Assert.NotNull(metric.MeterTags); + Assert.Single(metric.MeterTags.Where(kvp => kvp.Key == meterTags[0].Key && kvp.Value == meterTags[0].Value)); } @@ -202,13 +206,13 @@ public void MetricInstrumentationScopeAttributesAreNotTreatedAsIdentifyingProper var exportedItems = new List(); var meterName = "MyMeter"; var meterVersion = "1.0"; - var meterTags1 = new List> + var meterTags1 = new List> { new( "Key1", "Value1"), }; - var meterTags2 = new List> + var meterTags2 = new List> { new( "Key2", @@ -235,6 +239,8 @@ public void MetricInstrumentationScopeAttributesAreNotTreatedAsIdentifyingProper Assert.Equal(meterName, metric.MeterName); Assert.Equal(meterVersion, metric.MeterVersion); + Assert.NotNull(metric.MeterTags); + Assert.Single(metric.MeterTags.Where(kvp => kvp.Key == meterTags1[0].Key && kvp.Value == meterTags1[0].Value)); Assert.DoesNotContain(metric.MeterTags, kvp => kvp.Key == meterTags2[0].Key && kvp.Value == meterTags2[0].Value); @@ -777,19 +783,19 @@ public void ObservableCounterAggregationTest(bool exportDelta) public void ObservableCounterWithTagsAggregationTest(bool exportDelta) { var exportedItems = new List(); - var tags1 = new List> + var tags1 = new List> { new("statusCode", 200), new("verb", "get"), }; - var tags2 = new List> + var tags2 = new List> { new("statusCode", 200), new("verb", "post"), }; - var tags3 = new List> + var tags3 = new List> { new("statusCode", 500), new("verb", "get"), @@ -873,19 +879,19 @@ public void ObservableCounterWithTagsAggregationTest(bool exportDelta) public void ObservableCounterSpatialAggregationTest(bool exportDelta) { var exportedItems = new List(); - var tags1 = new List> + var tags1 = new List> { new("statusCode", 200), new("verb", "get"), }; - var tags2 = new List> + var tags2 = new List> { new("statusCode", 200), new("verb", "post"), }; - var tags3 = new List> + var tags3 = new List> { new("statusCode", 500), new("verb", "get"), @@ -924,7 +930,7 @@ public void ObservableCounterSpatialAggregationTest(bool exportDelta) Assert.Single(metricPoints); - var emptyTags = new List>(); + var emptyTags = new List>(); var metricPoint1 = metricPoints[0]; ValidateMetricPointTags(emptyTags, metricPoint1.Tags); @@ -1058,19 +1064,19 @@ public void ObservableUpDownCounterAggregationTest(bool exportDelta) public void ObservableUpDownCounterWithTagsAggregationTest(bool exportDelta) { var exportedItems = new List(); - var tags1 = new List> + var tags1 = new List> { new("statusCode", 200), new("verb", "get"), }; - var tags2 = new List> + var tags2 = new List> { new("statusCode", 200), new("verb", "post"), }; - var tags3 = new List> + var tags3 = new List> { new("statusCode", 500), new("verb", "get"), @@ -1177,33 +1183,33 @@ public void DimensionsAreOrderInsensitiveWithSortedKeysFirst(bool exportDelta) meterProvider.ForceFlush(MaxTimeToAllowForFlush); - List> expectedTagsForFirstMetricPoint = new List>() - { + List> expectedTagsForFirstMetricPoint = + [ new("Key1", "Value1"), new("Key2", "Value2"), new("Key3", "Value3"), - }; + ]; - List> expectedTagsForSecondMetricPoint = new List>() - { + List> expectedTagsForSecondMetricPoint = + [ new("Key1", "Value10"), new("Key2", "Value20"), new("Key3", "Value30"), - }; + ]; - List> expectedTagsForThirdMetricPoint = new List>() - { + List> expectedTagsForThirdMetricPoint = + [ new("Key4", "Value1"), new("Key5", "Value3"), new("Key6", "Value2"), - }; + ]; - List> expectedTagsForFourthMetricPoint = new List>() - { + List> expectedTagsForFourthMetricPoint = + [ new("Key4", "Value1"), new("Key5", "Value2"), new("Key6", "Value3"), - }; + ]; Assert.Equal(4, GetNumberOfMetricPoints(exportedItems)); CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFirstMetricPoint, 1); @@ -1268,33 +1274,33 @@ public void DimensionsAreOrderInsensitiveWithUnsortedKeysFirst(bool exportDelta) meterProvider.ForceFlush(MaxTimeToAllowForFlush); - List> expectedTagsForFirstMetricPoint = new List>() - { + List> expectedTagsForFirstMetricPoint = + [ new("Key1", "Value1"), new("Key2", "Value2"), new("Key3", "Value3"), - }; + ]; - List> expectedTagsForSecondMetricPoint = new List>() - { + List> expectedTagsForSecondMetricPoint = + [ new("Key1", "Value10"), new("Key2", "Value20"), new("Key3", "Value30"), - }; + ]; - List> expectedTagsForThirdMetricPoint = new List>() - { + List> expectedTagsForThirdMetricPoint = + [ new("Key4", "Value1"), new("Key5", "Value3"), new("Key6", "Value2"), - }; + ]; - List> expectedTagsForFourthMetricPoint = new List>() - { + List> expectedTagsForFourthMetricPoint = + [ new("Key4", "Value1"), new("Key5", "Value2"), new("Key6", "Value3"), - }; + ]; Assert.Equal(4, GetNumberOfMetricPoints(exportedItems)); CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFirstMetricPoint, 1); @@ -1351,37 +1357,37 @@ public void TestInstrumentDisposal(MetricReaderTemporalityPreference temporality metricReaderOptions.TemporalityPreference = temporality; })); - counter1.Add(10, new KeyValuePair("key", "value")); - counter2.Add(10, new KeyValuePair("key", "value")); + counter1.Add(10, new KeyValuePair("key", "value")); + counter2.Add(10, new KeyValuePair("key", "value")); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); exportedItems.Clear(); - counter1.Add(10, new KeyValuePair("key", "value")); - counter2.Add(10, new KeyValuePair("key", "value")); + counter1.Add(10, new KeyValuePair("key", "value")); + counter2.Add(10, new KeyValuePair("key", "value")); meter1.Dispose(); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); exportedItems.Clear(); - counter1.Add(10, new KeyValuePair("key", "value")); - counter2.Add(10, new KeyValuePair("key", "value")); + counter1.Add(10, new KeyValuePair("key", "value")); + counter2.Add(10, new KeyValuePair("key", "value")); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); exportedItems.Clear(); - counter1.Add(10, new KeyValuePair("key", "value")); - counter2.Add(10, new KeyValuePair("key", "value")); + counter1.Add(10, new KeyValuePair("key", "value")); + counter2.Add(10, new KeyValuePair("key", "value")); meter2.Dispose(); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); exportedItems.Clear(); - counter1.Add(10, new KeyValuePair("key", "value")); - counter2.Add(10, new KeyValuePair("key", "value")); + counter1.Add(10, new KeyValuePair("key", "value")); + counter2.Add(10, new KeyValuePair("key", "value")); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Empty(exportedItems); } @@ -1440,7 +1446,7 @@ int MetricPointCount() counterLong.Add(10); for (int i = 0; i < MeterProviderBuilderSdk.DefaultCardinalityLimit + 1; i++) { - counterLong.Add(10, new KeyValuePair("key", "value" + i)); + counterLong.Add(10, new KeyValuePair("key", "value" + i)); } meterProvider.ForceFlush(MaxTimeToAllowForFlush); @@ -1450,7 +1456,7 @@ int MetricPointCount() counterLong.Add(10); for (int i = 0; i < MeterProviderBuilderSdk.DefaultCardinalityLimit + 1; i++) { - counterLong.Add(10, new KeyValuePair("key", "value" + i)); + counterLong.Add(10, new KeyValuePair("key", "value" + i)); } meterProvider.ForceFlush(MaxTimeToAllowForFlush); @@ -1459,13 +1465,13 @@ int MetricPointCount() counterLong.Add(10); for (int i = 0; i < MeterProviderBuilderSdk.DefaultCardinalityLimit + 1; i++) { - counterLong.Add(10, new KeyValuePair("key", "value" + i)); + counterLong.Add(10, new KeyValuePair("key", "value" + i)); } // These updates would be dropped. - counterLong.Add(10, new KeyValuePair("key", "valueA")); - counterLong.Add(10, new KeyValuePair("key", "valueB")); - counterLong.Add(10, new KeyValuePair("key", "valueC")); + counterLong.Add(10, new KeyValuePair("key", "valueA")); + counterLong.Add(10, new KeyValuePair("key", "valueB")); + counterLong.Add(10, new KeyValuePair("key", "valueC")); exportedItems.Clear(); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(MeterProviderBuilderSdk.DefaultCardinalityLimit, MetricPointCount()); @@ -1577,7 +1583,7 @@ public void SetupSdkProviderWithNoReader(bool hasViews) var counter = meter.CreateCounter("counter"); - counter.Add(10, new KeyValuePair("key", "value")); + counter.Add(10, new KeyValuePair("key", "value")); } [Fact] @@ -1702,7 +1708,7 @@ public void GaugeHandlesNoNewMeasurementsCorrectlyWithTemporality(MetricReaderTe internal static IConfiguration BuildConfiguration(bool emitOverflowAttribute, bool shouldReclaimUnusedMetricPoints) { - var configurationData = new Dictionary(); + var configurationData = new Dictionary(); if (emitOverflowAttribute) { @@ -1719,18 +1725,19 @@ internal static IConfiguration BuildConfiguration(bool emitOverflowAttribute, bo .Build(); } - private static void CounterUpdateThread(object obj) + private static void CounterUpdateThread(object? obj) where T : struct, IComparable { - if (obj is not UpdateThreadArguments arguments) - { - throw new Exception("Invalid args"); - } + var arguments = obj as UpdateThreadArguments; + Debug.Assert(arguments != null, "arguments was null"); - var mre = arguments.MreToBlockUpdateThread; + var mre = arguments!.MreToBlockUpdateThread; var mreToEnsureAllThreadsStart = arguments.MreToEnsureAllThreadsStart; - var counter = arguments.Instrument as Counter; var valueToUpdate = arguments.ValuesToRecord[0]; + + var counter = arguments.Instrument as Counter; + Debug.Assert(counter != null, "counter was null"); + if (Interlocked.Increment(ref arguments.ThreadsStartedCount) == NumberOfThreads) { mreToEnsureAllThreadsStart.Set(); @@ -1741,21 +1748,20 @@ private static void CounterUpdateThread(object obj) for (int i = 0; i < NumberOfMetricUpdateByEachThread; i++) { - counter.Add(valueToUpdate, new KeyValuePair("verb", "GET")); + counter!.Add(valueToUpdate, new KeyValuePair("verb", "GET")); } } - private static void HistogramUpdateThread(object obj) + private static void HistogramUpdateThread(object? obj) where T : struct, IComparable { - if (obj is not UpdateThreadArguments arguments) - { - throw new Exception("Invalid args"); - } + var arguments = obj as UpdateThreadArguments; + Debug.Assert(arguments != null, "arguments was null"); - var mre = arguments.MreToBlockUpdateThread; + var mre = arguments!.MreToBlockUpdateThread; var mreToEnsureAllThreadsStart = arguments.MreToEnsureAllThreadsStart; var histogram = arguments.Instrument as Histogram; + Debug.Assert(histogram != null, "histogram was null"); if (Interlocked.Increment(ref arguments.ThreadsStartedCount) == NumberOfThreads) { @@ -1769,7 +1775,7 @@ private static void HistogramUpdateThread(object obj) { for (int j = 0; j < arguments.ValuesToRecord.Length; j++) { - histogram.Record(arguments.ValuesToRecord[j]); + histogram!.Record(arguments.ValuesToRecord[j]); } } } @@ -1785,13 +1791,7 @@ private void MultithreadedCounterTest(T deltaValueUpdatedByEachCall) .AddMeter(meter.Name) .AddInMemoryExporter(metricItems)); - var argToThread = new UpdateThreadArguments - { - ValuesToRecord = new T[] { deltaValueUpdatedByEachCall }, - Instrument = meter.CreateCounter("counter"), - MreToBlockUpdateThread = new ManualResetEvent(false), - MreToEnsureAllThreadsStart = new ManualResetEvent(false), - }; + var argToThread = new UpdateThreadArguments(new ManualResetEvent(false), new ManualResetEvent(false), meter.CreateCounter("counter"), [deltaValueUpdatedByEachCall]); Thread[] t = new Thread[NumberOfThreads]; for (int i = 0; i < NumberOfThreads; i++) @@ -1841,13 +1841,7 @@ private void MultithreadedHistogramTest(long[] expected, T[] values) .AddMeter(meter.Name) .AddReader(metricReader)); - var argsToThread = new UpdateThreadArguments - { - Instrument = meter.CreateHistogram("histogram"), - MreToBlockUpdateThread = new ManualResetEvent(false), - MreToEnsureAllThreadsStart = new ManualResetEvent(false), - ValuesToRecord = values, - }; + var argsToThread = new UpdateThreadArguments(new ManualResetEvent(false), new ManualResetEvent(false), meter.CreateHistogram("histogram"), values); Thread[] t = new Thread[NumberOfThreads]; for (int i = 0; i < NumberOfThreads; i++) @@ -1888,6 +1882,14 @@ private class UpdateThreadArguments public int ThreadsStartedCount; public Instrument Instrument; public T[] ValuesToRecord; + + public UpdateThreadArguments(ManualResetEvent mreToBlockUpdateThread, ManualResetEvent mreToEnsureAllThreadsStart, Instrument instrument, T[] valuesToRecord) + { + this.MreToBlockUpdateThread = mreToBlockUpdateThread; + this.MreToEnsureAllThreadsStart = mreToEnsureAllThreadsStart; + this.Instrument = instrument; + this.ValuesToRecord = valuesToRecord; + } } } diff --git a/test/OpenTelemetry.Tests/Metrics/MetricTestsBase.cs b/test/OpenTelemetry.Tests/Metrics/MetricTestsBase.cs index 7d72b773ea..ee1162f478 100644 --- a/test/OpenTelemetry.Tests/Metrics/MetricTestsBase.cs +++ b/test/OpenTelemetry.Tests/Metrics/MetricTestsBase.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + #if BUILDING_HOSTING_TESTS using System.Diagnostics; #endif @@ -19,7 +21,7 @@ public class MetricTestsBase public const string EmitOverFlowAttributeConfigKey = "OTEL_DOTNET_EXPERIMENTAL_METRICS_EMIT_OVERFLOW_ATTRIBUTE"; public const string ReclaimUnusedMetricPointsConfigKey = "OTEL_DOTNET_EXPERIMENTAL_METRICS_RECLAIM_UNUSED_METRIC_POINTS"; - protected readonly IConfiguration configuration; + protected readonly IConfiguration? configuration; protected MetricTestsBase() { @@ -33,10 +35,10 @@ protected MetricTestsBase(IConfiguration configuration) #if BUILDING_HOSTING_TESTS public static IHost BuildHost( bool useWithMetricsStyle, - Action configureAppConfiguration = null, - Action configureServices = null, - Action configureMetricsBuilder = null, - Action configureMeterProviderBuilder = null) + Action? configureAppConfiguration = null, + Action? configureServices = null, + Action? configureMetricsBuilder = null, + Action? configureMeterProviderBuilder = null) { var hostBuilder = new HostBuilder() .ConfigureDefaults(null) @@ -74,15 +76,15 @@ public static IHost BuildHost( return host; - static void ConfigureBuilder(MeterProviderBuilder builder, Action configureMeterProviderBuilder) + static void ConfigureBuilder(MeterProviderBuilder builder, Action? configureMeterProviderBuilder) { - IServiceCollection localServices = null; + IServiceCollection? localServices = null; builder.ConfigureServices(services => localServices = services); Debug.Assert(localServices != null, "localServices was null"); - var testBuilder = new HostingMeterProviderBuilder(localServices); + var testBuilder = new HostingMeterProviderBuilder(localServices!); configureMeterProviderBuilder?.Invoke(testBuilder); } } @@ -90,7 +92,7 @@ static void ConfigureBuilder(MeterProviderBuilder builder, Action> expectedTags, ReadOnlyTagCollection actualTags) + public static void ValidateMetricPointTags(List> expectedTags, ReadOnlyTagCollection actualTags) { int tagIndex = 0; foreach (var tag in actualTags) @@ -175,7 +177,7 @@ public static int GetNumberOfMetricPoints(List metrics) // This method relies on the assumption that MetricPoints are exported in the order in which they are emitted. // For Delta AggregationTemporality, this holds true only until the AggregatorStore has not begun recaliming the MetricPoints. // Provide tags input sorted by Key - public static void CheckTagsForNthMetricPoint(List metrics, List> tags, int n) + public static void CheckTagsForNthMetricPoint(List metrics, List> tags, int n) { var metric = metrics[0]; var metricPointEnumerator = metric.GetMetricPoints().GetEnumerator(); @@ -216,7 +218,7 @@ public IDisposable BuildMeterProvider( } }); - meterProvider = host.Services.GetService(); + meterProvider = host.Services.GetRequiredService(); return host; #else @@ -277,8 +279,8 @@ private sealed class MetricsSubscriptionManagerCleanupHostedService : IHostedSer public MetricsSubscriptionManagerCleanupHostedService(IServiceProvider serviceProvider) { - this.metricsSubscriptionManager = serviceProvider.GetService( - typeof(ConsoleMetrics).Assembly.GetType("Microsoft.Extensions.Diagnostics.Metrics.MetricsSubscriptionManager")); + this.metricsSubscriptionManager = serviceProvider.GetRequiredService( + typeof(ConsoleMetrics).Assembly.GetType("Microsoft.Extensions.Diagnostics.Metrics.MetricsSubscriptionManager")!); if (this.metricsSubscriptionManager == null) { @@ -292,7 +294,7 @@ public void Dispose() // be bugged in that it doesn't implement IDisposable. This hack // manually invokes Dispose so that tests don't clobber each other. // See: https://github.com/dotnet/runtime/issues/94434. - this.metricsSubscriptionManager.GetType().GetMethod("Dispose").Invoke(this.metricsSubscriptionManager, null); + this.metricsSubscriptionManager.GetType().GetMethod("Dispose")!.Invoke(this.metricsSubscriptionManager, null); } public Task StartAsync(CancellationToken cancellationToken) diff --git a/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs b/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs index 11c048512e..6dae582151 100644 --- a/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs +++ b/test/OpenTelemetry.Tests/Metrics/MetricViewTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable enable + using System.Diagnostics.Metrics; using OpenTelemetry.Internal; using OpenTelemetry.Tests; @@ -56,7 +58,7 @@ public void AddViewWithInvalidNameThrowsArgumentException(string viewNewName) } [Fact] - public void AddViewWithNullMetricStreamConfigurationThrowsArgumentnullException() + public void AddViewWithNullMetricStreamConfigurationThrowsArgumentNullException() { var exportedItems = new List(); @@ -64,7 +66,7 @@ public void AddViewWithNullMetricStreamConfigurationThrowsArgumentnullException( Assert.Throws(() => this.BuildMeterProvider(out var meterProvider, builder => builder .AddMeter(meter1.Name) - .AddView("name1", (MetricStreamConfiguration)null) + .AddView("name1", (MetricStreamConfiguration)null!) .AddInMemoryExporter(exportedItems))); } @@ -1233,7 +1235,7 @@ public void ViewConflict_TwoIdenticalInstruments_TwoViews_DifferentTags() var instrument1 = meter.CreateCounter("name"); var instrument2 = meter.CreateCounter("name"); - var tags = new KeyValuePair[] + var tags = new KeyValuePair[] { new("key1", "value"), new("key2", "value"), @@ -1247,8 +1249,8 @@ public void ViewConflict_TwoIdenticalInstruments_TwoViews_DifferentTags() Assert.Equal(2, exportedItems.Count); var metric1 = new List() { exportedItems[0] }; var metric2 = new List() { exportedItems[1] }; - var tag1 = new List> { tags[0] }; - var tag2 = new List> { tags[1] }; + var tag1 = new List> { tags[0] }; + var tag2 = new List> { tags[1] }; Assert.Equal("name", exportedItems[0].Name); Assert.Equal("name", exportedItems[1].Name); @@ -1280,7 +1282,7 @@ public void ViewConflict_TwoIdenticalInstruments_TwoViews_SameTags() var instrument1 = meter.CreateCounter("name"); var instrument2 = meter.CreateCounter("name"); - var tags = new KeyValuePair[] + var tags = new KeyValuePair[] { new("key1", "value"), new("key2", "value"), @@ -1294,13 +1296,13 @@ public void ViewConflict_TwoIdenticalInstruments_TwoViews_SameTags() Assert.Equal(2, exportedItems.Count); var metric1 = new List() { exportedItems[0] }; - var tag1 = new List> { tags[0] }; + var tag1 = new List> { tags[0] }; Assert.Equal("name", exportedItems[0].Name); Assert.Equal(20, GetLongSum(metric1)); CheckTagsForNthMetricPoint(metric1, tag1, 1); var metric2 = new List() { exportedItems[1] }; - var tag2 = new List> { tags[0] }; + var tag2 = new List> { tags[0] }; Assert.Equal("name", exportedItems[1].Name); Assert.Equal(20, GetLongSum(metric2)); CheckTagsForNthMetricPoint(metric2, tag2, 1); @@ -1408,7 +1410,7 @@ public void ViewConflict_TwoInstruments_OneMatchesView() var instrument1 = meter.CreateCounter("name"); var instrument2 = meter.CreateCounter("othername"); - var tags = new KeyValuePair[] + var tags = new KeyValuePair[] { new("key1", "value"), new("key2", "value"), @@ -1423,8 +1425,8 @@ public void ViewConflict_TwoInstruments_OneMatchesView() var metric1 = new List() { exportedItems[0] }; var metric2 = new List() { exportedItems[1] }; - var tags1 = new List> { tags[0] }; - var tags2 = new List> { tags[0], tags[1] }; + var tags1 = new List> { tags[0] }; + var tags2 = new List> { tags[0], tags[1] }; Assert.Equal("othername", exportedItems[0].Name); Assert.Equal("othername", exportedItems[1].Name); diff --git a/test/OpenTelemetry.Tests/Shared/SkipUnlessTrueTheoryAttribute.cs b/test/OpenTelemetry.Tests/Shared/SkipUnlessTrueTheoryAttribute.cs index 087bff4366..e1bb798391 100644 --- a/test/OpenTelemetry.Tests/Shared/SkipUnlessTrueTheoryAttribute.cs +++ b/test/OpenTelemetry.Tests/Shared/SkipUnlessTrueTheoryAttribute.cs @@ -23,7 +23,7 @@ public SkipUnlessTrueTheoryAttribute(Type typeContainingTest, string testFieldNa throw new InvalidOperationException($"Field '{testFieldName}' on '{typeContainingTest}' type should be defined as '{typeof(Func)}'."); } - var testFunc = (Func)field.GetValue(null); + var testFunc = (Func)field.GetValue(null)!; if (!testFunc()) {