From 8fcde672e906704f4169ff2cd7c8eca7d9f28aa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 20 Jun 2022 19:14:14 +0200 Subject: [PATCH 1/3] Enable nullables on common --- .../TestPlatform.cs | 2 +- .../Constants.cs | 2 - .../DataCollection/AfterTestRunEndResult.cs | 12 +- .../BeforeTestRunStartResult.cs | 2 - .../DataCollectionAttachmentManager.cs | 15 +- .../DataCollectionEnvironmentVariable.cs | 4 +- .../DataCollection/DataCollectionManager.cs | 139 ++++++++++-------- .../DataCollectionTelemetryManager.cs | 2 - .../DataCollection/DataCollectorConfig.cs | 40 +++-- .../DataCollectorInformation.cs | 12 +- .../IDataCollectionAttachmentManager.cs | 4 +- .../Interfaces/IDataCollectionManager.cs | 2 - .../IDataCollectionTelemetryManager.cs | 2 - .../DataCollection/Interfaces/IMessageSink.cs | 2 - .../TestPlatformDataCollectionEvents.cs | 14 +- .../TestPlatformDataCollectionLogger.cs | 2 - .../TestPlatformDataCollectionSink.cs | 5 +- .../Exceptions/InvalidLoggerException.cs | 6 +- .../DataCollectionExtensionManager.cs | 2 - .../TestDiscoveryExtensionManager.cs | 10 +- .../TestExecutorExtensionManager.cs | 22 +-- .../TestExtensionManager.cs | 41 +++--- .../TestLoggerExtensionManager.cs | 2 - .../ExtensionFramework/TestPluginCache.cs | 79 +++++----- .../TestPluginDiscoverer.cs | 57 +++---- .../ExtensionFramework/TestPluginManager.cs | 26 ++-- .../Utilities/LazyExtension.cs | 18 ++- .../TestDiscovererPluginInformation.cs | 2 +- .../TestExecutorPluginInformation.cs | 6 +- .../TestExtensionPluginInformation.cs | 14 +- .../Utilities/TestExtensions.cs | 103 ++++++------- .../Utilities/TestLoggerPluginInformation.cs | 8 +- .../Utilities/TestPluginInformation.cs | 14 +- .../Utilities/TestRunTimePluginInformation.cs | 12 +- .../TestSettingsProviderPluginInformation.cs | 12 +- .../ExtensionFramework/VSExtensionManager.cs | 71 +++++---- .../Filtering/Condition.cs | 20 +-- .../Filtering/FastFilter.cs | 70 ++++----- .../Filtering/FilterExpression.cs | 27 ++-- .../Filtering/FilterExpressionWrapper.cs | 26 ++-- .../Filtering/TestCaseFilterExpression.cs | 9 +- .../Hosting/TestRunTimeExtensionManager.cs | 2 - .../Hosting/TestRunTimeMetadata.cs | 2 - .../IParallelOperationManager.cs | 2 - .../IParallelProxyDiscoveryManager.cs | 4 +- .../IParallelProxyExecutionManager.cs | 8 +- .../ClientProtocol/IProxyDiscoveryManager.cs | 2 - .../ClientProtocol/IProxyExecutionManager.cs | 2 - .../IProxyTestSessionManager.cs | 6 +- .../Engine/ClientProtocol/ITestEngine.cs | 22 ++- .../ClientProtocol/ITestExtensionManager.cs | 4 +- .../ClientProtocol/ITestLoggerManager.cs | 3 - .../ClientProtocol/TestExecutionContext.cs | 12 +- .../Engine/IArtifactProcessingManager.cs | 2 - ...taCollectorAttachmentsProcessorsFactory.cs | 4 +- .../Engine/ITestCaseEventsHandler.cs | 2 - .../ITestRunAttachmentsProcessingManager.cs | 6 +- .../TesthostProtocol/IDiscoveryManager.cs | 4 +- .../TesthostProtocol/IExecutionManager.cs | 9 +- .../ITestHostManagerFactory.cs | 2 - .../Interfaces/IAssemblyProperties.cs | 2 - .../Interfaces/IBaseTestEventsRegistrar.cs | 2 - .../Interfaces/IDataCollectorCapabilities.cs | 2 - .../Interfaces/IRunSettingsProvider.cs | 4 +- .../ISettingsProviderCapabilities.cs | 2 - .../Interfaces/ITestDiscovererCapabilities.cs | 6 +- .../ITestDiscoveryEventsRegistrar.cs | 2 - .../Interfaces/ITestExecutorCapabilities.cs | 2 - .../Interfaces/ITestExtensionCapabilities.cs | 2 - .../Interfaces/ITestLoggerCapabilities.cs | 2 - .../Interfaces/ITestRunEventsRegistrar.cs | 2 - .../Interfaces/ITestRunTimeCapabilities.cs | 2 - .../Interfaces/IVSExtensionManager.cs | 2 - .../Logging/InternalTestLoggerEvents.cs | 38 +++-- .../Logging/TestSessionMessageLogger.cs | 8 +- .../RequestData.cs | 8 +- .../RunSettings.cs | 16 +- .../RunSettingsManager.cs | 9 +- .../SettingsProviderExtensionManager.cs | 20 ++- .../Telemetry/MetricsCollection.cs | 2 - .../Telemetry/NoOpMetricsCollection.cs | 2 - .../Telemetry/TelemetryDataConstants.cs | 2 - .../Utilities/AssemblyProperties.cs | 2 - .../Utilities/AssemblyResolver.cs | 10 +- .../Utilities/AssemblyType.cs | 2 - .../Utilities/CancellationTokenExtensions.cs | 2 - .../Utilities/ExceptionUtilities.cs | 4 +- .../Utilities/FakesUtilities.cs | 17 +-- .../Utilities/InstallationContext.cs | 2 - .../Utilities/MetadataReaderHelper.cs | 17 +-- .../RunSettingsProviderExtensions.cs | 27 ++-- .../Utilities/RunSettingsUtilities.cs | 41 +++--- .../Utilities/TypesToLoadUtilities.cs | 5 +- .../DataCollectionRequestHandler.cs | 1 + .../DataCollectionTestCaseEventHandler.cs | 8 +- .../ObjectModel/TestRunCriteriaWithSources.cs | 4 +- .../ObjectModel/TestRunCriteriaWithTests.cs | 4 +- ...DataCollectorAttachmentProcessorWrapper.cs | 3 +- ...taCollectorAttachmentsProcessorsFactory.cs | 44 +++--- .../Parallel/ParallelProxyDiscoveryManager.cs | 2 +- .../ProxyDataCollectionManager.cs | 2 +- .../Discovery/DiscovererEnumerator.cs | 12 +- .../Discovery/DiscoveryManager.cs | 2 +- .../EventHandlers/IPathConverter.cs | 2 +- .../EventHandlers/NullPathConverter.cs | 2 +- .../EventHandlers/PathConverter.cs | 4 +- .../EventHandlers/TestRequestHandler.cs | 2 +- .../Execution/ExecutionManager.cs | 2 +- .../Execution/RunTestsWithSources.cs | 4 +- .../Execution/RunTestsWithTests.cs | 4 +- .../TestExtensionManager.cs | 2 +- .../DataCollector/DataCollectionSink.cs | 4 +- .../DataCollector/Events/SessionEvents.cs | 6 +- .../Interfaces/Runtime/IAssemblyResolver.cs | 2 +- .../CommandLine/GenerateFakesUtilities.cs | 2 +- src/vstest.console/CommandLine/InferHelper.cs | 2 +- .../Processors/CollectArgumentProcessor.cs | 4 +- .../EnvironmentArgumentProcessor.cs | 2 +- .../RunSpecificTestsArgumentProcessor.cs | 3 +- .../Processors/RunTestsArgumentProcessor.cs | 1 + .../TestAdapterPathArgumentProcessor.cs | 2 +- .../TestPlatformHelpers/TestRequestManager.cs | 24 +-- .../DesignMode/DesignModeClientTests.cs | 10 -- .../DataCollectorExtensionManagerTests.cs | 2 +- .../TestDiscoveryExtensionManagerTests.cs | 4 +- .../TestExtensionManagerTests.cs | 2 +- .../TestLoggerExtensionManagerTests.cs | 2 +- .../TestPluginCacheTests.cs | 15 +- .../TestPluginDiscovererTests.cs | 17 +-- .../TestPluginManagerTests.cs | 2 +- .../Utilities/LazyExtensionTests.cs | 16 +- .../RunSettingsProviderExtensionsTests.cs | 32 ++-- .../Utilities/TestExtensionsTests.cs | 12 +- .../Filtering/ConditionTests.cs | 2 +- .../Filtering/FastFilterTests.cs | 116 ++++++++------- .../Filtering/FilterExpressionTests.cs | 2 +- .../TestCaseFilterExpressionTests.cs | 5 +- .../Hosting/TestHostExtensionManagerTests.cs | 2 +- .../Logging/InternalTestLoggerEventsTests.cs | 14 +- .../RequestDataTests.cs | 2 +- .../RunSettingsManagerTests.cs | 2 +- .../RunSettingsTests.cs | 6 +- .../SettingsProviderExtensionManagerTests.cs | 2 +- .../Utilities/FakesUtilitiesTests.cs | 4 +- .../DataCollectionRequestSenderTests.cs | 2 +- ...DataCollectionTestCaseEventHandlerTests.cs | 2 + .../TestRequestSenderTests.cs | 6 +- .../InProcessProxyexecutionManagerTests.cs | 12 +- ...arallelDataCollectionEventsHandlerTests.cs | 2 +- .../EventHandlers/TestRequestHandlerTests.cs | 6 +- .../Execution/ExecutionManagerTests.cs | 4 +- .../DataCollectionAttachmentManagerTests.cs | 6 +- .../DataCollectionEnvironmentVariableTests.cs | 2 +- .../DataCollectionManagerTests.cs | 14 +- .../DataCollectorConfigTests.cs | 8 +- .../DataCollectorInformationTests.cs | 2 +- .../TestPlatformDataCollectionEventsTests.cs | 2 +- .../TestPlatformDataCollectionLoggerTests.cs | 10 +- .../TestPlatformDataCollectionSinkTests.cs | 2 +- ...taCollectorAttachmentsProcessorsFactory.cs | 2 +- .../Fakes/FakeTestExtensionManager.cs | 2 +- .../CommandLine/InferHelperTests.cs | 28 ++-- .../Internal/ConsoleLoggerTests.cs | 4 +- .../CollectArgumentProcessorTests.cs | 2 +- .../EnableLoggersArgumentProcessorTests.cs | 2 +- .../EnvironmentArgumentProcessorTests.cs | 2 +- .../RunSettingsArgumentProcessorTests.cs | 2 +- 167 files changed, 848 insertions(+), 985 deletions(-) diff --git a/src/Microsoft.TestPlatform.Client/TestPlatform.cs b/src/Microsoft.TestPlatform.Client/TestPlatform.cs index ffd2f80bd6..229d016dc4 100644 --- a/src/Microsoft.TestPlatform.Client/TestPlatform.cs +++ b/src/Microsoft.TestPlatform.Client/TestPlatform.cs @@ -274,7 +274,7 @@ private static void AddExtensionAssembliesFromExtensionDirectory() // Otherwise we will always get a "No suitable test runtime provider found for this run." error. // I (@haplois) will modify this behavior later on, but we also need to consider legacy adapters // and make sure they still work after modification. - string runSettings = RunSettingsManager.Instance.ActiveRunSettings.SettingsXml; + string? runSettings = RunSettingsManager.Instance.ActiveRunSettings.SettingsXml; RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings); TestAdapterLoadingStrategy strategy = runConfiguration.TestAdapterLoadingStrategy; diff --git a/src/Microsoft.TestPlatform.Common/Constants.cs b/src/Microsoft.TestPlatform.Common/Constants.cs index 00013d01d1..b063862898 100644 --- a/src/Microsoft.TestPlatform.Common/Constants.cs +++ b/src/Microsoft.TestPlatform.Common/Constants.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common; /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/AfterTestRunEndResult.cs b/src/Microsoft.TestPlatform.Common/DataCollection/AfterTestRunEndResult.cs index 58281f5e5b..33b70f7344 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/AfterTestRunEndResult.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/AfterTestRunEndResult.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollection; /// @@ -21,7 +19,11 @@ public class AfterTestRunEndResult // We want to fallback to the non-public default constructor https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_ConstructorHandling.htm during deserialization private AfterTestRunEndResult() { - + // Forcing nulls to the differnet properties as this is only serialization ctor but + // we can guarantee non-null for the other ctors. + AttachmentSets = null!; + InvokedDataCollectors = null!; + Metrics = null!; } /// @@ -50,7 +52,7 @@ public AfterTestRunEndResult(Collection attachmentSets, IDictiona /// The metrics. /// public AfterTestRunEndResult(Collection attachmentSets, - Collection invokedDataCollectors, + Collection? invokedDataCollectors, IDictionary metrics) { AttachmentSets = attachmentSets; @@ -62,7 +64,7 @@ public AfterTestRunEndResult(Collection attachmentSets, public Collection AttachmentSets { get; private set; } [DataMember] - public Collection InvokedDataCollectors { get; private set; } + public Collection? InvokedDataCollectors { get; private set; } [DataMember] public IDictionary Metrics { get; private set; } diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs b/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs index b6db9da8c3..546a7cabbb 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs index 98284e7788..b7ceae4798 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs @@ -18,8 +18,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// @@ -48,7 +46,7 @@ internal class DataCollectionAttachmentManager : IDataCollectionAttachmentManage /// /// Logger for data collection messages /// - private IMessageSink _messageSink; + private IMessageSink? _messageSink; /// /// Attachment transfer tasks associated with a given datacollection context. @@ -88,7 +86,7 @@ protected DataCollectionAttachmentManager(IFileHelper fileHelper) /// /// Gets the session output directory. /// - internal string SessionOutputDirectory { get; private set; } + internal string? SessionOutputDirectory { get; private set; } /// /// Gets the attachment sets for the given datacollection context. @@ -162,7 +160,7 @@ public List GetAttachments(DataCollectionContext dataCollectionCo } /// - public void AddAttachment(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler sendFileCompletedCallback, Uri uri, string friendlyName) + public void AddAttachment(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler? sendFileCompletedCallback, Uri uri, string friendlyName) { ValidateArg.NotNull(fileTransferInfo, nameof(fileTransferInfo)); @@ -217,7 +215,7 @@ private static void Validate(FileTransferInformation fileTransferInfo, string lo if (!Directory.Exists(directoryName)) { - Directory.CreateDirectory(directoryName); + Directory.CreateDirectory(directoryName!); } else if (File.Exists(localFilePath)) { @@ -240,7 +238,7 @@ private static void Validate(FileTransferInformation fileTransferInfo, string lo /// /// The friendly Name. /// - private void AddNewFileTransfer(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler sendFileCompletedCallback, Uri uri, string friendlyName) + private void AddNewFileTransfer(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler? sendFileCompletedCallback, Uri uri, string friendlyName) { var context = fileTransferInfo.Context; TPDebug.Assert( @@ -251,6 +249,7 @@ private void AddNewFileTransfer(FileTransferInformation fileTransferInfo, AsyncC ? fileTransferInfo.Context.TestExecId.Id.ToString() : string.Empty; + TPDebug.Assert(SessionOutputDirectory is not null, "SessionOutputDirectory is null."); var directoryPath = Path.Combine( SessionOutputDirectory, testCaseId); @@ -354,7 +353,7 @@ private void LogError(string errorMessage, Uri collectorUri, string collectorFri args.TestCaseId = testCaseId; } - _messageSink.SendMessage(args); + _messageSink?.SendMessage(args); } } diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionEnvironmentVariable.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionEnvironmentVariable.cs index 3aa9f7704f..3d38d6401c 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionEnvironmentVariable.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionEnvironmentVariable.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// @@ -81,7 +79,7 @@ public string FirstDataCollectorThatRequested } /// - /// Adds the data collector to the list of data collectors that requested this variable. + /// Adds the data collector to the list of data collectors that requested this variable. /// /// Friendly name of requesting data collector. public void AddRequestingDataCollector(string requestingDataCollectorFriendlyName) diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs index 9eaa4c6456..10c21a3b81 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs @@ -17,8 +17,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// @@ -37,7 +35,7 @@ internal class DataCollectionManager : IDataCollectionManager /// /// Data collection environment context. /// - private DataCollectionEnvironmentContext _dataCollectionEnvironmentContext; + private DataCollectionEnvironmentContext? _dataCollectionEnvironmentContext; /// /// Attachment manager for performing file transfers for datacollectors. @@ -62,7 +60,7 @@ internal class DataCollectionManager : IDataCollectionManager /// /// Extension manager for data collectors. /// - private DataCollectorExtensionManager _dataCollectorExtensionManager; + private DataCollectorExtensionManager? _dataCollectorExtensionManager; /// /// Request data @@ -104,7 +102,7 @@ protected DataCollectionManager(IDataCollectionAttachmentManager datacollectionA /// /// Gets the instance of DataCollectionManager. /// - public static DataCollectionManager Instance { get; private set; } + public static DataCollectionManager? Instance { get; private set; } /// /// Gets cache of data collectors associated with the run. @@ -157,9 +155,9 @@ public static DataCollectionManager Create(IMessageSink messageSink, IRequestDat public IDictionary InitializeDataCollectors(string settingsXml) { ValidateArg.NotNull(settingsXml, nameof(settingsXml)); - if (settingsXml.IsNullOrEmpty()) + if (settingsXml.Length == 0) { - EqtTrace.Info("DataCollectionManager.InitializeDataCollectors: Runsettings is null or empty."); + EqtTrace.Info("DataCollectionManager.InitializeDataCollectors: Runsettings is empty."); } var sessionId = new SessionId(Guid.NewGuid()); @@ -233,6 +231,7 @@ public Collection SessionEnded(bool isCancelled = false) return new Collection(); } + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); var endEvent = new SessionEndEventArgs(_dataCollectionEnvironmentContext.SessionDataCollectionContext); SendEvent(endEvent); @@ -280,6 +279,7 @@ public void TestHostLaunched(int processId) return; } + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); var testHostLaunchedEventArgs = new TestHostLaunchedEventArgs(_dataCollectionEnvironmentContext.SessionDataCollectionContext, processId); SendEvent(testHostLaunchedEventArgs); @@ -294,6 +294,7 @@ public bool SessionStarted(SessionStartEventArgs sessionStartEventArgs) return false; } + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); sessionStartEventArgs.Context = new DataCollectionContext(_dataCollectionEnvironmentContext.SessionDataCollectionContext.SessionId); SendEvent(sessionStartEventArgs); @@ -308,6 +309,7 @@ public void TestCaseStarted(TestCaseStartEventArgs testCaseStartEventArgs) return; } + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); var context = new DataCollectionContext(_dataCollectionEnvironmentContext.SessionDataCollectionContext.SessionId, testCaseStartEventArgs.TestElement); testCaseStartEventArgs.Context = context; @@ -322,12 +324,13 @@ public Collection TestCaseEnded(TestCaseEndEventArgs testCaseEndE return new Collection(); } + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); var context = new DataCollectionContext(_dataCollectionEnvironmentContext.SessionDataCollectionContext.SessionId, testCaseEndEventArgs.TestElement); testCaseEndEventArgs.Context = context; SendEvent(testCaseEndEventArgs); - List result = null; + List? result = null; try { result = _attachmentManager.GetAttachments(testCaseEndEventArgs.Context); @@ -335,7 +338,8 @@ public Collection TestCaseEnded(TestCaseEndEventArgs testCaseEndE catch (Exception ex) { EqtTrace.Error("DataCollectionManager.TestCaseEnded: Failed to get attachments: {0}", ex); - return new Collection(result); + // TODO: It's possible we throw ArgumentNullException from catch, is it expected? + return new Collection(result!); } if (EqtTrace.IsVerboseEnabled) @@ -387,10 +391,10 @@ private void CleanupPlugins() /// The friendly Name. /// The data collector Uri. /// - protected virtual bool TryGetUriFromFriendlyName(string friendlyName, out string dataCollectorUri) + protected virtual bool TryGetUriFromFriendlyName(string friendlyName, out string? dataCollectorUri) { - var extensionManager = _dataCollectorExtensionManager; - foreach (var extension in extensionManager.TestExtensions) + TPDebug.Assert(_dataCollectorExtensionManager is not null, "_dataCollectorExtensionManager is null"); + foreach (var extension in _dataCollectorExtensionManager.TestExtensions) { if (string.Equals(friendlyName, extension.Metadata.FriendlyName, StringComparison.OrdinalIgnoreCase)) { @@ -412,29 +416,29 @@ protected virtual bool TryGetUriFromFriendlyName(string friendlyName, out string /// /// The . /// - protected virtual DataCollectorConfig TryGetDataCollectorConfig(string extensionUri) + protected virtual DataCollectorConfig? TryGetDataCollectorConfig(string extensionUri) { - var extensionManager = _dataCollectorExtensionManager; - foreach (var extension in extensionManager.TestExtensions) + TPDebug.Assert(_dataCollectorExtensionManager is not null, "_dataCollectorExtensionManager is null"); + foreach (var extension in _dataCollectorExtensionManager.TestExtensions) { - if (string.Equals(extension.TestPluginInfo.IdentifierData, extensionUri, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(extension.TestPluginInfo?.IdentifierData, extensionUri, StringComparison.OrdinalIgnoreCase)) { - return (DataCollectorConfig)extension.TestPluginInfo; + return (DataCollectorConfig)extension.TestPluginInfo!; } } return null; } - protected virtual bool IsUriValid(string uri) + protected virtual bool IsUriValid(string? uri) { if (uri.IsNullOrEmpty()) { return false; } - var extensionManager = _dataCollectorExtensionManager; - foreach (var extension in extensionManager.TestExtensions) + TPDebug.Assert(_dataCollectorExtensionManager is not null, "_dataCollectorExtensionManager is null"); + foreach (var extension in _dataCollectorExtensionManager.TestExtensions) { if (string.Equals(uri, extension.Metadata.ExtensionUri, StringComparison.OrdinalIgnoreCase)) { @@ -455,7 +459,9 @@ protected virtual bool IsUriValid(string uri) /// protected virtual ObjectModel.DataCollection.DataCollector TryGetTestExtension(string extensionUri) { - return DataCollectorExtensionManager.TryGetTestExtension(extensionUri).Value; + var extension = DataCollectorExtensionManager.TryGetTestExtension(extensionUri); + TPDebug.Assert(extension is not null, "extension is null"); + return extension.Value; } /// @@ -468,7 +474,7 @@ protected virtual ObjectModel.DataCollection.DataCollector TryGetTestExtension(s private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, string settingsXml) { DataCollectorInformation dataCollectorInfo; - DataCollectorConfig dataCollectorConfig; + DataCollectorConfig? dataCollectorConfig; try { @@ -481,7 +487,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.UnableToFetchUriString, dataCollectorSettings.FriendlyName)); } - ObjectModel.DataCollection.DataCollector dataCollector = null; + ObjectModel.DataCollection.DataCollector? dataCollector = null; if (!dataCollectorUri.IsNullOrWhiteSpace()) { dataCollector = TryGetTestExtension(dataCollectorUri); @@ -499,7 +505,9 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri return; } - dataCollectorConfig = TryGetDataCollectorConfig(dataCollectorUri); + dataCollectorConfig = TryGetDataCollectorConfig(dataCollectorUri!); + TPDebug.Assert(dataCollectorConfig is not null, "dataCollectorConfig is null"); + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); // Attempt to get the data collector information verifying that all of the required metadata for the collector is available. dataCollectorInfo = new DataCollectorInformation( @@ -524,6 +532,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri try { dataCollectorInfo.InitializeDataCollector(); + TPDebug.Assert(dataCollectorConfig is not null, "dataCollectorConfig is null"); lock (RunDataCollectors) { // Add data collectors to run cache. @@ -535,6 +544,8 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri EqtTrace.Error("DataCollectionManager.LoadAndInitialize: exception while initializing data collector {0} : {1}", dataCollectorSettings.FriendlyName, ex); // Log error. + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); + TPDebug.Assert(dataCollectorConfig is not null, "dataCollectorConfig is null"); dataCollectorInfo.Logger.LogError(_dataCollectionEnvironmentContext.SessionDataCollectionContext, string.Format(CultureInfo.CurrentCulture, Resources.Resources.DataCollectorInitializationError, dataCollectorConfig.FriendlyName, ex)); // Dispose datacollector. @@ -630,6 +641,7 @@ private Dictionary GetEnvironmentVari var friendlyName = dataCollectorInfo.DataCollectorConfig.FriendlyName; failedCollectors.Add(dataCollectorInfo); + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); dataCollectorInfo.Logger.LogError( _dataCollectionEnvironmentContext.SessionDataCollectionContext, string.Format(CultureInfo.CurrentCulture, Resources.Resources.DataCollectorErrorOnGetVariable, friendlyName, ex)); @@ -656,54 +668,57 @@ private void AddCollectorEnvironmentVariables( DataCollectorInformation dataCollectionWrapper, Dictionary dataCollectorEnvironmentVariables) { - if (dataCollectionWrapper.TestExecutionEnvironmentVariables != null) + if (dataCollectionWrapper.TestExecutionEnvironmentVariables == null) + { + return; + } + + var collectorFriendlyName = dataCollectionWrapper.DataCollectorConfig.FriendlyName; + foreach (var namevaluepair in dataCollectionWrapper.TestExecutionEnvironmentVariables) { - var collectorFriendlyName = dataCollectionWrapper.DataCollectorConfig.FriendlyName; - foreach (var namevaluepair in dataCollectionWrapper.TestExecutionEnvironmentVariables) + if (dataCollectorEnvironmentVariables.TryGetValue(namevaluepair.Key, out var alreadyRequestedVariable)) { - if (dataCollectorEnvironmentVariables.TryGetValue(namevaluepair.Key, out var alreadyRequestedVariable)) + // Dev10 behavior is to consider environment variables values as case sensitive. + if (string.Equals(namevaluepair.Value, alreadyRequestedVariable.Value, StringComparison.Ordinal)) { - // Dev10 behavior is to consider environment variables values as case sensitive. - if (string.Equals(namevaluepair.Value, alreadyRequestedVariable.Value, StringComparison.Ordinal)) + alreadyRequestedVariable.AddRequestingDataCollector(collectorFriendlyName); + } + else + { + // Data collector is overriding an already requested variable, possibly an error. + var message = string.Format( + CultureInfo.CurrentUICulture, + Resources.Resources.DataCollectorRequestedDuplicateEnvironmentVariable, + collectorFriendlyName, + namevaluepair.Key, + namevaluepair.Value, + alreadyRequestedVariable.FirstDataCollectorThatRequested, + alreadyRequestedVariable.Value); + + if (collectorFriendlyName.Equals(CodeCoverageFriendlyName, StringComparison.OrdinalIgnoreCase)) { - alreadyRequestedVariable.AddRequestingDataCollector(collectorFriendlyName); + // Do not treat this as error for Code Coverage Data Collector. This is expected in some Fakes integration scenarios + EqtTrace.Info(message); } else { - // Data collector is overriding an already requested variable, possibly an error. - var message = string.Format( - CultureInfo.CurrentUICulture, - Resources.Resources.DataCollectorRequestedDuplicateEnvironmentVariable, - collectorFriendlyName, - namevaluepair.Key, - namevaluepair.Value, - alreadyRequestedVariable.FirstDataCollectorThatRequested, - alreadyRequestedVariable.Value); - - if (collectorFriendlyName.Equals(CodeCoverageFriendlyName, StringComparison.OrdinalIgnoreCase)) - { - // Do not treat this as error for Code Coverage Data Collector. This is expected in some Fakes integration scenarios - EqtTrace.Info(message); - } - else - { - dataCollectionWrapper.Logger.LogError(_dataCollectionEnvironmentContext.SessionDataCollectionContext, message); - } + TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); + dataCollectionWrapper.Logger.LogError(_dataCollectionEnvironmentContext.SessionDataCollectionContext, message); } - - _dataCollectionTelemetryManager.RecordEnvironmentVariableConflict(dataCollectionWrapper, namevaluepair.Key, namevaluepair.Value, alreadyRequestedVariable.Value); } - else - { - // new variable, add to the list. - EqtTrace.Verbose("DataCollectionManager.AddCollectionEnvironmentVariables: Adding Environment variable '{0}' value '{1}'", namevaluepair.Key, namevaluepair.Value); - dataCollectorEnvironmentVariables.Add( - namevaluepair.Key, - new DataCollectionEnvironmentVariable(namevaluepair, collectorFriendlyName)); + _dataCollectionTelemetryManager.RecordEnvironmentVariableConflict(dataCollectionWrapper, namevaluepair.Key, namevaluepair.Value, alreadyRequestedVariable.Value); + } + else + { + // new variable, add to the list. + EqtTrace.Verbose("DataCollectionManager.AddCollectionEnvironmentVariables: Adding Environment variable '{0}' value '{1}'", namevaluepair.Key, namevaluepair.Value); - _dataCollectionTelemetryManager.RecordEnvironmentVariableAddition(dataCollectionWrapper, namevaluepair.Key, namevaluepair.Value); - } + dataCollectorEnvironmentVariables.Add( + namevaluepair.Key, + new DataCollectionEnvironmentVariable(namevaluepair, collectorFriendlyName)); + + _dataCollectionTelemetryManager.RecordEnvironmentVariableAddition(dataCollectionWrapper, namevaluepair.Key, namevaluepair.Value); } } } @@ -736,7 +751,7 @@ private void RemoveDataCollectors(IReadOnlyCollection } } - private void LogAttachments(List attachmentSets) + private static void LogAttachments(List attachmentSets) { if (attachmentSets is null) { diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs index aa78b337e2..3d30a542ca 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.Telemetry; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorConfig.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorConfig.cs index 84077f830e..c0a46e7423 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorConfig.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorConfig.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// @@ -41,7 +39,7 @@ public DataCollectorConfig(Type type) /// /// Gets the type uri. /// - public Uri TypeUri { get; private set; } + public Uri? TypeUri { get; private set; } /// /// Gets the friendly name. @@ -49,7 +47,7 @@ public DataCollectorConfig(Type type) public string FriendlyName { get; private set; } /// - public override string IdentifierData + public override string? IdentifierData { get { @@ -58,18 +56,18 @@ public override string IdentifierData } /// - public override ICollection Metadata + public override ICollection Metadata { get { - return new object[] { TypeUri.ToString(), FriendlyName, AttachmentsProcessorType != null }; + return new object?[] { TypeUri?.ToString(), FriendlyName, AttachmentsProcessorType != null }; } } /// /// Gets attachments processor /// - public Type AttachmentsProcessorType { get; private set; } + public Type? AttachmentsProcessorType { get; private set; } /// /// Check if collector registers an attachment processor. @@ -82,20 +80,19 @@ public override ICollection Metadata /// /// The data collector to get the Type URI for. /// Type Uri of the data collector. - private static Uri GetTypeUri(Type dataCollectorType) + private static Uri? GetTypeUri(Type dataCollectorType) { - Uri typeUri = null; var typeUriAttributes = GetAttributes(dataCollectorType, typeof(DataCollectorTypeUriAttribute)); - if (typeUriAttributes != null && typeUriAttributes.Length > 0) + if (typeUriAttributes.Length > 0) { var typeUriAttribute = (DataCollectorTypeUriAttribute)typeUriAttributes[0]; if (!typeUriAttribute.TypeUri.IsNullOrWhiteSpace()) { - typeUri = new Uri(typeUriAttribute.TypeUri); + return new Uri(typeUriAttribute.TypeUri); } } - return typeUri; + return null; } /// @@ -103,20 +100,19 @@ private static Uri GetTypeUri(Type dataCollectorType) /// /// The data collector to get the attachment processor for. /// Type of the attachment processor. - private static Type GetAttachmentsProcessors(Type dataCollectorType) + private static Type? GetAttachmentsProcessors(Type dataCollectorType) { - Type attachmentsProcessor = null; - var attachmenstProcessors = GetAttributes(dataCollectorType, typeof(DataCollectorAttachmentProcessorAttribute)); - if (attachmenstProcessors != null && attachmenstProcessors.Length > 0) + var attachmentsProcessor = GetAttributes(dataCollectorType, typeof(DataCollectorAttachmentProcessorAttribute)); + if (attachmentsProcessor.Length > 0) { - var attachmenstProcessorsAttribute = (DataCollectorAttachmentProcessorAttribute)attachmenstProcessors[0]; + var attachmenstProcessorsAttribute = (DataCollectorAttachmentProcessorAttribute)attachmentsProcessor[0]; if (attachmenstProcessorsAttribute.Type != null) { - attachmentsProcessor = attachmenstProcessorsAttribute.Type; + return attachmenstProcessorsAttribute.Type; } } - return attachmentsProcessor; + return null; } /// @@ -126,8 +122,6 @@ private static Type GetAttachmentsProcessors(Type dataCollectorType) /// Friendly name of the data collector. private static string GetFriendlyName(Type dataCollectorType) { - string friendlyName = string.Empty; - // Get the friendly name from the attribute. var friendlyNameAttributes = GetAttributes(dataCollectorType, typeof(DataCollectorFriendlyNameAttribute)); if (friendlyNameAttributes != null && friendlyNameAttributes.Length > 0) @@ -135,11 +129,11 @@ private static string GetFriendlyName(Type dataCollectorType) var friendlyNameAttribute = (DataCollectorFriendlyNameAttribute)friendlyNameAttributes[0]; if (!friendlyNameAttribute.FriendlyName.IsNullOrEmpty()) { - friendlyName = friendlyNameAttribute.FriendlyName; + return friendlyNameAttribute.FriendlyName; } } - return friendlyName; + return string.Empty; } /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorInformation.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorInformation.cs index 618451acee..b1a185e41a 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorInformation.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectorInformation.cs @@ -11,8 +11,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// @@ -45,7 +43,7 @@ internal class DataCollectorInformation /// The message Sink. /// /// - internal DataCollectorInformation(ObjectModel.DataCollection.DataCollector dataCollector, XmlElement configurationElement, DataCollectorConfig dataCollectorConfig, DataCollectionEnvironmentContext environmentContext, IDataCollectionAttachmentManager attachmentManager, TestPlatformDataCollectionEvents events, IMessageSink messageSink, string settingsXml) + internal DataCollectorInformation(ObjectModel.DataCollection.DataCollector dataCollector, XmlElement? configurationElement, DataCollectorConfig dataCollectorConfig, DataCollectionEnvironmentContext? environmentContext, IDataCollectionAttachmentManager attachmentManager, TestPlatformDataCollectionEvents events, IMessageSink messageSink, string settingsXml) { DataCollector = dataCollector; ConfigurationElement = configurationElement; @@ -65,7 +63,7 @@ internal DataCollectorInformation(ObjectModel.DataCollection.DataCollector dataC /// /// Gets or sets the configuration element. /// - public XmlElement ConfigurationElement { get; set; } + public XmlElement? ConfigurationElement { get; set; } /// /// Gets or sets the data collector config. @@ -85,7 +83,7 @@ internal DataCollectorInformation(ObjectModel.DataCollection.DataCollector dataC /// /// Gets the data collection environment context. /// - public DataCollectionEnvironmentContext EnvironmentContext { get; private set; } + public DataCollectionEnvironmentContext? EnvironmentContext { get; private set; } /// /// Gets the data collection logger @@ -103,7 +101,7 @@ internal DataCollectorInformation(ObjectModel.DataCollection.DataCollector dataC /// Gets or sets environment variables supplied by the data collector. /// These are available after the collector has been initialized. /// - public IEnumerable> TestExecutionEnvironmentVariables + public IEnumerable>? TestExecutionEnvironmentVariables { get; set; @@ -134,7 +132,7 @@ private void UpdateConfigurationElement() doc.Load(xmlReader); } - ConfigurationElement = doc.DocumentElement; + ConfigurationElement = doc.DocumentElement!; } // Add Framework config, since it could be required by DataCollector, to determine whether they support this Framework or not diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionAttachmentManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionAttachmentManager.cs index 719032539a..adda6c450e 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionAttachmentManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionAttachmentManager.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector.Interfaces; /// @@ -57,7 +55,7 @@ internal interface IDataCollectionAttachmentManager /// /// The friendly Name. /// - void AddAttachment(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler sendFileCompletedCallback, Uri dataCollectorUri, string friendlyName); + void AddAttachment(FileTransferInformation fileTransferInfo, AsyncCompletedEventHandler? sendFileCompletedCallback, Uri dataCollectorUri, string friendlyName); /// /// Stops processing further transfer requests as test run is canceled. diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs index 1bc1c364fa..64dbdfef6a 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionTelemetryManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionTelemetryManager.cs index 21e2efcb2c..5741e97e6b 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionTelemetryManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionTelemetryManager.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IMessageSink.cs b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IMessageSink.cs index 97fc194e64..1835a48795 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IMessageSink.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IMessageSink.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs index 79cea94824..86f5ee0438 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; using Microsoft.VisualStudio.TestPlatform.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// @@ -49,27 +47,27 @@ internal TestPlatformDataCollectionEvents() /// /// Raised when test host process has initialized /// - public override event EventHandler TestHostLaunched; + public override event EventHandler? TestHostLaunched; /// /// Raised when a session is starting /// - public override event EventHandler SessionStart; + public override event EventHandler? SessionStart; /// /// Raised when a session is ending /// - public override event EventHandler SessionEnd; + public override event EventHandler? SessionEnd; /// /// Raised when a test case is starting /// - public override event EventHandler TestCaseStart; + public override event EventHandler? TestCaseStart; /// /// Raised when a test case is ending /// - public override event EventHandler TestCaseEnd; + public override event EventHandler? TestCaseEnd; /// /// Raises the event corresponding to the event arguments to all registered handlers @@ -100,7 +98,7 @@ internal bool AreTestCaseEventsSubscribed() return (HasEventListener(TestCaseStart, valueOnFailure) || HasEventListener(TestCaseEnd, valueOnFailure)); } - private bool HasEventListener(MulticastDelegate eventToCheck, bool valueOnFailure) + private static bool HasEventListener(MulticastDelegate? eventToCheck, bool valueOnFailure) { try { diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionLogger.cs b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionLogger.cs index 6901630046..549aeec494 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionLogger.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionLogger.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionSink.cs b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionSink.cs index 5bfcc1cc49..49b19cdfb8 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionSink.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionSink.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector; /// @@ -36,7 +34,7 @@ internal TestPlatformDataCollectionSink(IDataCollectionAttachmentManager attachm /// /// Event handler for handling file transfer completed event. /// - public override event AsyncCompletedEventHandler SendFileCompleted; + public override event AsyncCompletedEventHandler? SendFileCompleted; /// /// Gets or sets message sink to transfer collection message. @@ -61,6 +59,7 @@ private DataCollectorConfig DataCollectorConfig public override void SendFileAsync(FileTransferInformation fileTransferInformation) { ValidateArg.NotNull(fileTransferInformation, nameof(fileTransferInformation)); + TPDebug.Assert(DataCollectorConfig.TypeUri is not null, "DataCollectorConfig.TypeUri is null"); AttachmentManager.AddAttachment(fileTransferInformation, SendFileCompleted, DataCollectorConfig.TypeUri, DataCollectorConfig.FriendlyName); } } diff --git a/src/Microsoft.TestPlatform.Common/Exceptions/InvalidLoggerException.cs b/src/Microsoft.TestPlatform.Common/Exceptions/InvalidLoggerException.cs index 07e00f58d2..2026abba6c 100644 --- a/src/Microsoft.TestPlatform.Common/Exceptions/InvalidLoggerException.cs +++ b/src/Microsoft.TestPlatform.Common/Exceptions/InvalidLoggerException.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Exceptions; public class InvalidLoggerException : TestPlatformException @@ -15,7 +13,7 @@ public class InvalidLoggerException : TestPlatformException /// Initializes with the message. /// /// Message for the exception. - public InvalidLoggerException(string message) + public InvalidLoggerException(string? message) : base(message) { } @@ -25,7 +23,7 @@ public InvalidLoggerException(string message) /// /// Message for the exception. /// The inner exception. - public InvalidLoggerException(string message, Exception innerException) + public InvalidLoggerException(string? message, Exception? innerException) : base(message, innerException) { } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/DataCollectionExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/DataCollectionExtensionManager.cs index e21ba15e92..2d3485ecc0 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/DataCollectionExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/DataCollectionExtensionManager.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.Interfaces; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestDiscoveryExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestDiscoveryExtensionManager.cs index af43a42e96..83ce5331b0 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestDiscoveryExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestDiscoveryExtensionManager.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// @@ -19,7 +17,7 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// internal class TestDiscoveryExtensionManager { - private static TestDiscoveryExtensionManager s_testDiscoveryExtensionManager; + private static TestDiscoveryExtensionManager? s_testDiscoveryExtensionManager; /// /// Default constructor. @@ -143,7 +141,7 @@ internal class TestDiscovererMetadata : ITestDiscovererCapabilities /// /// The file Extensions. /// The default Executor Uri. - public TestDiscovererMetadata(IReadOnlyCollection fileExtensions, string defaultExecutorUri, AssemblyType assemblyType = default) + public TestDiscovererMetadata(IReadOnlyCollection? fileExtensions, string? defaultExecutorUri, AssemblyType assemblyType = default) { if (fileExtensions != null && fileExtensions.Count > 0) { @@ -161,7 +159,7 @@ public TestDiscovererMetadata(IReadOnlyCollection fileExtensions, string /// /// Gets file extensions supported by the discoverer. /// - public IEnumerable FileExtension + public IEnumerable? FileExtension { get; private set; @@ -170,7 +168,7 @@ public IEnumerable FileExtension /// /// Gets the default executor Uri for this discoverer /// - public Uri DefaultExecutorUri + public Uri? DefaultExecutorUri { get; private set; diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExecutorExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExecutorExtensionManager.cs index 950b114a69..1e3c228254 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExecutorExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExecutorExtensionManager.cs @@ -12,8 +12,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// @@ -21,7 +19,7 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// internal class TestExecutorExtensionManager : TestExtensionManager { - private static TestExecutorExtensionManager s_testExecutorExtensionManager; + private static TestExecutorExtensionManager? s_testExecutorExtensionManager; private static readonly object Synclock = new(); /// @@ -45,14 +43,14 @@ protected TestExecutorExtensionManager( /// /// Merges two test extension lists. /// - /// + /// /// Type of first test extension. /// Type of second test extension. /// Type of the value used in the lazy extension expression. - /// + /// /// First test extension list. /// Second test extension list. - /// + /// /// A merged list of test extensions. private static IEnumerable> MergeTestExtensionLists( IEnumerable> testExtensions1, @@ -69,18 +67,20 @@ private static IEnumerable> MergeTestExtension // Create the cache used for merging by adding all extensions from the first list. foreach (var testExtension in testExtensions1) { - cache.Add(testExtension.TestPluginInfo.IdentifierData, testExtension); + if (testExtension.TestPluginInfo?.IdentifierData is not null) + { + cache.Add(testExtension.TestPluginInfo.IdentifierData, testExtension); + } } // Update the cache with extensions from the second list. Should there be any conflict // we prefer the second extension to the first. foreach (var testExtension in testExtensions2) { - if (cache.ContainsKey(testExtension.TestPluginInfo.IdentifierData)) + if (testExtension.TestPluginInfo?.IdentifierData is not null + && cache.ContainsKey(testExtension.TestPluginInfo.IdentifierData)) { - cache[testExtension.TestPluginInfo.IdentifierData] = - new LazyExtension( - (TExecutor1)testExtension.Value, testExtension.Metadata); + cache[testExtension.TestPluginInfo.IdentifierData] = new(testExtension.Value, testExtension.Metadata); } } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs index 54fbd2f8b4..66a1314448 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; @@ -12,8 +13,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// @@ -97,7 +96,7 @@ public Dictionary> TestExtensionByUri /// /// The URI of the test extension to be looked up. /// The test extension or null if one was not found. - public LazyExtension TryGetTestExtension(Uri extensionUri) + public LazyExtension? TryGetTestExtension(Uri extensionUri) { ValidateArg.NotNull(extensionUri, nameof(extensionUri)); TestExtensionByUri.TryGetValue(extensionUri, out var testExtension); @@ -110,10 +109,10 @@ public LazyExtension TryGetTestExtension(Uri extensionUri /// /// The URI of the test extension to be looked up. /// The test extension or null if one was not found. - public LazyExtension TryGetTestExtension(string extensionUri) + public LazyExtension? TryGetTestExtension(string extensionUri) { ValidateArg.NotNull(extensionUri, nameof(extensionUri)); - LazyExtension testExtension = null; + LazyExtension? testExtension = null; foreach (var availableExtensionUri in TestExtensionByUri.Keys) { if (string.Equals(extensionUri, availableExtensionUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase)) @@ -129,6 +128,7 @@ public LazyExtension TryGetTestExtension(string extension /// /// Populate the extension map. /// + [MemberNotNull(nameof(TestExtensionByUri))] private void PopulateMap() { TestExtensionByUri = new Dictionary>(); @@ -141,7 +141,7 @@ private void PopulateMap() foreach (var extension in TestExtensions) { // Convert the extension uri string to an actual uri. - Uri uri = null; + Uri? uri = null; try { uri = new Uri(extension.Metadata.ExtensionUri); @@ -156,22 +156,21 @@ private void PopulateMap() } } - if (uri != null) + if (uri == null) { - // Make sure we are not trying to add an extension with a duplicate uri. - if (!TestExtensionByUri.ContainsKey(uri)) - { - TestExtensionByUri.Add(uri, extension); - } - else - { - if (_logger != null) - { - _logger.SendMessage( - TestMessageLevel.Warning, - string.Format(CultureInfo.CurrentUICulture, CommonResources.DuplicateExtensionUri, extension.Metadata.ExtensionUri)); - } - } + continue; + } + + // Make sure we are not trying to add an extension with a duplicate uri. + if (!TestExtensionByUri.ContainsKey(uri)) + { + TestExtensionByUri.Add(uri, extension); + } + else if (_logger != null) + { + _logger.SendMessage( + TestMessageLevel.Warning, + string.Format(CultureInfo.CurrentUICulture, CommonResources.DuplicateExtensionUri, extension.Metadata.ExtensionUri)); } } } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestLoggerExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestLoggerExtensionManager.cs index e82dda5bf5..74cbb751e1 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestLoggerExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestLoggerExtensionManager.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginCache.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginCache.cs index b10a127687..e3cdf5ea07 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginCache.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginCache.cs @@ -7,6 +7,7 @@ #endif using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -18,8 +19,6 @@ using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// @@ -28,7 +27,7 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// Making this a singleton to offer better unit testing. public class TestPluginCache { - private readonly Dictionary _resolvedAssemblies; + private readonly Dictionary _resolvedAssemblies = new(); private List _filterableExtensionPaths; private List _unfilterableExtensionPaths; @@ -36,14 +35,14 @@ public class TestPluginCache /// /// Assembly resolver used to resolve the additional extensions /// - private AssemblyResolver _assemblyResolver; + private AssemblyResolver? _assemblyResolver; /// /// Lock for extensions update /// private readonly object _lockForExtensionsUpdate; - private static TestPluginCache s_instance; + private static TestPluginCache? s_instance; private readonly List _defaultExtensionPaths = new(); @@ -52,13 +51,13 @@ public class TestPluginCache /// protected TestPluginCache() { - _resolvedAssemblies = new Dictionary(); _filterableExtensionPaths = new List(); _unfilterableExtensionPaths = new List(); _lockForExtensionsUpdate = new object(); TestExtensions = null; } + [AllowNull] public static TestPluginCache Instance { get @@ -76,7 +75,7 @@ internal set /// Gets the test extensions discovered by the cache until now. /// /// Returns null if discovery of extensions is not done. - internal TestExtensions TestExtensions { get; private set; } + internal TestExtensions? TestExtensions { get; private set; } /// /// Gets a list of all extension paths filtered by input string. @@ -117,7 +116,7 @@ public List GetExtensionPaths(string endsWithPattern, bool skipDefaultEx /// /// The . of test plugin info. /// - public Dictionary DiscoverTestExtensions( + public Dictionary? DiscoverTestExtensions( string endsWithPattern) where TPluginInfo : TestPluginInformation { @@ -128,7 +127,7 @@ public Dictionary DiscoverTestExtensions(); } - Dictionary pluginInfos = null; + Dictionary? pluginInfos = null; SetupAssemblyResolver(null); // Some times TestPlatform.core.dll assembly fails to load in the current appdomain (from devenv.exe). @@ -210,7 +209,7 @@ public Dictionary DiscoverTestExtensions /// List of extension paths /// Skip extension name filtering (if true) - public void UpdateExtensions(IEnumerable additionalExtensionsPath, bool skipExtensionFilters) + public void UpdateExtensions(IEnumerable? additionalExtensionsPath, bool skipExtensionFilters) { lock (_lockForExtensionsUpdate) { @@ -273,7 +272,7 @@ public void ClearExtensions() /// public void AddResolverSearchDirectories(string[] directories) { - _assemblyResolver.AddSearchDirectories(directories); + _assemblyResolver?.AddSearchDirectories(directories); } internal IEnumerable DefaultExtensionPaths @@ -352,10 +351,10 @@ internal IList GetResolutionPaths(string extensionAssembly) { var resolutionPaths = new List(); - var extensionDirectory = Path.GetDirectoryName(Path.GetFullPath(extensionAssembly)); + var extensionDirectory = Path.GetDirectoryName(Path.GetFullPath(extensionAssembly))!; resolutionPaths.Add(extensionDirectory); - var currentDirectory = Path.GetDirectoryName(typeof(TestPluginCache).GetTypeInfo().Assembly.GetAssemblyLocation()); + var currentDirectory = Path.GetDirectoryName(typeof(TestPluginCache).GetTypeInfo().Assembly.GetAssemblyLocation())!; if (!resolutionPaths.Contains(currentDirectory)) { resolutionPaths.Add(currentDirectory); @@ -373,14 +372,14 @@ internal IList GetDefaultResolutionPaths() var resolutionPaths = new List(); // Add the extension directories for assembly resolution - var extensionDirectories = GetExtensionPaths(string.Empty).Select(e => Path.GetDirectoryName(Path.GetFullPath(e))).Distinct().ToList(); + var extensionDirectories = GetExtensionPaths(string.Empty).Select(e => Path.GetDirectoryName(Path.GetFullPath(e))!).Distinct().ToList(); if (extensionDirectories.Any()) { resolutionPaths.AddRange(extensionDirectories); } // Keep current directory for resolution - var currentDirectory = Path.GetDirectoryName(typeof(TestPluginCache).GetTypeInfo().Assembly.GetAssemblyLocation()); + var currentDirectory = Path.GetDirectoryName(typeof(TestPluginCache).GetTypeInfo().Assembly.GetAssemblyLocation())!; if (!resolutionPaths.Contains(currentDirectory)) { resolutionPaths.Add(currentDirectory); @@ -467,9 +466,11 @@ private Dictionary GetTestExtensions(extensionPaths); } - protected void SetupAssemblyResolver(string extensionAssembly) + protected void SetupAssemblyResolver(string? extensionAssembly) { - IList resolutionPaths = extensionAssembly.IsNullOrEmpty() ? GetDefaultResolutionPaths() : GetResolutionPaths(extensionAssembly); + IList resolutionPaths = extensionAssembly.IsNullOrEmpty() + ? GetDefaultResolutionPaths() + : GetResolutionPaths(extensionAssembly); // Add assembly resolver which can resolve the extensions from the specified directory. if (_assemblyResolver == null) @@ -482,11 +483,13 @@ protected void SetupAssemblyResolver(string extensionAssembly) } } - private Assembly CurrentDomainAssemblyResolve(object sender, AssemblyResolveEventArgs args) + private Assembly? CurrentDomainAssemblyResolve(object? sender, AssemblyResolveEventArgs? args) { - var assemblyName = new AssemblyName(args.Name); + // TODO: Avoid ArgumentNullException + var assemblyName = new AssemblyName(args?.Name!); + TPDebug.Assert(args?.Name is not null); - Assembly assembly = null; + Assembly? assembly = null; lock (_resolvedAssemblies) { try @@ -524,29 +527,33 @@ private Assembly CurrentDomainAssemblyResolve(object sender, AssemblyResolveEven /// private void LogExtensions() { - if (EqtTrace.IsVerboseEnabled) + if (!EqtTrace.IsVerboseEnabled) { - var discoverers = TestExtensions.TestDiscoverers != null ? string.Join(",", TestExtensions.TestDiscoverers.Keys.ToArray()) : null; - EqtTrace.Verbose("TestPluginCache: Discoverers are '{0}'.", discoverers); + return; + } - var executors = TestExtensions.TestExecutors != null ? string.Join(",", TestExtensions.TestExecutors.Keys.ToArray()) : null; - EqtTrace.Verbose("TestPluginCache: Executors are '{0}'.", executors); + TPDebug.Assert(TestExtensions is not null, "TestExtensions is null"); - var executors2 = TestExtensions.TestExecutors2 != null ? string.Join(",", TestExtensions.TestExecutors2.Keys.ToArray()) : null; - EqtTrace.Verbose("TestPluginCache: Executors2 are '{0}'.", executors2); + var discoverers = TestExtensions.TestDiscoverers != null ? string.Join(",", TestExtensions.TestDiscoverers.Keys.ToArray()) : null; + EqtTrace.Verbose("TestPluginCache: Discoverers are '{0}'.", discoverers); - var settingsProviders = TestExtensions.TestSettingsProviders != null ? string.Join(",", TestExtensions.TestSettingsProviders.Keys.ToArray()) : null; - EqtTrace.Verbose("TestPluginCache: Setting providers are '{0}'.", settingsProviders); + var executors = TestExtensions.TestExecutors != null ? string.Join(",", TestExtensions.TestExecutors.Keys.ToArray()) : null; + EqtTrace.Verbose("TestPluginCache: Executors are '{0}'.", executors); - var loggers = TestExtensions.TestLoggers != null ? string.Join(",", TestExtensions.TestLoggers.Keys.ToArray()) : null; - EqtTrace.Verbose("TestPluginCache: Loggers are '{0}'.", loggers); + var executors2 = TestExtensions.TestExecutors2 != null ? string.Join(",", TestExtensions.TestExecutors2.Keys.ToArray()) : null; + EqtTrace.Verbose("TestPluginCache: Executors2 are '{0}'.", executors2); - var testhosts = TestExtensions.TestHosts != null ? string.Join(",", TestExtensions.TestHosts.Keys.ToArray()) : null; - EqtTrace.Verbose("TestPluginCache: TestHosts are '{0}'.", testhosts); + var settingsProviders = TestExtensions.TestSettingsProviders != null ? string.Join(",", TestExtensions.TestSettingsProviders.Keys.ToArray()) : null; + EqtTrace.Verbose("TestPluginCache: Setting providers are '{0}'.", settingsProviders); - var dataCollectors = TestExtensions.DataCollectors != null ? string.Join(",", TestExtensions.DataCollectors.Keys.ToArray()) : null; - EqtTrace.Verbose("TestPluginCache: DataCollectors are '{0}'.", dataCollectors); - } + var loggers = TestExtensions.TestLoggers != null ? string.Join(",", TestExtensions.TestLoggers.Keys.ToArray()) : null; + EqtTrace.Verbose("TestPluginCache: Loggers are '{0}'.", loggers); + + var testhosts = TestExtensions.TestHosts != null ? string.Join(",", TestExtensions.TestHosts.Keys.ToArray()) : null; + EqtTrace.Verbose("TestPluginCache: TestHosts are '{0}'.", testhosts); + + var dataCollectors = TestExtensions.DataCollectors != null ? string.Join(",", TestExtensions.DataCollectors.Keys.ToArray()) : null; + EqtTrace.Verbose("TestPluginCache: DataCollectors are '{0}'.", dataCollectors); } } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs index be8570af1a..37864fdf52 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs @@ -16,8 +16,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// @@ -77,7 +75,7 @@ public Dictionary GetTestExtensionsInformation extensionPaths) + private static void AddKnownExtensions(ref IEnumerable extensionPaths) { // For C++ UWP adapter, & OLD C# UWP(MSTest V1) adapter // In UWP .Net Native Compilation mode managed dll's are packaged differently, & File.Exists() fails. @@ -116,7 +114,7 @@ private void GetTestExtensionsFromFiles( } try { - Assembly assembly = null; + Assembly? assembly = null; var assemblyName = Path.GetFileNameWithoutExtension(file); assembly = Assembly.Load(new AssemblyName(assemblyName)); if (assembly != null) @@ -190,7 +188,7 @@ private void GetTestExtensionsFromAssembly(Assembly ass if (e.Types?.Length > 0) { // Unloaded types on e.Types are null, make sure we skip them. - types.AddRange(e.Types.Where(type => type != null && type.GetTypeInfo().IsClass && !type.GetTypeInfo().IsAbstract)); + types.AddRange(e.Types.Where(type => type != null && type.GetTypeInfo().IsClass && !type.GetTypeInfo().IsAbstract)!); } if (e.LoaderExceptions != null) @@ -226,38 +224,41 @@ private void GetTestExtensionsFromAssembly(Assembly ass /// /// Test extensions collection to add to. /// - private void GetTestExtensionFromType( + private static void GetTestExtensionFromType( Type type, Type extensionType, Dictionary extensionCollection, string filePath) where TPluginInfo : TestPluginInformation { - if (extensionType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + if (!extensionType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) { - var rawPluginInfo = Activator.CreateInstance(typeof(TPluginInfo), type); - var pluginInfo = (TPluginInfo)rawPluginInfo; - pluginInfo.FilePath = filePath; + return; + } - if (pluginInfo == null || pluginInfo.IdentifierData == null) - { - EqtTrace.Error( - "GetTestExtensionFromType: Either PluginInformation is null or PluginInformation doesn't contain IdentifierData for type {0}.", type.FullName); - return; - } + var rawPluginInfo = Activator.CreateInstance(typeof(TPluginInfo), type); + TPDebug.Assert(rawPluginInfo is TPluginInfo, "rawPluginInfo is not of type TPluginInfo"); + var pluginInfo = (TPluginInfo)rawPluginInfo; + pluginInfo.FilePath = filePath; - if (extensionCollection.ContainsKey(pluginInfo.IdentifierData)) - { - EqtTrace.Warning( - "GetTestExtensionFromType: Discovered multiple test extensions with identifier data '{0}' and type '{1}' inside file '{2}'; keeping the first one '{3}'.", - pluginInfo.IdentifierData, pluginInfo.AssemblyQualifiedName, filePath, extensionCollection[pluginInfo.IdentifierData].AssemblyQualifiedName); - } - else - { - extensionCollection.Add(pluginInfo.IdentifierData, pluginInfo); - EqtTrace.Info("GetTestExtensionFromType: Register extension with identifier data '{0}' and type '{1}' inside file '{2}'", - pluginInfo.IdentifierData, pluginInfo.AssemblyQualifiedName, filePath); - } + if (pluginInfo == null || pluginInfo.IdentifierData == null) + { + EqtTrace.Error( + "GetTestExtensionFromType: Either PluginInformation is null or PluginInformation doesn't contain IdentifierData for type {0}.", type.FullName); + return; + } + + if (extensionCollection.ContainsKey(pluginInfo.IdentifierData)) + { + EqtTrace.Warning( + "GetTestExtensionFromType: Discovered multiple test extensions with identifier data '{0}' and type '{1}' inside file '{2}'; keeping the first one '{3}'.", + pluginInfo.IdentifierData, pluginInfo.AssemblyQualifiedName, filePath, extensionCollection[pluginInfo.IdentifierData].AssemblyQualifiedName); + } + else + { + extensionCollection.Add(pluginInfo.IdentifierData, pluginInfo); + EqtTrace.Info("GetTestExtensionFromType: Register extension with identifier data '{0}' and type '{1}' inside file '{2}'", + pluginInfo.IdentifierData, pluginInfo.AssemblyQualifiedName, filePath); } } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginManager.cs index b835c56304..b3f0c130f8 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginManager.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// @@ -17,7 +15,7 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// internal class TestPluginManager { - private static TestPluginManager s_instance; + private static TestPluginManager? s_instance; /// /// Gets the singleton instance of TestPluginManager. @@ -30,9 +28,9 @@ public static TestPluginManager Instance /// /// Assembly qualified name of the test extension /// Data type of the test extension - public static Type GetTestExtensionType(string extensionTypeName) + public static Type? GetTestExtensionType(string extensionTypeName) { - Type extensionType; + Type? extensionType; try { extensionType = Type.GetType(extensionTypeName, true); @@ -62,9 +60,9 @@ public static T CreateTestExtension(Type extensionType) try { - object rawPlugin = Activator.CreateInstance(extensionType); + object? rawPlugin = Activator.CreateInstance(extensionType); - T testExtension = (T)rawPlugin; + T testExtension = (T)rawPlugin!; return testExtension; } catch (Exception ex) @@ -114,7 +112,8 @@ public static void GetSpecificTestExtensions> filtered) where TMetadata : IMetadata where TPluginInfo : TestPluginInformation { var extensions = TestPluginCache.Instance.DiscoverTestExtensions(endsWithPattern); - TestPluginManager.GetExtensions(extensions, out unfiltered, out filtered); + TPDebug.Assert(extensions is not null, "extensions is null"); + GetExtensions(extensions, out unfiltered, out filtered); } /// @@ -150,7 +149,7 @@ public static void GetTestExtensions(extensionAssembly, skipCache); - TestPluginManager.GetExtensions(extensions, out unfiltered, out filtered); + GetExtensions(extensions, out unfiltered, out filtered); } /// @@ -159,7 +158,8 @@ public static void GetTestExtensions Type of TestPluginIInformation. /// The dictionary containing plugin identifier data and its info. /// Collection of test plugins information - private static IEnumerable GetValuesFromDictionary(Dictionary dictionary) where T : TestPluginInformation + private static IEnumerable GetValuesFromDictionary(Dictionary dictionary) + where T : TestPluginInformation { var values = new List(); @@ -197,12 +197,14 @@ private static IEnumerable GetValuesFromDictionary(Dic private static void GetExtensions( Dictionary testPluginInfo, out IEnumerable>> unfiltered, - out IEnumerable> filtered) where TMetadata : IMetadata where TPluginInfo : TestPluginInformation + out IEnumerable> filtered) + where TMetadata : IMetadata + where TPluginInfo : TestPluginInformation { var unfilteredExtensions = new List>>(); var filteredExtensions = new List>(); - var testPlugins = TestPluginManager.GetValuesFromDictionary(testPluginInfo); + var testPlugins = GetValuesFromDictionary(testPluginInfo); foreach (var plugin in testPlugins) { if (!plugin.IdentifierData.IsNullOrEmpty()) diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/LazyExtension.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/LazyExtension.cs index 0951bedc4e..657920b9ed 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/LazyExtension.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/LazyExtension.cs @@ -4,8 +4,6 @@ using System; using System.Linq; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; /// @@ -16,10 +14,10 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilitie public class LazyExtension { private static readonly object Synclock = new(); - private TExtension _extension; - private TMetadata _metadata; - private readonly Type _metadataType; - private readonly Func _extensionCreator; + private readonly Type? _metadataType; + private readonly Func? _extensionCreator; + private TExtension? _extension; + private TMetadata? _metadata; /// /// The constructor. @@ -74,7 +72,7 @@ public LazyExtension(Func creator, TMetadata metadata) /// internal bool IsExtensionCreated { get; private set; } - internal TestPluginInformation TestPluginInfo { get; } + internal TestPluginInformation? TestPluginInfo { get; } /// /// Gets the test extension instance. @@ -95,7 +93,9 @@ public TExtension Value { if (_extension == null && TestPluginInfo != null) { + TPDebug.Assert(TestPluginInfo.AssemblyQualifiedName is not null, "TestPluginInfo.AssemblyQualifiedName is null"); var pluginType = TestPluginManager.GetTestExtensionType(TestPluginInfo.AssemblyQualifiedName); + TPDebug.Assert(pluginType is not null, "pluginType is null"); _extension = TestPluginManager.CreateTestExtension(pluginType); } } @@ -104,6 +104,7 @@ public TExtension Value IsExtensionCreated = true; } + TPDebug.Assert(_extension is not null, "_extension is null"); return _extension; } } @@ -122,12 +123,15 @@ public TMetadata Metadata if (_metadata == null && TestPluginInfo != null) { var parameters = TestPluginInfo.Metadata?.ToArray(); + TPDebug.Assert(_metadataType is not null, "_metadataType is null"); var dataObject = Activator.CreateInstance(_metadataType, parameters); + TPDebug.Assert(dataObject is not null, "dataObject is null"); _metadata = (TMetadata)dataObject; } } } + TPDebug.Assert(_metadata is not null, "_metadata is null"); return _metadata; } } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestDiscovererPluginInformation.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestDiscovererPluginInformation.cs index a143623f99..3f1c5f9ced 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestDiscovererPluginInformation.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestDiscovererPluginInformation.cs @@ -38,7 +38,7 @@ public TestDiscovererPluginInformation(Type testDiscovererType) /// /// Metadata for the test plugin /// - public override ICollection Metadata + public override ICollection Metadata { get { diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExecutorPluginInformation.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExecutorPluginInformation.cs index aadde9a29a..688bc948fa 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExecutorPluginInformation.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExecutorPluginInformation.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; /// @@ -16,7 +14,7 @@ internal class TestExecutorPluginInformation : TestExtensionPluginInformation /// Default constructor /// /// The test Executor Type. - public TestExecutorPluginInformation(Type testExecutorType) + public TestExecutorPluginInformation(Type? testExecutorType) : base(testExecutorType) { } @@ -31,7 +29,7 @@ internal class TestExecutorPluginInformation2 : TestExtensionPluginInformation /// Default constructor /// /// The test Executor Type. - public TestExecutorPluginInformation2(Type testExecutorType) + public TestExecutorPluginInformation2(Type? testExecutorType) : base(testExecutorType) { } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensionPluginInformation.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensionPluginInformation.cs index 95018f3d41..6aaa8bd8c0 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensionPluginInformation.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensionPluginInformation.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; /// @@ -21,7 +19,7 @@ internal abstract class TestExtensionPluginInformation : TestPluginInformation /// Default constructor /// /// The test Logger Type. - public TestExtensionPluginInformation(Type type) + public TestExtensionPluginInformation(Type? type) : base(type) { if (type != null) @@ -33,7 +31,7 @@ public TestExtensionPluginInformation(Type type) /// /// Gets data value identifying the test plugin /// - public override string IdentifierData + public override string? IdentifierData { get { @@ -44,18 +42,18 @@ public override string IdentifierData /// /// Metadata for the test plugin /// - public override ICollection Metadata + public override ICollection Metadata { get { - return new object[] { ExtensionUri }; + return new object?[] { ExtensionUri }; } } /// /// Gets the Uri identifying the test extension. /// - public string ExtensionUri + public string? ExtensionUri { get; private set; @@ -71,7 +69,7 @@ private static string GetExtensionUri(Type testLoggerType) string extensionUri = string.Empty; object[] attributes = testLoggerType.GetTypeInfo().GetCustomAttributes(typeof(ExtensionUriAttribute), false).ToArray(); - if (attributes != null && attributes.Length > 0) + if (attributes.Length > 0) { ExtensionUriAttribute extensionUriAttribute = (ExtensionUriAttribute)attributes[0]; diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensions.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensions.cs index f8c23c0540..efb40f74a4 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensions.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestExtensions.cs @@ -13,8 +13,6 @@ using SimpleJSON; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; /// @@ -25,7 +23,7 @@ public class TestExtensions /// /// Gets or sets test discoverer extensions. /// - internal Dictionary TestDiscoverers { get; set; } + internal Dictionary? TestDiscoverers { get; set; } /// /// Gets or sets a value indicating whether are test discoverers cached. @@ -35,7 +33,7 @@ public class TestExtensions /// /// Gets or sets test executor extensions. /// - internal Dictionary TestExecutors { get; set; } + internal Dictionary? TestExecutors { get; set; } /// /// Gets or sets a value indicating whether are test executors cached. @@ -45,7 +43,7 @@ public class TestExtensions /// /// Gets or sets test executor 2 extensions. /// - internal Dictionary TestExecutors2 { get; set; } + internal Dictionary? TestExecutors2 { get; set; } /// /// Gets or sets a value indicating whether are test executors 2 cached. @@ -55,7 +53,7 @@ public class TestExtensions /// /// Gets or sets test setting provider extensions. /// - internal Dictionary TestSettingsProviders { get; set; } + internal Dictionary? TestSettingsProviders { get; set; } /// /// Gets or sets a value indicating whether are test settings providers cached. @@ -65,7 +63,7 @@ public class TestExtensions /// /// Gets or sets test logger extensions. /// - internal Dictionary TestLoggers { get; set; } + internal Dictionary? TestLoggers { get; set; } /// /// Gets or sets a value indicating whether are test loggers cached. @@ -75,7 +73,7 @@ public class TestExtensions /// /// Gets or sets test logger extensions. /// - internal Dictionary TestHosts { get; set; } + internal Dictionary? TestHosts { get; set; } /// /// Gets or sets a value indicating whether are test hosts cached. @@ -85,7 +83,7 @@ public class TestExtensions /// /// Gets or sets data collectors extensions. /// - internal Dictionary DataCollectors { get; set; } + internal Dictionary? DataCollectors { get; set; } /// /// Gets or sets a value indicating whether are test hosts cached. @@ -95,16 +93,16 @@ public class TestExtensions /// /// Merge two extension dictionaries. /// - /// + /// /// First extension dictionary. /// Second extension dictionary. - /// + /// /// /// A dictionary representing the merger between the two input dictionaries. /// internal static Dictionary> CreateMergedDictionary( - Dictionary> first, - Dictionary> second) + Dictionary>? first, + Dictionary>? second) { var isFirstNullOrEmpty = first == null || first.Count == 0; var isSecondNullOrEmpty = second == null || second.Count == 0; @@ -114,20 +112,22 @@ internal static Dictionary> CreateMergedDictionary( { return new Dictionary>(); } + if (isFirstNullOrEmpty) { - return new Dictionary>(second); + return new Dictionary>(second!); } + if (isSecondNullOrEmpty) { - return new Dictionary>(first); + return new Dictionary>(first!); } // Copy all the keys in the first dictionary into the resulting dictionary. - var result = first.Where(kvp => (kvp.Value != null && kvp.Value.Count > 0)) + var result = first!.Where(kvp => kvp.Value != null && kvp.Value.Count > 0) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - foreach (var kvp in second) + foreach (var kvp in second!) { // If the "source" set is empty there's no reason to continue merging for this key. if (kvp.Value == null || kvp.Value.Count == 0) @@ -155,7 +155,7 @@ internal static Dictionary> CreateMergedDictionary( /// /// Add extension-related telemetry. /// - /// + /// /// A collection representing the telemetry data. /// The input extension collection. internal static void AddExtensionTelemetry( @@ -179,8 +179,8 @@ internal static void AddExtensionTelemetry( /// /// The of extensions discovered /// - internal Dictionary AddExtension( - Dictionary newExtensions) where TPluginInfo : TestPluginInformation + internal Dictionary? AddExtension(Dictionary? newExtensions) + where TPluginInfo : TestPluginInformation { var existingExtensions = GetTestExtensionCache(); if (newExtensions == null) @@ -216,38 +216,24 @@ internal Dictionary AddExtension( /// /// The extension assembly. /// The test extensions defined the extension assembly if it is already discovered. null if not. - internal TestExtensions GetExtensionsDiscoveredFromAssembly(string extensionAssembly) + internal TestExtensions? GetExtensionsDiscoveredFromAssembly(string? extensionAssembly) { var testExtensions = new TestExtensions(); testExtensions.TestDiscoverers = - GetExtensionsDiscoveredFromAssembly( - TestDiscoverers, - extensionAssembly); + GetExtensionsDiscoveredFromAssembly(TestDiscoverers, extensionAssembly); testExtensions.TestExecutors = - GetExtensionsDiscoveredFromAssembly( - TestExecutors, - extensionAssembly); + GetExtensionsDiscoveredFromAssembly(TestExecutors, extensionAssembly); testExtensions.TestExecutors2 = - GetExtensionsDiscoveredFromAssembly( - TestExecutors2, - extensionAssembly); + GetExtensionsDiscoveredFromAssembly(TestExecutors2, extensionAssembly); testExtensions.TestSettingsProviders = - GetExtensionsDiscoveredFromAssembly( - TestSettingsProviders, - extensionAssembly); + GetExtensionsDiscoveredFromAssembly(TestSettingsProviders, extensionAssembly); testExtensions.TestLoggers = - GetExtensionsDiscoveredFromAssembly( - TestLoggers, - extensionAssembly); + GetExtensionsDiscoveredFromAssembly(TestLoggers, extensionAssembly); testExtensions.TestHosts = - GetExtensionsDiscoveredFromAssembly( - TestHosts, - extensionAssembly); + GetExtensionsDiscoveredFromAssembly(TestHosts, extensionAssembly); testExtensions.DataCollectors = - GetExtensionsDiscoveredFromAssembly( - DataCollectors, - extensionAssembly); + GetExtensionsDiscoveredFromAssembly(DataCollectors, extensionAssembly); if (testExtensions.TestDiscoverers.Any() || testExtensions.TestExecutors.Any() @@ -264,37 +250,37 @@ internal TestExtensions GetExtensionsDiscoveredFromAssembly(string extensionAsse return null; } - internal Dictionary GetTestExtensionCache() where TPluginInfo : TestPluginInformation + internal Dictionary? GetTestExtensionCache() where TPluginInfo : TestPluginInformation { Type type = typeof(TPluginInfo); if (type == typeof(TestDiscovererPluginInformation)) { - return (Dictionary)(object)TestDiscoverers; + return (Dictionary?)(object?)TestDiscoverers; } else if (type == typeof(TestExecutorPluginInformation)) { - return (Dictionary)(object)TestExecutors; + return (Dictionary?)(object?)TestExecutors; } else if (type == typeof(TestExecutorPluginInformation2)) { - return (Dictionary)(object)TestExecutors2; + return (Dictionary?)(object?)TestExecutors2; } else if (type == typeof(TestLoggerPluginInformation)) { - return (Dictionary)(object)TestLoggers; + return (Dictionary?)(object?)TestLoggers; } else if (type == typeof(TestSettingsProviderPluginInformation)) { - return (Dictionary)(object)TestSettingsProviders; + return (Dictionary?)(object?)TestSettingsProviders; } else if (type == typeof(TestRuntimePluginInformation)) { - return (Dictionary)(object)TestHosts; + return (Dictionary?)(object?)TestHosts; } else if (type == typeof(DataCollectorConfig)) { - return (Dictionary)(object)DataCollectors; + return (Dictionary?)(object?)DataCollectors; } return null; @@ -386,7 +372,7 @@ internal void SetTestExtensionsCacheStatusToTrue() where TPluginInf /// /// Gets the cached extensions for the current process. /// - /// + /// /// A dictionary representing the cached extensions for the current process. internal Dictionary> GetCachedExtensions() { @@ -433,8 +419,8 @@ internal void InvalidateCache() /// The . of extensions discovered in assembly /// internal Dictionary GetExtensionsDiscoveredFromAssembly( - Dictionary extensionCollection, - string extensionAssembly) + Dictionary? extensionCollection, + string? extensionAssembly) { var extensions = new Dictionary(); if (extensionCollection != null) @@ -442,8 +428,9 @@ internal Dictionary GetExtensionsDiscoveredFromAssembly(Dictionary } } - private void AddCachedExtensionToDictionary( + private static void AddCachedExtensionToDictionary( Dictionary> extensionDict, string extensionType, - IEnumerable extensions) + IEnumerable? extensions) where T : TestPluginInformation { if (extensions == null) @@ -498,7 +485,7 @@ private void AddCachedExtensionToDictionary( return; } - extensionDict.Add(extensionType, new HashSet(extensions.Select(e => e.IdentifierData))); + extensionDict.Add(extensionType, new HashSet(extensions.Select(e => e.IdentifierData!))); } private static string SerializeExtensionDictionary(IDictionary> extensions) diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestLoggerPluginInformation.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestLoggerPluginInformation.cs index b00f2c310b..4e57bcd94c 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestLoggerPluginInformation.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestLoggerPluginInformation.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; /// @@ -39,11 +37,11 @@ public string FriendlyName /// /// Metadata for the test plugin /// - public override ICollection Metadata + public override ICollection Metadata { get { - return new Object[] { ExtensionUri, FriendlyName }; + return new object?[] { ExtensionUri, FriendlyName }; } } @@ -57,7 +55,7 @@ private static string GetFriendlyName(Type testLoggerType) string friendlyName = string.Empty; object[] attributes = testLoggerType.GetTypeInfo().GetCustomAttributes(typeof(FriendlyNameAttribute), false).ToArray(); - if (attributes != null && attributes.Length > 0) + if (attributes.Length > 0) { FriendlyNameAttribute friendlyNameAttribute = (FriendlyNameAttribute)attributes[0]; diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestPluginInformation.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestPluginInformation.cs index ebff843b1d..2f25733405 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestPluginInformation.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestPluginInformation.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; public abstract class TestPluginInformation @@ -14,7 +12,7 @@ public abstract class TestPluginInformation /// Default constructor /// /// Data type of the test plugin - protected TestPluginInformation(Type testExtensionType) + protected TestPluginInformation(Type? testExtensionType) { if (testExtensionType != null) { @@ -25,7 +23,7 @@ protected TestPluginInformation(Type testExtensionType) /// /// Gets data value identifying the test plugin /// - public virtual string IdentifierData + public virtual string? IdentifierData { get { @@ -36,18 +34,18 @@ public virtual string IdentifierData /// /// Metadata for the test plugin /// - public virtual ICollection Metadata + public virtual ICollection Metadata { get { - return new object[] { AssemblyQualifiedName }; + return new object?[] { AssemblyQualifiedName }; } } /// /// Gets the Assembly qualified name of the plugin /// - public string AssemblyQualifiedName + public string? AssemblyQualifiedName { get; private set; @@ -56,7 +54,7 @@ public string AssemblyQualifiedName /// /// Gets the file path of the plugin /// - public string FilePath + public string? FilePath { get; internal set; diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestRunTimePluginInformation.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestRunTimePluginInformation.cs index 02dd83f7b8..4a7060713a 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestRunTimePluginInformation.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestRunTimePluginInformation.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; /// @@ -21,7 +19,7 @@ internal class TestRuntimePluginInformation : TestExtensionPluginInformation /// Default constructor /// /// The testhost Type. - public TestRuntimePluginInformation(Type testHostType) + public TestRuntimePluginInformation(Type? testHostType) : base(testHostType) { FriendlyName = GetFriendlyName(testHostType); @@ -39,11 +37,11 @@ public string FriendlyName /// /// Metadata for the testhost plugin /// - public override ICollection Metadata + public override ICollection Metadata { get { - return new Object[] { ExtensionUri, FriendlyName }; + return new object?[] { ExtensionUri, FriendlyName }; } } @@ -52,11 +50,11 @@ public override ICollection Metadata /// /// Data type of the testhost /// FriendlyName identifying the testhost - private static string GetFriendlyName(Type testHostType) + private static string GetFriendlyName(Type? testHostType) { string friendlyName = string.Empty; - object[] attributes = testHostType.GetTypeInfo().GetCustomAttributes(typeof(FriendlyNameAttribute), false).ToArray(); + object[]? attributes = testHostType?.GetTypeInfo().GetCustomAttributes(typeof(FriendlyNameAttribute), false).ToArray(); if (attributes != null && attributes.Length > 0) { FriendlyNameAttribute friendlyNameAttribute = (FriendlyNameAttribute)attributes[0]; diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestSettingsProviderPluginInformation.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestSettingsProviderPluginInformation.cs index ae3cc33632..6322353be3 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestSettingsProviderPluginInformation.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/Utilities/TestSettingsProviderPluginInformation.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; /// @@ -21,7 +19,7 @@ internal class TestSettingsProviderPluginInformation : TestPluginInformation /// Default constructor /// /// The test Settings Provider Type. - public TestSettingsProviderPluginInformation(Type testSettingsProviderType) + public TestSettingsProviderPluginInformation(Type? testSettingsProviderType) : base(testSettingsProviderType) { if (testSettingsProviderType != null) @@ -33,7 +31,7 @@ public TestSettingsProviderPluginInformation(Type testSettingsProviderType) /// /// Gets data value identifying the test plugin /// - public override string IdentifierData + public override string? IdentifierData { get { @@ -44,18 +42,18 @@ public override string IdentifierData /// /// Metadata for the test plugin /// - public override ICollection Metadata + public override ICollection Metadata { get { - return new object[] { SettingsName }; + return new object?[] { SettingsName }; } } /// /// Gets name of test settings supported by plugin. /// - public string SettingsName + public string? SettingsName { get; private set; diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs index 9ed75a147d..4daf3af725 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs @@ -12,8 +12,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; /// @@ -30,12 +28,12 @@ public class VSExtensionManager : IVSExtensionManager private readonly IFileHelper _fileHelper; - private Assembly _extensionManagerAssembly; - private Assembly _extensionManagerImplAssembly; - private Type _extensionManagerServiceType; + private Assembly? _extensionManagerAssembly; + private Assembly? _extensionManagerImplAssembly; + private Type? _extensionManagerServiceType; - private Assembly _settingsManagerAssembly; - private Type _settingsManagerType; + private Assembly? _settingsManagerAssembly; + private Type? _settingsManagerType; /// /// Default constructor for manager for Visual Studio based extensions @@ -73,7 +71,7 @@ public IEnumerable GetUnitTestExtensions() /// private IEnumerable GetTestExtensionsInternal(string extensionType) { - IEnumerable installedExtensions = new List(); + IEnumerable? installedExtensions = new List(); // Navigate up to the IDE folder // In case of xcopyable vstest.console, this functionality is not supported. @@ -87,44 +85,42 @@ private IEnumerable GetTestExtensionsInternal(string extensionType) var resolutionPaths = installContext.GetVisualStudioCommonLocations(vsInstallPath); using (var assemblyResolver = new AssemblyResolver(resolutionPaths)) { - object extensionManager; - object settingsManager; + object? extensionManager; + object? settingsManager; + + settingsManager = SettingsManagerType.GetMethod("CreateForApplication", new Type[] { typeof(string) })?.Invoke(null, new object[] { installContext.GetVisualStudioPath(vsInstallPath) }); + if (settingsManager == null) + { + EqtTrace.Warning("VSExtensionManager : Unable to create settings manager"); + return installedExtensions; + } - settingsManager = SettingsManagerType.GetMethod("CreateForApplication", new Type[] { typeof(string) }).Invoke(null, new object[] { installContext.GetVisualStudioPath(vsInstallPath) }); - if (settingsManager != null) + try { - try + // create extension manager + extensionManager = Activator.CreateInstance(ExtensionManagerServiceType, settingsManager); + + if (extensionManager != null) { - // create extension manager - extensionManager = Activator.CreateInstance(ExtensionManagerServiceType, settingsManager); - - if (extensionManager != null) - { - installedExtensions = ExtensionManagerServiceType.GetMethod("GetEnabledExtensionContentLocations", new Type[] { typeof(string) }).Invoke( - extensionManager, new object[] { extensionType }) as IEnumerable; - } - else - { - EqtTrace.Warning("VSExtensionManager : Unable to create extension manager"); - } + installedExtensions = ExtensionManagerServiceType.GetMethod("GetEnabledExtensionContentLocations", new Type[] { typeof(string) })?.Invoke( + extensionManager, new object[] { extensionType }) as IEnumerable; } - finally + else { - // Dispose the settings manager - IDisposable disposable = (settingsManager as IDisposable); - if (disposable != null) - { - disposable.Dispose(); - } + EqtTrace.Warning("VSExtensionManager : Unable to create extension manager"); } } - else + finally { - EqtTrace.Warning("VSExtensionManager : Unable to create settings manager"); + // Dispose the settings manager + if (settingsManager is IDisposable disposable) + { + disposable.Dispose(); + } } } - return installedExtensions; + return installedExtensions ?? new List(); } /// @@ -145,7 +141,7 @@ private Assembly ExtensionManagerDefAssembly /// /// Used to explicitly load Microsoft.VisualStudio.ExtensionManager.Implementation.dll /// - private Assembly ExtensionManagerImplAssembly + private Assembly? ExtensionManagerImplAssembly { get { @@ -172,7 +168,9 @@ private Type ExtensionManagerServiceType { if (_extensionManagerServiceType == null) { + TPDebug.Assert(ExtensionManagerImplAssembly is not null, "ExtensionManagerImplAssembly is null"); _extensionManagerServiceType = ExtensionManagerImplAssembly.GetType(ExtensionManagerService); + TPDebug.Assert(_extensionManagerServiceType is not null, "_extensionManagerServiceType is null"); } return _extensionManagerServiceType; } @@ -201,6 +199,7 @@ private Type SettingsManagerType if (_settingsManagerType == null) { _settingsManagerType = SettingsManagerAssembly.GetType(SettingsManagerTypeName); + TPDebug.Assert(_settingsManagerType is not null, "_settingsManagerType is null"); } return _settingsManagerType; diff --git a/src/Microsoft.TestPlatform.Common/Filtering/Condition.cs b/src/Microsoft.TestPlatform.Common/Filtering/Condition.cs index 8ce20d665d..c333120b49 100644 --- a/src/Microsoft.TestPlatform.Common/Filtering/Condition.cs +++ b/src/Microsoft.TestPlatform.Common/Filtering/Condition.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text; @@ -12,8 +13,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Filtering; internal enum Operation @@ -89,7 +88,7 @@ internal Condition(string name, Operation operation, string value) /// /// Evaluate this condition for testObject. /// - internal bool Evaluate(Func propertyValueProvider) + internal bool Evaluate(Func propertyValueProvider) { ValidateArg.NotNull(propertyValueProvider, nameof(propertyValueProvider)); var result = false; @@ -170,7 +169,7 @@ internal bool Evaluate(Func propertyValueProvider) /// /// Returns a condition object after parsing input string of format 'Operation' /// - internal static Condition Parse(string conditionString) + internal static Condition Parse(string? conditionString) { if (conditionString.IsNullOrWhiteSpace()) { @@ -204,7 +203,8 @@ internal static Condition Parse(string conditionString) return condition; } - private static void ThrownFormatExceptionForInvalidCondition(string conditionString) + [DoesNotReturn] + private static void ThrownFormatExceptionForInvalidCondition(string? conditionString) { throw new FormatException(string.Format(CultureInfo.CurrentCulture, CommonResources.TestCaseFilterFormatException, string.Format(CultureInfo.CurrentCulture, CommonResources.InvalidCondition, conditionString))); @@ -213,7 +213,7 @@ private static void ThrownFormatExceptionForInvalidCondition(string conditionStr /// /// Check if condition validates any property in properties. /// - internal bool ValidForProperties(IEnumerable properties, Func propertyProvider) + internal bool ValidForProperties(IEnumerable properties, Func? propertyProvider) { bool valid = false; @@ -230,7 +230,7 @@ internal bool ValidForProperties(IEnumerable properties, Func propertyProvider) + private bool ValidForContainsOperation(Func? propertyProvider) { bool valid = true; @@ -240,7 +240,7 @@ private bool ValidForContainsOperation(Func propertyProvid // if null, it might be custom validation ignore it. if (null != propertyProvider) { - TestProperty testProperty = propertyProvider(Name); + TestProperty? testProperty = propertyProvider(Name); if (null != testProperty) { Type propertyType = testProperty.GetValueType(); @@ -269,7 +269,7 @@ private static Operation GetOperator(string operationString) /// /// Returns property value for Property using propertValueProvider. /// - private string[] GetPropertyValue(Func propertyValueProvider) + private string[]? GetPropertyValue(Func propertyValueProvider) { var propertyValue = propertyValueProvider(Name); if (null != propertyValue) @@ -277,7 +277,7 @@ private string[] GetPropertyValue(Func propertyValueProvider) if (propertyValue is not string[] multiValue) { multiValue = new string[1]; - multiValue[0] = propertyValue.ToString(); + multiValue[0] = propertyValue.ToString()!; } return multiValue; } diff --git a/src/Microsoft.TestPlatform.Common/Filtering/FastFilter.cs b/src/Microsoft.TestPlatform.Common/Filtering/FastFilter.cs index 3b6c5e402d..856a1c1487 100644 --- a/src/Microsoft.TestPlatform.Common/Filtering/FastFilter.cs +++ b/src/Microsoft.TestPlatform.Common/Filtering/FastFilter.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Filtering; internal sealed class FastFilter @@ -20,9 +18,9 @@ internal sealed class FastFilter internal bool IsFilteredOutWhenMatched { get; } - internal Regex PropertyValueRegex { get; set; } + internal Regex? PropertyValueRegex { get; set; } - internal string PropertyValueRegexReplacement { get; set; } + internal string? PropertyValueRegexReplacement { get; set; } internal FastFilter(ImmutableDictionary> filterProperties, Operation filterOperation, Operator filterOperator) { @@ -30,26 +28,26 @@ internal FastFilter(ImmutableDictionary> filterProperties, FilterProperties = filterProperties; - if (filterOperation == Operation.Equal && (filterOperator == Operator.Or || filterOperator == Operator.None)) - { - IsFilteredOutWhenMatched = false; - } - else - { - IsFilteredOutWhenMatched = filterOperation == Operation.NotEqual && (filterOperator == Operator.And || filterOperator == Operator.None) + IsFilteredOutWhenMatched = + (filterOperation != Operation.Equal || filterOperator != Operator.Or && filterOperator != Operator.None) + && (filterOperation == Operation.NotEqual && (filterOperator == Operator.And || filterOperator == Operator.None) ? true - : throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.FastFilterException)); - } + : throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.FastFilterException))); } - internal string[] ValidForProperties(IEnumerable properties) + internal string[]? ValidForProperties(IEnumerable? properties) { + if (properties is null) + { + return null; + } + return FilterProperties.Keys.All(name => properties.Contains(name)) ? null : FilterProperties.Keys.Where(name => !properties.Contains(name)).ToArray(); } - internal bool Evaluate(Func propertyValueProvider) + internal bool Evaluate(Func propertyValueProvider) { ValidateArg.NotNull(propertyValueProvider, nameof(propertyValueProvider)); @@ -57,23 +55,25 @@ internal bool Evaluate(Func propertyValueProvider) foreach (var name in FilterProperties.Keys) { // If there is no value corresponding to given name, treat it as unmatched. - if (TryGetPropertyValue(name, propertyValueProvider, out var singleValue, out var multiValues)) + if (!TryGetPropertyValue(name, propertyValueProvider, out var singleValue, out var multiValues)) { - if (singleValue != null) - { - var value = PropertyValueRegex == null ? singleValue : ApplyRegex(singleValue); - matched = value != null && FilterProperties[name].Contains(value); - } - else - { - matched = (PropertyValueRegex == null ? multiValues : multiValues.Select(value => ApplyRegex(value))) - .Any(result => result != null && FilterProperties[name].Contains(result)); - } + continue; + } - if (matched) - { - break; - } + if (singleValue != null) + { + var value = PropertyValueRegex == null ? singleValue : ApplyRegex(singleValue); + matched = value != null && FilterProperties[name].Contains(value); + } + else + { + var values = PropertyValueRegex == null ? multiValues : multiValues?.Select(value => ApplyRegex(value)); + matched = values?.Any(result => result != null && FilterProperties[name].Contains(result)) == true; + } + + if (matched) + { + break; } } @@ -84,11 +84,11 @@ internal bool Evaluate(Func propertyValueProvider) /// Apply regex matching or replacement to given value. /// /// For matching, returns the result of matching, null if no match found. For replacement, returns the result of replacement. - private string ApplyRegex(string value) + private string? ApplyRegex(string value) { TPDebug.Assert(PropertyValueRegex != null); - string result = null; + string? result = null; if (PropertyValueRegexReplacement == null) { var match = PropertyValueRegex.Match(value); @@ -107,7 +107,7 @@ private string ApplyRegex(string value) /// /// Returns property value for Property using propertValueProvider. /// - private static bool TryGetPropertyValue(string name, Func propertyValueProvider, out string singleValue, out string[] multiValues) + private static bool TryGetPropertyValue(string name, Func propertyValueProvider, out string? singleValue, out string[]? multiValues) { var propertyValue = propertyValueProvider(name); if (null != propertyValue) @@ -201,14 +201,14 @@ private void AddProperty(string name, string value) { if (!_filterDictionaryBuilder.TryGetValue(name, out var values)) { - values = ImmutableHashSet.CreateBuilder(StringComparer.OrdinalIgnoreCase); + values = ImmutableHashSet.CreateBuilder(StringComparer.OrdinalIgnoreCase); _filterDictionaryBuilder.Add(name, values); } values.Add(value); } - internal FastFilter ToFastFilter() + internal FastFilter? ToFastFilter() { return ContainsValidFilter ? new FastFilter( diff --git a/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs b/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs index 33ad230914..1d2976a137 100644 --- a/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs +++ b/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs @@ -14,8 +14,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Filtering; /// @@ -30,17 +28,17 @@ internal class FilterExpression /// /// Condition, if expression is conditional expression. /// - private readonly Condition _condition; + private readonly Condition? _condition; /// /// Left operand, when expression is logical expression. /// - private readonly FilterExpression _left; + private readonly FilterExpression? _left; /// /// Right operand, when expression is logical expression. /// - private readonly FilterExpression _right; + private readonly FilterExpression? _right; /// /// If logical expression is using logical And ('&') operator. @@ -119,9 +117,9 @@ private static void ProcessOperator(Stack filterStack, Operato /// True, if filter is valid for given set of properties. /// When False, invalidProperties would contain properties making filter invalid. /// - internal string[] ValidForProperties(IEnumerable properties, Func propertyProvider) + internal string[]? ValidForProperties(IEnumerable? properties, Func? propertyProvider) { - string[] invalidProperties = null; + string[]? invalidProperties = null; if (null == properties) { @@ -140,8 +138,8 @@ internal string[] ValidForProperties(IEnumerable properties, Func properties, Func /// Return FilterExpression after parsing the given filter expression, and a FastFilter when possible. /// - internal static FilterExpression Parse(string filterString, out FastFilter fastFilter) + internal static FilterExpression Parse(string filterString, out FastFilter? fastFilter) { ValidateArg.NotNull(filterString, nameof(filterString)); @@ -172,7 +171,7 @@ internal static FilterExpression Parse(string filterString, out FastFilter fastF var operatorStack = new Stack(); var filterStack = new Stack(); - var fastFilterBuilder = FastFilter.CreateBuilder(); + FastFilter.Builder fastFilterBuilder = FastFilter.CreateBuilder(); // This is based on standard parsing of in order expression using two stacks (operand stack and operator stack) // Precedence(And) > Precedence(Or) @@ -272,7 +271,7 @@ internal static FilterExpression Parse(string filterString, out FastFilter fastF /// /// The property Value Provider. /// True if evaluation is successful. - internal bool Evaluate(Func propertyValueProvider) + internal bool Evaluate(Func propertyValueProvider) { ValidateArg.NotNull(propertyValueProvider, nameof(propertyValueProvider)); bool filterResult = false; @@ -283,8 +282,8 @@ internal bool Evaluate(Func propertyValueProvider) else { // & or | operator - bool leftResult = _left.Evaluate(propertyValueProvider); - bool rightResult = _right.Evaluate(propertyValueProvider); + bool leftResult = _left!.Evaluate(propertyValueProvider); + bool rightResult = _right!.Evaluate(propertyValueProvider); filterResult = _areJoinedByAnd ? leftResult && rightResult : leftResult || rightResult; } return filterResult; diff --git a/src/Microsoft.TestPlatform.Common/Filtering/FilterExpressionWrapper.cs b/src/Microsoft.TestPlatform.Common/Filtering/FilterExpressionWrapper.cs index 78d5b3283b..d01e6b45a9 100644 --- a/src/Microsoft.TestPlatform.Common/Filtering/FilterExpressionWrapper.cs +++ b/src/Microsoft.TestPlatform.Common/Filtering/FilterExpressionWrapper.cs @@ -3,13 +3,12 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Filtering; /// @@ -20,19 +19,20 @@ public class FilterExpressionWrapper /// /// FilterExpression corresponding to filter criteria /// - private readonly FilterExpression _filterExpression; + private readonly FilterExpression? _filterExpression; /// /// Exposed for testing purpose. /// - internal readonly FastFilter FastFilter; + internal readonly FastFilter? FastFilter; + [MemberNotNullWhen(true, nameof(FastFilter))] private bool UseFastFilter => FastFilter != null; /// /// Initializes FilterExpressionWrapper with given filterString and options. /// - public FilterExpressionWrapper(string filterString, FilterOptions options) + public FilterExpressionWrapper(string filterString, FilterOptions? options) { ValidateArg.NotNullOrEmpty(filterString, nameof(filterString)); @@ -55,7 +55,7 @@ public FilterExpressionWrapper(string filterString, FilterOptions options) var regexString = options?.FilterRegEx; if (!regexString.IsNullOrEmpty()) { - TPDebug.Assert(options.FilterRegExReplacement == null || options.FilterRegEx != null); + TPDebug.Assert(options!.FilterRegExReplacement == null || options.FilterRegEx != null); FastFilter.PropertyValueRegex = new Regex(regexString, RegexOptions.Compiled); FastFilter.PropertyValueRegexReplacement = options.FilterRegExReplacement; } @@ -93,7 +93,7 @@ public string FilterString /// /// User specified additional filter options. /// - public FilterOptions FilterOptions + public FilterOptions? FilterOptions { get; private set; @@ -102,7 +102,7 @@ public FilterOptions FilterOptions /// /// Parsing error (if any), when parsing 'FilterString' with built-in parser. /// - public string ParseError + public string? ParseError { get; private set; @@ -111,15 +111,15 @@ public string ParseError /// /// Validate if underlying filter expression is valid for given set of supported properties. /// - public string[] ValidForProperties(IEnumerable supportedProperties, Func propertyProvider) - { - return UseFastFilter ? FastFilter.ValidForProperties(supportedProperties) : _filterExpression?.ValidForProperties(supportedProperties, propertyProvider); - } + public string[]? ValidForProperties(IEnumerable? supportedProperties, Func? propertyProvider) + => UseFastFilter + ? FastFilter.ValidForProperties(supportedProperties) + : _filterExpression?.ValidForProperties(supportedProperties, propertyProvider); /// /// Evaluate filterExpression with given propertyValueProvider. /// - public bool Evaluate(Func propertyValueProvider) + public bool Evaluate(Func propertyValueProvider) { ValidateArg.NotNull(propertyValueProvider, nameof(propertyValueProvider)); diff --git a/src/Microsoft.TestPlatform.Common/Filtering/TestCaseFilterExpression.cs b/src/Microsoft.TestPlatform.Common/Filtering/TestCaseFilterExpression.cs index 5a1d07e966..2af8bce930 100644 --- a/src/Microsoft.TestPlatform.Common/Filtering/TestCaseFilterExpression.cs +++ b/src/Microsoft.TestPlatform.Common/Filtering/TestCaseFilterExpression.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Filtering; /// @@ -48,9 +46,9 @@ public string TestCaseFilterValue /// /// Validate if underlying filter expression is valid for given set of supported properties. /// - public string[] ValidForProperties(IEnumerable supportedProperties, Func propertyProvider) + public string[]? ValidForProperties(IEnumerable? supportedProperties, Func propertyProvider) { - string[] invalidProperties = null; + string[]? invalidProperties = null; if (null != _filterWrapper && _validForMatch) { invalidProperties = _filterWrapper.ValidForProperties(supportedProperties, propertyProvider); @@ -61,7 +59,7 @@ public string[] ValidForProperties(IEnumerable supportedProperties, Func /// /// Match test case with filter criteria. /// - public bool MatchTestCase(TestCase testCase, Func propertyValueProvider) + public bool MatchTestCase(TestCase testCase, Func propertyValueProvider) { ValidateArg.NotNull(testCase, nameof(testCase)); ValidateArg.NotNull(propertyValueProvider, nameof(propertyValueProvider)); @@ -76,6 +74,7 @@ public bool MatchTestCase(TestCase testCase, Func propertyValueP // can be null when parsing error occurs. Invalid filter results in no match. return false; } + return _filterWrapper.Evaluate(propertyValueProvider); } diff --git a/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeExtensionManager.cs b/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeExtensionManager.cs index 47035b29dc..b0cb405cf9 100644 --- a/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeExtensionManager.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Host; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Hosting; /// diff --git a/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeMetadata.cs b/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeMetadata.cs index 1455058276..eec613bcf0 100644 --- a/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeMetadata.cs +++ b/src/Microsoft.TestPlatform.Common/Hosting/TestRunTimeMetadata.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Hosting; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelOperationManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelOperationManager.cs index f0300abddd..7d4354449a 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelOperationManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelOperationManager.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyDiscoveryManager.cs index 9e32610fd4..334a8c9c1b 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyDiscoveryManager.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// @@ -29,6 +27,6 @@ public interface IParallelProxyDiscoveryManager : IProxyDiscoveryManager bool HandlePartialDiscoveryComplete( IProxyDiscoveryManager proxyDiscoveryManager, long totalTests, - IEnumerable lastChunk, + IEnumerable? lastChunk, bool isAborted); } diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyExecutionManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyExecutionManager.cs index 8b18e34d47..35dcea64ff 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyExecutionManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IParallelProxyExecutionManager.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// @@ -27,7 +25,7 @@ public interface IParallelProxyExecutionManager : IProxyExecutionManager bool HandlePartialRunComplete( IProxyExecutionManager proxyExecutionManager, TestRunCompleteEventArgs testRunCompleteArgs, - TestRunChangedEventArgs lastChunkArgs, - ICollection runContextAttachments, - ICollection executorUris); + TestRunChangedEventArgs? lastChunkArgs, + ICollection? runContextAttachments, + ICollection? executorUris); } diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyDiscoveryManager.cs index b18b957817..412ba6818f 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyDiscoveryManager.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyExecutionManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyExecutionManager.cs index cb64260cc3..66857ec088 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyExecutionManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyExecutionManager.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyTestSessionManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyTestSessionManager.cs index 026219dea8..3a2acca8ac 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyTestSessionManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/IProxyTestSessionManager.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// @@ -16,12 +14,12 @@ public interface IProxyTestSessionManager /// /// Starts the test session based on the test session criteria. /// - /// + /// /// /// Event handler for handling events fired during test session management operations. /// /// The request data. - /// + /// /// True if the operation succeeded, false otherwise. bool StartSession(ITestSessionEventsHandler eventsHandler, IRequestData requestData); diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestEngine.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestEngine.cs index abf9f1ce6b..eb40e4328c 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestEngine.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestEngine.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// @@ -18,13 +16,13 @@ public interface ITestEngine /// Fetches the DiscoveryManager for this engine. This manager would provide all /// functionality required for discovery. /// - /// + /// /// /// The request data for providing discovery services and data. /// /// Test host manager for the current test discovery. /// The discovery criteria. - /// + /// /// An IProxyDiscoveryManager object that can do discovery. IProxyDiscoveryManager GetDiscoveryManager( IRequestData requestData, @@ -36,13 +34,13 @@ IProxyDiscoveryManager GetDiscoveryManager( /// Fetches the ExecutionManager for this engine. This manager would provide all /// functionality required for execution. /// - /// + /// /// /// The request data for providing common execution services and data. /// /// Test host manager for the current test run. /// Test run criteria of the current test run. - /// + /// /// An IProxyExecutionManager object that can do execution. IProxyExecutionManager GetExecutionManager( IRequestData requestData, @@ -54,16 +52,16 @@ IProxyExecutionManager GetExecutionManager( /// Fetches the TestSessionManager for this engine. This manager would provide all /// functionality required for test session management. /// - /// + /// /// /// The request data for providing test session services and data. /// /// /// Test session criteria of the current test session. /// - /// + /// /// An IProxyTestSessionManager object that can manage test sessions. - IProxyTestSessionManager GetTestSessionManager( + IProxyTestSessionManager? GetTestSessionManager( IRequestData requestData, StartTestSessionCriteria testSessionCriteria, IDictionary sourceToSourceDetailMap, @@ -73,7 +71,7 @@ IProxyTestSessionManager GetTestSessionManager( /// Fetches the extension manager for this engine. This manager would provide extensibility /// features that this engine supports. /// - /// + /// /// An ITestExtensionManager object that helps with extensibility. ITestExtensionManager GetExtensionManager(); @@ -81,11 +79,11 @@ IProxyTestSessionManager GetTestSessionManager( /// Fetches the logger manager for this engine. This manager will provide logger /// extensibility features that this engine supports. /// - /// + /// /// /// The request data for providing common execution services and data. /// - /// + /// /// An ITestLoggerManager object that helps with logger extensibility. ITestLoggerManager GetLoggerManager(IRequestData requestData); } diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestExtensionManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestExtensionManager.cs index df8bfc77fd..c361792106 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestExtensionManager.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// @@ -17,7 +15,7 @@ public interface ITestExtensionManager /// /// List of extension paths /// Skips filtering of extensions (if true) - void UseAdditionalExtensions(IEnumerable pathToAdditionalExtensions, bool skipExtensionFilters); + void UseAdditionalExtensions(IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters); /// /// Clear the extensions data diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs index 6b4dc807e3..d8f220ad7c 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs @@ -4,11 +4,8 @@ using System; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; - using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/TestExecutionContext.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/TestExecutionContext.cs index dd94fe0e21..23147e4415 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/TestExecutionContext.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/TestExecutionContext.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine.ClientProtocol; /// @@ -47,8 +45,8 @@ public TestExecutionContext( bool areTestCaseLevelEventsRequired, bool hasTestRun, bool isDebug, - string testCaseFilter, - FilterOptions filterOptions) + string? testCaseFilter, + FilterOptions? filterOptions) { FrequencyOfRunStatsChangeEvent = frequencyOfRunStatsChangeEvent; RunStatsChangeEventTimeout = runStatsChangeEventTimeout; @@ -128,7 +126,7 @@ public bool IsDebug /// Gets or sets the filter criteria for run with sources to filter test cases. /// [DataMember] - public string TestCaseFilter + public string? TestCaseFilter { get; set; @@ -139,7 +137,7 @@ public string TestCaseFilter /// Gets or sets additional options for filtering. /// [DataMember] - public FilterOptions FilterOptions + public FilterOptions? FilterOptions { get; set; @@ -171,7 +169,7 @@ public bool HasTestRun /// /// It is not serialized over wcf as the information is available in the run settings [IgnoreDataMember] - public RunConfiguration TestRunConfiguration + public RunConfiguration? TestRunConfiguration { get; set; diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IArtifactProcessingManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IArtifactProcessingManager.cs index b8440d4cd7..b9724b5dd0 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IArtifactProcessingManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IArtifactProcessingManager.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; internal interface IArtifactProcessingManager diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IDataCollectorAttachmentsProcessorsFactory.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IDataCollectorAttachmentsProcessorsFactory.cs index 3ab460645e..250e3460a5 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IDataCollectorAttachmentsProcessorsFactory.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/IDataCollectorAttachmentsProcessorsFactory.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// @@ -22,7 +20,7 @@ internal interface IDataCollectorAttachmentsProcessorsFactory /// List of invoked data collectors /// Message logger /// List of attachments processors - DataCollectorAttachmentProcessor[] Create(InvokedDataCollector[] invokedDataCollectors, IMessageLogger logger); + DataCollectorAttachmentProcessor[] Create(InvokedDataCollector[]? invokedDataCollectors, IMessageLogger logger); } /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs index ca122f2527..48db81376c 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs index 9c4365496b..31ca7d406d 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// @@ -25,7 +23,7 @@ internal interface ITestRunAttachmentsProcessingManager /// Collection of invoked data collectors /// EventHandler for handling test run attachments processing event /// Cancellation token - Task ProcessTestRunAttachmentsAsync(string runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler eventHandler, CancellationToken cancellationToken); + Task ProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler eventHandler, CancellationToken cancellationToken); /// /// Processes attachments @@ -35,5 +33,5 @@ internal interface ITestRunAttachmentsProcessingManager /// Collection of invoked data collectors /// Cancellation token /// Collection of attachments. - Task> ProcessTestRunAttachmentsAsync(string runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable invokedDataCollector, CancellationToken cancellationToken); + Task> ProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable invokedDataCollector, CancellationToken cancellationToken); } diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IDiscoveryManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IDiscoveryManager.cs index 273a311124..c3c2ffdae2 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IDiscoveryManager.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine.TesthostProtocol; /// @@ -18,7 +16,7 @@ public interface IDiscoveryManager /// Initializes the discovery manager. /// /// The path to additional extensions. - void Initialize(IEnumerable pathToAdditionalExtensions, ITestDiscoveryEventsHandler2 eventHandler); + void Initialize(IEnumerable pathToAdditionalExtensions, ITestDiscoveryEventsHandler2? eventHandler); /// /// Discovers tests diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IExecutionManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IExecutionManager.cs index 6bec52cb4e..15ca486b19 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IExecutionManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/IExecutionManager.cs @@ -4,11 +4,8 @@ using System.Collections.Generic; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; - using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine.ClientProtocol; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine.TesthostProtocol; /// @@ -20,7 +17,7 @@ public interface IExecutionManager /// Initializes the execution manager. /// /// The path to additional extensions. - void Initialize(IEnumerable pathToAdditionalExtensions, ITestMessageEventHandler testMessageEventsHandler); + void Initialize(IEnumerable pathToAdditionalExtensions, ITestMessageEventHandler? testMessageEventsHandler); /// /// Starts the test run with sources. @@ -33,7 +30,7 @@ public interface IExecutionManager /// The test Execution Context. /// EventHandler for handling test cases level events from Engine. /// EventHandler for handling execution events from Engine. - void StartTestRun(Dictionary> adapterSourceMap, string package, string runSettings, TestExecutionContext testExecutionContext, ITestCaseEventsHandler testCaseEvents, IInternalTestRunEventsHandler eventHandler); + void StartTestRun(Dictionary> adapterSourceMap, string? package, string? runSettings, TestExecutionContext testExecutionContext, ITestCaseEventsHandler? testCaseEvents, IInternalTestRunEventsHandler eventHandler); /// /// Starts the test run with tests. @@ -46,7 +43,7 @@ public interface IExecutionManager /// The test Execution Context. /// /// EventHandler for handling test cases level events from Engine. /// EventHandler for handling execution events from Engine. - void StartTestRun(IEnumerable tests, string package, string runSettings, TestExecutionContext testExecutionContext, ITestCaseEventsHandler testCaseEvents, IInternalTestRunEventsHandler eventHandler); + void StartTestRun(IEnumerable tests, string? package, string? runSettings, TestExecutionContext testExecutionContext, ITestCaseEventsHandler? testCaseEvents, IInternalTestRunEventsHandler eventHandler); /// /// Cancel the test execution. diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/ITestHostManagerFactory.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/ITestHostManagerFactory.cs index 6712de7285..5ac7dcfd65 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/ITestHostManagerFactory.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/TesthostProtocol/ITestHostManagerFactory.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine.TesthostProtocol; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/IAssemblyProperties.cs b/src/Microsoft.TestPlatform.Common/Interfaces/IAssemblyProperties.cs index 4787d28bfe..86b88cdba0 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/IAssemblyProperties.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/IAssemblyProperties.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/IBaseTestEventsRegistrar.cs b/src/Microsoft.TestPlatform.Common/Interfaces/IBaseTestEventsRegistrar.cs index 1149367cb5..44b7aa72a9 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/IBaseTestEventsRegistrar.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/IBaseTestEventsRegistrar.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; public interface IBaseTestEventsRegistrar diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/IDataCollectorCapabilities.cs b/src/Microsoft.TestPlatform.Common/Interfaces/IDataCollectorCapabilities.cs index ca74017ca6..ef076542f3 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/IDataCollectorCapabilities.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/IDataCollectorCapabilities.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/IRunSettingsProvider.cs b/src/Microsoft.TestPlatform.Common/Interfaces/IRunSettingsProvider.cs index 863a2f1a47..a3c0a05535 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/IRunSettingsProvider.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/IRunSettingsProvider.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// @@ -13,7 +11,7 @@ internal interface IRunSettingsProvider /// /// The active run settings. /// - RunSettings ActiveRunSettings { get; } + RunSettings? ActiveRunSettings { get; } /// /// Set the active run settings. diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ISettingsProviderCapabilities.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ISettingsProviderCapabilities.cs index c3f7b4c467..199c97fdfe 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ISettingsProviderCapabilities.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ISettingsProviderCapabilities.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscovererCapabilities.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscovererCapabilities.cs index a06fab86d8..a3b87c4152 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscovererCapabilities.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscovererCapabilities.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// @@ -18,12 +16,12 @@ public interface ITestDiscovererCapabilities /// /// List of file extensions that the test discoverer can process tests from. /// - IEnumerable FileExtension { get; } + IEnumerable? FileExtension { get; } /// /// Default executor Uri for this discoverer /// - Uri DefaultExecutorUri { get; } + Uri? DefaultExecutorUri { get; } /// /// Assembly type that the test discoverer supports. diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscoveryEventsRegistrar.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscoveryEventsRegistrar.cs index ae5b0eac19..f0f7617202 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscoveryEventsRegistrar.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ITestDiscoveryEventsRegistrar.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; public interface ITestDiscoveryEventsRegistrar : IBaseTestEventsRegistrar diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ITestExecutorCapabilities.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ITestExecutorCapabilities.cs index b52f2509e2..7b1efd634d 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ITestExecutorCapabilities.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ITestExecutorCapabilities.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ITestExtensionCapabilities.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ITestExtensionCapabilities.cs index 381b5d86c8..adec51043b 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ITestExtensionCapabilities.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ITestExtensionCapabilities.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ITestLoggerCapabilities.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ITestLoggerCapabilities.cs index 211f05f576..e49b720c51 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ITestLoggerCapabilities.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ITestLoggerCapabilities.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunEventsRegistrar.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunEventsRegistrar.cs index 458ae50af0..958b84b1f8 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunEventsRegistrar.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunEventsRegistrar.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; public interface ITestRunEventsRegistrar : IBaseTestEventsRegistrar diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunTimeCapabilities.cs b/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunTimeCapabilities.cs index ae2c271638..8b4ebedbbc 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunTimeCapabilities.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/ITestRunTimeCapabilities.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/IVSExtensionManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/IVSExtensionManager.cs index 58665f5c8a..5b722d5494 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/IVSExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/IVSExtensionManager.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Interfaces; public interface IVSExtensionManager diff --git a/src/Microsoft.TestPlatform.Common/Logging/InternalTestLoggerEvents.cs b/src/Microsoft.TestPlatform.Common/Logging/InternalTestLoggerEvents.cs index 35f2d84c8f..f555febb2f 100644 --- a/src/Microsoft.TestPlatform.Common/Logging/InternalTestLoggerEvents.cs +++ b/src/Microsoft.TestPlatform.Common/Logging/InternalTestLoggerEvents.cs @@ -13,8 +13,6 @@ using System.Configuration; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Logging; /// @@ -75,42 +73,42 @@ public InternalTestLoggerEvents(TestSessionMessageLogger testSessionMessageLogge /// /// Raised when a test message is received. /// - public override event EventHandler TestRunMessage; + public override event EventHandler? TestRunMessage; /// /// Raised when a test run starts. /// - public override event EventHandler TestRunStart; + public override event EventHandler? TestRunStart; /// /// Raised when a test result is received. /// - public override event EventHandler TestResult; + public override event EventHandler? TestResult; /// /// Raised when a test run is complete. /// - public override event EventHandler TestRunComplete; + public override event EventHandler? TestRunComplete; /// /// Raised when test discovery starts. /// - public override event EventHandler DiscoveryStart; + public override event EventHandler? DiscoveryStart; /// /// Raised when a discovery message is received. /// - public override event EventHandler DiscoveryMessage; + public override event EventHandler? DiscoveryMessage; /// /// Raised when discovered tests are received /// - public override event EventHandler DiscoveredTests; + public override event EventHandler? DiscoveredTests; /// /// Raised when test discovery is complete /// - public override event EventHandler DiscoveryComplete; + public override event EventHandler? DiscoveryComplete; #region IDisposable @@ -287,7 +285,7 @@ internal void RaiseTestRunComplete(TestRunCompleteEventArgs args) /// Run level attachment sets /// Invoked data collectors /// Time elapsed in just running the tests. - internal void CompleteTestRun(ITestRunStatistics stats, bool isCanceled, bool isAborted, Exception error, Collection attachmentSet, Collection invokedDataCollectors, TimeSpan elapsedTime) + internal void CompleteTestRun(ITestRunStatistics? stats, bool isCanceled, bool isAborted, Exception? error, Collection? attachmentSet, Collection? invokedDataCollectors, TimeSpan elapsedTime) { CheckDisposed(); @@ -303,7 +301,7 @@ internal void CompleteTestRun(ITestRunStatistics stats, bool isCanceled, bool is /// /// Called when a test run message is sent through the ITestRunMessageLogger which is exported. /// - private void TestRunMessageHandler(object sender, TestRunMessageEventArgs e) + private void TestRunMessageHandler(object? sender, TestRunMessageEventArgs e) { // Broadcast the message to the loggers. SafeInvokeAsync(() => TestRunMessage, e, 0, "InternalTestLoggerEvents.SendMessage"); @@ -314,7 +312,7 @@ private void TestRunMessageHandler(object sender, TestRunMessageEventArgs e) /// ensuring that each handler is invoked even if one throws. /// The actual calling of the subscribers is done on a background thread. /// - private void SafeInvokeAsync(Func eventHandlersFactory, EventArgs args, int size, string traceDisplayName) + private void SafeInvokeAsync(Func eventHandlersFactory, EventArgs args, int size, string traceDisplayName) { // If you are wondering why this is taking a Func rather than just a MulticastDelegate it is because // taking just that will capture only the subscribers that were present at the time we passed the delegate into this @@ -347,9 +345,9 @@ private void SafeInvokeAsync(Func eventHandlersFactory, Event /// /// Method called to process a job which is coming from the logger event queue. /// - private void ProcessQueuedJob(Action action) + private void ProcessQueuedJob(Action? action) { - action(); + action?.Invoke(); } /// @@ -367,7 +365,7 @@ private void CheckDisposed() /// The method parses the config file of vstest.console.exe to see if the Max Job Queue Length is defined. /// Return the Max Queue Length so defined or a default value specified by TestPlatformDefaults.DefaultMaxLoggerEventsToCache /// - private int GetMaxNumberOfJobsInQueue() + private static int GetMaxNumberOfJobsInQueue() { return GetSetting(TestPlatformDefaults.MaxNumberOfEventsLoggerEventQueueCanHold, TestPlatformDefaults.DefaultMaxNumberOfEventsLoggerEventQueueCanHold); @@ -377,7 +375,7 @@ private int GetMaxNumberOfJobsInQueue() /// The method parses the config file of vstest.console.exe to see if the Max Job Queue size is defined. /// Return the Max Queue size so defined or a default value specified by TestPlatformDefaults.DefaultMaxJobQueueSize /// - private int GetMaxBytesQueueCanHold() + private static int GetMaxBytesQueueCanHold() { return GetSetting(TestPlatformDefaults.MaxBytesLoggerEventQueueCanHold, TestPlatformDefaults.DefaultMaxBytesLoggerEventQueueCanHold); @@ -389,7 +387,7 @@ private int GetMaxBytesQueueCanHold() private static bool IsBoundsEnabledOnLoggerEventQueue() { bool enableBounds; - string enableBoundsOnEventQueueIsDefined = + string? enableBoundsOnEventQueueIsDefined = #if NETFRAMEWORK ConfigurationManager.AppSettings[TestPlatformDefaults.EnableBoundsOnLoggerEventQueue]; #else @@ -433,10 +431,10 @@ private static int FindTestResultSize(TestResultEventArgs args) /// Get the appsetting value for the parameter appSettingKey. Use the parameter defaultValue if /// value is not there or is invalid. /// - private int GetSetting(string appSettingKey, int defaultValue) + private static int GetSetting(string appSettingKey, int defaultValue) { int value; - string appSettingValue = + string? appSettingValue = #if NETFRAMEWORK ConfigurationManager.AppSettings[appSettingKey]; #else diff --git a/src/Microsoft.TestPlatform.Common/Logging/TestSessionMessageLogger.cs b/src/Microsoft.TestPlatform.Common/Logging/TestSessionMessageLogger.cs index ca439a2525..933db98cb3 100644 --- a/src/Microsoft.TestPlatform.Common/Logging/TestSessionMessageLogger.cs +++ b/src/Microsoft.TestPlatform.Common/Logging/TestSessionMessageLogger.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; @@ -9,8 +10,6 @@ using ObjectModelCommonResources = Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources.CommonResources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Logging; /// @@ -18,7 +17,7 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.Logging; /// internal class TestSessionMessageLogger : IMessageLogger { - private static TestSessionMessageLogger s_instance; + private static TestSessionMessageLogger? s_instance; /// /// Initializes a new instance of the class. @@ -31,11 +30,12 @@ protected TestSessionMessageLogger() /// /// Raised when a discovery message is received. /// - internal event EventHandler TestRunMessage; + internal event EventHandler? TestRunMessage; /// /// Gets the instance of the singleton. /// + [AllowNull] public static TestSessionMessageLogger Instance { get diff --git a/src/Microsoft.TestPlatform.Common/RequestData.cs b/src/Microsoft.TestPlatform.Common/RequestData.cs index 948e842971..86f251f55f 100644 --- a/src/Microsoft.TestPlatform.Common/RequestData.cs +++ b/src/Microsoft.TestPlatform.Common/RequestData.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.Common.Telemetry; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common; /// @@ -24,14 +22,14 @@ public class RequestData : IRequestData /// /// The protocol config. /// - private ProtocolConfig _protocolConfig; + private ProtocolConfig? _protocolConfig; /// /// The default constructor for request data. /// public RequestData() { - MetricsCollection = new NoOpMetricsCollection(); + _metricsCollection = new NoOpMetricsCollection(); IsTelemetryOptedIn = false; } @@ -47,7 +45,7 @@ public IMetricsCollection MetricsCollection /// /// Gets or sets the protocol config. /// - public ProtocolConfig ProtocolConfig + public ProtocolConfig? ProtocolConfig { get => _protocolConfig; set => _protocolConfig = value ?? throw new ArgumentNullException(nameof(value)); diff --git a/src/Microsoft.TestPlatform.Common/RunSettings.cs b/src/Microsoft.TestPlatform.Common/RunSettings.cs index 3bb046d36d..10a9b2825a 100644 --- a/src/Microsoft.TestPlatform.Common/RunSettings.cs +++ b/src/Microsoft.TestPlatform.Common/RunSettings.cs @@ -19,8 +19,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources; using ObjectModelCommonResources = Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources.CommonResources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common; /// @@ -49,14 +47,14 @@ public RunSettings() /// /// Gets the settings in the form of Xml string. /// - public string SettingsXml { get; private set; } + public string? SettingsXml { get; private set; } /// /// Get the settings for the provided settings name. /// /// Name of the settings section to get. /// The settings provider for the settings or null if one was not found. - public ISettingsProvider GetSettings(string settingsName) + public ISettingsProvider? GetSettings(string settingsName) { if (StringUtilities.IsNullOrWhiteSpace(settingsName)) { @@ -64,16 +62,10 @@ public ISettingsProvider GetSettings(string settingsName) } // Try and lookup the settings provider. - ISettingsProvider result = null; _settings.TryGetValue(settingsName, out var provider); // If a provider was found, return it. - if (provider != null) - { - result = provider.Value; - } - - return result; + return provider?.Value; } /// @@ -244,7 +236,7 @@ private void LoadSection(XmlReader reader, SettingsProviderExtensionManager sett private static LazyExtension CreateLazyThrower( string message, ISettingsProviderCapabilities metadata, - Exception innerException = null) + Exception? innerException = null) { return new LazyExtension( () => throw new SettingsException(message, innerException), diff --git a/src/Microsoft.TestPlatform.Common/RunSettingsManager.cs b/src/Microsoft.TestPlatform.Common/RunSettingsManager.cs index 6edc90deb2..217da5c245 100644 --- a/src/Microsoft.TestPlatform.Common/RunSettingsManager.cs +++ b/src/Microsoft.TestPlatform.Common/RunSettingsManager.cs @@ -2,11 +2,10 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestPlatform.Common.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common; /// @@ -16,7 +15,7 @@ internal class RunSettingsManager : IRunSettingsProvider { private static readonly object LockObject = new(); - private static RunSettingsManager s_runSettingsManagerInstance; + private static RunSettingsManager? s_runSettingsManagerInstance; /// /// Default constructor. @@ -26,8 +25,6 @@ private RunSettingsManager() ActiveRunSettings = new RunSettings(); } - - #region IRunSettingsProvider /// @@ -36,6 +33,8 @@ private RunSettingsManager() public RunSettings ActiveRunSettings { get; private set; } #endregion + + [AllowNull] public static RunSettingsManager Instance { get diff --git a/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs b/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs index fe11287eb6..93d8d0f12e 100644 --- a/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs @@ -16,8 +16,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources; using ObjectModelCommonResources = Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources.CommonResources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.SettingsProvider; /// @@ -29,7 +27,7 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.SettingsProvider; /// public class SettingsProviderExtensionManager { - private static SettingsProviderExtensionManager s_settingsProviderExtensionManager; + private static SettingsProviderExtensionManager? s_settingsProviderExtensionManager; private static readonly object Synclock = new(); /// @@ -63,18 +61,24 @@ protected SettingsProviderExtensionManager( foreach (var settingsProvider in _settingsProviders) { - if (SettingsProvidersMap.ContainsKey(settingsProvider.Metadata.SettingsName)) + var settingsName = settingsProvider.Metadata?.SettingsName; + if (settingsName is null) + { + continue; + } + + if (SettingsProvidersMap.ContainsKey(settingsName)) { _logger.SendMessage( TestMessageLevel.Error, string.Format( CultureInfo.CurrentUICulture, CommonResources.DuplicateSettingsName, - settingsProvider.Metadata.SettingsName)); + settingsName)); } else { - SettingsProvidersMap.Add(settingsProvider.Metadata.SettingsName, settingsProvider); + SettingsProvidersMap.Add(settingsName, settingsProvider); } } } @@ -160,14 +164,14 @@ public static void LoadAndInitializeAllExtensions(bool shouldThrowOnError) /// /// Name of the settings to get. /// Settings provider with the provided name or null if one was not found. - internal LazyExtension GetSettingsProvider(string settingsName) + internal LazyExtension? GetSettingsProvider(string settingsName) { if (settingsName.IsNullOrWhiteSpace()) { throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, nameof(settingsName)); } - SettingsProvidersMap.TryGetValue(settingsName, out LazyExtension settingsProvider); + SettingsProvidersMap.TryGetValue(settingsName, out var settingsProvider); return settingsProvider; } diff --git a/src/Microsoft.TestPlatform.Common/Telemetry/MetricsCollection.cs b/src/Microsoft.TestPlatform.Common/Telemetry/MetricsCollection.cs index 101d3df00e..180d228995 100644 --- a/src/Microsoft.TestPlatform.Common/Telemetry/MetricsCollection.cs +++ b/src/Microsoft.TestPlatform.Common/Telemetry/MetricsCollection.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Telemetry; /// diff --git a/src/Microsoft.TestPlatform.Common/Telemetry/NoOpMetricsCollection.cs b/src/Microsoft.TestPlatform.Common/Telemetry/NoOpMetricsCollection.cs index 5eac850438..47a8848b8f 100644 --- a/src/Microsoft.TestPlatform.Common/Telemetry/NoOpMetricsCollection.cs +++ b/src/Microsoft.TestPlatform.Common/Telemetry/NoOpMetricsCollection.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Telemetry; /// diff --git a/src/Microsoft.TestPlatform.Common/Telemetry/TelemetryDataConstants.cs b/src/Microsoft.TestPlatform.Common/Telemetry/TelemetryDataConstants.cs index ba3c2f8fd5..a864b79b3b 100644 --- a/src/Microsoft.TestPlatform.Common/Telemetry/TelemetryDataConstants.cs +++ b/src/Microsoft.TestPlatform.Common/Telemetry/TelemetryDataConstants.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Telemetry; /// diff --git a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs index 6917d01926..7e285db13f 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; public class AssemblyProperties : IAssemblyProperties diff --git a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs index c4c1f7275f..866986f199 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs @@ -12,8 +12,6 @@ using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; internal class AssemblyResolver : IDisposable @@ -27,7 +25,7 @@ internal class AssemblyResolver : IDisposable /// Dictionary of Assemblies discovered to date. Must be locked as it may /// be accessed in a multi-threaded context. /// - private readonly Dictionary _resolvedAssemblies; + private readonly Dictionary _resolvedAssemblies = new(); /// /// Specifies whether the resolver is disposed or not @@ -52,8 +50,6 @@ public AssemblyResolver(IEnumerable directories) { EqtTrace.Info($"AssemblyResolver.ctor: Creating AssemblyResolver with searchDirectories {string.Join(",", directories)}"); - _resolvedAssemblies = new Dictionary(); - _searchDirectories = directories == null || !directories.Any() ? new HashSet() : new HashSet(directories); _platformAssemblyResolver = new PlatformAssemblyResolver(); @@ -83,7 +79,7 @@ internal void AddSearchDirectories(IEnumerable directories) /// /// The . /// - private Assembly OnResolve(object sender, AssemblyResolveEventArgs args) + private Assembly? OnResolve(object? sender, AssemblyResolveEventArgs? args) { if (StringUtils.IsNullOrEmpty(args?.Name)) { @@ -108,7 +104,7 @@ private Assembly OnResolve(object sender, AssemblyResolveEventArgs args) return assembly; } - AssemblyName requestedName = null; + AssemblyName? requestedName = null; try { // Can throw ArgumentException, FileLoadException if arg is empty/wrong format, etc. Should not return null. diff --git a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyType.cs b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyType.cs index e13f845d27..75892e3aba 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyType.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyType.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; public enum AssemblyType diff --git a/src/Microsoft.TestPlatform.Common/Utilities/CancellationTokenExtensions.cs b/src/Microsoft.TestPlatform.Common/Utilities/CancellationTokenExtensions.cs index 2038d315b8..5c5f1df4aa 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/CancellationTokenExtensions.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/CancellationTokenExtensions.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; public static class CancellationTokenExtensions diff --git a/src/Microsoft.TestPlatform.Common/Utilities/ExceptionUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/ExceptionUtilities.cs index 1d80047362..7ed96e95b1 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/ExceptionUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/ExceptionUtilities.cs @@ -4,8 +4,6 @@ using System; using System.Text; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; /// @@ -18,7 +16,7 @@ public class ExceptionUtilities /// /// The exception. /// The formatted string message of the exception. - public static string GetExceptionMessage(Exception exception) + public static string GetExceptionMessage(Exception? exception) { if (exception == null) { diff --git a/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs index 03838e4716..c3295e3b51 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs @@ -11,8 +11,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; /// @@ -126,7 +124,7 @@ internal static void InsertOrReplaceFakesDataCollectorNode(XmlDocument runSettin { // override current settings var navigator = runSettings.CreateNavigator(); - var nodes = navigator.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); + var nodes = navigator!.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); foreach (XPathNavigator dataCollectorNavigator in nodes) { @@ -135,7 +133,7 @@ internal static void InsertOrReplaceFakesDataCollectorNode(XmlDocument runSettin if (string.Equals(FakesMetadata.DataCollectorUriV1, uri, StringComparison.OrdinalIgnoreCase) || string.Equals(FakesMetadata.DataCollectorUriV2, uri, StringComparison.OrdinalIgnoreCase)) { - dataCollectorNavigator.ReplaceSelf(settings.ToXml().CreateNavigator()); + dataCollectorNavigator.ReplaceSelf(settings.ToXml().CreateNavigator()!); return; } } @@ -174,7 +172,7 @@ and not FrameworkVersion.Framework40 return false; } - Func, string> netFrameworkConfigurator = TryGetNetFrameworkFakesDataCollectorConfigurator(); + Func, string>? netFrameworkConfigurator = TryGetNetFrameworkFakesDataCollectorConfigurator(); if (netFrameworkConfigurator == null) { return false; @@ -217,7 +215,7 @@ private static void EnsureSettingsNode(XmlDocument settings, TestRunSettings set TPDebug.Assert(settingsNode != null, "Invalid Settings Node"); TPDebug.Assert(settings != null, "Invalid Settings"); - var root = settings.DocumentElement; + var root = settings.DocumentElement!; if (root[settingsNode.Name] == null) { var newElement = settingsNode.ToXml(); @@ -226,7 +224,7 @@ private static void EnsureSettingsNode(XmlDocument settings, TestRunSettings set } } - private static Func, string> TryGetNetFrameworkFakesDataCollectorConfigurator() + private static Func, string>? TryGetNetFrameworkFakesDataCollectorConfigurator() { #if NETFRAMEWORK try @@ -247,7 +245,7 @@ private static Func, string> TryGetNetFrameworkFakesDataColl return null; } - private static Func, DataCollectorSettings> TryGetFakesCrossPlatformDataCollectorConfigurator() + private static Func, DataCollectorSettings>? TryGetFakesCrossPlatformDataCollectorConfigurator() { try { @@ -266,7 +264,8 @@ private static Func, DataCollectorSettings return null; } - private static Assembly LoadTestPlatformAssembly() + + private static Assembly? LoadTestPlatformAssembly() { try { diff --git a/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs b/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs index 358dfaa65e..2acc877874 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; public class InstallationContext diff --git a/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs b/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs index 183848a7ab..a0083b970c 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs @@ -13,8 +13,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; /* Expected attribute shape @@ -69,7 +67,7 @@ private Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAsse Assembly assemblyToAnalyze = loadedAssembly; #endif - List> extensions = null; + List>? extensions = null; using (var stream = new FileStream(assemblyFilePath, FileMode.Open, FileAccess.Read)) using (var reader = new PEReader(stream, PEStreamOptions.Default)) { @@ -78,7 +76,7 @@ private Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAsse // Search for the custom attribute TestExtensionTypesAttributeV2 - ECMA-335 II.22.10 CustomAttribute : 0x0C foreach (var customAttributeHandle in metadataReader.CustomAttributes) { - string attributeFullName = null; + string? attributeFullName = null; try { if (customAttributeHandle.IsNil) @@ -138,8 +136,8 @@ private Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAsse // string is null, its PackedLen has the value 0xFF(with no following characters).If // the string is empty(“”), then PackedLen has the value 0x00(with no following // characters). - string extension = valueReader.ReadSerializedString(); - string extensionIdentifier = valueReader.ReadSerializedString(); + string? extension = valueReader.ReadSerializedString(); + string? extensionIdentifier = valueReader.ReadSerializedString(); // If the parameter kind is System.Type, (also, the middle line in above diagram) its // value is stored as a SerString(as defined in the previous paragraph), representing its @@ -148,7 +146,7 @@ private Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAsse // assembly name is omitted, the CLI looks first in the current assembly, and then in // the system library(mscorlib); in these two special cases, it is permitted to omit the // assembly-name, version, culture and public-key-token. - string extensionImplementation = valueReader.ReadSerializedString(); + string? extensionImplementation = valueReader.ReadSerializedString(); // If the parameter kind is simple(first line in the above diagram) (bool, char, float32, // float64, int8, int16, int32, int64, unsigned int8, unsigned int16, unsigned int32 or @@ -159,6 +157,7 @@ private Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAsse int version = valueReader.ReadInt32(); try { + TPDebug.Assert(extensionImplementation is not null, "extensionImplementation is null"); var extensionType = assemblyToAnalyze.GetType(extensionImplementation); if (extensionType is null) { @@ -187,10 +186,10 @@ private Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAsse return extensions?.OrderByDescending(t => t.Item1).Select(t => t.Item2).ToArray() ?? EmptyTypeArray; } - private string FormatException(Exception ex) + private static string FormatException(Exception ex) { StringBuilder log = new(); - Exception current = ex; + Exception? current = ex; while (current != null) { log.AppendLine(current.ToString()); diff --git a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs index a93fecdd2f..b2fb297f9e 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using Microsoft.VisualStudio.TestPlatform.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; /// @@ -73,6 +71,7 @@ public static void AddDefaultRunSettings(this IRunSettingsProvider runSettingsPr public static void UpdateRunSettingsXmlDocumentInnerXml(XmlDocument xmlDocument, string key, string data) { var node = GetXmlNode(xmlDocument, key) ?? CreateNode(xmlDocument, key); + TPDebug.Assert(node is not null, "node is null"); node.InnerXml = data; } @@ -83,7 +82,7 @@ public static void UpdateRunSettingsNode(this IRunSettingsProvider runSettingsPr ValidateArg.NotNull(data, nameof(data)); var xmlDocument = runSettingsProvider.GetRunSettingXmlDocument(); - UpdateRunSettingsXmlDocument(xmlDocument, key, data); + UpdateRunSettingsXmlDocumentInnerText(xmlDocument, key, data); runSettingsProvider.UpdateRunSettings(xmlDocument.OuterXml); } @@ -121,7 +120,7 @@ public static void UpdateTestRunParameterSettingsNode(this IRunSettingsProvider element.SetAttribute(NameString, attrName); element.SetAttribute(ValueString, attrValue); testRunParameterNode.AppendChild(element); - xmlDocument.DocumentElement.AppendChild(testRunParameterNode); + xmlDocument.DocumentElement!.AppendChild(testRunParameterNode); } runSettingsProvider.UpdateRunSettings(xmlDocument.OuterXml); @@ -131,9 +130,9 @@ private static bool TryOverrideAttributeValue(XmlNode xmlNode, string attrName, { foreach (XmlNode node in xmlNode.ChildNodes) { - if (string.Compare(node.Attributes[NameString].Value, attrName) == 0) + if (string.Compare(node.Attributes![NameString]!.Value, attrName) == 0) { - node.Attributes[ValueString].Value = attrValue; + node.Attributes[ValueString]!.Value = attrValue; return true; } } @@ -152,7 +151,7 @@ public static void UpdateRunSettingsNodeInnerXml(this IRunSettingsProvider runSe runSettingsProvider.UpdateRunSettings(xmlDocument.OuterXml); } - public static string QueryRunSettingsNode(this IRunSettingsProvider runSettingsProvider, string key) + public static string? QueryRunSettingsNode(this IRunSettingsProvider runSettingsProvider, string key) { ValidateArg.NotNull(runSettingsProvider, nameof(runSettingsProvider)); ValidateArg.NotNullOrWhiteSpace(key, nameof(key)); @@ -162,16 +161,17 @@ public static string QueryRunSettingsNode(this IRunSettingsProvider runSettingsP return node?.InnerText; } - internal static XmlNode GetXmlNode(XmlDocument xmlDocument, string key) + internal static XmlNode? GetXmlNode(XmlDocument xmlDocument, string key) { var xPath = key.Replace('.', '/'); var node = xmlDocument.SelectSingleNode(string.Format("//RunSettings/{0}", xPath)); return node; } - internal static void UpdateRunSettingsXmlDocument(XmlDocument xmlDocument, string key, string data) + internal static void UpdateRunSettingsXmlDocumentInnerText(XmlDocument xmlDocument, string key, string data) { var node = GetXmlNode(xmlDocument, key) ?? CreateNode(xmlDocument, key); + TPDebug.Assert(node is not null, "node is null"); node.InnerText = data; } @@ -195,14 +195,15 @@ private static string AddDefaultRunSettings(string runSettings) return document.OuterXml; } - private static XmlNode CreateNode(XmlDocument doc, string xPath) + private static XmlNode? CreateNode(XmlDocument doc, string xPath) { var path = xPath.Split('.'); - XmlNode node = null; - XmlNode parent = doc.DocumentElement; + XmlNode? node = null; + XmlNode? parent = doc.DocumentElement!; for (var i = 0; i < path.Length; i++) { + TPDebug.Assert(parent is not null, "parent is null"); node = parent.SelectSingleNode(path[i]) ?? parent.AppendChild(doc.CreateElement(path[i])); parent = node; } @@ -235,7 +236,7 @@ private static XmlDocument GetRunSettingXmlDocument(this IRunSettingsProvider ru using var reader = XmlReader.Create( new StringReader( - XmlRunSettingsUtilities.CreateDefaultRunSettings().CreateNavigator().OuterXml), + XmlRunSettingsUtilities.CreateDefaultRunSettings().CreateNavigator()!.OuterXml), new XmlReaderSettings() { CloseInput = true, DtdProcessing = DtdProcessing.Prohibit }); doc.Load(reader); #endif diff --git a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs index 798c37d130..ee01858b53 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs @@ -3,13 +3,12 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; /// @@ -20,11 +19,11 @@ public static class RunSettingsUtilities /// /// Create RunSettings object corresponding to settingsXml /// - public static RunSettings CreateAndInitializeRunSettings(string settingsXml) + public static RunSettings? CreateAndInitializeRunSettings(string? settingsXml) { - RunSettings settings = null; + RunSettings? settings = null; - if (!StringUtilities.IsNullOrWhiteSpace(settingsXml)) + if (!settingsXml.IsNullOrWhiteSpace()) { settings = new RunSettings(); settings.LoadSettingsXml(settingsXml); @@ -38,16 +37,16 @@ public static RunSettings CreateAndInitializeRunSettings(string settingsXml) /// /// Test run configuration /// Test results directory - public static string GetTestResultsDirectory(RunConfiguration runConfiguration) + [return: NotNullIfNotNull("runConfiguration")] + public static string? GetTestResultsDirectory(RunConfiguration? runConfiguration) { - string resultsDirectory = null; if (runConfiguration != null) { // It will try to get path from runsettings, if not found then it will return default path. - resultsDirectory = Environment.ExpandEnvironmentVariables(runConfiguration.ResultsDirectory); + return Environment.ExpandEnvironmentVariables(runConfiguration.ResultsDirectory); } - return resultsDirectory; + return null; } /// @@ -55,16 +54,16 @@ public static string GetTestResultsDirectory(RunConfiguration runConfiguration) /// /// Test run configuration /// Target Framework - public static Framework GetTargetFramework(RunConfiguration runConfiguration) + [return: NotNullIfNotNull("runConfiguration")] + public static Framework? GetTargetFramework(RunConfiguration? runConfiguration) { - Framework targetFramework = null; if (runConfiguration != null) { // It will get target framework from runsettings - targetFramework = runConfiguration.TargetFramework; + return runConfiguration.TargetFramework; } - return targetFramework; + return null; } /// @@ -72,9 +71,9 @@ public static Framework GetTargetFramework(RunConfiguration runConfiguration) /// /// Test run configuration /// Solution directory - public static string GetSolutionDirectory(RunConfiguration runConfiguration) + public static string? GetSolutionDirectory(RunConfiguration? runConfiguration) { - string solutionDirectory = null; + string? solutionDirectory = null; if (runConfiguration != null) { if (!runConfiguration.SolutionDirectory.IsNullOrEmpty()) @@ -92,7 +91,7 @@ public static string GetSolutionDirectory(RunConfiguration runConfiguration) /// /// setting xml /// Maximum CPU Count - public static int GetMaxCpuCount(string settingXml) + public static int GetMaxCpuCount(string? settingXml) { int cpuCount = Constants.DefaultCpuCount; @@ -119,7 +118,7 @@ public static int GetMaxCpuCount(string settingXml) /// /// Test run configuration /// Maximum CPU Count - public static int GetMaxCpuCount(RunConfiguration runConfiguration) + public static int GetMaxCpuCount(RunConfiguration? runConfiguration) { int cpuCount = Constants.DefaultCpuCount; @@ -135,7 +134,7 @@ public static int GetMaxCpuCount(RunConfiguration runConfiguration) /// /// Runsetting string value /// The value of TreatNoTestsAsError - public static bool GetTreatNoTestsAsError(string runSettings) + public static bool GetTreatNoTestsAsError(string? runSettings) { bool treatNoTestsAsError = false; @@ -155,7 +154,7 @@ public static bool GetTreatNoTestsAsError(string runSettings) return treatNoTestsAsError; } - private static bool GetTreatNoTestsAsError(RunConfiguration runConfiguration) + private static bool GetTreatNoTestsAsError(RunConfiguration? runConfiguration) { bool treatNoTestsAsError = false; @@ -174,7 +173,7 @@ private static bool GetTreatNoTestsAsError(RunConfiguration runConfiguration) /// Test run settings /// True to return null, if adapter paths is not set. /// Test adapters paths - public static IEnumerable GetTestAdaptersPaths(string runSettings) + public static IEnumerable GetTestAdaptersPaths(string? runSettings) { var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings); @@ -195,7 +194,7 @@ public static IEnumerable GetTestAdaptersPaths(string runSettings) /// /// Test run settings /// Test adapter loading strategy - internal static TestAdapterLoadingStrategy GetLoadingStrategy(string runSettings) + internal static TestAdapterLoadingStrategy GetLoadingStrategy(string? runSettings) { var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings); diff --git a/src/Microsoft.TestPlatform.Common/Utilities/TypesToLoadUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/TypesToLoadUtilities.cs index 31e981c111..808e36636d 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/TypesToLoadUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/TypesToLoadUtilities.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; internal static class TypesToLoadUtilities @@ -34,6 +32,7 @@ private static IEnumerable GetTypesToLoad(Attribute attribute) var type = attribute.GetType(); var typesProperty = type.GetProperty("Types"); - return typesProperty == null ? Enumerable.Empty() : typesProperty.GetValue(attribute) as Type[]; + + return typesProperty?.GetValue(attribute) as Type[] ?? Enumerable.Empty(); } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs index 8772d50d6b..fd3d7861e8 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs @@ -323,6 +323,7 @@ private void HandleBeforeTestRunStart(Message message) UpdateRequestData(payload.IsTelemetryOptedIn); AddExtensionAssemblies(payload); + TPDebug.Assert(payload.SettingsXml is not null, "payload.SettingsXml is null"); var envVariables = _dataCollectionManager.InitializeDataCollectors(payload.SettingsXml); var properties = new Dictionary diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs index 777251c439..e472ee3eba 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs @@ -21,7 +21,7 @@ namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.DataCollect internal class DataCollectionTestCaseEventHandler : IDataCollectionTestCaseEventHandler { private readonly ICommunicationManager _communicationManager; - private readonly IDataCollectionManager _dataCollectionManager; + private readonly IDataCollectionManager? _dataCollectionManager; private readonly IDataSerializer _dataSerializer; private readonly IMessageSink _messageSink; @@ -38,7 +38,7 @@ internal DataCollectionTestCaseEventHandler(IMessageSink messageSink) /// Communication manager implementation. /// Data collection manager implementation. /// Serializer for serialization and deserialization of the messages. - internal DataCollectionTestCaseEventHandler(IMessageSink messageSink, ICommunicationManager communicationManager, IDataCollectionManager dataCollectionManager, IDataSerializer dataSerializer) + internal DataCollectionTestCaseEventHandler(IMessageSink messageSink, ICommunicationManager communicationManager, IDataCollectionManager? dataCollectionManager, IDataSerializer dataSerializer) { _communicationManager = communicationManager; _dataCollectionManager = dataCollectionManager; @@ -83,6 +83,8 @@ public void ProcessRequests() try { + TPDebug.Assert(_dataCollectionManager is not null, "_dataCollectionManager is null"); + TPDebug.Assert(testCaseStartEventArgs is not null, "testCaseStartEventArgs is null"); _dataCollectionManager.TestCaseStarted(testCaseStartEventArgs); } catch (Exception ex) @@ -105,6 +107,8 @@ public void ProcessRequests() Collection attachmentSets; try { + TPDebug.Assert(_dataCollectionManager is not null, "_dataCollectionManager is null"); + TPDebug.Assert(testCaseEndEventArgs is not null, "testCaseEndEventArgs is null"); attachmentSets = _dataCollectionManager.TestCaseEnded(testCaseEndEventArgs); } catch (Exception ex) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs index 6625842ae9..2af05c6121 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs @@ -24,7 +24,7 @@ public class TestRunCriteriaWithSources /// The run settings. /// The test Execution Context. [JsonConstructor] - public TestRunCriteriaWithSources(Dictionary> adapterSourceMap, string? package, string? runSettings, TestExecutionContext? testExecutionContext) + public TestRunCriteriaWithSources(Dictionary> adapterSourceMap, string? package, string? runSettings, TestExecutionContext testExecutionContext) { AdapterSourceMap = adapterSourceMap; Package = package; @@ -45,7 +45,7 @@ public TestRunCriteriaWithSources(Dictionary> adapte /// /// Gets or sets the test execution context. /// - public TestExecutionContext? TestExecutionContext { get; set; } + public TestExecutionContext TestExecutionContext { get; set; } /// /// Gets the test Containers (e.g. .appx, .appxrecipie) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs index 069ee9566c..0dcd9c35ba 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs @@ -26,7 +26,7 @@ public class TestRunCriteriaWithTests /// The test run settings. /// The test Execution Context. [JsonConstructor] - public TestRunCriteriaWithTests(IEnumerable tests, string? package, string? runSettings, TestExecutionContext? testExecutionContext) + public TestRunCriteriaWithTests(IEnumerable tests, string? package, string? runSettings, TestExecutionContext testExecutionContext) { Tests = tests; Package = package; @@ -47,7 +47,7 @@ public TestRunCriteriaWithTests(IEnumerable tests, string? package, st /// /// Gets or sets the test execution context. /// - public TestExecutionContext? TestExecutionContext { get; set; } + public TestExecutionContext TestExecutionContext { get; set; } /// /// Gets the test Containers (e.g. .appx, .appxrecipie) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorWrapper.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorWrapper.cs index 5e65455982..7858a5293b 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorWrapper.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorWrapper.cs @@ -91,7 +91,8 @@ public bool LoadExtension(string filePath, Uri dataCollectorUri) return false; } - Type attachmentProcessorType = ((DataCollectorConfig)dataCollectorExtension.TestPluginInfo).AttachmentsProcessorType; + TPDebug.Assert(dataCollectorExtension.TestPluginInfo is not null, "dataCollectorExtension.TestPluginInfo is null"); + Type attachmentProcessorType = ((DataCollectorConfig)dataCollectorExtension.TestPluginInfo).AttachmentsProcessorType!; try { _dataCollectorAttachmentProcessorInstance = TestPluginManager.CreateTestExtension(attachmentProcessorType); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactory.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactory.cs index c357c555bc..335b055609 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactory.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactory.cs @@ -89,32 +89,32 @@ public DataCollectorAttachmentProcessor[] Create(InvokedDataCollector[]? invoked // We cache extension locally by file path var dataCollectorExtensionManager = DataCollectorExtensionManagerCache.GetOrAdd(invokedDataCollector.FilePath, DataCollectorExtensionManager.Create(invokedDataCollector.FilePath, true, TestSessionMessageLogger.Instance)); var dataCollectorExtension = dataCollectorExtensionManager.TryGetTestExtension(invokedDataCollector.Uri); - if (dataCollectorExtension?.Metadata.HasAttachmentProcessor == true) + if ((dataCollectorExtension?.Metadata.HasAttachmentProcessor) != true) { - Type attachmentProcessorType = ((DataCollectorConfig)dataCollectorExtension.TestPluginInfo).AttachmentsProcessorType; - IDataCollectorAttachmentProcessor? dataCollectorAttachmentProcessorInstance = null; - try - { - dataCollectorAttachmentProcessorInstance = TestPluginManager.CreateTestExtension(attachmentProcessorType); - EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Creation of collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}' from file '{invokedDataCollector.FilePath}' succeded"); - } - catch (Exception ex) - { - EqtTrace.Error($"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}'\n{ex}"); - logger?.SendMessage(TestMessageLevel.Error, $"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}'\n{ex}"); - } + EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: DataCollectorExtension not found for uri '{invokedDataCollector.Uri}'"); + continue; + } - var attachmentQualifiedName = attachmentProcessorType.AssemblyQualifiedName; - TPDebug.Assert(attachmentQualifiedName is not null, "attachmentQualifiedName is null"); - if (dataCollectorAttachmentProcessorInstance is not null && !datacollectorsAttachmentsProcessors.ContainsKey(attachmentQualifiedName)) - { - datacollectorsAttachmentsProcessors.Add(attachmentQualifiedName, new Tuple(dataCollectorExtension.Metadata.FriendlyName, dataCollectorAttachmentProcessorInstance)); - EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}' from file '{invokedDataCollector.FilePath}' added to the 'run list'"); - } + TPDebug.Assert(dataCollectorExtension.TestPluginInfo is not null, "dataCollectorExtension.TestPluginInfo is null"); + Type attachmentProcessorType = ((DataCollectorConfig)dataCollectorExtension.TestPluginInfo!).AttachmentsProcessorType!; + IDataCollectorAttachmentProcessor? dataCollectorAttachmentProcessorInstance = null; + try + { + dataCollectorAttachmentProcessorInstance = TestPluginManager.CreateTestExtension(attachmentProcessorType); + EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Creation of collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}' from file '{invokedDataCollector.FilePath}' succeded"); } - else + catch (Exception ex) { - EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: DataCollectorExtension not found for uri '{invokedDataCollector.Uri}'"); + EqtTrace.Error($"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}'\n{ex}"); + logger?.SendMessage(TestMessageLevel.Error, $"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}'\n{ex}"); + } + + var attachmentQualifiedName = attachmentProcessorType.AssemblyQualifiedName; + TPDebug.Assert(attachmentQualifiedName is not null, "attachmentQualifiedName is null"); + if (dataCollectorAttachmentProcessorInstance is not null && !datacollectorsAttachmentsProcessors.ContainsKey(attachmentQualifiedName)) + { + datacollectorsAttachmentsProcessors.Add(attachmentQualifiedName, new Tuple(dataCollectorExtension.Metadata.FriendlyName, dataCollectorAttachmentProcessorInstance)); + EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}' from file '{invokedDataCollector.FilePath}' added to the 'run list'"); } } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs index 692efcdc14..60e361786a 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs @@ -143,7 +143,7 @@ public void Close() #region IParallelProxyDiscoveryManager methods /// - public bool HandlePartialDiscoveryComplete(IProxyDiscoveryManager proxyDiscoveryManager, long totalTests, IEnumerable lastChunk, bool isAborted) + public bool HandlePartialDiscoveryComplete(IProxyDiscoveryManager proxyDiscoveryManager, long totalTests, IEnumerable? lastChunk, bool isAborted) { #if DEBUG // Ensures that the total count of sources remains the same between each discovery diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs index f34712c309..52bbc709ed 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs @@ -361,7 +361,7 @@ private static string GetTimestampedLogFile(string logFile) extensionsFolder = string.Concat(tapNode.InnerText, ';', extensionsFolder); } - RunSettingsProviderExtensions.UpdateRunSettingsXmlDocument(document, "RunConfiguration.TestAdaptersPaths", extensionsFolder); + RunSettingsProviderExtensions.UpdateRunSettingsXmlDocumentInnerText(document, "RunConfiguration.TestAdaptersPaths", extensionsFolder); return document.OuterXml; } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs index a774a90433..add9534264 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs @@ -95,7 +95,7 @@ public DiscovererEnumerator(IRequestData requestData, /// The settings. /// The test case filter. /// The logger. - public void LoadTests(IDictionary> testExtensionSourceMap, IRunSettings settings, string? testCaseFilter, IMessageLogger logger) + public void LoadTests(IDictionary> testExtensionSourceMap, IRunSettings? settings, string? testCaseFilter, IMessageLogger logger) { _testPlatformEventSource.DiscoveryStart(); try @@ -121,7 +121,7 @@ public void LoadTests(IDictionary> testExtensionSour /// The settings. /// The test case filter. /// The logger. - private void LoadTestsFromAnExtension(string extensionAssembly, IEnumerable sources, IRunSettings settings, string? testCaseFilter, IMessageLogger logger) + private void LoadTestsFromAnExtension(string extensionAssembly, IEnumerable sources, IRunSettings? settings, string? testCaseFilter, IMessageLogger logger) { // Stopwatch to collect metrics var timeStart = DateTime.UtcNow; @@ -293,8 +293,8 @@ private static bool TryToLoadDiscoverer(LazyExtension discoverer) { - if (CrossPlatEngine.Constants.DefaultAdapters.Contains(discoverer.Metadata.DefaultExecutorUri.ToString(), - StringComparer.OrdinalIgnoreCase)) + TPDebug.Assert(discoverer.Metadata.DefaultExecutorUri is not null, "discoverer.Metadata.DefaultExecutorUri is null"); + if (Constants.DefaultAdapters.Contains(discoverer.Metadata.DefaultExecutorUri.ToString(), StringComparer.OrdinalIgnoreCase)) { return false; } @@ -302,7 +302,7 @@ private static bool IsDiscovererFromDeprecatedLocations( var discovererLocation = discoverer.Value.GetType().GetTypeInfo().Assembly.GetAssemblyLocation(); return Path.GetDirectoryName(discovererLocation)! - .Equals(CrossPlatEngine.Constants.DefaultAdapterLocation, StringComparison.OrdinalIgnoreCase); + .Equals(Constants.DefaultAdapterLocation, StringComparison.OrdinalIgnoreCase); } private static void LogWarningOnNoTestsDiscovered(IEnumerable sources, string? testCaseFilter, IMessageLogger logger) @@ -329,7 +329,7 @@ private static void LogWarningOnNoTestsDiscovered(IEnumerable sources, s } } - private void SetAdapterLoggingSettings(IMessageLogger messageLogger, IRunSettings runSettings) + private static void SetAdapterLoggingSettings(IMessageLogger messageLogger, IRunSettings? runSettings) { if (messageLogger is TestSessionMessageLogger discoveryMessageLogger && runSettings != null) { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscoveryManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscoveryManager.cs index f7e333a6c9..790bbfc12a 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscoveryManager.cs @@ -69,7 +69,7 @@ protected DiscoveryManager(IRequestData requestData, ITestPlatformEventSource te /// Initializes the discovery manager. /// /// The path to additional extensions. - public void Initialize(IEnumerable? pathToAdditionalExtensions, ITestDiscoveryEventsHandler2 eventHandler) + public void Initialize(IEnumerable? pathToAdditionalExtensions, ITestDiscoveryEventsHandler2? eventHandler) { // Clear the request data metrics left over from a potential previous run. _requestData.MetricsCollection?.Metrics?.Clear(); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs index 28be7e59bf..7df4ee456c 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs @@ -14,7 +14,7 @@ internal interface IPathConverter { string? UpdatePath(string? path, PathConversionDirection updateDirection); - IEnumerable UpdatePaths(IEnumerable paths, PathConversionDirection updateDirection); + IEnumerable UpdatePaths(IEnumerable paths, PathConversionDirection updateDirection); TestCase UpdateTestCase(TestCase testCase, PathConversionDirection updateDirection); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs index 6aba702f6c..1db65b3bbb 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs @@ -26,7 +26,7 @@ private NullPathConverter() { } string? IPathConverter.UpdatePath(string? path, PathConversionDirection _) => path; - IEnumerable IPathConverter.UpdatePaths(IEnumerable paths, PathConversionDirection _) => paths; + IEnumerable IPathConverter.UpdatePaths(IEnumerable paths, PathConversionDirection _) => paths; TestCase IPathConverter.UpdateTestCase(TestCase testCase, PathConversionDirection _) => testCase; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs index 148f554f2a..bcf270600c 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs @@ -69,10 +69,10 @@ public PathConverter(string originalPath, string deploymentPath, IFileHelper fil return result; } - public IEnumerable UpdatePaths(IEnumerable paths, PathConversionDirection updateDirection) + public IEnumerable UpdatePaths(IEnumerable paths, PathConversionDirection updateDirection) { ValidateArg.NotNull(paths, nameof(paths)); - return paths.Select(i => UpdatePath(i, updateDirection)).ToList(); + return paths.Select(p => UpdatePath(p, updateDirection)).ToList(); } public TestCase UpdateTestCase(TestCase testCase, PathConversionDirection updateDirection) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs index 3c54829f76..6085055b78 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs @@ -427,7 +427,7 @@ public void OnMessageReceived(object? sender, MessageReceivedEventArgs messageRe { _testHostManagerFactoryReady.Wait(); var testInitializeEventsHandler = new TestInitializeEventsHandler(this); - var pathToAdditionalExtensions = _dataSerializer.DeserializePayload>(message); + var pathToAdditionalExtensions = _dataSerializer.DeserializePayload>(message); TPDebug.Assert(pathToAdditionalExtensions is not null, "pathToAdditionalExtensions is null"); pathToAdditionalExtensions = _pathConverter.UpdatePaths(pathToAdditionalExtensions, PathConversionDirection.Receive); Action job = () => diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/ExecutionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/ExecutionManager.cs index dfef658b2c..a8a53fefa7 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/ExecutionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/ExecutionManager.cs @@ -61,7 +61,7 @@ protected ExecutionManager(ITestPlatformEventSource testPlatformEventSource, IRe /// Initializes the execution manager. /// /// The path to additional extensions. - public void Initialize(IEnumerable? pathToAdditionalExtensions, ITestMessageEventHandler testMessageEventsHandler) + public void Initialize(IEnumerable? pathToAdditionalExtensions, ITestMessageEventHandler? testMessageEventsHandler) { // Clear the request data metrics left over from a potential previous run. _requestData.MetricsCollection?.Metrics?.Clear(); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs index 654976ead2..162441b0b0 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs @@ -221,9 +221,9 @@ protected override void SendSessionStart() return; } - var properties = new Dictionary + var properties = new Dictionary { - { "TestSources", TestSourcesUtility.GetSources(_adapterSourceMap!) } + { "TestSources", TestSourcesUtility.GetSources(_adapterSourceMap!)! } }; _testCaseEventsHandler.SendSessionStart(properties); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs index bab406d8eb..b5026a8952 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs @@ -103,9 +103,9 @@ protected override void SendSessionStart() return; } - var properties = new Dictionary + var properties = new Dictionary { - { "TestSources", TestSourcesUtility.GetSources(_testCases) } + { "TestSources", TestSourcesUtility.GetSources(_testCases)! } }; _testCaseEventsHandler.SendSessionStart(properties); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/TestExtensionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/TestExtensionManager.cs index 2f046c4f69..6a3e9df5ed 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/TestExtensionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/TestExtensionManager.cs @@ -20,7 +20,7 @@ public void ClearExtensions() } /// - public void UseAdditionalExtensions(IEnumerable pathToAdditionalExtensions, bool skipExtensionFilters) + public void UseAdditionalExtensions(IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters) { TestPluginCache.Instance.UpdateExtensions(pathToAdditionalExtensions, skipExtensionFilters); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionSink.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionSink.cs index 710ad80b49..bb55a6e855 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionSink.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionSink.cs @@ -3,8 +3,6 @@ using System.ComponentModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -22,7 +20,7 @@ protected DataCollectionSink() /// /// Called when sending of a file has completed. /// - public abstract event AsyncCompletedEventHandler SendFileCompleted; + public abstract event AsyncCompletedEventHandler? SendFileCompleted; /// /// Sends a file to up-stream components. diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs index c4fadb393f..22d55f52f3 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs @@ -25,7 +25,8 @@ public sealed class SessionStartEventArgs : DataCollectionEventArgs /// Default constructor with empty properties and default DataCollectionContext. /// DataCollectionContext with empty session signifies that is it irrelevant in the current context. /// - public SessionStartEventArgs() : this(new DataCollectionContext(new SessionId(Guid.Empty)), new Dictionary()) + public SessionStartEventArgs() + : this(new DataCollectionContext(new SessionId(Guid.Empty)), new Dictionary()) { } @@ -37,7 +38,8 @@ public sealed class SessionStartEventArgs : DataCollectionEventArgs /// constructor with properties and default DataCollectionContext. /// DataCollectionContext with empty session signifies that is it irrelevant in the current context. /// - public SessionStartEventArgs(IDictionary properties) : this(new DataCollectionContext(new SessionId(Guid.Empty)), properties) + public SessionStartEventArgs(IDictionary properties) + : this(new DataCollectionContext(new SessionId(Guid.Empty)), properties) { } diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Runtime/IAssemblyResolver.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Runtime/IAssemblyResolver.cs index 98d677c8b8..10ab276d2b 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Runtime/IAssemblyResolver.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Runtime/IAssemblyResolver.cs @@ -14,7 +14,7 @@ namespace Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces; /// The assembly that resolves the type, assembly, or resource; or null if the assembly /// cannot be resolved. /// -public delegate Assembly AssemblyResolveEventHandler(object? sender, AssemblyResolveEventArgs? args); +public delegate Assembly? AssemblyResolveEventHandler(object? sender, AssemblyResolveEventArgs? args); /// /// The AssemblyResolver interface. diff --git a/src/vstest.console/CommandLine/GenerateFakesUtilities.cs b/src/vstest.console/CommandLine/GenerateFakesUtilities.cs index 596c1e8cdb..89e971ecc3 100644 --- a/src/vstest.console/CommandLine/GenerateFakesUtilities.cs +++ b/src/vstest.console/CommandLine/GenerateFakesUtilities.cs @@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.TestPlatform.CommandLineUtilities; public static class GenerateFakesUtilities { - internal static void GenerateFakesSettings(CommandLineOptions? commandLineOptions, IEnumerable sources, ref string runSettingsXml) + internal static void GenerateFakesSettings(CommandLineOptions? commandLineOptions, IEnumerable sources, ref string runSettingsXml) { // dynamically compute the fakes datacollector settings // This runs with or without design mode. diff --git a/src/vstest.console/CommandLine/InferHelper.cs b/src/vstest.console/CommandLine/InferHelper.cs index 1e105985e7..d7134ee027 100644 --- a/src/vstest.console/CommandLine/InferHelper.cs +++ b/src/vstest.console/CommandLine/InferHelper.cs @@ -23,7 +23,7 @@ internal InferHelper(IAssemblyMetadataProvider assemblyMetadataProvider) /// /// Determines Architecture from sources. /// - public Architecture AutoDetectArchitecture(IList? sources, Architecture defaultArchitecture, out IDictionary sourceToPlatformMap) + public Architecture AutoDetectArchitecture(IList? sources, Architecture defaultArchitecture, out IDictionary sourceToPlatformMap) { sourceToPlatformMap = new Dictionary(); if (sources == null || sources.Count == 0) diff --git a/src/vstest.console/Processors/CollectArgumentProcessor.cs b/src/vstest.console/Processors/CollectArgumentProcessor.cs index a4bc735f71..c795a2f530 100644 --- a/src/vstest.console/Processors/CollectArgumentProcessor.cs +++ b/src/vstest.console/Processors/CollectArgumentProcessor.cs @@ -105,7 +105,7 @@ public void Initialize(string? argument) throw new CommandLineException(exceptionMessage); } - if (InferRunSettingsHelper.IsTestSettingsEnabled(_runSettingsManager.ActiveRunSettings.SettingsXml)) + if (InferRunSettingsHelper.IsTestSettingsEnabled(_runSettingsManager.ActiveRunSettings?.SettingsXml)) { throw new SettingsException(string.Format(CommandLineResources.CollectWithTestSettingErrorMessage, argument)); } @@ -117,7 +117,7 @@ public void Initialize(string? argument) /// private static string? GetCoverletCodeBasePath(IRunSettingsProvider runSettingProvider, IFileHelper fileHelper) { - foreach (string adapterPath in RunSettingsUtilities.GetTestAdaptersPaths(runSettingProvider.ActiveRunSettings.SettingsXml)) + foreach (string adapterPath in RunSettingsUtilities.GetTestAdaptersPaths(runSettingProvider.ActiveRunSettings?.SettingsXml)) { string collectorPath = Path.Combine(adapterPath, CoverletConstants.CoverletDataCollectorCodebase); if (fileHelper.Exists(collectorPath)) diff --git a/src/vstest.console/Processors/EnvironmentArgumentProcessor.cs b/src/vstest.console/Processors/EnvironmentArgumentProcessor.cs index 0345992a12..0c5c773a5e 100644 --- a/src/vstest.console/Processors/EnvironmentArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnvironmentArgumentProcessor.cs @@ -85,7 +85,7 @@ public void Initialize(string? argument) TPDebug.Assert(!StringUtils.IsNullOrWhiteSpace(argument)); TPDebug.Assert(_output != null); TPDebug.Assert(_commandLineOptions != null); - TPDebug.Assert(!StringUtils.IsNullOrWhiteSpace(_runSettingsProvider.ActiveRunSettings.SettingsXml)); + TPDebug.Assert(!StringUtils.IsNullOrWhiteSpace(_runSettingsProvider.ActiveRunSettings?.SettingsXml)); var key = argument; var value = string.Empty; diff --git a/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs b/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs index 76d577250b..3799927b25 100644 --- a/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs @@ -181,7 +181,7 @@ public ArgumentProcessorResult Execute() TPDebug.Assert(Output != null); TPDebug.Assert(_commandLineOptions != null); TPDebug.Assert(_testRequestManager != null); - TPDebug.Assert(!_runSettingsManager.ActiveRunSettings.SettingsXml.IsNullOrWhiteSpace()); + TPDebug.Assert(!StringUtils.IsNullOrWhiteSpace(_runSettingsManager.ActiveRunSettings?.SettingsXml)); if (!_commandLineOptions.Sources.Any()) { @@ -366,6 +366,7 @@ private void TestRunRequest_OnRunCompletion(object sender, TestRunCompleteEventA // Collect tests session artifacts for post processing if (_commandLineOptions.ArtifactProcessingMode == ArtifactProcessingMode.Collect) { + TPDebug.Assert(RunSettingsManager.Instance.ActiveRunSettings.SettingsXml is not null, "RunSettingsManager.Instance.ActiveRunSettings.SettingsXml is null"); _artifactProcessingManager.CollectArtifacts(e, RunSettingsManager.Instance.ActiveRunSettings.SettingsXml); } } diff --git a/src/vstest.console/Processors/RunTestsArgumentProcessor.cs b/src/vstest.console/Processors/RunTestsArgumentProcessor.cs index ce85086351..27fe174735 100644 --- a/src/vstest.console/Processors/RunTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunTestsArgumentProcessor.cs @@ -228,6 +228,7 @@ private void TestRunRequest_OnRunCompletion(object sender, TestRunCompleteEventA // Collect tests session artifacts for post processing if (_commandLineOptions.ArtifactProcessingMode == ArtifactProcessingMode.Collect) { + TPDebug.Assert(RunSettingsManager.Instance.ActiveRunSettings.SettingsXml is not null, "RunSettingsManager.Instance.ActiveRunSettings.SettingsXml is null"); _artifactProcessingManager.CollectArtifacts(e, RunSettingsManager.Instance.ActiveRunSettings.SettingsXml); } } diff --git a/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs b/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs index e1d2b35d2b..f18af53704 100644 --- a/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs +++ b/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs @@ -167,7 +167,7 @@ public ArgumentProcessorResult Execute() /// /// Source paths joined by semicolons. /// Paths. - internal static string[] SplitPaths(string paths) + internal static string[] SplitPaths(string? paths) { return paths.IsNullOrWhiteSpace() ? new string[0] : paths.Split(ArgumentSeparators, StringSplitOptions.RemoveEmptyEntries); } diff --git a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs index 634ebd39b5..956da011f4 100644 --- a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs +++ b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs @@ -280,7 +280,7 @@ public void RunTests( if (UpdateRunSettingsIfRequired( runsettings, - sources, + sources!, testRunEventsRegistrar, out string updatedRunsettings, out IDictionary sourceToArchitectureMap, @@ -574,7 +574,7 @@ public void StopTestSession( } } - private void LogTelemetryForLegacySettings(IRequestData requestData, string runsettings) + private static void LogTelemetryForLegacySettings(IRequestData requestData, string runsettings) { requestData.MetricsCollection.Add( TelemetryDataConstants.TestSettingsUsed, @@ -651,7 +651,7 @@ private void Dispose(bool disposing) private bool UpdateRunSettingsIfRequired( string runsettingsXml, - IList? sources, + IList? sources, IBaseTestEventsRegistrar? registrar, out string updatedRunSettingsXml, out IDictionary sourceToArchitectureMap, @@ -679,7 +679,7 @@ private bool UpdateRunSettingsIfRequired( var frameworkWasAutodetected = UpdateFrameworkInRunSettingsIfRequired( document, navigator, - sources, + sources!, registrar, out Framework chosenFramework, out sourceToFrameworkMap); @@ -927,7 +927,7 @@ private bool UpdateDesignMode(XmlDocument document, RunConfiguration runConfigur return updateRequired; } - private void CheckSourcesForCompatibility( + private static void CheckSourcesForCompatibility( Framework chosenFramework, Architecture chosenPlatform, Architecture defaultArchitecture, @@ -959,7 +959,7 @@ private void CheckSourcesForCompatibility( private bool UpdatePlatform( XmlDocument document, XPathNavigator navigator, - IList? sources, + IList? sources, Architecture defaultArchitecture, out Architecture commonPlatform, out IDictionary sourceToPlatformMap) @@ -1058,7 +1058,7 @@ private static void WriteWarningForNetFramework35IsUnsupported(IBaseTestEventsRe /// /// Runsettings document. /// Logger run settings. - private void AddConsoleLogger(XmlDocument document, LoggerRunSettings loggerRunSettings) + private static void AddConsoleLogger(XmlDocument document, LoggerRunSettings loggerRunSettings) { var consoleLogger = new LoggerSettings { @@ -1082,7 +1082,7 @@ private void AddConsoleLogger(XmlDocument document, LoggerRunSettings loggerRunS /// Runsettings document. /// Logger run settings. /// True if updated console logger in runsettings successfully. - private bool UpdateConsoleLoggerIfExists( + private static bool UpdateConsoleLoggerIfExists( XmlDocument document, LoggerRunSettings loggerRunSettings) { @@ -1245,7 +1245,7 @@ private bool IsPlatformSetByRunSettings( /// /// Request data for common Discovery/Execution services. /// Run configuration. - private void CollectMetrics(IRequestData requestData, RunConfiguration runConfiguration) + private static void CollectMetrics(IRequestData requestData, RunConfiguration runConfiguration) { // Collecting Target Framework. requestData.MetricsCollection.Add( @@ -1400,10 +1400,10 @@ private IRequestData GetRequestData(ProtocolConfig protocolConfig) }; } - private static List GetSources(TestRunRequestPayload testRunRequestPayload) + private static List GetSources(TestRunRequestPayload testRunRequestPayload) { // TODO: This should also use hashset to only return distinct sources. - List sources = new(); + List sources = new(); if (testRunRequestPayload.Sources != null && testRunRequestPayload.Sources.Count > 0) { @@ -1412,7 +1412,7 @@ private IRequestData GetRequestData(ProtocolConfig protocolConfig) else if (testRunRequestPayload.TestCases != null && testRunRequestPayload.TestCases.Count > 0) { - ISet sourcesSet = new HashSet(); + ISet sourcesSet = new HashSet(); foreach (var testCase in testRunRequestPayload.TestCases) { sourcesSet.Add(testCase.Source); diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs index b81ab0551c..9e62fcbffd 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs @@ -84,16 +84,6 @@ public void TestRunMessageHandlerShouldCallCommmunicationManagerIfMessageisWarni _mockCommunicationManager.Verify(cm => cm.SendMessage(It.IsAny(), It.IsAny()), Times.Once()); } - [TestMethod] - public void TestRunMessageHandlerShouldNotCallCommmunicationManagerIfMessageisInformational() - { - _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny())); - - _designModeClient.TestRunMessageHandler(new object(), new TestRunMessageEventArgs(TestMessageLevel.Informational, "message")); - - _mockCommunicationManager.Verify(cm => cm.SendMessage(It.IsAny(), It.IsAny()), Times.Never()); - } - [TestMethod] public void DesignModeClientConnectShouldSetupChannel() { diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/DataCollectorExtensionManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/DataCollectorExtensionManagerTests.cs index 11fc225329..4422bceb8e 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/DataCollectorExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/DataCollectorExtensionManagerTests.cs @@ -24,7 +24,7 @@ public void CreateShouldThrowExceptionIfMessageLoggerIsNull() { Assert.ThrowsException(() => { - var dataCollectionExtensionManager = DataCollectorExtensionManager.Create(null); + var dataCollectionExtensionManager = DataCollectorExtensionManager.Create(null!); }); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestDiscoveryExtensionManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestDiscoveryExtensionManagerTests.cs index 3e94df02e4..216bf9e494 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestDiscoveryExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestDiscoveryExtensionManagerTests.cs @@ -116,7 +116,7 @@ public void TestDiscovererMetadataCtorSetsFileExtensions() var extensions = new List { "csv", "dll" }; var metadata = new TestDiscovererMetadata(extensions, null); - CollectionAssert.AreEqual(extensions, metadata.FileExtension.ToList()); + CollectionAssert.AreEqual(extensions, metadata.FileExtension!.ToList()); } [TestMethod] @@ -124,7 +124,7 @@ public void TestDiscovererMetadataCtorSetsDefaultUri() { var metadata = new TestDiscovererMetadata(null, "executor://helloworld"); - Assert.AreEqual("executor://helloworld/", metadata.DefaultExecutorUri.AbsoluteUri); + Assert.AreEqual("executor://helloworld/", metadata.DefaultExecutorUri!.AbsoluteUri); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestExtensionManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestExtensionManagerTests.cs index ece1cadd0e..f31173f945 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestExtensionManagerTests.cs @@ -62,7 +62,7 @@ public void TryGetTestExtensionShouldThrowExceptionWithNullUri() TestPluginCacheHelper.SetupMockAdditionalPathExtensions(typeof(TestExtensionManagerTests)); Assert.ThrowsException(() => { - var result = _testExtensionManager.TryGetTestExtension(default(Uri)); + var result = _testExtensionManager.TryGetTestExtension(default(Uri)!); } ); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestLoggerExtensionManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestLoggerExtensionManagerTests.cs index 1907bfb290..e6990a0641 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestLoggerExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestLoggerExtensionManagerTests.cs @@ -24,7 +24,7 @@ public void CreateShouldThrowExceptionIfMessageLoggerIsNull() { Assert.ThrowsException(() => { - var testLoggerExtensionManager = TestLoggerExtensionManager.Create(null); + var testLoggerExtensionManager = TestLoggerExtensionManager.Create(null!); }); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs index 1f1a079610..277f2d68e3 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs @@ -250,7 +250,7 @@ public void GetDefaultResolutionPathsShouldReturnDirectoryFromDefaultExtensionsP var resolutionPaths = TestPluginCache.Instance.GetDefaultResolutionPaths(); Assert.IsNotNull(resolutionPaths); - Assert.IsTrue(resolutionPaths.Contains(Path.GetDirectoryName(defaultExtensionsFile))); + Assert.IsTrue(resolutionPaths.Contains(Path.GetDirectoryName(defaultExtensionsFile)!)); } #endregion @@ -260,7 +260,7 @@ public void GetDefaultResolutionPathsShouldReturnDirectoryFromDefaultExtensionsP [TestMethod] public void GetResolutionPathsShouldThrowIfExtensionAssemblyIsNull() { - Assert.ThrowsException(() => TestPluginCache.Instance.GetResolutionPaths(null)); + Assert.ThrowsException(() => TestPluginCache.Instance.GetResolutionPaths(null!)); } [TestMethod] @@ -299,7 +299,7 @@ public void GetTestExtensionsShouldReturnExtensionsInAssembly() TestPluginCache.Instance.GetTestExtensions(typeof(TestPluginCacheTests).GetTypeInfo().Assembly.Location); Assert.IsNotNull(TestPluginCache.Instance.TestExtensions); - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestDiscoverers.Count > 0); + Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestDiscoverers!.Count > 0); } [TestMethod] @@ -309,8 +309,9 @@ public void GetTestExtensionsShouldAddTestExtensionsDiscoveredToCache() var testDiscovererPluginInfos = _testablePluginCache.GetTestExtensions(extensionAssembly); + Assert.IsNotNull(_testablePluginCache.TestExtensions); CollectionAssert.AreEqual( - _testablePluginCache.TestExtensions.TestDiscoverers.Keys, + _testablePluginCache.TestExtensions.TestDiscoverers!.Keys, testDiscovererPluginInfos.Keys); } @@ -322,7 +323,7 @@ public void GetTestExtensionsShouldGetTestExtensionsFromCache() Assert.IsFalse(testDiscovererPluginInfos.ContainsKey("td")); // Set the cache. - _testablePluginCache.TestExtensions.TestDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestPluginCacheTests))); + _testablePluginCache.TestExtensions!.TestDiscoverers!.Add("td", new TestDiscovererPluginInformation(typeof(TestPluginCacheTests))); testDiscovererPluginInfos = _testablePluginCache.GetTestExtensions(extensionAssembly); Assert.IsTrue(testDiscovererPluginInfos.ContainsKey("td")); @@ -352,7 +353,7 @@ public void DiscoverTestExtensionsShouldDiscoverExtensionsFromExtensionsFolder() Assert.IsNotNull(TestPluginCache.Instance.TestExtensions); // Validate the discoverers to be absolutely certain. - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestDiscoverers.Count > 0); + Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestDiscoverers!.Count > 0); } [TestMethod] @@ -362,7 +363,7 @@ public void DiscoverTestExtensionsShouldSetCachedBoolToTrue() TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.AreTestDiscoverersCached); + Assert.IsTrue(TestPluginCache.Instance.TestExtensions!.AreTestDiscoverersCached); Assert.IsTrue(TestPluginCache.Instance.TestExtensions.AreTestExtensionsCached()); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs index a1f9cfbcf1..4821050ff3 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs @@ -50,7 +50,7 @@ public void GetTestExtensionsInformationShouldNotConsiderAbstractClasses() // The below should not throw an exception. var testExtensions = _testPluginDiscoverer.GetTestExtensionsInformation(pathToExtensions); var discovererPluginInformation = new TestDiscovererPluginInformation(typeof(AbstractTestDiscoverer)); - Assert.IsFalse(testExtensions.ContainsKey(discovererPluginInformation.IdentifierData)); + Assert.IsFalse(testExtensions.ContainsKey(discovererPluginInformation.IdentifierData!)); } [TestMethod] @@ -64,8 +64,8 @@ public void GetTestExtensionsInformationShouldReturnDiscovererExtensions() var discovererPluginInformation = new TestDiscovererPluginInformation(typeof(ValidDiscoverer)); var discovererPluginInformation2 = new TestDiscovererPluginInformation(typeof(ValidDiscoverer2)); - Assert.IsTrue(testExtensions.ContainsKey(discovererPluginInformation.IdentifierData)); - Assert.IsTrue(testExtensions.ContainsKey(discovererPluginInformation2.IdentifierData)); + Assert.IsTrue(testExtensions.ContainsKey(discovererPluginInformation.IdentifierData!)); + Assert.IsTrue(testExtensions.ContainsKey(discovererPluginInformation2.IdentifierData!)); } [TestMethod] @@ -80,8 +80,8 @@ public void GetTestExtensionsInformationShouldReturnExecutorExtensions() var pluginInformation2 = new TestExecutorPluginInformation(typeof(ValidExecutor2)); Assert.AreEqual(2, testExtensions.Keys.Count(k => k.Contains("ValidExecutor"))); - Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData)); - Assert.IsTrue(testExtensions.ContainsKey(pluginInformation2.IdentifierData)); + Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData!)); + Assert.IsTrue(testExtensions.ContainsKey(pluginInformation2.IdentifierData!)); } [TestMethod] @@ -96,8 +96,7 @@ public void GetTestExtensionsInformationShouldReturnLoggerExtensions() var pluginInformation2 = new TestLoggerPluginInformation(typeof(ValidLogger2)); Assert.AreEqual(1, testExtensions.Keys.Count(k => k.Contains("csv"))); - Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData)); - Assert.IsTrue(testExtensions.ContainsKey(pluginInformation2.IdentifierData)); + Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData!)); } [TestMethod] @@ -127,8 +126,8 @@ public void GetTestExtensionsInformationShouldReturnSettingsProviderExtensions() var pluginInformation2 = new TestSettingsProviderPluginInformation(typeof(ValidSettingsProvider2)); Assert.IsTrue(testExtensions.Keys.Select(k => k.Contains("ValidSettingsProvider")).Count() >= 3); - Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData)); - Assert.IsTrue(testExtensions.ContainsKey(pluginInformation2.IdentifierData)); + Assert.IsTrue(testExtensions.ContainsKey(pluginInformation.IdentifierData!)); + Assert.IsTrue(testExtensions.ContainsKey(pluginInformation2.IdentifierData!)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs index db4885ae36..d057f27cac 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs @@ -25,7 +25,7 @@ public class TestPluginManagerTests [TestMethod] public void GetTestExtensionTypeShouldReturnExtensionType() { - var type = TestPluginManager.GetTestExtensionType(typeof(TestPluginManagerTests).AssemblyQualifiedName); + var type = TestPluginManager.GetTestExtensionType(typeof(TestPluginManagerTests).AssemblyQualifiedName!); Assert.AreEqual(typeof(TestPluginManagerTests), type); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/LazyExtensionTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/LazyExtensionTests.cs index b37104ea20..28cb1041f5 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/LazyExtensionTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/LazyExtensionTests.cs @@ -77,10 +77,7 @@ public void MetadataShouldReturnMetadataSpecified() { var testDiscovererPluginInfo = new TestDiscovererPluginInformation(typeof(DummyExtension)); var mockMetadata = new Mock(); - LazyExtension extension = - new( - testDiscovererPluginInfo, - mockMetadata.Object); + LazyExtension extension = new(testDiscovererPluginInfo, mockMetadata.Object); Assert.AreEqual(mockMetadata.Object, extension.Metadata); } @@ -89,17 +86,14 @@ public void MetadataShouldReturnMetadataSpecified() public void MetadataShouldCreateMetadataFromMetadataType() { var testDiscovererPluginInfo = new TestDiscovererPluginInformation(typeof(DummyExtension)); - LazyExtension extension = - new( - testDiscovererPluginInfo, - typeof(DummyDiscovererCapability)); + LazyExtension extension = new(testDiscovererPluginInfo, typeof(DummyDiscovererCapability)); var metadata = extension.Metadata; Assert.IsNotNull(metadata); Assert.AreEqual(typeof(DummyDiscovererCapability), metadata.GetType()); - CollectionAssert.AreEqual(new List { "csv" }, (metadata as ITestDiscovererCapabilities).FileExtension.ToArray()); - Assert.AreEqual("executor://unittestexecutor/", (metadata as ITestDiscovererCapabilities).DefaultExecutorUri.AbsoluteUri); - Assert.AreEqual(AssemblyType.Native, (metadata as ITestDiscovererCapabilities).AssemblyType); + CollectionAssert.AreEqual(new List { "csv" }, metadata.FileExtension!.ToArray()); + Assert.AreEqual("executor://unittestexecutor/", metadata.DefaultExecutorUri!.AbsoluteUri); + Assert.AreEqual(AssemblyType.Native, metadata.AssemblyType); } #endregion diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs index d897e94cdd..d7e4575f31 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs @@ -34,21 +34,21 @@ public void UpdateRunSettingsShouldUpdateGivenSettingsXml() _runSettingsProvider.UpdateRunSettings(runSettingsXml); - StringAssert.Contains(_runSettingsProvider.ActiveRunSettings.SettingsXml, runSettingsXml); + StringAssert.Contains(_runSettingsProvider.ActiveRunSettings!.SettingsXml, runSettingsXml); } [TestMethod] public void UpdateRunSettingsShouldThrownExceptionIfRunSettingsProviderIsNull() { Assert.ThrowsException( - () => RunSettingsProviderExtensions.UpdateRunSettings(null, "")); + () => RunSettingsProviderExtensions.UpdateRunSettings(null!, "")); } [TestMethod] public void UpdateRunSettingsShouldThrownExceptionIfSettingsXmlIsNull() { Assert.ThrowsException( - () => _runSettingsProvider.UpdateRunSettings(null)); + () => _runSettingsProvider.UpdateRunSettings(null!)); } [TestMethod] @@ -64,7 +64,7 @@ public void AddDefaultRunSettingsShouldSetDefaultSettingsForEmptySettings() _runSettingsProvider.AddDefaultRunSettings(); var runConfiguration = - XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings.SettingsXml); + XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings!.SettingsXml); Assert.AreEqual(runConfiguration.ResultsDirectory, Constants.DefaultResultsDirectory); Assert.AreEqual(runConfiguration.TargetFramework.ToString(), Framework.DefaultFramework.ToString()); Assert.AreEqual(runConfiguration.TargetPlatform, Constants.DefaultPlatform); @@ -83,7 +83,7 @@ public void AddDefaultRunSettingsShouldAddUnspecifiedSettings() _runSettingsProvider.AddDefaultRunSettings(); var runConfiguration = - XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings.SettingsXml); + XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings!.SettingsXml); Assert.AreEqual(runConfiguration.ResultsDirectory, Constants.DefaultResultsDirectory); Assert.AreEqual(runConfiguration.TargetFramework.ToString(), Framework.DefaultFramework.ToString()); } @@ -100,7 +100,7 @@ public void AddDefaultRunSettingsShouldNotChangeSpecifiedSettings() _runSettingsProvider.AddDefaultRunSettings(); var runConfiguration = - XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings.SettingsXml); + XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings!.SettingsXml); Assert.AreEqual(runConfiguration.TargetPlatform, Architecture.X64); } @@ -108,14 +108,14 @@ public void AddDefaultRunSettingsShouldNotChangeSpecifiedSettings() public void AddDefaultRunSettingsShouldThrowExceptionIfArgumentIsNull() { Assert.ThrowsException(() => - RunSettingsProviderExtensions.AddDefaultRunSettings(null)); + RunSettingsProviderExtensions.AddDefaultRunSettings(null!)); } [TestMethod] public void UpdateRunSettingsNodeShouldThrowExceptionIfKeyIsNull() { Assert.ThrowsException(() => - _runSettingsProvider.UpdateRunSettingsNode(null, "data")); + _runSettingsProvider.UpdateRunSettingsNode(null!, "data")); } [TestMethod] @@ -129,14 +129,14 @@ public void UpdateRunSettingsNodeShouldThrowExceptionIfKeyIsEmptyOrWhiteSpace() public void UpdateRunSettingsNodeShouldThrowExceptionIfDataIsNull() { Assert.ThrowsException(() => - _runSettingsProvider.UpdateRunSettingsNode("Key", null)); + _runSettingsProvider.UpdateRunSettingsNode("Key", null!)); } [TestMethod] public void UpdateRunSettingsNodeShouldThrowExceptionIfRunSettingsProviderIsNull() { Assert.ThrowsException(() => - RunSettingsProviderExtensions.UpdateRunSettingsNode(null, "Key", "data")); + RunSettingsProviderExtensions.UpdateRunSettingsNode(null!, "Key", "data")); } [TestMethod] @@ -179,7 +179,7 @@ public void UpdateTetsRunParameterSettingsNodeShouldOverrideValueIfKeyIsAlreadyP _runSettingsProvider.UpdateTestRunParameterSettingsNode(match); Assert.AreEqual(runSettingsWithTestRunParametersOverrode, - _runSettingsProvider.ActiveRunSettings.SettingsXml); + _runSettingsProvider.ActiveRunSettings!.SettingsXml); } [TestMethod] @@ -213,7 +213,7 @@ public void UpdateRunSettingsNodeShouldUpdateKeyIfAlreadyPresent() public void UpdateRunSettingsNodeInnerXmlShouldThrowExceptionIfKeyIsNull() { Assert.ThrowsException(() => - _runSettingsProvider.UpdateRunSettingsNodeInnerXml(null, "")); + _runSettingsProvider.UpdateRunSettingsNodeInnerXml(null!, "")); } [TestMethod] @@ -227,14 +227,14 @@ public void UpdateRunSettingsNodeInnerXmlShouldThrowExceptionIfKeyIsEmptyOrWhite public void UpdateRunSettingsNodeInnerXmlShouldThrowExceptionIfXmlIsNull() { Assert.ThrowsException(() => - _runSettingsProvider.UpdateRunSettingsNodeInnerXml("Key", null)); + _runSettingsProvider.UpdateRunSettingsNodeInnerXml("Key", null!)); } [TestMethod] public void UpdateRunSettingsNodeInnerXmlShouldThrowExceptionIfRunSettingsProviderIsNull() { Assert.ThrowsException(() => - RunSettingsProviderExtensions.UpdateRunSettingsNodeInnerXml(null, "Key", "")); + RunSettingsProviderExtensions.UpdateRunSettingsNodeInnerXml(null!, "Key", "")); } [TestMethod] @@ -259,7 +259,7 @@ public void UpdateRunSettingsNodeInnerXmlShouldUpdateKeyIfAlreadyPresent() [TestMethod] public void QueryRunSettingsNodeShouldThrowIfKeyIsNull() { - Assert.ThrowsException(() => _runSettingsProvider.QueryRunSettingsNode(null)); + Assert.ThrowsException(() => _runSettingsProvider.QueryRunSettingsNode(null!)); } [TestMethod] @@ -298,7 +298,7 @@ private void CheckRunSettingsAreUpdated(string parameterName, string parameterVa _runSettingsProvider.UpdateRunSettings("\r\n "); _runSettingsProvider.UpdateTestRunParameterSettingsNode(match); - Assert.AreEqual(runSettingsWithTestRunParameters, _runSettingsProvider.ActiveRunSettings.SettingsXml); + Assert.AreEqual(runSettingsWithTestRunParameters, _runSettingsProvider.ActiveRunSettings!.SettingsXml); } private class TestableRunSettingsProvider : IRunSettingsProvider diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs index b5f6c3f921..c7c8fcd484 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs @@ -147,7 +147,7 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestDiscoverers() { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; - CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestDiscoverers.Keys); + CollectionAssert.AreEqual(expectedExtensions.Keys, extensions!.TestDiscoverers!.Keys); } [TestMethod] @@ -167,7 +167,7 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestExecutors() { { "te", new TestExecutorPluginInformation(typeof(TestExtensionsTests)) } }; - CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestExecutors.Keys); + CollectionAssert.AreEqual(expectedExtensions.Keys, extensions!.TestExecutors!.Keys); } [TestMethod] @@ -187,7 +187,7 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestSettingsProviders { { "tsp", new TestSettingsProviderPluginInformation(typeof(TestExtensionsTests)) } }; - CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestSettingsProviders.Keys); + CollectionAssert.AreEqual(expectedExtensions.Keys, extensions!.TestSettingsProviders!.Keys); } [TestMethod] @@ -207,7 +207,7 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestLoggers() { { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } }; - CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestLoggers.Keys); + CollectionAssert.AreEqual(expectedExtensions.Keys, extensions!.TestLoggers!.Keys); } [TestMethod] @@ -231,13 +231,13 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestDiscoveresAndLogg { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; - CollectionAssert.AreEqual(expectedDiscoverers.Keys, extensions.TestDiscoverers.Keys); + CollectionAssert.AreEqual(expectedDiscoverers.Keys, extensions!.TestDiscoverers!.Keys); var expectedLoggers = new Dictionary { { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } }; - CollectionAssert.AreEqual(expectedLoggers.Keys, extensions.TestLoggers.Keys); + CollectionAssert.AreEqual(expectedLoggers.Keys, extensions.TestLoggers!.Keys); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs index 6ff464458b..ab7d08c6fc 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/ConditionTests.cs @@ -128,7 +128,7 @@ public void ParseStringWithSingleUnescapedBangThrowsFormatException2() [TestMethod] public void TokenizeNullThrowsArgumentNullException() { - Assert.ThrowsException(() => Condition.TokenizeFilterConditionString(null), "str"); + Assert.ThrowsException(() => Condition.TokenizeFilterConditionString(null!), "str"); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs index 9583e4b6cb..9ac8fe8614 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FastFilterTests.cs @@ -86,8 +86,8 @@ public void FastFilterWithSingleEqualsClause() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test1")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test2")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test1")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test2")); } [TestMethod] @@ -105,10 +105,10 @@ public void FastFilterWithMultipleEqualsClause() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test1")); - Assert.IsTrue(fastFilter.Evaluate((s) => "test2")); - Assert.IsTrue(fastFilter.Evaluate((s) => "test3")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test4")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test1")); + Assert.IsTrue(fastFilter.Evaluate(s => "test2")); + Assert.IsTrue(fastFilter.Evaluate(s => "test3")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test4")); } [TestMethod] @@ -126,10 +126,10 @@ public void FastFilterWithMultipleEqualsClauseAndParentheses() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test1")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test2")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test3")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test4")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test1")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test2")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test3")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test4")); } [TestMethod] @@ -147,14 +147,14 @@ public void FastFilterWithMultipleEqualsClauseAndRegex() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test1")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test2")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test3")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test1 (123)")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test2(123)")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test3 (123)")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test4")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test4 ()")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test1")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test2")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test3")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test1 (123)")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test2(123)")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test3 (123)")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test4")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test4 ()")); } [TestMethod] @@ -172,12 +172,12 @@ public void FastFilterWithMultipleEqualsClauseForMultiplePropertyValues() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "Category" }, null)); - Assert.IsTrue(fastFilter.Evaluate((s) => new[] { "UnitTest" })); - Assert.IsTrue(fastFilter.Evaluate((s) => new[] { "PerfTest" })); - Assert.IsTrue(fastFilter.Evaluate((s) => new[] { "UnitTest", "PerfTest" })); - Assert.IsTrue(fastFilter.Evaluate((s) => new[] { "UnitTest", "IntegrationTest" })); - Assert.IsFalse(fastFilter.Evaluate((s) => new[] { "IntegrationTest" })); - Assert.IsFalse(fastFilter.Evaluate((s) => null)); + Assert.IsTrue(fastFilter.Evaluate(s => new[] { "UnitTest" })); + Assert.IsTrue(fastFilter.Evaluate(s => new[] { "PerfTest" })); + Assert.IsTrue(fastFilter.Evaluate(s => new[] { "UnitTest", "PerfTest" })); + Assert.IsTrue(fastFilter.Evaluate(s => new[] { "UnitTest", "IntegrationTest" })); + Assert.IsFalse(fastFilter.Evaluate(s => new[] { "IntegrationTest" })); + Assert.IsFalse(fastFilter.Evaluate(s => null)); } [TestMethod] @@ -195,16 +195,16 @@ public void FastFilterWithMultipleEqualsClauseAndRegexReplacement() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsTrue(fastFilter.Evaluate((s) => "TestClass(1).Test1")); - Assert.IsTrue(fastFilter.Evaluate((s) => "TestClass().Test1()")); - Assert.IsTrue(fastFilter.Evaluate((s) => "TestClass(1, 2).Test2")); - Assert.IsTrue(fastFilter.Evaluate((s) => "TestClass.Test3 (abcd1234)")); - Assert.IsTrue(fastFilter.Evaluate((s) => "TestClass(1).Test1(123)")); - Assert.IsTrue(fastFilter.Evaluate((s) => "TestClass(1, 2).Test2(x:1, y:2, z:3)")); - Assert.IsTrue(fastFilter.Evaluate((s) => "TestClass(1, 2,3).Test3(1) (123)")); - Assert.IsFalse(fastFilter.Evaluate((s) => "TestClass1.Test1")); - Assert.IsFalse(fastFilter.Evaluate((s) => "TestClass1(1).Test1")); - Assert.IsFalse(fastFilter.Evaluate((s) => "TestClass((1, 2, 3)).Test1")); + Assert.IsTrue(fastFilter.Evaluate(s => "TestClass(1).Test1")); + Assert.IsTrue(fastFilter.Evaluate(s => "TestClass().Test1()")); + Assert.IsTrue(fastFilter.Evaluate(s => "TestClass(1, 2).Test2")); + Assert.IsTrue(fastFilter.Evaluate(s => "TestClass.Test3 (abcd1234)")); + Assert.IsTrue(fastFilter.Evaluate(s => "TestClass(1).Test1(123)")); + Assert.IsTrue(fastFilter.Evaluate(s => "TestClass(1, 2).Test2(x:1, y:2, z:3)")); + Assert.IsTrue(fastFilter.Evaluate(s => "TestClass(1, 2,3).Test3(1) (123)")); + Assert.IsFalse(fastFilter.Evaluate(s => "TestClass1.Test1")); + Assert.IsFalse(fastFilter.Evaluate(s => "TestClass1(1).Test1")); + Assert.IsFalse(fastFilter.Evaluate(s => "TestClass((1, 2, 3)).Test1")); } [TestMethod] @@ -235,8 +235,8 @@ private static void CheckFastFailureWithNotEqualClause(string filterString) Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test1")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test2")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test1")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test2")); } [TestMethod] @@ -254,10 +254,10 @@ public void FastFilterWithMultipleNotEqualsClause() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test1")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test2")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test3")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test4")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test1")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test2")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test3")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test4")); } [TestMethod] @@ -275,14 +275,14 @@ public void FastFilterWithMultipleNotEqualsClauseAndRegex() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName" }, null)); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test1")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test2")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test3")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test1 (123)")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test2(123)")); - Assert.IsFalse(fastFilter.Evaluate((s) => "Test3 (123)")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test4")); - Assert.IsTrue(fastFilter.Evaluate((s) => "Test4 (123)")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test1")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test2")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test3")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test1 (123)")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test2(123)")); + Assert.IsFalse(fastFilter.Evaluate(s => "Test3 (123)")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test4")); + Assert.IsTrue(fastFilter.Evaluate(s => "Test4 (123)")); } [TestMethod] @@ -300,12 +300,12 @@ public void FastFilterWithMultipleNotEqualsClauseForMultiplePropertyValues() Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "Category" }, null)); - Assert.IsFalse(fastFilter.Evaluate((s) => new[] { "UnitTest" })); - Assert.IsFalse(fastFilter.Evaluate((s) => new[] { "PerfTest" })); - Assert.IsFalse(fastFilter.Evaluate((s) => new[] { "UnitTest", "PerfTest" })); - Assert.IsFalse(fastFilter.Evaluate((s) => new[] { "UnitTest", "IntegrationTest" })); - Assert.IsTrue(fastFilter.Evaluate((s) => new[] { "IntegrationTest" })); - Assert.IsTrue(fastFilter.Evaluate((s) => null)); + Assert.IsFalse(fastFilter.Evaluate(s => new[] { "UnitTest" })); + Assert.IsFalse(fastFilter.Evaluate(s => new[] { "PerfTest" })); + Assert.IsFalse(fastFilter.Evaluate(s => new[] { "UnitTest", "PerfTest" })); + Assert.IsFalse(fastFilter.Evaluate(s => new[] { "UnitTest", "IntegrationTest" })); + Assert.IsTrue(fastFilter.Evaluate(s => new[] { "IntegrationTest" })); + Assert.IsTrue(fastFilter.Evaluate(s => null)); } [TestMethod] @@ -347,7 +347,8 @@ public void MultiplePropertyNamesEqualOr() Assert.IsTrue(fastFilter.FilterProperties["Category"].SequenceEqual(new[] { "IntegrationTest" })); Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName", "Category" }, null)); - Assert.AreEqual("FullyQualifiedName", filterExpressionWrapper.ValidForProperties(new List() { "Category" }, null).Single()); + Assert.AreEqual("FullyQualifiedName", + filterExpressionWrapper.ValidForProperties(new List() { "Category" }, null)!.Single()); Assert.IsFalse(fastFilter.Evaluate(s => s == "Category" ? new[] { "UnitTest" } : null)); Assert.IsFalse(fastFilter.Evaluate(s => s == "Category" ? new[] { "PerfTest" } : null)); @@ -372,7 +373,7 @@ public void MultiplePropertyNamesEqualOr() "FullyQualifiedName" => new[] { "Test2" }, _ => null, })); - Assert.IsFalse(fastFilter.Evaluate((s) => null)); + Assert.IsFalse(fastFilter.Evaluate(s => null)); } [TestMethod] @@ -390,7 +391,8 @@ public void MultiplePropertyNamesNotEqualAnd() Assert.IsTrue(fastFilter.FilterProperties["Category"].SequenceEqual(new[] { "IntegrationTest" })); Assert.IsNull(filterExpressionWrapper.ValidForProperties(new List() { "FullyQualifiedName", "Category" }, null)); - Assert.AreEqual("FullyQualifiedName", filterExpressionWrapper.ValidForProperties(new List() { "Category" }, null).Single()); + Assert.AreEqual("FullyQualifiedName", + filterExpressionWrapper.ValidForProperties(new List() { "Category" }, null)!.Single()); Assert.IsTrue(fastFilter.Evaluate(s => s == "Category" ? new[] { "UnitTest" } : null)); Assert.IsFalse(fastFilter.Evaluate(s => s == "Category" ? new[] { "UnitTest", "IntegrationTest" } : null)); diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs index 7ceed3a2c8..99a5f7964e 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/FilterExpressionTests.cs @@ -16,7 +16,7 @@ public class FilterExpressionTests [TestMethod] public void TokenizeNullThrowsArgumentNullException() { - Assert.ThrowsException(() => FilterExpression.TokenizeFilterExpressionString(null), "str"); + Assert.ThrowsException(() => FilterExpression.TokenizeFilterExpressionString(null!), "str"); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/TestCaseFilterExpressionTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/TestCaseFilterExpressionTests.cs index 5f70b494f7..35afc403bb 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/TestCaseFilterExpressionTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Filtering/TestCaseFilterExpressionTests.cs @@ -20,10 +20,11 @@ public void ValidForPropertiesShouldNotSetvalidForMatchVariableTofalseIfFilterIs var filterExpressionWrapper = new FilterExpressionWrapper("highlyunlikelyproperty=unused"); var testCaseFilterExpression = new TestCaseFilterExpression(filterExpressionWrapper); - Assert.AreEqual("highlyunlikelyproperty", testCaseFilterExpression.ValidForProperties(new List() { "TestCategory" }, (s) => null).Single()); + Assert.AreEqual("highlyunlikelyproperty", + testCaseFilterExpression.ValidForProperties(new List() { "TestCategory" }, s => null)!.Single()); TestCase dummyTestCase = new(); - bool result = testCaseFilterExpression.MatchTestCase(dummyTestCase, (s) => "unused"); + bool result = testCaseFilterExpression.MatchTestCase(dummyTestCase, s => "unused"); Assert.IsTrue(result); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostExtensionManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostExtensionManagerTests.cs index a720d405d6..f693fe887a 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostExtensionManagerTests.cs @@ -24,7 +24,7 @@ public void CreateShouldThrowExceptionIfMessageLoggerIsNull() { Assert.ThrowsException(() => { - var testLoggerExtensionManager = TestRuntimeExtensionManager.Create(null); + var testLoggerExtensionManager = TestRuntimeExtensionManager.Create(null!); }); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs index f1c6aaa953..849484134a 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs @@ -102,13 +102,13 @@ public void RaiseTestResultShouldInvokeRegisteredEventHandlerIfTestResultEventAr [TestMethod] public void RaiseTestResultShouldThrowExceptionIfNullTestResultEventArgsIsPassed() { - Assert.ThrowsException(() => _loggerEvents.RaiseTestResult(null)); + Assert.ThrowsException(() => _loggerEvents.RaiseTestResult(null!)); } [TestMethod] public void RaiseTestRunMessageShouldThrowExceptioIfNullTestRunMessageEventArgsIsPassed() { - Assert.ThrowsException(() => _loggerEvents.RaiseTestRunMessage(null)); + Assert.ThrowsException(() => _loggerEvents.RaiseTestRunMessage(null!)); } [TestMethod] @@ -231,7 +231,7 @@ public void TestLoggerProxySendMessageShouldNotInvokeRegisterdEventHandlerIfAlre [TestMethod] public void RaiseDiscoveryStartShouldThrowExceptionIfNullDiscoveryStartEventArgsIsPassed() { - Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveryStart(null)); + Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveryStart(null!)); } /// @@ -240,7 +240,7 @@ public void RaiseDiscoveryStartShouldThrowExceptionIfNullDiscoveryStartEventArgs [TestMethod] public void RaiseDiscoveredTestsShouldThrowExceptionIfNullDiscoveredTestsEventArgsIsPassed() { - Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveredTests(null)); + Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveredTests(null!)); } /// @@ -294,7 +294,7 @@ public void RaiseDiscoveredTestsShouldInvokeRegisteredEventHandler() [TestMethod] public void RaiseDiscoveryCompleteShouldThrowExceptionIfNullDiscoveryCompleteEventArgsIsPassed() { - Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveryComplete(null)); + Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveryComplete(null!)); } /// @@ -392,7 +392,7 @@ public void RaiseDiscoveryCompleteShouldInvokeRegisteredEventHandler() [TestMethod] public void RaiseTestRunStartShouldThrowExceptionIfNullTestRunStartEventArgsIsPassed() { - Assert.ThrowsException(() => _loggerEvents.RaiseTestRunStart(null)); + Assert.ThrowsException(() => _loggerEvents.RaiseTestRunStart(null!)); } /// @@ -401,7 +401,7 @@ public void RaiseTestRunStartShouldThrowExceptionIfNullTestRunStartEventArgsIsPa [TestMethod] public void RaiseDiscoveryMessageShouldThrowExceptionIfNullTestRunMessageEventArgsIsPassed() { - Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveryMessage(null)); + Assert.ThrowsException(() => _loggerEvents.RaiseDiscoveryMessage(null!)); } /// diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/RequestDataTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/RequestDataTests.cs index d25ace760a..3767137f3e 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/RequestDataTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/RequestDataTests.cs @@ -38,7 +38,7 @@ public void RequestDataShouldReturnValidProtocolConfig() public void RequestDataShouldThrowArgumentNullExpectionOnNullMetricsCollection() { var requestData = new RequestData(); - requestData.MetricsCollection = null; + requestData.MetricsCollection = null!; } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsManagerTests.cs index 33494735d8..75bf473528 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsManagerTests.cs @@ -48,7 +48,7 @@ public void SetActiveRunSettingsShouldThrowIfRunSettingsPassedIsNull() { var instance = RunSettingsManager.Instance; - Assert.ThrowsException(() => instance.SetActiveRunSettings(null)); + Assert.ThrowsException(() => instance.SetActiveRunSettings(null!)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs index 9b681e06f6..a21b3d16b4 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/RunSettingsTests.cs @@ -30,7 +30,7 @@ public void TestCleanup() public void LoadSettingsXmlShouldThrowOnNullSettings() { var runSettings = new RunSettings(); - Assert.ThrowsException(() => runSettings.LoadSettingsXml(null)); + Assert.ThrowsException(() => runSettings.LoadSettingsXml(null!)); } [TestMethod] @@ -76,7 +76,7 @@ public void LoadSettingsXmlShouldThrowOnInvalidSettings() public void InitializeSettingsProvidersShouldThrowOnNullSettings() { var runSettings = new RunSettings(); - Assert.ThrowsException(() => runSettings.InitializeSettingsProviders(null)); + Assert.ThrowsException(() => runSettings.InitializeSettingsProviders(null!)); } [TestMethod] @@ -211,7 +211,7 @@ public void GetSettingsShouldThrowIfSettingsNameIsNull() { var runSettings = new RunSettings(); - Assert.ThrowsException(() => runSettings.GetSettings(null)); + Assert.ThrowsException(() => runSettings.GetSettings(null!)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs index c34ded0552..fb62513667 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/SettingsProvider/SettingsProviderExtensionManagerTests.cs @@ -135,7 +135,7 @@ public void GetSettingsProviderShouldThrowIfSettingsNameIsNullOrEmpty() }; var spm = new TestableSettingsProviderManager(extensions, unfilteredExtensions, new Mock().Object); - Assert.ThrowsException(() => spm.GetSettingsProvider(null)); + Assert.ThrowsException(() => spm.GetSettingsProvider(null!)); Assert.ThrowsException(() => spm.GetSettingsProvider(string.Empty)); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs index 5e52835ae0..0d94e142a1 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs @@ -19,13 +19,13 @@ public class FakesUtilitiesTests public void FakesSettingsShouldThrowExceptionIfSourcesArePassedAsNull() { string runSettingsXml = @".netstandard,Version=5.0"; - Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration(null, runSettingsXml)); + Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration(null!, runSettingsXml)); } [TestMethod] public void FakesSettingsShouldThrowExceptionIfRunSettingsIsPassedAsNull() { - Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration(new string[] { }, null)); + Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration(new string[] { }, null!)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs index 59c131ccd8..810012e9fb 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs @@ -51,7 +51,7 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachments() Assert.IsNotNull(result.AttachmentSets); Assert.IsNotNull(result.Metrics); Assert.AreEqual(1, result.AttachmentSets.Count); - Assert.AreEqual(1, result.InvokedDataCollectors.Count); + Assert.AreEqual(1, result.InvokedDataCollectors!.Count); Assert.AreEqual(0, result.Metrics.Count); Assert.IsNotNull(result.AttachmentSets[0]); Assert.AreEqual(displayName, result.AttachmentSets[0].DisplayName); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs index a46afb2b75..15db3a0b47 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs @@ -110,6 +110,7 @@ public void ProcessRequestsShouldProcessBeforeTestCaseStartEvent() _mockCommunicationManager.SetupSequence(x => x.ReceiveMessage()).Returns(message).Returns(new Message() { MessageType = MessageType.SessionEnd, Payload = "false" }); var requestHandler = new DataCollectionTestCaseEventHandler(_messageSink.Object, _mockCommunicationManager.Object, _mockDataCollectionManager.Object, _dataSerializer.Object); + _dataSerializer.Setup(x => x.DeserializePayload(message)).Returns(new TestCaseStartEventArgs()); requestHandler.ProcessRequests(); @@ -127,6 +128,7 @@ public void ProcessRequestsShouldProcessAfterTestCaseCompleteEvent() _mockCommunicationManager.SetupSequence(x => x.ReceiveMessage()).Returns(message).Returns(new Message() { MessageType = MessageType.SessionEnd, Payload = "false" }); var requestHandler = new DataCollectionTestCaseEventHandler(_messageSink.Object, _mockCommunicationManager.Object, _mockDataCollectionManager.Object, _dataSerializer.Object); + _dataSerializer.Setup(x => x.DeserializePayload(message)).Returns(new TestCaseEndEventArgs()); requestHandler.ProcessRequests(); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs index 983a274571..826ab805fb 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs @@ -57,7 +57,7 @@ public TestRequestSenderTests() _connectedEventArgs = new ConnectedEventArgs(_mockChannel.Object); _mockDiscoveryEventsHandler = new Mock(); _mockExecutionEventsHandler = new Mock(); - _testRunCriteriaWithSources = new TestRunCriteriaWithSources(new Dictionary>(), "runsettings", null, null); + _testRunCriteriaWithSources = new TestRunCriteriaWithSources(new Dictionary>(), "runsettings", null, null!); } [TestCleanup] @@ -529,7 +529,7 @@ public void StartTestRunShouldSendStartTestExecutionWithSourcesOnChannelWithVers [TestMethod] public void StartTestRunWithTestsShouldSendStartTestExecutionWithTestsOnChannel() { - var runCriteria = new TestRunCriteriaWithTests(new TestCase[2], "runsettings", null, null); + var runCriteria = new TestRunCriteriaWithTests(new TestCase[2], "runsettings", null, null!); SetupFakeCommunicationChannel(); _testRequestSender.StartTestRun(runCriteria, _mockExecutionEventsHandler.Object); @@ -541,7 +541,7 @@ public void StartTestRunWithTestsShouldSendStartTestExecutionWithTestsOnChannel( [TestMethod] public void StartTestRunWithTestsShouldSendStartTestExecutionWithTestsOnChannelWithVersion() { - var runCriteria = new TestRunCriteriaWithTests(new TestCase[2], "runsettings", null, null); + var runCriteria = new TestRunCriteriaWithTests(new TestCase[2], "runsettings", null, null!); SetupFakeChannelWithVersionNegotiation(Dummynegotiatedprotocolversion); _testRequestSender.StartTestRun(runCriteria, _mockExecutionEventsHandler.Object); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs index c7bf485f59..b4f7216bfe 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs @@ -67,7 +67,7 @@ public void StartTestRunShouldCallExecutionManagerStartTestRunWithAdapterSourceM var testRunCriteria = new TestRunCriteria(new List { "source.dll" }, 10); var manualResetEvent = new ManualResetEvent(true); - _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.AdapterSourceMap, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null)).Callback( + _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.AdapterSourceMap, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null!)).Callback( () => manualResetEvent.Set()); _inProcessProxyExecutionManager.StartTestRun(testRunCriteria, null!); @@ -95,7 +95,7 @@ public void StartTestRunShouldCallExecutionManagerStartTestRunWithTestCase() frequencyOfRunStatsChangeEvent: 10); var manualResetEvent = new ManualResetEvent(true); - _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.Tests, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null)).Callback( + _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.Tests, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null!)).Callback( () => manualResetEvent.Set()); _inProcessProxyExecutionManager.StartTestRun(testRunCriteria, null!); @@ -116,7 +116,7 @@ public void StartTestRunShouldUpdateTestCaseSourceIfTestCaseSourceDiffersFromTes _mockTestHostManager.Setup(hm => hm.GetTestSources(inputSource)).Returns(actualSources); - _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.Tests, inputSource.FirstOrDefault(), testRunCriteria.TestRunSettings, It.IsAny(), null, null)) + _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.Tests, inputSource.FirstOrDefault(), testRunCriteria.TestRunSettings, It.IsAny(), null, null!)) .Callback(() => manualResetEvent.Set()); _inProcessProxyExecutionManager = new InProcessProxyExecutionManager(_mockTestHostManager.Object, _mockTestHostManagerFactory.Object); @@ -124,7 +124,7 @@ public void StartTestRunShouldUpdateTestCaseSourceIfTestCaseSourceDiffersFromTes _inProcessProxyExecutionManager.StartTestRun(testRunCriteria, null!); Assert.IsTrue(manualResetEvent.WaitOne(5000), "IExecutionManager.StartTestRun should get called"); - _mockExecutionManager.Verify(o => o.StartTestRun(testRunCriteria.Tests, inputSource.FirstOrDefault(), testRunCriteria.TestRunSettings, It.IsAny(), null, null)); + _mockExecutionManager.Verify(o => o.StartTestRun(testRunCriteria.Tests, inputSource.FirstOrDefault(), testRunCriteria.TestRunSettings, It.IsAny(), null, null!)); _mockTestHostManager.Verify(hm => hm.GetTestSources(inputSource), Times.Once); Assert.AreEqual(actualSources.FirstOrDefault(), testRunCriteria.Tests.FirstOrDefault()?.Source); } @@ -140,13 +140,13 @@ public void StartTestRunShouldNotUpdateTestCaseSourceIfTestCaseSourceDiffersFrom _mockTestHostManager.Setup(hm => hm.GetTestSources(actualSources)).Returns(actualSources); - _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.Tests, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null)) + _mockExecutionManager.Setup(o => o.StartTestRun(testRunCriteria.Tests, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null!)) .Callback(() => manualResetEvent.Set()); _inProcessProxyExecutionManager.StartTestRun(testRunCriteria, null!); Assert.IsTrue(manualResetEvent.WaitOne(5000), "IExecutionManager.StartTestRun should get called"); - _mockExecutionManager.Verify(o => o.StartTestRun(testRunCriteria.Tests, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null)); + _mockExecutionManager.Verify(o => o.StartTestRun(testRunCriteria.Tests, null, testRunCriteria.TestRunSettings, It.IsAny(), null, null!)); _mockTestHostManager.Verify(hm => hm.GetTestSources(actualSources)); Assert.AreEqual(actualSources.FirstOrDefault(), testRunCriteria.Tests.FirstOrDefault()?.Source); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs index b60d215f91..681ac0e675 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs @@ -87,7 +87,7 @@ public void HandleTestRunComplete_ShouldCallProcessTestRunAttachmentsAsyncWithAt new AttachmentSet(new Uri(Uri3), "uri3_input1") }; - _mockTestRunAttachmentsProcessingManager.Setup(f => f.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult((Collection?)null)); + _mockTestRunAttachmentsProcessingManager.Setup(f => f.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult((Collection)null!)); // act _parallelDataCollectionEventsHandler.HandleTestRunComplete(new TestRunCompleteEventArgs(null, false, false, null, null, null, TimeSpan.FromSeconds(1)), null, inputAttachments, null); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs index af8338f0bd..62591e1c16 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs @@ -233,7 +233,7 @@ public void ProcessRequestsExecutionStartShouldStartExecutionWithGivenSources() { ["mstestv2"] = new[] { "test1.dll", "test2.dll" } }; - var testRunCriteriaWithSources = new TestRunCriteriaWithSources(asm, "runsettings", null, null); + var testRunCriteriaWithSources = new TestRunCriteriaWithSources(asm, "runsettings", null, null!); var message = _dataSerializer.SerializePayload(MessageType.StartTestExecutionWithSources, testRunCriteriaWithSources); ProcessRequestsAsync(_mockTestHostManagerFactory.Object); @@ -256,7 +256,7 @@ public void ProcessRequestsExecutionStartShouldStartExecutionWithGivenTests() var t1 = new TestCase("N.C.M1", new Uri("executor://mstest/v2"), "test1.dll"); var t2 = new TestCase("N.C.M2", new Uri("executor://mstest/v2"), "test1.dll"); var testCases = new[] { t1, t2 }; - var testRunCriteriaWithTests = new TestRunCriteriaWithTests(testCases, "runsettings", null, null); + var testRunCriteriaWithTests = new TestRunCriteriaWithTests(testCases, "runsettings", null, null!); var message = _dataSerializer.SerializePayload(MessageType.StartTestExecutionWithTests, testRunCriteriaWithTests); ProcessRequestsAsync(_mockTestHostManagerFactory.Object); @@ -317,7 +317,7 @@ public void SendExecutionCompleteShouldSendTestRunCompletePayloadOnChannel() var t1 = new TestCase("N.C.M1", new Uri("executor://mstest/v2"), "test1.dll"); var t2 = new TestCase("N.C.M2", new Uri("executor://mstest/v2"), "test1.dll"); var testCases = new[] { t1, t2 }; - var testRunCriteriaWithTests = new TestRunCriteriaWithTests(testCases, "runsettings", null, null); + var testRunCriteriaWithTests = new TestRunCriteriaWithTests(testCases, "runsettings", null, null!); var message = _dataSerializer.SerializePayload(MessageType.StartTestExecutionWithTests, testRunCriteriaWithTests); _mockExecutionManager.Setup(em => em.StartTestRun(It.IsAny>(), It.IsAny(), It.IsAny(), diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs index 22e734bcfa..828831a659 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs @@ -88,7 +88,7 @@ public void InitializeShouldLoadAndInitializeAllExtensions() Assert.IsNotNull(TestPluginCache.Instance.TestExtensions); // Executors - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestExecutors.Count > 0); + Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestExecutors!.Count > 0); var allExecutors = TestExecutorExtensionManager.Create().TestExtensions; foreach (var executor in allExecutors) @@ -97,7 +97,7 @@ public void InitializeShouldLoadAndInitializeAllExtensions() } // Settings Providers - Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestSettingsProviders.Count > 0); + Assert.IsTrue(TestPluginCache.Instance.TestExtensions.TestSettingsProviders!.Count > 0); var settingsProviders = SettingsProviderExtensionManager.Create().SettingsProvidersMap.Values; foreach (var provider in settingsProviders) diff --git a/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs b/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs index e823a66d30..2bf24fb441 100644 --- a/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionAttachmentManagerTests.cs @@ -95,13 +95,13 @@ List TestCaseEvent(string uri) [TestMethod] public void InitializeShouldThrowExceptionIfSessionIdIsNull() { - Assert.ThrowsException(() => _attachmentManager.Initialize(null, string.Empty, _messageSink.Object)); + Assert.ThrowsException(() => _attachmentManager.Initialize(null!, string.Empty, _messageSink.Object)); } [TestMethod] public void InitializeShouldThrowExceptionIfMessageSinkIsNull() { - Assert.ThrowsException(() => _attachmentManager.Initialize(_sessionId, string.Empty, null)); + Assert.ThrowsException(() => _attachmentManager.Initialize(_sessionId, string.Empty, null!)); } [TestMethod] @@ -263,7 +263,7 @@ public void AddAttachmentShouldAddMultipleAttachmentsForSameDc() [TestMethod] public void AddAttachmentShouldNotAddNewFileTransferIfNullIsPassed() { - Assert.ThrowsException(() => _attachmentManager.AddAttachment(null, null, null, null)); + Assert.ThrowsException(() => _attachmentManager.AddAttachment(null!, null, null!, null!)); } [TestMethod] diff --git a/test/datacollector.UnitTests/DataCollectionEnvironmentVariableTests.cs b/test/datacollector.UnitTests/DataCollectionEnvironmentVariableTests.cs index 9119c4b2f1..9f3a0c881d 100644 --- a/test/datacollector.UnitTests/DataCollectionEnvironmentVariableTests.cs +++ b/test/datacollector.UnitTests/DataCollectionEnvironmentVariableTests.cs @@ -17,7 +17,7 @@ public void ConstructorShouldThrowExceptionIfKeyValueIsNull() Assert.ThrowsException( () => { - var envvariable = new DataCollectionEnvironmentVariable(default, null); + var envvariable = new DataCollectionEnvironmentVariable(default, null!); }); } diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index 315c7b607d..0b1ee93de2 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -58,7 +58,7 @@ public DataCollectionManagerTests() [TestMethod] public void InitializeDataCollectorsShouldThrowExceptionIfSettingsXmlIsNull() { - Assert.ThrowsException(() => _dataCollectionManager.InitializeDataCollectors(null)); + Assert.ThrowsException(() => _dataCollectionManager.InitializeDataCollectors(null!)); } [TestMethod] @@ -525,24 +525,24 @@ protected override bool TryGetUriFromFriendlyName(string friendlyName, out strin } } - protected override bool IsUriValid(string uri) + protected override bool IsUriValid(string? uri) { - return uri.Equals("my://custom/datacollector") || uri.Equals("my://custom/ccdatacollector"); + return string.Equals(uri, "my://custom/datacollector") || string.Equals(uri, "my://custom/ccdatacollector"); } - protected override ObjectModel.DataCollection.DataCollector? TryGetTestExtension(string extensionUri) + protected override ObjectModel.DataCollection.DataCollector TryGetTestExtension(string extensionUri) { if (extensionUri.Equals("my://custom/datacollector")) { - return _dataCollector; + return _dataCollector!; } if (extensionUri.Equals("my://custom/ccdatacollector")) { - return _ccDataCollector; + return _ccDataCollector!; } - return null; + return null!; } protected override DataCollectorConfig? TryGetDataCollectorConfig(string extensionUri) diff --git a/test/datacollector.UnitTests/DataCollectorConfigTests.cs b/test/datacollector.UnitTests/DataCollectorConfigTests.cs index f8fd8a2f3a..05ff4fdbfe 100644 --- a/test/datacollector.UnitTests/DataCollectorConfigTests.cs +++ b/test/datacollector.UnitTests/DataCollectorConfigTests.cs @@ -17,14 +17,14 @@ public void ConstructorShouldSetCorrectFriendlyNameAndUri() var dataCollectorConfig = new DataCollectorConfig(typeof(CustomDataCollector)); Assert.AreEqual("CustomDataCollector", dataCollectorConfig.FriendlyName); - Assert.AreEqual("my://custom/datacollector", dataCollectorConfig.TypeUri.ToString()); + Assert.AreEqual("my://custom/datacollector", dataCollectorConfig.TypeUri!.ToString()); } [TestMethod] public void ConstructorShouldThrowExceptionIfTypeIsNull() { Assert.ThrowsException( - () => new DataCollectorConfig(null)); + () => new DataCollectorConfig(null!)); } [TestMethod] @@ -40,7 +40,7 @@ public void ConstructorShouldNotThrowExceptionIfFriendlyNameIsEmpty() { var dataCollectorConfig = new DataCollectorConfig(typeof(CustomDataCollectorWithEmptyFriendlyName)); Assert.AreEqual("", dataCollectorConfig.FriendlyName); - Assert.AreEqual("my://custom/datacollector", dataCollectorConfig.TypeUri.ToString()); + Assert.AreEqual("my://custom/datacollector", dataCollectorConfig.TypeUri!.ToString()); } [TestMethod] @@ -48,6 +48,6 @@ public void ConstructorShouldNotThrowExceptionIfFriendlyNameIsNotSpecified() { var dataCollectorConfig = new DataCollectorConfig(typeof(CustomDataCollectorWithoutFriendlyName)); Assert.AreEqual("", dataCollectorConfig.FriendlyName); - Assert.AreEqual("my://custom/datacollector", dataCollectorConfig.TypeUri.ToString()); + Assert.AreEqual("my://custom/datacollector", dataCollectorConfig.TypeUri!.ToString()); } } diff --git a/test/datacollector.UnitTests/DataCollectorInformationTests.cs b/test/datacollector.UnitTests/DataCollectorInformationTests.cs index f889c7bf8f..710987f42d 100644 --- a/test/datacollector.UnitTests/DataCollectorInformationTests.cs +++ b/test/datacollector.UnitTests/DataCollectorInformationTests.cs @@ -49,7 +49,7 @@ public void InitializeDataCollectorShouldInitializeDataCollector() _dataCollectorInfo.InitializeDataCollector(); _dataCollectorInfo.SetTestExecutionEnvironmentVariables(); - CollectionAssert.AreEqual(_envVarList, _dataCollectorInfo.TestExecutionEnvironmentVariables.ToList()); + CollectionAssert.AreEqual(_envVarList, _dataCollectorInfo.TestExecutionEnvironmentVariables!.ToList()); } [TestMethod] diff --git a/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs b/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs index 5d315cef24..33be9826db 100644 --- a/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs +++ b/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs @@ -26,7 +26,7 @@ public TestPlatformDataCollectionEventsTests() [TestMethod] public void RaiseEventsShouldThrowExceptionIfEventArgsIsNull() { - Assert.ThrowsException(() => _events.RaiseEvent(null)); + Assert.ThrowsException(() => _events.RaiseEvent(null!)); } [TestMethod] diff --git a/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs b/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs index 7f5fb3b8e0..9ad86673d9 100644 --- a/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs +++ b/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs @@ -35,19 +35,19 @@ public TestPlatformDataCollectionLoggerTests() [TestMethod] public void LogErrorShouldThrowExceptionIfContextIsNull() { - Assert.ThrowsException(() => _logger.LogError(null, string.Empty)); + Assert.ThrowsException(() => _logger.LogError(null!, string.Empty)); Assert.ThrowsException(() => _logger.LogError(null, new Exception())); - Assert.ThrowsException(() => _logger.LogError(null, string.Empty, new Exception())); + Assert.ThrowsException(() => _logger.LogError(null!, string.Empty, new Exception())); } [TestMethod] public void LogErrorShouldThrowExceptionIfTextIsNull() { - Assert.ThrowsException(() => _logger.LogError(_context, (string?)null)); + Assert.ThrowsException(() => _logger.LogError(_context, (string)null!)); - Assert.ThrowsException(() => _logger.LogError(_context, null, new Exception())); + Assert.ThrowsException(() => _logger.LogError(_context, null!, new Exception())); } [TestMethod] @@ -55,7 +55,7 @@ public void LogErrorShouldThrowExceptionIfExceptionIsNull() { Assert.ThrowsException(() => _logger.LogError(_context, (Exception?)null)); - Assert.ThrowsException(() => _logger.LogError(_context, string.Empty, null)); + Assert.ThrowsException(() => _logger.LogError(_context, string.Empty, null!)); } [TestMethod] diff --git a/test/datacollector.UnitTests/TestPlatformDataCollectionSinkTests.cs b/test/datacollector.UnitTests/TestPlatformDataCollectionSinkTests.cs index 26739db109..11f6c3fe23 100644 --- a/test/datacollector.UnitTests/TestPlatformDataCollectionSinkTests.cs +++ b/test/datacollector.UnitTests/TestPlatformDataCollectionSinkTests.cs @@ -41,7 +41,7 @@ public void Cleanup() [TestMethod] public void SendFileAsyncShouldThrowExceptionIfFileTransferInformationIsNull() { - Assert.ThrowsException(() => _dataCollectionSink.SendFileAsync(default)); + Assert.ThrowsException(() => _dataCollectionSink.SendFileAsync(default!)); } [TestMethod] diff --git a/test/vstest.ProgrammerTests/Fakes/FakeDataCollectorAttachmentsProcessorsFactory.cs b/test/vstest.ProgrammerTests/Fakes/FakeDataCollectorAttachmentsProcessorsFactory.cs index 9b841da414..8a5f923382 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeDataCollectorAttachmentsProcessorsFactory.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeDataCollectorAttachmentsProcessorsFactory.cs @@ -16,7 +16,7 @@ public FakeDataCollectorAttachmentsProcessorsFactory(FakeErrorAggregator fakeErr public FakeErrorAggregator FakeErrorAggregator { get; } - public DataCollectorAttachmentProcessor[] Create(InvokedDataCollector[] invokedDataCollectors, IMessageLogger logger) + public DataCollectorAttachmentProcessor[] Create(InvokedDataCollector[]? invokedDataCollectors, IMessageLogger logger) { throw new NotImplementedException(); } diff --git a/test/vstest.ProgrammerTests/Fakes/FakeTestExtensionManager.cs b/test/vstest.ProgrammerTests/Fakes/FakeTestExtensionManager.cs index 50eccd23fa..812522fe74 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeTestExtensionManager.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeTestExtensionManager.cs @@ -12,7 +12,7 @@ public void ClearExtensions() throw new NotImplementedException(); } - public void UseAdditionalExtensions(IEnumerable pathToAdditionalExtensions, bool skipExtensionFilters) + public void UseAdditionalExtensions(IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters) { throw new NotImplementedException(); } diff --git a/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs b/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs index 42bd0db434..df27595f0a 100644 --- a/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs +++ b/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs @@ -41,40 +41,40 @@ public void AutoDetectArchitectureShouldReturnDefaultArchitectureOnNullSources() [TestMethod] public void AutoDetectArchitectureShouldReturnDefaultArchitectureOnEmptySources() { - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List(0), _defaultArchitecture, out _)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List(0), _defaultArchitecture, out _)); } [TestMethod] public void AutoDetectArchitectureShouldReturnDefaultArchitectureOnNullItemInSources() { - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { null! }, _defaultArchitecture, out _)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { null! }, _defaultArchitecture, out _)); } [TestMethod] public void AutoDetectArchitectureShouldReturnDefaultArchitectureOnWhiteSpaceItemInSources() { - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { " " }, _defaultArchitecture, out _)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { " " }, _defaultArchitecture, out _)); } [TestMethod] public void AutoDetectArchitectureShouldReturnCorrectArchForOneSource() { _mockAssemblyHelper.Setup(ah => ah.GetArchitecture(It.IsAny())).Returns(Architecture.X86); - Assert.AreEqual(Architecture.X86, _inferHelper.AutoDetectArchitecture(new List() { "1.dll" }, _defaultArchitecture, out _)); + Assert.AreEqual(Architecture.X86, _inferHelper.AutoDetectArchitecture(new List() { "1.dll" }, _defaultArchitecture, out _)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny())); } [TestMethod] public void AutoDetectArchitectureShouldReturnCorrectDefaultArchForNotDotNetAssembly() { - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "NotDotNetAssebly.appx" }, _defaultArchitecture, out _)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "NotDotNetAssebly.appx" }, _defaultArchitecture, out _)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny()), Times.Never); } [TestMethod] public void AutoDetectArchitectureShouldSetDefaultArchForNotDotNetAssembly() { - _inferHelper.AutoDetectArchitecture(new List() { "NotDotNetAssebly.appx" }, _defaultArchitecture, out var sourceArchitectures); + _inferHelper.AutoDetectArchitecture(new List() { "NotDotNetAssebly.appx" }, _defaultArchitecture, out var sourceArchitectures); Assert.AreEqual(_defaultArchitecture, sourceArchitectures["NotDotNetAssebly.appx"]); } @@ -83,7 +83,7 @@ public void AutoDetectArchitectureShouldReturnDefaultArchForAllAnyCpuAssemblies( { _mockAssemblyHelper.SetupSequence(ah => ah.GetArchitecture(It.IsAny())) .Returns(Architecture.AnyCPU).Returns(Architecture.AnyCPU).Returns(Architecture.AnyCPU); - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "AnyCPU2.exe", "AnyCPU3.dll" }, _defaultArchitecture, out _)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "AnyCPU2.exe", "AnyCPU3.dll" }, _defaultArchitecture, out _)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny()), Times.Exactly(3)); } @@ -92,7 +92,7 @@ public void AutoDetectArchitectureShouldReturnX86ArchIfOneX86AssemblyAndRestAnyC { _mockAssemblyHelper.SetupSequence(ah => ah.GetArchitecture(It.IsAny())) .Returns(Architecture.AnyCPU).Returns(Architecture.AnyCPU).Returns(Architecture.X86); - Assert.AreEqual(Architecture.X86, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "AnyCPU2.exe", "x86.dll" }, _defaultArchitecture, out _)); + Assert.AreEqual(Architecture.X86, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "AnyCPU2.exe", "x86.dll" }, _defaultArchitecture, out _)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny()), Times.Exactly(3)); } @@ -101,7 +101,7 @@ public void AutoDetectArchitectureShouldReturnARMArchIfOneARMAssemblyAndRestAnyC { _mockAssemblyHelper.SetupSequence(ah => ah.GetArchitecture(It.IsAny())) .Returns(Architecture.ARM).Returns(Architecture.ARM).Returns(Architecture.ARM); - Assert.AreEqual(Architecture.ARM, _inferHelper.AutoDetectArchitecture(new List() { "ARM1.dll", "ARM2.dll", "ARM3.dll" }, _defaultArchitecture, out _)); + Assert.AreEqual(Architecture.ARM, _inferHelper.AutoDetectArchitecture(new List() { "ARM1.dll", "ARM2.dll", "ARM3.dll" }, _defaultArchitecture, out _)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny()), Times.Exactly(3)); } @@ -110,7 +110,7 @@ public void AutoDetectArchitectureShouldReturnX64ArchIfOneX64AssemblyAndRestAnyC { _mockAssemblyHelper.SetupSequence(ah => ah.GetArchitecture(It.IsAny())) .Returns(Architecture.AnyCPU).Returns(Architecture.AnyCPU).Returns(Architecture.X64); - Assert.AreEqual(Architecture.X64, _inferHelper.AutoDetectArchitecture(new List() { "x64.dll", "AnyCPU2.exe", "x64-2.dll" }, _defaultArchitecture, out _)); + Assert.AreEqual(Architecture.X64, _inferHelper.AutoDetectArchitecture(new List() { "x64.dll", "AnyCPU2.exe", "x64-2.dll" }, _defaultArchitecture, out _)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny()), Times.Exactly(3)); } @@ -119,7 +119,7 @@ public void AutoDetectArchitectureShouldReturnDefaultArchOnConflictArches() { _mockAssemblyHelper.SetupSequence(ah => ah.GetArchitecture(It.IsAny())) .Returns(Architecture.AnyCPU).Returns(Architecture.X64).Returns(Architecture.X86); - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "x64.exe", "x86.dll" }, _defaultArchitecture, out _)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "x64.exe", "x86.dll" }, _defaultArchitecture, out _)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny()), Times.Exactly(3)); } @@ -129,7 +129,7 @@ public void AutoDetectArchitectureShouldPoulateSourceArchitectureDictionary() _mockAssemblyHelper.SetupSequence(ah => ah.GetArchitecture(It.IsAny())) .Returns(Architecture.AnyCPU).Returns(Architecture.X64).Returns(Architecture.X86); - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "x64.exe", "x86.dll" }, _defaultArchitecture, out var sourceArchitectures)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "x64.exe", "x86.dll" }, _defaultArchitecture, out var sourceArchitectures)); Assert.AreEqual(3, sourceArchitectures.Count); Assert.AreEqual(_defaultArchitecture, sourceArchitectures["AnyCPU1.dll"]); Assert.AreEqual(Architecture.X64, sourceArchitectures["x64.exe"]); @@ -143,7 +143,7 @@ public void AutoDetectArchitectureShouldReturnDefaultArchIfthereIsNotDotNetAssem { _mockAssemblyHelper.SetupSequence(ah => ah.GetArchitecture(It.IsAny())) .Returns(Architecture.AnyCPU); - Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "NotDotNetAssebly.appx" }, _defaultArchitecture, out var sourceArchitectures)); + Assert.AreEqual(_defaultArchitecture, _inferHelper.AutoDetectArchitecture(new List() { "AnyCPU1.dll", "NotDotNetAssebly.appx" }, _defaultArchitecture, out var sourceArchitectures)); _mockAssemblyHelper.Verify(ah => ah.GetArchitecture(It.IsAny()), Times.Exactly(1)); } @@ -162,7 +162,7 @@ public void AutoDetectFrameworkShouldReturnDefaultFrameworkOnEmptySources() [TestMethod] public void AutoDetectFrameworkShouldReturnDefaultFrameworkOnNullItemInSources() { - Assert.AreEqual(_defaultFramework, _inferHelper.AutoDetectFramework(new List() { null }, out _)); + Assert.AreEqual(_defaultFramework, _inferHelper.AutoDetectFramework(new List() { null! }, out _)); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs index e9e211b644..f7ab28faad 100644 --- a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs +++ b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs @@ -158,7 +158,7 @@ public void TestMessageHandlerShouldThrowExceptionIfEventArgsIsNull() var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - Assert.ThrowsException(() => loggerEvents.RaiseTestRunMessage(default)); + Assert.ThrowsException(() => loggerEvents.RaiseTestRunMessage(default!)); } [TestMethod] @@ -229,7 +229,7 @@ public void TestResultHandlerShouldThowExceptionIfEventArgsIsNull() var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - Assert.ThrowsException(() => loggerEvents.RaiseTestResult(default)); + Assert.ThrowsException(() => loggerEvents.RaiseTestResult(default!)); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs index c5a0bd3b7b..3184736b1a 100644 --- a/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs @@ -318,7 +318,7 @@ public void UpdageXPlatCodeCoverageCodebaseWithFullPathFromTestAdaptersPaths_Fou $" ", " ", " ", - "").ShowWhiteSpace(), _settingsProvider.ActiveRunSettings!.SettingsXml.ShowWhiteSpace()); + "").ShowWhiteSpace(), _settingsProvider.ActiveRunSettings!.SettingsXml!.ShowWhiteSpace()); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs index cc61259f7f..7ae16e5630 100644 --- a/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs @@ -241,7 +241,7 @@ public void ExecutorInitializeShouldCorrectlyAddLoggerWhenRunSettingsNotPassed() "; - Assert.IsTrue(RunSettingsManager.Instance.ActiveRunSettings.SettingsXml.Contains(expectedSettingsXml)); + Assert.IsTrue(RunSettingsManager.Instance.ActiveRunSettings!.SettingsXml!.Contains(expectedSettingsXml)); } [TestMethod] diff --git a/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs index 0e12256e90..bad4d57a37 100644 --- a/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs @@ -171,7 +171,7 @@ public void ShoudWarnWhenAValueIsOverriden() private XmlParseResult ParseSettingsXml(IRunSettingsProvider provider) { - var document = XDocument.Parse(provider.ActiveRunSettings.SettingsXml); + var document = XDocument.Parse(provider.ActiveRunSettings!.SettingsXml!); var runConfiguration = document ?.Root diff --git a/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs index 4fd93bbbe8..da5dd95147 100644 --- a/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs @@ -323,7 +323,7 @@ public void InitializeShouldPreserveActualJapaneseString() null); executor.Initialize(runsettingsFile); - Assert.IsTrue(_settingsProvider.ActiveRunSettings!.SettingsXml.Contains(@"C:\新しいフォルダー")); + Assert.IsTrue(_settingsProvider.ActiveRunSettings!.SettingsXml!.Contains(@"C:\新しいフォルダー")); File.Delete(runsettingsFile); } From 645be7d948867d7b542b636d154f41690bd114c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 21 Jun 2022 10:33:38 +0200 Subject: [PATCH 2/3] Fix broken test --- test/datacollector.UnitTests/DataCollectionManagerTests.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index 0b1ee93de2..59b80a8790 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -527,6 +527,12 @@ protected override bool TryGetUriFromFriendlyName(string friendlyName, out strin protected override bool IsUriValid(string? uri) { + if (uri is null) + { + // This is needed for test InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorrectAndUriIsNull + throw new ArgumentNullException(nameof(uri)); + } + return string.Equals(uri, "my://custom/datacollector") || string.Equals(uri, "my://custom/ccdatacollector"); } From 53460e3dd024068ec6857e8077d6a2bcc925f918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 21 Jun 2022 10:43:44 +0200 Subject: [PATCH 3/3] Remove test that is unhelpful --- .../DataCollectionManagerTests.cs | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index 59b80a8790..86d6cd1cb7 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -122,16 +122,6 @@ public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorre _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } - [TestMethod] - public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorrectAndUriIsNull() - { - var dataCollectorSettingsWithNullUri = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, string.Empty, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty).Replace("uri=\"\"", string.Empty)); - _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithNullUri); - - Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); - _mockDataCollector.Verify(x => x.Initialize(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); - } - [TestMethod] public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsNullAndUriIsCorrect() { @@ -527,12 +517,6 @@ protected override bool TryGetUriFromFriendlyName(string friendlyName, out strin protected override bool IsUriValid(string? uri) { - if (uri is null) - { - // This is needed for test InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorrectAndUriIsNull - throw new ArgumentNullException(nameof(uri)); - } - return string.Equals(uri, "my://custom/datacollector") || string.Equals(uri, "my://custom/ccdatacollector"); }