From b58c1cebd41ade14419d1dcc5bdbaa4ab868adbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 22 Jun 2022 14:31:41 +0200 Subject: [PATCH] Enable nullable on ObjectModel (#3793) --- playground/TestPlatform.Playground/Program.cs | 32 +++--- .../BannedSymbols.txt | 4 +- .../EventLogContainer.cs | 5 +- .../EventLogDataCollector.cs | 15 +-- .../PublicAPI/PublicAPI.Shipped.txt | 2 +- .../ManagedNameUtilities/ManagedNameParser.cs | 5 +- ...osoft.TestPlatform.AdapterUtilities.csproj | 23 +++++ .../NullableHelpers.cs | 42 ++++++++ .../NullableHelpers.tt | 45 +++++++++ .../BannedSymbols.txt | 4 +- ...stRunAttachmentsProcessingEventsHandler.cs | 4 +- .../Discovery/DiscoveryRequest.cs | 6 +- .../Execution/TestRunRequest.cs | 6 +- .../PublicAPI/PublicAPI.Shipped.txt | 8 +- .../TestPlatform.cs | 22 +++-- .../TestSession/TestSessionEventsHandler.cs | 6 +- .../BannedSymbols.txt | 4 +- .../BeforeTestRunStartResult.cs | 4 +- .../DataCollection/DataCollectionManager.cs | 16 +-- .../Interfaces/IDataCollectionManager.cs | 2 +- .../ClientProtocol/ITestLoggerManager.cs | 2 +- .../Engine/ITestCaseEventsHandler.cs | 2 +- .../ITestRunAttachmentsProcessingManager.cs | 4 +- .../RunSettings.cs | 2 +- .../Utilities/FakesUtilities.cs | 4 +- .../Utilities/RunSettingsUtilities.cs | 1 - .../TestDiscoveryEventHandler.cs | 4 +- .../TestInitializeEventsHandler.cs | 4 +- .../EventHandlers/TestRunEventsHandler.cs | 8 +- .../Interfaces/ITestRequestHandler.cs | 8 +- .../Messages/DiscoveryCompletePayload.cs | 10 +- .../Serialization/TestCaseConverter.cs | 6 +- .../Serialization/TestObjectConverter.cs | 10 +- .../TestRequestSender.cs | 4 +- .../Output/ConsoleOutput.cs | 4 +- .../Output/IOutput.cs | 4 +- .../Tracing/EqtTrace.cs | 20 ++-- .../Utilities/JobQueue.cs | 4 +- .../ValidateArg.cs | 26 ++--- .../Adapter/FrameworkHandle.cs | 2 +- .../TestRunAttachmentsProcessingManager.cs | 10 +- .../LoggerNameValueConfigurationManager.cs | 4 +- .../ParallelDiscoveryEventsHandler.cs | 6 +- .../Parallel/ParallelProxyDiscoveryManager.cs | 2 +- .../Parallel/ParallelProxyExecutionManager.cs | 2 +- .../Parallel/ParallelRunDataAggregator.cs | 2 +- .../Parallel/ParallelRunEventsHandler.cs | 6 +- .../Client/ProxyDiscoveryManager.cs | 4 +- .../Client/ProxyExecutionManager.cs | 4 +- ...ProxyExecutionManagerWithDataCollection.cs | 14 +-- .../Client/ProxyOperationManager.cs | 10 +- ...ProxyOperationManagerWithDataCollection.cs | 4 +- .../Client/TestLoggerManager.cs | 44 +++++---- .../Client/TestRunCriteriaExtensions.cs | 4 +- .../DataCollection/DataCollectionLauncher.cs | 2 +- .../DataCollectionLauncherFactory.cs | 2 +- .../DataCollectionParameters.cs | 4 +- .../DataCollectionTestRunEventsHandler.cs | 2 +- .../DefaultDataCollectionLauncher.cs | 2 +- .../DotnetDataCollectionLauncher.cs | 2 +- .../InProcDataCollectionExtensionManager.cs | 10 +- .../InProcDataCollectionSink.cs | 4 +- .../DataCollection/InProcDataCollector.cs | 2 +- .../Interfaces/IDataCollectionLauncher.cs | 2 +- .../ProxyDataCollectionManager.cs | 2 +- .../EventHandlers/IPathConverter.cs | 6 +- .../EventHandlers/NullPathConverter.cs | 2 +- .../EventHandlers/PathConverter.cs | 16 +-- .../EventHandlers/TestCaseEventsHandler.cs | 2 +- .../EventHandlers/TestRequestHandler.cs | 12 +-- .../Execution/BaseRunTests.cs | 6 +- .../Execution/RunTestsWithSources.cs | 2 +- .../Execution/RunTestsWithTests.cs | 2 +- ...stRunAttachmentsProcessingEventsHandler.cs | 4 +- .../TestEngine.cs | 44 ++++----- .../TestSession/ProxyTestSessionManager.cs | 3 +- .../Utilities/SourceDetailHelper.cs | 6 +- .../BannedSymbols.txt | 4 +- .../BlameCollector.cs | 10 +- .../PublicAPI/PublicAPI.Shipped.txt | 2 +- .../BannedSymbols.txt | 4 +- .../ObjectModel/TestResult.cs | 2 +- .../TrxLogger.cs | 10 +- .../Utility/Converter.cs | 6 +- .../Adapter/Interfaces/IDiscoveryContext.cs | 4 +- .../Adapter/Interfaces/IFrameworkHandle.cs | 4 +- .../Adapter/Interfaces/IFrameworkHandle2.cs | 2 - .../Adapter/Interfaces/IRunContext.cs | 8 +- .../Adapter/Interfaces/IRunSettings.cs | 6 +- .../Adapter/Interfaces/ISettingsProvider.cs | 2 - .../Interfaces/ITestCaseDiscoverySink.cs | 2 - .../Interfaces/ITestCaseFilterExpression.cs | 2 - .../Adapter/Interfaces/ITestDiscoverer.cs | 2 - .../Adapter/Interfaces/ITestExecutor.cs | 6 +- .../Adapter/Interfaces/ITestExecutor2.cs | 6 +- .../Adapter/Interfaces/ITestLog.cs | 2 - .../Adapter/TestPlatformFormatException.cs | 10 +- .../Adapter/TestsCanceledException.cs | 6 +- .../Architecture.cs | 2 - .../AttachmentSet.cs | 6 +- .../Client/DiscoveryCriteria.cs | 20 ++-- .../Client/Events/DiscoveredTestsEventArgs.cs | 6 +- .../Events/DiscoveryCompleteEventArgs.cs | 14 ++- .../Client/Events/DiscoveryStartEventArgs.cs | 2 - .../StartTestSessionCompleteEventArgs.cs | 6 +- .../StopTestSessionCompleteEventArgs.cs | 10 +- ...nAttachmentsProcessingCompleteEventArgs.cs | 8 +- ...nAttachmentsProcessingProgressEventArgs.cs | 2 - .../Client/Events/TestRunChangedEventArgs.cs | 10 +- .../Client/Events/TestRunCompleteEventArgs.cs | 24 ++--- .../Client/Events/TestRunStartEventArgs.cs | 2 - .../Client/FilterOptions.cs | 12 +-- .../Client/Interfaces/IBaseProxy.cs | 6 +- .../Client/Interfaces/IDiscoveryRequest.cs | 2 - .../IInternalTestRunEventsHandler.cs | 6 +- .../Client/Interfaces/IMetricsCollection.cs | 2 - .../Client/Interfaces/IRequest.cs | 2 - .../Client/Interfaces/IRequestData.cs | 4 +- .../Interfaces/ITestDiscoveryEventsHandler.cs | 8 +- .../ITestDiscoveryEventsHandler2.cs | 6 +- .../Client/Interfaces/ITestHostLauncher.cs | 2 - .../Client/Interfaces/ITestPlatform.cs | 8 +- .../Interfaces/ITestPlatformCapabilities.cs | 2 - ...stRunAttachmentsProcessingEventsHandler.cs | 4 +- .../Interfaces/ITestRunConfiguration.cs | 2 - .../Interfaces/ITestRunEventsHandler.cs | 8 +- .../Interfaces/ITestRunEventsHandler2.cs | 2 - .../Client/Interfaces/ITestRunRequest.cs | 2 - .../Client/Interfaces/ITestRunStatistics.cs | 4 +- .../Interfaces/ITestSessionEventsHandler.cs | 10 +- .../Payloads/CustomHostLaunchAckPayload.cs | 4 +- .../Payloads/DiscoveryRequestPayload.cs | 10 +- .../EditorAttachDebuggerAckPayload.cs | 4 +- .../Payloads/StartTestSessionAckPayload.cs | 4 +- .../Payloads/StartTestSessionPayload.cs | 8 +- .../Payloads/StopTestSessionAckPayload.cs | 4 +- .../Client/Payloads/StopTestSessionPayload.cs | 6 +- .../TestRunAttachmentsProcessingPayload.cs | 8 +- .../Client/Payloads/TestRunRequestPayload.cs | 12 +-- .../Client/ProtocolConfig.cs | 2 - .../Client/StartTestSessionCriteria.cs | 8 +- .../Client/TestPlatformOptions.cs | 10 +- .../Client/TestRunCriteria.cs | 10 +- .../Client/TestRunState.cs | 2 - .../Client/TestRunStatistics.cs | 12 +-- .../Client/TestSessionInfo.cs | 16 ++- .../CodeCoverage/TestSDKAutoGeneratedCode.cs | 2 - .../TestRunnerConnectionInfo.cs | 4 +- .../TestRunnerConnectionInfoExtensions.cs | 6 +- .../Constants.cs | 2 - .../DataCollectorAttachmentProcessor.cs | 2 - .../DataCollectorFriendlyNameAttribute.cs | 2 - .../DataCollectorTypeUriAttribute.cs | 2 - .../Common/DataCollectorMessageLevel.cs | 2 - .../DataCollector/Common/FileHelper.cs | 12 +-- .../DataCollector/Common/RequestId.cs | 18 ++-- .../DataCollector/Common/Session.cs | 17 +--- .../Common/TestCaseFailureType.cs | 2 - .../DataCollector/Common/TestExecId.cs | 17 +--- .../DataCollector/DataCollectionContext.cs | 28 +++--- .../DataCollectionEnvironmentContext.cs | 21 ++-- .../DataCollector/DataCollectionLogger.cs | 2 - .../DataCollectionRunSettings.cs | 2 - .../DataCollector/DataCollector.cs | 6 +- .../DataCollector/DataCollectorSettings.cs | 24 ++--- .../Events/DataCollectionEventArgs.cs | 23 +---- .../Events/DataCollectionEvents.cs | 12 +-- .../DataCollector/Events/SessionEvents.cs | 23 +++-- .../DataCollector/Events/TestCaseEvents.cs | 19 ++-- .../Events/TestHostLaunchedEvent.cs | 2 - .../DataCollector/IDataCollectionSink.cs | 2 - .../IDataCollectorAttachmentProcessor.cs | 6 +- .../IDataCollectorAttachments.cs | 2 - .../ITestExecutionEnvironmentSpecifier.cs | 2 - .../InProcDataCollectionArgs.cs | 2 - .../InProcDataCollector.cs | 2 - .../InProcDataCollector/TestCaseStartArgs.cs | 6 +- .../TestSessionStartArgs.cs | 21 ++-- .../BaseTransferInformation.cs | 9 +- .../FileTransferInformation.cs | 2 - .../DefaultExecutorUriAttribute.cs | 10 +- .../ExceptionConverter.cs | 10 +- .../ExtensionUriAttribute.cs | 10 +- .../FileExtensionAttribute.cs | 10 +- .../Framework.cs | 18 ++-- .../FrameworkVersion.cs | 2 - .../FriendlyNameAttribute.cs | 10 +- .../Host/ITestRunTimeProvider.cs | 9 +- .../Host/ITestRuntimeProvider2.cs | 2 - .../InvokedDataCollector.cs | 20 ++-- .../LazyPropertyValue.cs | 8 +- .../Logger/ITestLogger.cs | 2 - .../Logger/ITestLoggerWithParams.cs | 4 +- .../Logger/LoggerRunSettings.cs | 2 - .../Logger/LoggerSettings.cs | 24 ++--- .../Logger/TestLoggerEvents.cs | 18 ++-- .../Events/DataCollectionMessageEventArgs.cs | 9 +- .../Logging/Events/TestResultEventArgs.cs | 2 - .../Logging/Events/TestRunMessageEventArgs.cs | 9 +- .../Logging/Events/TestRunStartedEventArgs.cs | 6 +- .../Logging/Interfaces/IMessageLogger.cs | 2 - .../Logging/TestMessageLevel.cs | 2 - .../Navigation/DiaNavigationData.cs | 6 +- .../Navigation/DiaSession.cs | 23 ++--- .../Navigation/FullSymbolReader.cs | 82 ++++++++-------- .../Navigation/INavigationData.cs | 4 +- .../Navigation/INavigationSession.cs | 4 +- .../Navigation/ISymbolReader.cs | 6 +- .../Navigation/NativeMethods.cs | 10 +- .../Navigation/PortablePdbReader.cs | 18 ++-- .../Navigation/PortableSymbolReader.cs | 19 ++-- .../PublicAPI/net6.0/PublicAPI.Shipped.txt | 1 - .../PublicAPI/net6.0/PublicAPI.Unshipped.txt | 1 - .../RegistryFreeActivationContext.cs | 2 - .../RunSettings/RunConfiguration.cs | 98 +++++++------------ .../RunSettings/SettingsException.cs | 6 +- .../RunSettings/SettingsNameAttribute.cs | 10 +- .../RunSettings/TestRunParameters.cs | 70 ++++++------- .../RunSettings/TestRunSettings.cs | 3 - .../SourceDetail.cs | 6 +- .../TestAdapterLoadingStrategy.cs | 8 +- .../TestCase.cs | 85 ++++++++-------- .../TestObject.cs | 61 ++++++------ .../TestOutcome.cs | 2 - .../TestOutcomeHelper.cs | 31 ++---- .../TestProcessStartInfo.cs | 12 +-- .../TestProperty/CustomKeyValueConverter.cs | 16 ++- .../CustomStringArrayConverter.cs | 8 +- .../TestProperty/TestProperty.cs | 27 +++-- .../TestProperty/TestPropertyAttributes.cs | 2 - .../TestResult.cs | 42 ++++---- .../TestServiceLocator.cs | 2 +- .../Trait.cs | 2 - .../TraitCollection.cs | 2 - .../UapConstants.cs | 2 - .../Utilities/AssemblyHelper.cs | 90 +++++++++-------- .../Utilities/AssemblyLoadWorker.cs | 17 ++-- .../Utilities/EqtHash.cs | 7 +- .../Utilities/FilterHelper.cs | 2 - .../Utilities/Sha1Helper.cs | 4 +- .../Utilities/StringUtilities.cs | 12 +-- .../Utilities/SuspendCodeCoverage.cs | 4 +- .../Utilities/XmlReaderUtilities.cs | 2 - .../Utilities/XmlRunSettingsUtilities.cs | 88 +++++++++-------- .../Interfaces/System/IProcessHelper.cs | 2 +- .../Interfaces/Tracing/IPlatformEqtTrace.cs | 2 +- .../PublicAPI/PublicAPI.Shipped.txt | 4 +- .../PublicAPI/net45/PublicAPI.Shipped.txt | 4 +- .../PublicAPI/net451/PublicAPI.Shipped.txt | 4 +- .../PublicAPI/net6.0/PublicAPI.Shipped.txt | 4 +- .../netcoreapp1.0/PublicAPI.Shipped.txt | 4 +- .../netcoreapp2.1/PublicAPI.Shipped.txt | 4 +- .../netstandard1.0/PublicAPI.Shipped.txt | 4 +- .../netstandard1.3/PublicAPI.Shipped.txt | 4 +- .../netstandard2.0/PublicAPI.Shipped.txt | 4 +- .../PublicAPI/uap10.0/PublicAPI.Shipped.txt | 4 +- .../common/System/ProcessHelper.cs | 2 +- .../common/Tracing/PlatformEqtTrace.cs | 8 +- .../net451/Tracing/PlatformEqtTrace.cs | 2 +- .../netstandard/System/ProcessHelper.cs | 2 +- .../netstandard/Tracing/PlatformEqtTrace.cs | 2 +- .../uap10.0/System/ProcessHelper.cs | 2 +- .../uap10.0/Tracing/PlatformEqtTrace.cs | 2 +- .../uap10.0/Tracing/UnitTestEventSource.cs | 10 +- .../BannedSymbols.txt | 4 +- .../Hosting/DefaultTestHostManager.cs | 13 ++- .../Hosting/DotnetTestHostManager.cs | 15 ++- .../InferRunSettingsHelper.cs | 8 +- .../DiscoveryEventsHandleConverter.cs | 2 +- .../VsTestConsoleRequestSender.cs | 23 +++-- src/testhost.x86/DefaultEngineInvoker.cs | 2 +- src/testhost.x86/TestHostTraceListener.cs | 4 +- src/vstest.console/BannedSymbols.txt | 4 +- src/vstest.console/CommandLine/InferHelper.cs | 6 +- src/vstest.console/Internal/ConsoleLogger.cs | 2 +- .../CLIRunSettingsArgumentProcessor.cs | 2 +- .../Processors/CollectArgumentProcessor.cs | 2 +- .../EnableBlameArgumentProcessor.cs | 26 ++--- .../Processors/ListTestsArgumentProcessor.cs | 4 +- .../RunSettingsArgumentProcessor.cs | 2 +- .../RunSpecificTestsArgumentProcessor.cs | 2 +- .../Processors/RunTestsArgumentProcessor.cs | 4 +- .../Publisher/TextFileTelemetryPublisher.cs | 1 - .../TestPlatformHelpers/TestRequestManager.cs | 47 ++++----- .../EventLogDataCollectorTests.cs | 2 +- .../DebugAssertTests.cs | 6 +- .../CodeCoverageTests.cs | 8 +- .../CustomTestHostTests.cs | 4 +- .../EventHandler/DiscoveryEventHandler.cs | 24 ++--- .../EventHandler/RunEventHandler.cs | 14 +-- ...estRunAttachmentsProcessingEventHandler.cs | 8 +- .../FindMethodExtensions.cs | 5 +- ...Platform.AdapterUtilities.UnitTests.csproj | 11 +++ .../DesignMode/DesignModeClientTests.cs | 6 +- .../Execution/TestRunRequestTests.cs | 6 +- .../TestPluginDiscovererTests.cs | 20 ++-- .../TestPluginManagerTests.cs | 4 +- .../RunSettingsProviderExtensionsTests.cs | 4 +- .../Hosting/TestHostProviderManagerTests.cs | 16 +-- .../Utilities/FakesUtilitiesTests.cs | 2 +- .../DataCollectionRequestHandlerTests.cs | 4 +- .../DataCollectionRequestSenderTests.cs | 2 +- .../Serialization/TestObjectConverterTests.cs | 4 +- ...lectorAttachmentProcessorAppDomainTests.cs | 8 +- ...lectorAttachmentsProcessorsFactoryTests.cs | 30 +++--- ...estRunAttachmentsProcessingManagerTests.cs | 10 +- .../InProcessProxyexecutionManagerTests.cs | 4 +- .../ParallelProxyExecutionManagerTests.cs | 4 +- .../ParallelRunDataAggregatorTests.cs | 8 +- .../Client/ProxyBaseManagerTests.cs | 2 +- .../Client/ProxyExecutionManagerTests.cs | 4 +- ...ExecutionManagerWithDataCollectionTests.cs | 4 +- .../Client/ProxyOperationManagerTests.cs | 18 ++-- .../Client/ProxyTestSessionManagerTests.cs | 28 +++--- ...DataCollectionTestRunEventsHandlerTests.cs | 4 +- .../DotnetDataCollectionLauncherTests.cs | 6 +- ...ProcDataCollectionExtensionManagerTests.cs | 2 +- .../InProcDataCollectionSinkTests.cs | 4 +- .../ProxyDataCollectionManagerTests.cs | 10 +- .../Execution/BaseRunTestsTests.cs | 16 +-- .../Execution/ExecutionManagerTests.cs | 24 ++--- .../Execution/RunTestsWithSourcesTests.cs | 14 +-- .../Execution/RunTestsWithTestsTests.cs | 4 +- .../Execution/TestRunCacheTests.cs | 8 +- .../TestLoggerManagerTests.cs | 4 +- .../TestableRuntimeProvider.cs | 18 ++-- .../TrxLoggerTests.cs | 6 +- .../DiaSessionTests.cs | 10 +- .../Events/SessionEventsTests.cs | 2 +- .../FrameworkTests.cs | 16 +-- .../RunSettings/RunConfigurationTests.cs | 14 +-- .../RunSettings/RunSettingsTests.cs | 4 +- .../TestObjectTests.cs | 2 +- .../Utilities/FilterHelperTests.cs | 4 +- .../Utilities/XmlRunSettingsUtilitiesTests.cs | 50 +++++----- .../TranslationLayer/DiscoveryPerfTests.cs | 4 +- .../EventHandler/DiscoveryEventHandler.cs | 8 +- .../EventHandler/RunEventHandler.cs | 12 +-- .../TranslationLayer/ExecutionPerfTests.cs | 4 +- .../Hosting/DefaultTestHostManagerTests.cs | 14 +-- .../Hosting/DotnetTestHostManagerTests.cs | 36 +++---- .../InferRunSettingsHelperTests.cs | 6 +- .../VsTestConsoleRequestSenderTests.cs | 64 ++++++------ .../CustomDataCollector.cs | 4 +- .../DataCollectionManagerTests.cs | 4 +- .../DummyDataCollectors.cs | 20 ++-- .../TestPlatformDataCollectionEventsTests.cs | 6 +- .../TestPlatformDataCollectionLoggerTests.cs | 4 +- test/testhost.UnitTests/NullableHelpers.cs | 42 ++++++++ test/testhost.UnitTests/NullableHelpers.tt | 45 +++++++++ .../TestHostTraceListenerTests.cs | 2 +- .../testhost.UnitTests.csproj | 19 ++++ .../Fakes/FakeOutput.cs | 4 +- .../Fakes/FakeProcess.cs | 6 +- .../Fakes/FakeProcessHelper.cs | 2 +- .../Fakes/FakeTestRuntimeProvider.cs | 18 ++-- .../Fakes/FakeTestSessionEventsHandler.cs | 12 +-- test/vstest.ProgrammerTests/Fakes/Fixture.cs | 4 +- .../Fakes/OutputMessage.cs | 4 +- .../Fakes/TestMessage.cs | 4 +- .../MultiTFMRunAndDiscovery.cs | 2 +- .../CommandLine/InferHelperTests.cs | 18 ++-- .../ExecutorUnitTests.cs | 30 +++--- .../Internal/ConsoleLoggerTests.cs | 88 ++++++++--------- ...nableCodeCoverageArgumentProcessorTests.cs | 2 +- .../Processors/HelpArgumentProcessorTests.cs | 8 +- .../RunSettingsArgumentProcessorTests.cs | 2 +- .../TestRequestManagerTests.cs | 58 +++++------ 368 files changed, 1786 insertions(+), 1962 deletions(-) create mode 100644 src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.cs create mode 100644 src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.tt delete mode 100644 src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Shipped.txt delete mode 100644 src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Unshipped.txt create mode 100644 test/testhost.UnitTests/NullableHelpers.cs create mode 100644 test/testhost.UnitTests/NullableHelpers.tt diff --git a/playground/TestPlatform.Playground/Program.cs b/playground/TestPlatform.Playground/Program.cs index 59b93ffec7..9c17968abd 100644 --- a/playground/TestPlatform.Playground/Program.cs +++ b/playground/TestPlatform.Playground/Program.cs @@ -42,7 +42,7 @@ static void Main(string[] args) var sourceSettings = $$$""" - + @@ -135,7 +135,7 @@ public class PlaygroundTestDiscoveryHandler : ITestDiscoveryEventsHandler, ITest public List TestCases { get; internal set; } = new List(); - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { Console.WriteLine($"[DISCOVERY.PROGRESS]"); Console.WriteLine(WriteTests(discoveredTestCases)); @@ -143,7 +143,7 @@ public void HandleDiscoveredTests(IEnumerable discoveredTestCases) if (discoveredTestCases != null) { TestCases.AddRange(discoveredTestCases); } } - public void HandleDiscoveryComplete(long totalTests, IEnumerable lastChunk, bool isAborted) + public void HandleDiscoveryComplete(long totalTests, IEnumerable? lastChunk, bool isAborted) { Console.WriteLine($"[DISCOVERY.COMPLETE] aborted? {isAborted}, tests count: {totalTests}"); Console.WriteLine("Last chunk:"); @@ -151,7 +151,7 @@ public void HandleDiscoveryComplete(long totalTests, IEnumerable lastC if (lastChunk != null) { TestCases.AddRange(lastChunk); } } - public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable lastChunk) + public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable? lastChunk) { Console.WriteLine($"[DISCOVERY.COMPLETE] aborted? {discoveryCompleteEventArgs.IsAborted}, tests count: {discoveryCompleteEventArgs.TotalCount}, discovered count: {_testCasesCount}"); Console.WriteLine("Last chunk:"); @@ -167,7 +167,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete if (lastChunk != null) { TestCases.AddRange(lastChunk); } } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { Console.WriteLine($"[DISCOVERY.{level.ToString().ToUpper()}] {message}"); } @@ -177,12 +177,12 @@ public void HandleRawMessage(string rawMessage) Console.WriteLine($"[DISCOVERY.MESSAGE] {rawMessage}"); } - private static string WriteTests(IEnumerable testCases) + private static string WriteTests(IEnumerable? testCases) => testCases?.Any() == true - ? "\t" + string.Join("\n\t", testCases.Select(r => r.Source + " " + r.DisplayName)) + ? "\t" + string.Join("\n\t", testCases?.Select(r => r.Source + " " + r.DisplayName)) : "\t"; - private static string WriteSources(IEnumerable sources) + private static string WriteSources(IEnumerable? sources) => sources?.Any() == true ? "\t" + string.Join("\n\t", sources) : "\t"; @@ -195,7 +195,7 @@ public TestRunHandler() { } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { Console.WriteLine($"[{level.ToString().ToUpper()}]: {message}"); } @@ -205,16 +205,16 @@ public void HandleRawMessage(string rawMessage) Console.WriteLine($"[RUN.MESSAGE]: {rawMessage}"); } - public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection runContextAttachments, ICollection executorUris) + public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs? lastChunkArgs, ICollection? runContextAttachments, ICollection? executorUris) { Console.WriteLine($"[RUN.COMPLETE]: err: {testRunCompleteArgs.Error}, lastChunk:"); Console.WriteLine(WriteTests(lastChunkArgs?.NewTestResults)); } - public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) + public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs) { Console.WriteLine($"[RUN.PROGRESS]"); - Console.WriteLine(WriteTests(testRunChangedArgs.NewTestResults)); + Console.WriteLine(WriteTests(testRunChangedArgs?.NewTestResults)); } public int LaunchProcessWithDebuggerAttached(TestProcessStartInfo testProcessStartInfo) @@ -261,7 +261,7 @@ internal class TestSessionHandler : ITestSessionEventsHandler { public TestSessionInfo? TestSessionInfo { get; private set; } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { } @@ -271,12 +271,12 @@ public void HandleRawMessage(string rawMessage) } - public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs eventArgs) + public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs? eventArgs) { - TestSessionInfo = eventArgs.TestSessionInfo; + TestSessionInfo = eventArgs?.TestSessionInfo; } - public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs eventArgs) + public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs? eventArgs) { } diff --git a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/BannedSymbols.txt b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/BannedSymbols.txt index c3370ddb45..209d2ca894 100644 --- a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/BannedSymbols.txt +++ b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/BannedSymbols.txt @@ -1,4 +1,4 @@ -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead -M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead diff --git a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs index 33049428e5..737cb666b0 100644 --- a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs +++ b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs @@ -24,8 +24,7 @@ internal class EventLogContainer : IEventLogContainer private readonly int _maxLogEntries; private readonly DataCollectionLogger _dataCollectionLogger; - - private readonly DataCollectionContext? _dataCollectionContext; + private readonly DataCollectionContext _dataCollectionContext; /// /// Keeps track of if we are disposed. @@ -53,7 +52,7 @@ internal class EventLogContainer : IEventLogContainer /// /// Data Collection Context /// - public EventLogContainer(string eventLogName, ISet? eventSources, ISet entryTypes, int maxLogEntries, DataCollectionLogger dataCollectionLogger, DataCollectionContext? dataCollectionContext) + public EventLogContainer(string eventLogName, ISet? eventSources, ISet entryTypes, int maxLogEntries, DataCollectionLogger dataCollectionLogger, DataCollectionContext dataCollectionContext) { EventLog = new EventLog(eventLogName); EventLog.EnableRaisingEvents = true; diff --git a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs index e69b72c5d4..d72079d4d7 100644 --- a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs +++ b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs @@ -147,13 +147,13 @@ internal EventLogDataCollector(IFileHelper fileHelper) /// Used by the data collector to send warnings, errors, or other messages /// /// Provides contextual information about the agent environment - [MemberNotNull(nameof(_events), nameof(_dataSink), nameof(_logger))] + [MemberNotNull(nameof(_events), nameof(_dataSink), nameof(_logger), nameof(_dataCollectorContext))] public override void Initialize( XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext dataCollectionEnvironmentContext) + DataCollectionEnvironmentContext? dataCollectionEnvironmentContext) { ValidateArg.NotNull(events, nameof(events)); ValidateArg.NotNull(dataSink, nameof(dataSink)); @@ -163,7 +163,7 @@ public override void Initialize( _events = events; _dataSink = dataSink; _logger = logger; - _dataCollectorContext = dataCollectionEnvironmentContext.SessionDataCollectionContext; + _dataCollectorContext = dataCollectionEnvironmentContext!.SessionDataCollectionContext; // Load the configuration CollectorNameValueConfigurationManager nameValueSettings = @@ -173,7 +173,7 @@ public override void Initialize( ConfigureEventSources(nameValueSettings); ConfigureEntryTypes(nameValueSettings); ConfigureMaxEntries(nameValueSettings); - ConfigureEventLogNames(nameValueSettings); + ConfigureEventLogNames(nameValueSettings, _dataCollectorContext); // Register for events events.SessionStart += _sessionStartEventHandler; @@ -183,6 +183,7 @@ public override void Initialize( } #endregion + /// /// The write event logs. /// @@ -444,7 +445,7 @@ private void WriteCollectedEventLogEntries( } [MemberNotNull(nameof(EventLogNames))] - private void ConfigureEventLogNames(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager) + private void ConfigureEventLogNames(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager, DataCollectionContext dataCollectorContext) { EventLogNames = new HashSet(); string? eventLogs = collectorNameValueConfigurationManager[EventLogConstants.SettingEventLogs]; @@ -476,7 +477,7 @@ private void ConfigureEventLogNames(CollectorNameValueConfigurationManager colle EntryTypes, int.MaxValue, _logger, - _dataCollectorContext); + dataCollectorContext); _eventLogContainerMap.Add(eventLogName, eventLogContainer); } @@ -485,7 +486,7 @@ private void ConfigureEventLogNames(CollectorNameValueConfigurationManager colle catch (Exception ex) { _logger.LogError( - _dataCollectorContext, + dataCollectorContext, new EventLogCollectorException(string.Format(CultureInfo.CurrentCulture, Resource.ReadError, eventLogName, Environment.MachineName), ex)); } } diff --git a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/PublicAPI/PublicAPI.Shipped.txt b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/PublicAPI/PublicAPI.Shipped.txt index 31068b5e95..d60cc5e95a 100644 --- a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/PublicAPI/PublicAPI.Shipped.txt +++ b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/PublicAPI/PublicAPI.Shipped.txt @@ -2,4 +2,4 @@ Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.EventLogDataCollector() -> void override Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.Dispose(bool disposing) -> void -override Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.Initialize(System.Xml.XmlElement? configurationElement, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEvents! events, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionSink! dataSink, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEnvironmentContext! dataCollectionEnvironmentContext) -> void +override Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.Initialize(System.Xml.XmlElement? configurationElement, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEvents! events, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionSink! dataSink, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEnvironmentContext? dataCollectionEnvironmentContext) -> void diff --git a/src/Microsoft.TestPlatform.AdapterUtilities/ManagedNameUtilities/ManagedNameParser.cs b/src/Microsoft.TestPlatform.AdapterUtilities/ManagedNameUtilities/ManagedNameParser.cs index 4c5ddf6a47..72bf06d66c 100644 --- a/src/Microsoft.TestPlatform.AdapterUtilities/ManagedNameUtilities/ManagedNameParser.cs +++ b/src/Microsoft.TestPlatform.AdapterUtilities/ManagedNameUtilities/ManagedNameParser.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; using Microsoft.TestPlatform.AdapterUtilities.Helpers; @@ -116,7 +115,7 @@ private static int ParseMethodName(string managedMethodName, int start, out stri // parse arity in the form `nn where nn is an integer value. private static int ParseArity(string managedMethodName, int start, out int arity) { - Debug.Assert(managedMethodName[start] == '`'); + TPDebug.Assert(managedMethodName[start] == '`'); int i = start + 1; // skip initial '`' char for (; i < managedMethodName.Length; i++) @@ -137,7 +136,7 @@ private static int ParseParameterTypeList(string managedMethodName, int start, o { return start; } - Debug.Assert(managedMethodName[start] == '('); + TPDebug.Assert(managedMethodName[start] == '('); var types = new List(); diff --git a/src/Microsoft.TestPlatform.AdapterUtilities/Microsoft.TestPlatform.AdapterUtilities.csproj b/src/Microsoft.TestPlatform.AdapterUtilities/Microsoft.TestPlatform.AdapterUtilities.csproj index 1f918f8c14..f13e7bc8fe 100644 --- a/src/Microsoft.TestPlatform.AdapterUtilities/Microsoft.TestPlatform.AdapterUtilities.csproj +++ b/src/Microsoft.TestPlatform.AdapterUtilities/Microsoft.TestPlatform.AdapterUtilities.csproj @@ -76,5 +76,28 @@ + + + + + + + NullableHelpers.cs + TextTemplatingFileGenerator + + + + + + + + + + True + True + NullableHelpers.tt + + + diff --git a/src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.cs b/src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.cs new file mode 100644 index 0000000000..6e7df36a1f --- /dev/null +++ b/src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// This code is auto-generated. Changes to this file will be lost! +// This T4 file is copied in various projects because inclusion as link or through shared project +// doesn't allow to generate the C# file locally. If some modification is required, please update +// all instances. +// + +#nullable enable + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.TestPlatform.AdapterUtilities; + +internal static class StringUtils +{ + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrEmpty(value); + + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrWhiteSpace(value); +} + +[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] +internal static class TPDebug +{ + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b) + => Debug.Assert(b); + + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b, string message) + => Debug.Assert(b, message); +} diff --git a/src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.tt b/src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.tt new file mode 100644 index 0000000000..7e3d8e7270 --- /dev/null +++ b/src/Microsoft.TestPlatform.AdapterUtilities/NullableHelpers.tt @@ -0,0 +1,45 @@ +<#@ template debug="true" hostspecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ assembly name="System.Core" #> +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// This code is auto-generated. Changes to this file will be lost! +// This T4 file is copied in various projects because inclusion as link or through shared project +// doesn't allow to generate the C# file locally. If some modification is required, please update +// all instances. +// + +#nullable enable + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace <#= System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint") #>; + +internal static class StringUtils +{ + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrEmpty(value); + + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrWhiteSpace(value); +} + +[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] +internal static class TPDebug +{ + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b) + => Debug.Assert(b); + + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b, string message) + => Debug.Assert(b, message); +} diff --git a/src/Microsoft.TestPlatform.Build/BannedSymbols.txt b/src/Microsoft.TestPlatform.Build/BannedSymbols.txt index c3370ddb45..209d2ca894 100644 --- a/src/Microsoft.TestPlatform.Build/BannedSymbols.txt +++ b/src/Microsoft.TestPlatform.Build/BannedSymbols.txt @@ -1,4 +1,4 @@ -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead -M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead diff --git a/src/Microsoft.TestPlatform.Client/AttachmentsProcessing/TestRunAttachmentsProcessingEventsHandler.cs b/src/Microsoft.TestPlatform.Client/AttachmentsProcessing/TestRunAttachmentsProcessingEventsHandler.cs index be4cc1b76c..bc7b100d52 100644 --- a/src/Microsoft.TestPlatform.Client/AttachmentsProcessing/TestRunAttachmentsProcessingEventsHandler.cs +++ b/src/Microsoft.TestPlatform.Client/AttachmentsProcessing/TestRunAttachmentsProcessingEventsHandler.cs @@ -29,7 +29,7 @@ public TestRunAttachmentsProcessingEventsHandler(ICommunicationManager communica } /// - public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable lastChunk) + public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable? lastChunk) { EqtTrace.Info("Test run attachments processing completed."); @@ -60,7 +60,7 @@ public void HandleProcessedAttachmentsChunk(IEnumerable attachmen } /// - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { var testMessagePayload = new TestMessagePayload { MessageLevel = level, Message = message }; _communicationManager.SendMessage(MessageType.TestMessage, testMessagePayload); diff --git a/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs b/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs index 2396ef04d1..03837c58fa 100644 --- a/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs +++ b/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs @@ -262,7 +262,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete if (RequestData.IsTelemetryOptedIn) { TestExtensions.AddExtensionTelemetry( - discoveryCompleteEventArgs.Metrics, + discoveryCompleteEventArgs.Metrics!, discoveryCompleteEventArgs.DiscoveredExtensions); } @@ -330,7 +330,7 @@ public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) /// /// Output level of the message being sent. /// Actual contents of the message - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { EqtTrace.Verbose("DiscoveryRequest.HandleLogMessage: Starting."); @@ -342,7 +342,7 @@ public void HandleLogMessage(TestMessageLevel level, string message) return; } - var testRunMessageEvent = new TestRunMessageEventArgs(level, message); + var testRunMessageEvent = new TestRunMessageEventArgs(level, message!); LoggerManager.HandleDiscoveryMessage(testRunMessageEvent); OnDiscoveryMessage.SafeInvoke(this, testRunMessageEvent, "DiscoveryRequest.OnTestMessageRecieved"); } diff --git a/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs b/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs index 3265d9dab1..76ceae3dca 100644 --- a/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs +++ b/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs @@ -413,7 +413,7 @@ public void HandleTestRunComplete(TestRunCompleteEventArgs runCompleteArgs, Test if (_requestData.IsTelemetryOptedIn) { TestExtensions.AddExtensionTelemetry( - runCompleteArgs.Metrics, + runCompleteArgs.Metrics!, runCompleteArgs.DiscoveredExtensions); } @@ -501,7 +501,7 @@ public virtual void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunCha /// /// Invoked when log messages are received /// - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { EqtTrace.Verbose("TestRunRequest:SendTestRunMessage: Starting."); @@ -514,7 +514,7 @@ public void HandleLogMessage(TestMessageLevel level, string message) return; } - var testRunMessageEvent = new TestRunMessageEventArgs(level, message); + var testRunMessageEvent = new TestRunMessageEventArgs(level, message!); LoggerManager.HandleTestRunMessage(testRunMessageEvent); TestRunMessage.SafeInvoke(this, testRunMessageEvent, "TestRun.LogMessages"); } diff --git a/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt index 8efd952404..233c10308c 100644 --- a/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt @@ -31,7 +31,7 @@ Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.DiscoveryC Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.Dispose() -> void Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.HandleDiscoveredTests(System.Collections.Generic.IEnumerable? discoveredTestCases) -> void Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.HandleDiscoveryComplete(Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.DiscoveryCompleteEventArgs! discoveryCompleteEventArgs, System.Collections.Generic.IEnumerable? lastChunk) -> void -Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.HandleLogMessage(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.TestMessageLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.HandleLogMessage(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.TestMessageLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.HandleRawMessage(string! rawMessage) -> void Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.OnDiscoveredTests -> System.EventHandler? Microsoft.VisualStudio.TestPlatform.Client.Discovery.DiscoveryRequest.OnDiscoveryComplete -> System.EventHandler? @@ -44,7 +44,7 @@ Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.CancelAsync( Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.DataCollectionMessage -> System.EventHandler? Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.Dispose() -> void Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.ExecuteAsync() -> int -Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.HandleLogMessage(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.TestMessageLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.HandleLogMessage(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.TestMessageLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.HandleRawMessage(string! rawMessage) -> void Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.HandleTestRunComplete(Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.TestRunCompleteEventArgs! runCompleteArgs, Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.TestRunChangedEventArgs? lastChunkArgs, System.Collections.Generic.ICollection? runContextAttachments, System.Collections.Generic.ICollection? executorUris) -> void Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.LaunchProcessWithDebuggerAttached(Microsoft.VisualStudio.TestPlatform.ObjectModel.TestProcessStartInfo! testProcessStartInfo) -> int @@ -69,10 +69,10 @@ Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.Res Microsoft.VisualStudio.TestPlatform.Client.TestPlatformFactory Microsoft.VisualStudio.TestPlatform.Client.TestPlatformFactory.TestPlatformFactory() -> void Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler -Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.HandleLogMessage(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.TestMessageLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.HandleLogMessage(Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.TestMessageLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.HandleProcessedAttachmentsChunk(System.Collections.Generic.IEnumerable! attachments) -> void Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.HandleRawMessage(string! rawMessage) -> void -Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.HandleTestRunAttachmentsProcessingComplete(Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.TestRunAttachmentsProcessingCompleteEventArgs! attachmentsProcessingCompleteEventArgs, System.Collections.Generic.IEnumerable! lastChunk) -> void +Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.HandleTestRunAttachmentsProcessingComplete(Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.TestRunAttachmentsProcessingCompleteEventArgs! attachmentsProcessingCompleteEventArgs, System.Collections.Generic.IEnumerable? lastChunk) -> void Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.HandleTestRunAttachmentsProcessingProgress(Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.TestRunAttachmentsProcessingProgressEventArgs! attachmentsProcessingProgressEventArgs) -> void Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing.TestRunAttachmentsProcessingEventsHandler.TestRunAttachmentsProcessingEventsHandler(Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces.ICommunicationManager! communicationManager) -> void static Microsoft.VisualStudio.TestPlatform.Client.DesignMode.DesignModeClient.Initialize() -> void diff --git a/src/Microsoft.TestPlatform.Client/TestPlatform.cs b/src/Microsoft.TestPlatform.Client/TestPlatform.cs index 229d016dc4..05bfe258d2 100644 --- a/src/Microsoft.TestPlatform.Client/TestPlatform.cs +++ b/src/Microsoft.TestPlatform.Client/TestPlatform.cs @@ -154,7 +154,7 @@ public bool StartTestSession( return testSessionManager.StartSession(eventsHandler, requestData); } - private void PopulateExtensions(string runSettings, IEnumerable sources) + private void PopulateExtensions(string? runSettings, IEnumerable sources) { RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings); TestAdapterLoadingStrategy strategy = runConfiguration.TestAdapterLoadingStrategy; @@ -203,22 +203,24 @@ private static void ThrowExceptionIfTestHostManagerIsNull( } - private void AddExtensionAssemblies(string runSettings, TestAdapterLoadingStrategy adapterLoadingStrategy) + private void AddExtensionAssemblies(string? runSettings, TestAdapterLoadingStrategy adapterLoadingStrategy) { IEnumerable customTestAdaptersPaths = RunSettingsUtilities.GetTestAdaptersPaths(runSettings); - if (customTestAdaptersPaths != null) + if (customTestAdaptersPaths == null) { - foreach (string customTestAdaptersPath in customTestAdaptersPaths) - { - IEnumerable extensionAssemblies = ExpandTestAdapterPaths(customTestAdaptersPath, _fileHelper, adapterLoadingStrategy); + return; + } - if (extensionAssemblies.Any()) - { - UpdateExtensions(extensionAssemblies, skipExtensionFilters: false); - } + foreach (string customTestAdaptersPath in customTestAdaptersPaths) + { + IEnumerable extensionAssemblies = ExpandTestAdapterPaths(customTestAdaptersPath, _fileHelper, adapterLoadingStrategy); + if (extensionAssemblies.Any()) + { + UpdateExtensions(extensionAssemblies, skipExtensionFilters: false); } + } } diff --git a/src/Microsoft.TestPlatform.Client/TestSession/TestSessionEventsHandler.cs b/src/Microsoft.TestPlatform.Client/TestSession/TestSessionEventsHandler.cs index 417a54cf7f..232a56a26d 100644 --- a/src/Microsoft.TestPlatform.Client/TestSession/TestSessionEventsHandler.cs +++ b/src/Microsoft.TestPlatform.Client/TestSession/TestSessionEventsHandler.cs @@ -29,9 +29,9 @@ public TestSessionEventsHandler(ICommunicationManager communicationManager) } /// - public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs eventArgs) + public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs? eventArgs) { - var ackPayload = new StartTestSessionAckPayload() + var ackPayload = new StartTestSessionAckPayload { EventArgs = eventArgs }; @@ -40,7 +40,7 @@ public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs eve } /// - public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs eventArgs) + public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs? eventArgs) { var ackPayload = new StopTestSessionAckPayload() { diff --git a/src/Microsoft.TestPlatform.Common/BannedSymbols.txt b/src/Microsoft.TestPlatform.Common/BannedSymbols.txt index c3370ddb45..209d2ca894 100644 --- a/src/Microsoft.TestPlatform.Common/BannedSymbols.txt +++ b/src/Microsoft.TestPlatform.Common/BannedSymbols.txt @@ -1,4 +1,4 @@ -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead -M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs b/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs index 546a7cabbb..44b0956ba1 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/BeforeTestRunStartResult.cs @@ -21,7 +21,7 @@ public class BeforeTestRunStartResult /// /// The data Collection Events Port. /// - public BeforeTestRunStartResult(IDictionary environmentVariables, int dataCollectionEventsPort) + public BeforeTestRunStartResult(IDictionary environmentVariables, int dataCollectionEventsPort) { EnvironmentVariables = environmentVariables; DataCollectionEventsPort = dataCollectionEventsPort; @@ -31,7 +31,7 @@ public BeforeTestRunStartResult(IDictionary environmentVariables /// Gets the environment variable dictionary. /// [DataMember] - public IDictionary EnvironmentVariables { get; private set; } + public IDictionary EnvironmentVariables { get; private set; } /// /// Gets the data collection events port. diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs index 10c21a3b81..d221a949bd 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs @@ -152,7 +152,7 @@ public static DataCollectionManager Create(IMessageSink messageSink, IRequestDat } /// - public IDictionary InitializeDataCollectors(string settingsXml) + public IDictionary InitializeDataCollectors(string settingsXml) { ValidateArg.NotNull(settingsXml, nameof(settingsXml)); if (settingsXml.Length == 0) @@ -171,11 +171,11 @@ public IDictionary InitializeDataCollectors(string settingsXml) // Environment variables are passed to testhost process, through ProcessStartInfo.EnvironmentVariables, which handles the key in a case-insensitive manner, which is translated to lowercase. // Therefore, using StringComparer.OrdinalIgnoreCase so that same keys with different cases are treated as same. - var executionEnvironmentVariables = new Dictionary(StringComparer.OrdinalIgnoreCase); + var executionEnvironmentVariables = new Dictionary(StringComparer.OrdinalIgnoreCase); var dataCollectionRunSettings = XmlRunSettingsUtilities.GetDataCollectionRunSettings(settingsXml); - _isDataCollectionEnabled = dataCollectionRunSettings.IsCollectionEnabled; + _isDataCollectionEnabled = dataCollectionRunSettings?.IsCollectionEnabled ?? false; // If dataCollectionRunSettings is null, that means datacollectors are not configured. if (dataCollectionRunSettings == null || !dataCollectionRunSettings.IsCollectionEnabled) @@ -261,10 +261,10 @@ public Collection GetInvokedDataCollectors() List invokedDataCollector = new(); foreach (DataCollectorInformation dataCollectorInformation in RunDataCollectors.Values) { - invokedDataCollector.Add(new InvokedDataCollector(dataCollectorInformation.DataCollectorConfig.TypeUri, + invokedDataCollector.Add(new InvokedDataCollector(dataCollectorInformation.DataCollectorConfig.TypeUri!, dataCollectorInformation.DataCollectorConfig.FriendlyName, - dataCollectorInformation.DataCollectorConfig.DataCollectorType.AssemblyQualifiedName, - dataCollectorInformation.DataCollectorConfig.FilePath, + dataCollectorInformation.DataCollectorConfig.DataCollectorType.AssemblyQualifiedName!, + dataCollectorInformation.DataCollectorConfig.FilePath!, dataCollectorInformation.DataCollectorConfig.HasAttachmentsProcessor())); } @@ -310,6 +310,7 @@ public void TestCaseStarted(TestCaseStartEventArgs testCaseStartEventArgs) } TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); + TPDebug.Assert(testCaseStartEventArgs.TestElement is not null, "testCaseStartEventArgs.TestElement is null"); var context = new DataCollectionContext(_dataCollectionEnvironmentContext.SessionDataCollectionContext.SessionId, testCaseStartEventArgs.TestElement); testCaseStartEventArgs.Context = context; @@ -325,6 +326,7 @@ public Collection TestCaseEnded(TestCaseEndEventArgs testCaseEndE } TPDebug.Assert(_dataCollectionEnvironmentContext is not null, "_dataCollectionEnvironmentContext is null"); + TPDebug.Assert(testCaseEndEventArgs.TestElement is not null, "testCaseEndEventArgs.TestElement is null"); var context = new DataCollectionContext(_dataCollectionEnvironmentContext.SessionDataCollectionContext.SessionId, testCaseEndEventArgs.TestElement); testCaseEndEventArgs.Context = context; @@ -391,7 +393,7 @@ 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) { TPDebug.Assert(_dataCollectorExtensionManager is not null, "_dataCollectorExtensionManager is null"); foreach (var extension in _dataCollectorExtensionManager.TestExtensions) diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs index 64dbdfef6a..c89a8d6053 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/Interfaces/IDataCollectionManager.cs @@ -20,7 +20,7 @@ internal interface IDataCollectionManager : IDisposable /// /// Run Settings which has DataCollector configuration. /// Environment variables. - IDictionary InitializeDataCollectors(string settingsXml); + IDictionary InitializeDataCollectors(string settingsXml); /// /// Raises TestCaseStart event to all data collectors configured for run. diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs index d8f220ad7c..5eb9d2e120 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ClientProtocol/ITestLoggerManager.cs @@ -24,7 +24,7 @@ bool LoggersInitialized /// /// Initialize loggers. /// - void Initialize(string runSettings); + void Initialize(string? runSettings); /// /// Handles test run message. diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs index 48db81376c..a0357cced0 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestCaseEventsHandler.cs @@ -34,7 +34,7 @@ public interface ITestCaseEventsHandler /// The purpose of this is to perform any initialization before the test case level events are sent. /// /// The session start properties. - void SendSessionStart(IDictionary properties); + void SendSessionStart(IDictionary properties); /// /// Sends session end event. diff --git a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs index 31ca7d406d..b04cfc66e5 100644 --- a/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs +++ b/src/Microsoft.TestPlatform.Common/Interfaces/Engine/ITestRunAttachmentsProcessingManager.cs @@ -23,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 @@ -33,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/RunSettings.cs b/src/Microsoft.TestPlatform.Common/RunSettings.cs index 10a9b2825a..8d9997db98 100644 --- a/src/Microsoft.TestPlatform.Common/RunSettings.cs +++ b/src/Microsoft.TestPlatform.Common/RunSettings.cs @@ -56,7 +56,7 @@ public RunSettings() /// The settings provider for the settings or null if one was not found. public ISettingsProvider? GetSettings(string settingsName) { - if (StringUtilities.IsNullOrWhiteSpace(settingsName)) + if (settingsName.IsNullOrWhiteSpace()) { throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, nameof(settingsName)); } diff --git a/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs index c3295e3b51..c493b0c380 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs @@ -139,7 +139,7 @@ internal static void InsertOrReplaceFakesDataCollectorNode(XmlDocument runSettin } // insert new node - XmlRunSettingsUtilities.InsertDataCollectorsNode(runSettings.CreateNavigator(), settings); + XmlRunSettingsUtilities.InsertDataCollectorsNode(runSettings.CreateNavigator()!, settings); } private static IDictionary CreateDictionary(IEnumerable sources, FrameworkVersion framework) @@ -200,7 +200,7 @@ and not FrameworkVersion.Framework40 } fakesSettings.Configuration = doc.DocumentElement; - XmlRunSettingsUtilities.InsertDataCollectorsNode(runSettings.CreateNavigator(), fakesSettings); + XmlRunSettingsUtilities.InsertDataCollectorsNode(runSettings.CreateNavigator()!, fakesSettings); return true; } diff --git a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs index ee01858b53..a66a6ec57b 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs @@ -54,7 +54,6 @@ public static class RunSettingsUtilities /// /// Test run configuration /// Target Framework - [return: NotNullIfNotNull("runConfiguration")] public static Framework? GetTargetFramework(RunConfiguration? runConfiguration) { if (runConfiguration != null) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs index 9b3792b07f..540f597038 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs @@ -30,7 +30,7 @@ public TestDiscoveryEventHandler(ITestRequestHandler requestHandler) /// Handles discovered tests /// /// List of test cases - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { EqtTrace.Info("Test Cases found "); _requestHandler.SendTestCases(discoveredTestCases); @@ -53,7 +53,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete /// /// Logging level. /// Logging message. - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { switch (level) { diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestInitializeEventsHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestInitializeEventsHandler.cs index 067e4f3e24..0ac0b0d1a1 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestInitializeEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestInitializeEventsHandler.cs @@ -30,9 +30,9 @@ public TestInitializeEventsHandler(ITestRequestHandler requestHandler) /// /// The level. /// The message. - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { - switch ((TestMessageLevel)level) + switch (level) { case TestMessageLevel.Informational: EqtTrace.Info(message); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs index b15c28d16f..af4a23256c 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs @@ -32,7 +32,7 @@ public TestRunEventsHandler(ITestRequestHandler requestHandler) /// Handle test run stats change. /// /// The test run changed args. - public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) + public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs) { EqtTrace.Info("Sending test run statistics"); _requestHandler.SendTestRunStatistics(testRunChangedArgs); @@ -45,7 +45,7 @@ public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) /// The last chunk args. /// The run context attachments. /// The executor uris. - public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection runContextAttachments, ICollection executorUris) + public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs? lastChunkArgs, ICollection? runContextAttachments, ICollection? executorUris) { EqtTrace.Info("Sending test run complete"); _requestHandler.SendExecutionComplete(testRunCompleteArgs, lastChunkArgs, runContextAttachments, executorUris); @@ -56,9 +56,9 @@ public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, /// /// The level. /// The message. - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { - switch ((TestMessageLevel)level) + switch (level) { case TestMessageLevel.Informational: EqtTrace.Info(message); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs index d64271926a..162f06ded7 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs @@ -49,20 +49,20 @@ public interface ITestRequestHandler : IDisposable /// The send test cases. /// /// The discovered test cases. - void SendTestCases(IEnumerable discoveredTestCases); + void SendTestCases(IEnumerable? discoveredTestCases); /// /// The send test run statistics. /// /// The test run changed args. - void SendTestRunStatistics(TestRunChangedEventArgs testRunChangedArgs); + void SendTestRunStatistics(TestRunChangedEventArgs? testRunChangedArgs); /// /// Sends the logs back to the server. /// /// The message level. /// The message. - void SendLog(TestMessageLevel messageLevel, string message); + void SendLog(TestMessageLevel messageLevel, string? message); /// /// The send execution complete. @@ -71,7 +71,7 @@ public interface ITestRequestHandler : IDisposable /// The last chunk args. /// The run context attachments. /// The executor uris. - void SendExecutionComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection runContextAttachments, ICollection executorUris); + void SendExecutionComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs? lastChunkArgs, ICollection? runContextAttachments, ICollection? executorUris); /// /// The discovery complete handler diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs index 0cb4d5ccf0..2096c6b37a 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs @@ -35,25 +35,25 @@ public class DiscoveryCompletePayload /// /// Gets or sets list of sources which were fully discovered. /// - public IList FullyDiscoveredSources { get; set; } = new List(); + public IList? FullyDiscoveredSources { get; set; } = new List(); /// /// Gets or sets list of sources which were partially discovered (started discover tests, but then discovery aborted). /// - public IList PartiallyDiscoveredSources { get; set; } = new List(); + public IList? PartiallyDiscoveredSources { get; set; } = new List(); /// /// Gets or sets list of sources which were not discovered at all. /// - public IList NotDiscoveredSources { get; set; } = new List(); + public IList? NotDiscoveredSources { get; set; } = new List(); /// /// Gets or sets list of sources which skipped in discovery on purpose, e.g. because they are known dlls that have no tests, or there is no runtime provider to run them. /// - public IList SkippedDiscoverySources { get; set; } = new List(); + public IList? SkippedDiscoverySources { get; set; } = new List(); /// /// Gets or sets the collection of discovered extensions. /// - public Dictionary> DiscoveredExtensions { get; set; } = new(); + public Dictionary>? DiscoveredExtensions { get; set; } = new(); } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs index f0b3ddc0f1..c6f2d5b30a 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs @@ -65,11 +65,11 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist case "TestCase.ExecutorUri": testCase.ExecutorUri = new Uri(propertyData!); break; case "TestCase.FullyQualifiedName": - testCase.FullyQualifiedName = propertyData; break; + testCase.FullyQualifiedName = propertyData!; break; case "TestCase.DisplayName": - testCase.DisplayName = propertyData; break; + testCase.DisplayName = propertyData!; break; case "TestCase.Source": - testCase.Source = propertyData; break; + testCase.Source = propertyData!; break; case "TestCase.CodeFilePath": testCase.CodeFilePath = propertyData; break; case "TestCase.LineNumber": diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs index ea82810608..2d37268fae 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs @@ -145,12 +145,12 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { // This call will fail with NRE on .NET Standard 1.3 var testProperty = (TestProperty)TestPropertyCtor!.Invoke(EmptyObjectArray); - testProperty.Id = property.Key.Id; - testProperty.Label = property.Key.Label; - testProperty.Category = property.Key.Category; - testProperty.Description = property.Key.Description; + testProperty.Id = property.Key.Id!; + testProperty.Label = property.Key.Label!; + testProperty.Category = property.Key.Category!; + testProperty.Description = property.Key.Description!; testProperty.Attributes = (TestPropertyAttributes)property.Key.Attributes; - testProperty.ValueType = property.Key.ValueType; + testProperty.ValueType = property.Key.ValueType!; object? propertyData = null; diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs index a99ba997fa..acf538675e 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs @@ -501,7 +501,7 @@ private void OnExecutionMessageReceived(MessageReceivedEventArgs messageReceived TPDebug.Assert(testRunCompletePayload is not null, "testRunCompletePayload is null"); testRunEventsHandler.HandleTestRunComplete( - testRunCompletePayload.TestRunCompleteArgs, + testRunCompletePayload.TestRunCompleteArgs!, testRunCompletePayload.LastRunTests, testRunCompletePayload.RunAttachments, testRunCompletePayload.ExecutorUris); @@ -515,7 +515,7 @@ private void OnExecutionMessageReceived(MessageReceivedEventArgs messageReceived break; case MessageType.LaunchAdapterProcessWithDebuggerAttached: var testProcessStartInfo = _dataSerializer.DeserializePayload(message); - int processId = testRunEventsHandler.LaunchProcessWithDebuggerAttached(testProcessStartInfo); + int processId = testRunEventsHandler.LaunchProcessWithDebuggerAttached(testProcessStartInfo!); var data = _dataSerializer.SerializePayload( diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs b/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs index 7734512571..cabca0c0f7 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs @@ -57,7 +57,7 @@ public static ConsoleOutput Instance /// /// Message to be output. /// Level of the message. - public void WriteLine(string message, OutputLevel level) + public void WriteLine(string? message, OutputLevel level) { Write(message, level); Write(Environment.NewLine, level); @@ -68,7 +68,7 @@ public void WriteLine(string message, OutputLevel level) /// /// Message to be output. /// Level of the message. - public void Write(string message, OutputLevel level) + public void Write(string? message, OutputLevel level) { switch (level) { diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.cs b/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.cs index 9cf43b6046..42e61f766f 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.cs @@ -13,12 +13,12 @@ public interface IOutput /// /// Message to be output. /// Level of the message. - void WriteLine(string message, OutputLevel level); + void WriteLine(string? message, OutputLevel level); /// /// Writes the message with no new line. /// /// Message to be output. /// Level of the message. - void Write(string message, OutputLevel level); + void Write(string? message, OutputLevel level); } diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs index ea8d3305dd..a8626373e9 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs @@ -203,7 +203,7 @@ public static void Fail(string format, params object?[] args) /// /// Error message. [Conditional("TRACE")] - public static void Error(string message) + public static void Error(string? message) { if (TraceImpl.ShouldTrace(PlatformTraceLevel.Error)) { @@ -264,7 +264,7 @@ public static void ErrorUnlessAlterTrace(bool condition, PlatformTraceLevel bump [Conditional("TRACE")] public static void Error(string format, params object?[] args) { - Debug.Assert(format != null, "format != null"); + TPDebug.Assert(format != null, "format != null"); // Check level before doing string.Format to avoid string creation if tracing is off. if (TraceImpl.ShouldTrace(PlatformTraceLevel.Error)) @@ -329,7 +329,7 @@ public static void ErrorIf(bool condition, string format, params object?[] args) [Conditional("TRACE")] public static void ErrorAssert(string format, params object?[] args) { - Debug.Assert(format != null, "format != null"); + TPDebug.Assert(format != null, "format != null"); var message = string.Format(CultureInfo.InvariantCulture, format, args); Error(message); FailDebugger(message); @@ -358,7 +358,7 @@ public static void Error(Exception exceptionToTrace) /// /// Trace message. [Conditional("TRACE")] - public static void Warning(string message) + public static void Warning(string? message) { if (TraceImpl.ShouldTrace(PlatformTraceLevel.Warning)) { @@ -419,7 +419,7 @@ public static void WarningUnlessAlterTrace(bool condition, PlatformTraceLevel bu [Conditional("TRACE")] public static void Warning(string format, params object?[] args) { - Debug.Assert(format != null, "format != null"); + TPDebug.Assert(format != null, "format != null"); // Check level before doing string.Format to avoid string creation if tracing is off. if (TraceImpl.ShouldTrace(PlatformTraceLevel.Warning)) @@ -481,7 +481,7 @@ public static void WarningUnlessAlterTrace(bool condition, PlatformTraceLevel bu /// /// Trace message. [Conditional("TRACE")] - public static void Info(string message) + public static void Info(string? message) { if (TraceImpl.ShouldTrace(PlatformTraceLevel.Info)) { @@ -542,7 +542,7 @@ public static void InfoUnlessAlterTrace(bool condition, PlatformTraceLevel bumpL [Conditional("TRACE")] public static void Info(string format, params object?[] args) { - Debug.Assert(format != null, "format != null"); + TPDebug.Assert(format != null, "format != null"); // Check level before doing string.Format to avoid string creation if tracing is off. if (TraceImpl.ShouldTrace(PlatformTraceLevel.Info)) @@ -665,7 +665,7 @@ public static void VerboseUnlessAlterTrace(bool condition, PlatformTraceLevel le [Conditional("TRACE")] public static void Verbose(string format, params object?[] args) { - Debug.Assert(format != null, "format != null"); + TPDebug.Assert(format != null, "format != null"); // Check level before doing string.Format to avoid string creation if tracing is off. if (TraceImpl.ShouldTrace(PlatformTraceLevel.Verbose)) @@ -817,7 +817,7 @@ private static void WriteAtLevel(PlatformTraceLevel level, string message) private static void WriteAtLevel(PlatformTraceLevel level, string format, params object?[] args) { - Debug.Assert(format != null, "format != null"); + TPDebug.Assert(format != null, "format != null"); WriteAtLevel(level, string.Format(CultureInfo.InvariantCulture, format, args)); } @@ -825,7 +825,7 @@ private static void FailDebugger(string message) { #if DEBUG #if NETSTANDARD1_0 - Debug.Assert(false, message); + TPDebug.Assert(false, message); #else Debug.Fail(message); #endif diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs index 8800ced76b..eba17dc8e6 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs @@ -3,12 +3,12 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestPlatform.Common.Utilities; +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Resources; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -145,7 +145,7 @@ public void QueueJob(T job, int jobSize) { CheckDisposed(); - Debug.Assert(jobSize >= 0, "Job size should never be negative"); + TPDebug.Assert(jobSize >= 0, "Job size should never be negative"); // Add the job and signal that a new job is available. InternalQueueJob(new Job(job, jobSize)); diff --git a/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs b/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs index 0b559e3225..fe0ec99b4d 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs @@ -4,9 +4,11 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Resources; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -32,7 +34,7 @@ public static class ValidateArg /// Type of argument. /// [DebuggerStepThrough] - public static T NotNull([ValidatedNotNull] T arg, string parameterName) + public static T NotNull([ValidatedNotNull] T? arg, string parameterName) { return arg ?? throw new ArgumentNullException(parameterName); } @@ -53,9 +55,9 @@ public static T NotNull([ValidatedNotNull] T arg, string parameterName) /// Thrown if the input string is null or empty. /// [DebuggerStepThrough] - public static string NotNullOrEmpty([ValidatedNotNull] string arg, string parameterName) + public static string NotNullOrEmpty([ValidatedNotNull] string? arg, string parameterName) { - return string.IsNullOrEmpty(arg) ? throw new ArgumentNullException(parameterName) : arg; + return arg.IsNullOrEmpty() ? throw new ArgumentNullException(parameterName) : arg; } /// @@ -74,9 +76,9 @@ public static string NotNullOrEmpty([ValidatedNotNull] string arg, string parame /// Thrown if the input string is null, empty or consists only of white-space characters. /// [DebuggerStepThrough] - public static string NotNullOrWhiteSpace([ValidatedNotNull] string arg, string parameterName) + public static string NotNullOrWhiteSpace([ValidatedNotNull] string? arg, string parameterName) { - return string.IsNullOrWhiteSpace(arg) ? throw new ArgumentNullException(parameterName) : arg; + return arg.IsNullOrWhiteSpace() ? throw new ArgumentNullException(parameterName) : arg; } /// @@ -116,11 +118,11 @@ public static void NotNegative(long arg, string parameterName) /// The argument to check. /// The parameter name of the argument. [DebuggerStepThrough] - public static void NotNullOrEmpty([ValidatedNotNull] IEnumerable arg, string parameterName) + public static void NotNullOrEmpty([ValidatedNotNull] IEnumerable? arg, string parameterName) { NotNull(arg, parameterName); - if (!arg.Any()) + if (!arg!.Any()) { var message = string.Format(CultureInfo.CurrentCulture, Resources.Error_ArgumentIsEmpty); throw new ArgumentException(message, parameterName); @@ -134,7 +136,7 @@ public static void NotNullOrEmpty([ValidatedNotNull] IEnumerable arg, stri /// The parameter name of the argument. /// The type of the expected argument. [DebuggerStepThrough] - public static void TypeOf([ValidatedNotNull] object arg, string parameterName) + public static void TypeOf([ValidatedNotNull] object? arg, string parameterName) where T : class { NotNull(arg, parameterName); @@ -222,11 +224,3 @@ public static void TypeOf([ValidatedNotNull] object arg, string parameterName } } } - -/// -/// Secret attribute that tells the CA1062 validate arguments rule that this method validates the argument is not null. -/// -[AttributeUsage(AttributeTargets.Parameter)] -internal sealed class ValidatedNotNullAttribute : Attribute -{ -} diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Adapter/FrameworkHandle.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Adapter/FrameworkHandle.cs index 6a86c8c549..6237da60fe 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Adapter/FrameworkHandle.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Adapter/FrameworkHandle.cs @@ -69,7 +69,7 @@ public FrameworkHandle(ITestCaseEventsHandler? testCaseEventsHandler, ITestRunCa /// Command line arguments the process should be launched with. /// Environment variables to be set in target process /// Process ID of the started process. - public int LaunchProcessWithDebuggerAttached(string filePath, string? workingDirectory, string? arguments, IDictionary? environmentVariables) + public int LaunchProcessWithDebuggerAttached(string filePath, string? workingDirectory, string? arguments, IDictionary? environmentVariables) { // If an adapter attempts to launch a process after the run is complete (=> this object is disposed) // throw an error. diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/TestRunAttachmentsProcessingManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/TestRunAttachmentsProcessingManager.cs index 70e4676403..cdd135e2d6 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/TestRunAttachmentsProcessingManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/TestRunAttachmentsProcessingManager.cs @@ -42,17 +42,17 @@ public TestRunAttachmentsProcessingManager(ITestPlatformEventSource testPlatform } /// - public async Task ProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler eventHandler, CancellationToken cancellationToken) + public async Task ProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable? invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler eventHandler, CancellationToken cancellationToken) { await InternalProcessTestRunAttachmentsAsync(runSettingsXml, requestData, attachments, invokedDataCollector, eventHandler, cancellationToken).ConfigureAwait(false); } /// - public Task> ProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable invokedDataCollector, CancellationToken cancellationToken) + public Task> ProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable? invokedDataCollector, CancellationToken cancellationToken) { return InternalProcessTestRunAttachmentsAsync(runSettingsXml, requestData, attachments, invokedDataCollector, null, cancellationToken); } - private async Task> InternalProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler? eventHandler, CancellationToken cancellationToken) + private async Task> InternalProcessTestRunAttachmentsAsync(string? runSettingsXml, IRequestData requestData, IEnumerable attachments, IEnumerable? invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler? eventHandler, CancellationToken cancellationToken) { var stopwatch = Stopwatch.StartNew(); Collection localAttachments = new(attachments.ToList()); @@ -103,7 +103,7 @@ private async Task> InternalProcessTestRunAttachmentsA } } - private async Task> ProcessAttachmentsAsync(string? runSettingsXml, Collection attachments, IEnumerable invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler? eventsHandler, CancellationToken cancellationToken) + private async Task> ProcessAttachmentsAsync(string? runSettingsXml, Collection attachments, IEnumerable? invokedDataCollector, ITestRunAttachmentsProcessingEventsHandler? eventsHandler, CancellationToken cancellationToken) { if (attachments.Count == 0) { @@ -169,7 +169,7 @@ private async Task> ProcessAttachmentsAsync(string? ru EqtTrace.Info($"TestRunAttachmentsProcessingManager: Invocation of data collector attachment processor AssemblyQualifiedName: '{dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName}' FriendlyName: '{dataCollectorAttachmentsProcessor.FriendlyName}' with configuration '{(configuration == null ? "null" : configuration.OuterXml)}'"); ICollection processedAttachments = await dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.ProcessAttachmentSetsAsync( - configuration, + configuration!, new Collection(attachmentsToBeProcessed), progressReporter, logger, diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/LoggerNameValueConfigurationManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/LoggerNameValueConfigurationManager.cs index 4237430e62..2e39bd1c7a 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/LoggerNameValueConfigurationManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/LoggerNameValueConfigurationManager.cs @@ -21,14 +21,14 @@ internal class LoggerNameValueConfigurationManager /// /// XML element containing the configuration /// - public LoggerNameValueConfigurationManager(XmlElement configurationElement) + public LoggerNameValueConfigurationManager(XmlElement? configurationElement) { Initialize(configurationElement); } public Dictionary NameValuePairs { get; } = new(); - private void Initialize(XmlElement configurationElement) + private void Initialize(XmlElement? configurationElement) { if (configurationElement == null) { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelDiscoveryEventsHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelDiscoveryEventsHandler.cs index 840aa59e07..faa65eb1e8 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelDiscoveryEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelDiscoveryEventsHandler.cs @@ -181,13 +181,13 @@ public void HandleRawMessage(string rawMessage) } /// - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { _actualDiscoveryEventsHandler.HandleDiscoveredTests(discoveredTestCases); } /// - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { _actualDiscoveryEventsHandler.HandleLogMessage(level, message); } @@ -199,7 +199,7 @@ public void HandleLogMessage(TestMessageLevel level, string message) /// private void ConvertToRawMessageAndSend(string messageType, object payload) { - var rawMessage = _dataSerializer.SerializePayload(messageType, payload, _requestData.ProtocolConfig.Version); + var rawMessage = _dataSerializer.SerializePayload(messageType, payload, _requestData.ProtocolConfig!.Version); _actualDiscoveryEventsHandler.HandleRawMessage(rawMessage); } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs index 60e361786a..ea30a418e1 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs @@ -63,7 +63,7 @@ internal ParallelProxyDiscoveryManager( _isParallel = parallelLevel > 1; _parallelOperationManager = new(actualProxyManagerCreator, parallelLevel); _sourceToTestHostProviderMap = testHostProviders - .SelectMany(provider => provider.SourceDetails.Select(s => new KeyValuePair(s.Source, provider))) + .SelectMany(provider => provider.SourceDetails.Select(s => new KeyValuePair(s.Source!, provider))) .ToDictionary(pair => pair.Key, pair => pair.Value); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs index fb6793a45b..895806f460 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs @@ -80,7 +80,7 @@ internal ParallelProxyExecutionManager( _isParallel = parallelLevel > 1; _parallelOperationManager = new(actualProxyManagerCreator, parallelLevel); _sourceToTestHostProviderMap = testHostProviders - .SelectMany(provider => provider.SourceDetails.Select(s => new KeyValuePair(s.Source, provider))) + .SelectMany(provider => provider.SourceDetails.Select(s => new KeyValuePair(s.Source!, provider))) .ToDictionary(pair => pair.Key, pair => pair.Value); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs index 22a0ff14b4..1661ebee74 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs @@ -78,7 +78,7 @@ public ITestRunStatistics GetAggregatedRunStats() foreach (var runStats in _testRunStatsList) { // TODO: we get nullref here if the stats are empty. - foreach (var outcome in runStats.Stats.Keys) + foreach (var outcome in runStats.Stats!.Keys) { if (!testOutcomeMap.ContainsKey(outcome)) { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunEventsHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunEventsHandler.cs index 19f5c540b3..1ea36cfd62 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunEventsHandler.cs @@ -171,12 +171,12 @@ public void HandleRawMessage(string rawMessage) } } - public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) + public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs) { _actualRunEventsHandler.HandleTestRunStatsChange(testRunChangedArgs); } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { _actualRunEventsHandler.HandleLogMessage(level, message); } @@ -194,7 +194,7 @@ public bool AttachDebuggerToProcess(AttachDebuggerInfo attachDebuggerInfo) private void ConvertToRawMessageAndSend(string messageType, object payload) { - var rawMessage = _dataSerializer.SerializePayload(messageType, payload, _requestData.ProtocolConfig.Version); + var rawMessage = _dataSerializer.SerializePayload(messageType, payload, _requestData.ProtocolConfig!.Version); _actualRunEventsHandler.HandleRawMessage(rawMessage); } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs index bdf8a5a727..cd7efafb71 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs @@ -278,7 +278,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete } /// - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { _previousSource = _discoveryDataAggregator.MarkSourcesBasedOnDiscoveredTestCases(_previousSource, discoveredTestCases); _baseTestDiscoveryEventsHandler?.HandleDiscoveredTests(discoveredTestCases); @@ -297,7 +297,7 @@ public void HandleRawMessage(string rawMessage) } /// - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { _baseTestDiscoveryEventsHandler?.HandleLogMessage(level, message); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs index 10e84f0ce8..1a4f1ae31d 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs @@ -374,7 +374,7 @@ public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, } /// - public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) + public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs) { _baseTestRunEventsHandler?.HandleTestRunStatsChange(testRunChangedArgs); } @@ -396,7 +396,7 @@ public void HandleRawMessage(string rawMessage) } /// - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { _baseTestRunEventsHandler?.HandleLogMessage(level, message); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManagerWithDataCollection.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManagerWithDataCollection.cs index 1d0ff0a114..d0d9cc817b 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManagerWithDataCollection.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManagerWithDataCollection.cs @@ -20,7 +20,7 @@ namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client; /// internal class ProxyExecutionManagerWithDataCollection : ProxyExecutionManager { - private IDictionary? _dataCollectionEnvironmentVariables; + private IDictionary? _dataCollectionEnvironmentVariables; private int _dataCollectionPort; private readonly IRequestData _requestData; @@ -54,7 +54,7 @@ public ProxyExecutionManagerWithDataCollection( ProxyDataCollectionManager = proxyDataCollectionManager; DataCollectionRunEventsHandler = new DataCollectionRunEventsHandler(); _requestData = requestData; - _dataCollectionEnvironmentVariables = new Dictionary(); + _dataCollectionEnvironmentVariables = new Dictionary(); testHostManager.HostLaunched += TestHostLaunchedHandler; } @@ -150,7 +150,7 @@ public override int LaunchProcessWithDebuggerAttached(TestProcessStartInfo testP { if (testProcessStartInfo.EnvironmentVariables == null) { - testProcessStartInfo.EnvironmentVariables = new Dictionary(); + testProcessStartInfo.EnvironmentVariables = new Dictionary(); } foreach (var envVariable in _dataCollectionEnvironmentVariables) @@ -202,18 +202,18 @@ internal class DataCollectionRunEventsHandler : ITestMessageEventHandler /// public DataCollectionRunEventsHandler() { - Messages = new List>(); + Messages = new List>(); } /// /// Gets the cached messages. /// - public List> Messages { get; private set; } + public List> Messages { get; private set; } /// - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { - Messages.Add(new Tuple(level, message)); + Messages.Add(new Tuple(level, message)); } /// diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs index dc2f02b9bf..dc56206cd8 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; @@ -403,6 +404,7 @@ public virtual TestProcessStartInfo UpdateTestProcessStartInfo(TestProcessStartI return updatedRunSettingsXml; } + [return: NotNullIfNotNull("logFile")] private static string? GetTimestampedLogFile(string? logFile) { return logFile.IsNullOrWhiteSpace() @@ -437,16 +439,16 @@ private void CompatIssueWithVersionCheckAndRunsettings() } } - private void TestHostManagerHostLaunched(object? sender, HostProviderEventArgs e) + private void TestHostManagerHostLaunched(object? sender, HostProviderEventArgs? e) { - EqtTrace.Verbose(e.Data); + EqtTrace.Verbose(e!.Data); _testHostProcessId = e.ProcessId; } - private void TestHostManagerHostExited(object? sender, HostProviderEventArgs e) + private void TestHostManagerHostExited(object? sender, HostProviderEventArgs? e) { EqtTrace.Verbose("CrossPlatEngine.TestHostManagerHostExited: calling on client process exit callback."); - _testHostProcessStdError = e.Data; + _testHostProcessStdError = e!.Data; // This needs to be set before we call the OnClientProcess exit because the // OnClientProcess will short-circuit WaitForRequestHandlerConnection in SetupChannel diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManagerWithDataCollection.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManagerWithDataCollection.cs index a83c6bed74..3edacd86b9 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManagerWithDataCollection.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManagerWithDataCollection.cs @@ -17,7 +17,7 @@ namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client; /// public class ProxyOperationManagerWithDataCollection : ProxyOperationManager { - private IDictionary? _dataCollectionEnvironmentVariables; + private IDictionary? _dataCollectionEnvironmentVariables; private readonly IRequestData _requestData; private int _dataCollectionPort; @@ -45,7 +45,7 @@ public ProxyOperationManagerWithDataCollection( ProxyDataCollectionManager = proxyDataCollectionManager; DataCollectionRunEventsHandler = new DataCollectionRunEventsHandler(); _requestData = requestData; - _dataCollectionEnvironmentVariables = new Dictionary(); + _dataCollectionEnvironmentVariables = new Dictionary(); testHostManager.HostLaunched += TestHostLaunchedHandler; } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs index 0d6907e68d..a9295aa32d 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs @@ -155,7 +155,7 @@ public void Initialize(string? runSettings) // Try initializing logger by type. if (!StringUtils.IsNullOrWhiteSpace(logger.AssemblyQualifiedName)) { - loggerInitialized = InitializeLoggerByType(logger.AssemblyQualifiedName, logger.CodeBase, parameters); + loggerInitialized = InitializeLoggerByType(logger.AssemblyQualifiedName, logger.CodeBase!, parameters); } // Try initializing logger by uri. @@ -220,7 +220,7 @@ public void HandleTestRunStatsChange(TestRunChangedEventArgs e) return; } - foreach (TestResult result in e.NewTestResults) + foreach (TestResult result in e.NewTestResults!) { _loggerEvents.RaiseTestResult(new TestResultEventArgs(result)); } @@ -393,30 +393,32 @@ internal bool InitializeLoggerByUri(Uri uri, Dictionary? parame /// The friendly Name. /// The logger Uri. /// - internal bool TryGetUriFromFriendlyName(string friendlyName, out Uri? loggerUri) + internal bool TryGetUriFromFriendlyName(string? friendlyName, out Uri? loggerUri) { var extensionManager = TestLoggerExtensionManager; foreach (var extension in extensionManager.TestExtensions) { - if (string.Equals(friendlyName, extension.Metadata.FriendlyName, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(friendlyName, extension.Metadata.FriendlyName, StringComparison.OrdinalIgnoreCase)) { - try - { - loggerUri = new Uri(extension.Metadata.ExtensionUri); - } - catch (UriFormatException) - { - loggerUri = null; - - throw new InvalidLoggerException( - string.Format( - CultureInfo.CurrentUICulture, - CommonResources.LoggerUriInvalid, - extension.Metadata.ExtensionUri)); - } + continue; + } - return true; + try + { + loggerUri = new Uri(extension.Metadata.ExtensionUri); } + catch (UriFormatException) + { + loggerUri = null; + + throw new InvalidLoggerException( + string.Format( + CultureInfo.CurrentUICulture, + CommonResources.LoggerUriInvalid, + extension.Metadata.ExtensionUri)); + } + + return true; } loggerUri = null; @@ -520,7 +522,7 @@ internal virtual void Dispose(bool disposing) /// /// /// - private static Dictionary GetParametersFromConfigurationElement(XmlElement configuration) + private static Dictionary GetParametersFromConfigurationElement(XmlElement? configuration) { var configurationManager = new LoggerNameValueConfigurationManager(configuration); return configurationManager.NameValuePairs; @@ -596,7 +598,7 @@ private bool InitializeLogger(object? logger, string? extensionUri, Dictionary? inputPackages, [NotNullWhen(true)] out IEnumerable? actualTestSources) { - actualTestSources = testRuntimeProvider?.GetTestSources(inputPackages); + actualTestSources = testRuntimeProvider?.GetTestSources(inputPackages!); if (inputPackages is null || actualTestSources is null) { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncher.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncher.cs index b99a5fa35f..bb5f749bd6 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncher.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncher.cs @@ -92,6 +92,6 @@ public DataCollectionLauncher(IProcessHelper processHelper, IMessageLogger messa /// The . /// public abstract int LaunchDataCollector( - IDictionary? environmentVariables, + IDictionary? environmentVariables, IList commandLineArguments); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncherFactory.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncherFactory.cs index d8157276fc..f905f8f2f1 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncherFactory.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionLauncherFactory.cs @@ -26,7 +26,7 @@ internal static IDataCollectionLauncher GetDataCollectorLauncher(IProcessHelper if (!settingsXml.IsNullOrWhiteSpace()) { var dataCollectionRunSettings = XmlRunSettingsUtilities.GetDataCollectionRunSettings(settingsXml); - foreach (var dataCollectorSettings in dataCollectionRunSettings.DataCollectorSettingsList) + foreach (var dataCollectorSettings in dataCollectionRunSettings!.DataCollectorSettingsList) { if (string.Equals(dataCollectorSettings.FriendlyName, "event Log", StringComparison.OrdinalIgnoreCase) || string.Equals(dataCollectorSettings.Uri?.ToString(), @"datacollector://Microsoft/EventLog/2.0", StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionParameters.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionParameters.cs index 923d9e5f78..15a98b317a 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionParameters.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionParameters.cs @@ -24,7 +24,7 @@ public class DataCollectionParameters /// public DataCollectionParameters( bool areTestCaseLevelEventsRequired, - IDictionary? environmentVariables, + IDictionary? environmentVariables, int dataCollectionEventsPort) { AreTestCaseLevelEventsRequired = areTestCaseLevelEventsRequired; @@ -41,7 +41,7 @@ public DataCollectionParameters( /// /// Gets BeforeTestRunStart Call on the DataCollectors can yield/return a set of environment variables /// - public IDictionary? EnvironmentVariables { get; private set; } + public IDictionary? EnvironmentVariables { get; private set; } /// /// Gets the data collection events port. diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionTestRunEventsHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionTestRunEventsHandler.cs index dc4f1d62d2..faa3d72162 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionTestRunEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DataCollectionTestRunEventsHandler.cs @@ -164,7 +164,7 @@ public void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, /// /// The test run changed args. /// - public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) + public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs) { _testRunEventsHandler.HandleTestRunStatsChange(testRunChangedArgs); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DefaultDataCollectionLauncher.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DefaultDataCollectionLauncher.cs index 97ce9bc9b9..685a80fc5e 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DefaultDataCollectionLauncher.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DefaultDataCollectionLauncher.cs @@ -51,7 +51,7 @@ internal DefaultDataCollectionLauncher(IProcessHelper processHelper, IMessageLog /// Environment variables for the process. /// The command line arguments to pass to the process. /// ProcessId of launched Process. 0 means not launched. - public override int LaunchDataCollector(IDictionary? environmentVariables, IList commandLineArguments) + public override int LaunchDataCollector(IDictionary? environmentVariables, IList commandLineArguments) { var dataCollectorDirectory = Path.GetDirectoryName(typeof(DefaultDataCollectionLauncher).GetTypeInfo().Assembly.GetAssemblyLocation()); TPDebug.Assert(dataCollectorDirectory is not null, "dataCollectorDirectory is not null"); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DotnetDataCollectionLauncher.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DotnetDataCollectionLauncher.cs index a6e40a9e4e..93943b5da4 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DotnetDataCollectionLauncher.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/DotnetDataCollectionLauncher.cs @@ -59,7 +59,7 @@ internal DotnetDataCollectionLauncher(IProcessHelper processHelper, IFileHelper /// Environment variables for the process. /// The command line arguments to pass to the process. /// ProcessId of launched Process. 0 means not launched. - public override int LaunchDataCollector(IDictionary? environmentVariables, IList commandLineArguments) + public override int LaunchDataCollector(IDictionary? environmentVariables, IList commandLineArguments) { var dataCollectorDirectory = Path.GetDirectoryName(typeof(DefaultDataCollectionLauncher).GetTypeInfo().Assembly.GetAssemblyLocation()); TPDebug.Assert(dataCollectorDirectory is not null, "dataCollectorDirectory is null"); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs index 27ddd496f7..413db1d17a 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs @@ -218,9 +218,9 @@ private void InitializeInProcDataCollectors(string? runSettings) var interfaceTypeInfo = typeof(InProcDataCollection).GetTypeInfo(); foreach (var inProcDc in _inProcDataCollectorSettingsCollection) { - var codeBase = GetCodebase(inProcDc.CodeBase); - var assemblyQualifiedName = inProcDc.AssemblyQualifiedName; - var configuration = inProcDc.Configuration; + var codeBase = GetCodebase(inProcDc.CodeBase!); + var assemblyQualifiedName = inProcDc.AssemblyQualifiedName!; + var configuration = inProcDc.Configuration!; var inProcDataCollector = CreateDataCollector(assemblyQualifiedName, codeBase, configuration, interfaceTypeInfo); InProcDataCollectors[inProcDataCollector.AssemblyQualifiedName!] = inProcDataCollector; } @@ -265,9 +265,9 @@ private string GetCodebase(string codeBase) return codeBase; } - private static IDictionary GetSessionStartProperties(SessionStartEventArgs sessionStartEventArgs) + private static IDictionary GetSessionStartProperties(SessionStartEventArgs sessionStartEventArgs) { - var properties = new Dictionary + var properties = new Dictionary { { Constants.TestSourcesPropertyName, sessionStartEventArgs.GetPropertyValue>(Constants.TestSourcesPropertyName) } }; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionSink.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionSink.cs index 17fb22dd03..cd90081849 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionSink.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionSink.cs @@ -26,9 +26,9 @@ public void SendData(DataCollectionContext dataCollectionContext, string key, st { ValidateArg.NotNullOrEmpty(key, nameof(key)); ValidateArg.NotNullOrEmpty(value, nameof(value)); - ValidateArg.NotNullOrEmpty(dataCollectionContext.TestCase.Id.ToString(), "dataCollectionContext.TestCase.Id"); + ValidateArg.NotNullOrEmpty(dataCollectionContext?.TestCase?.Id.ToString(), "dataCollectionContext.TestCase.Id"); - var testCaseId = dataCollectionContext.TestCase.Id; + var testCaseId = dataCollectionContext!.TestCase!.Id; AddKeyValuePairToDictionary(testCaseId, key, value); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs index 43dd5cff7e..c3d1684291 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs @@ -117,7 +117,7 @@ public void TriggerInProcDataCollectionMethod(string methodName, InProcDataColle if (methodName.Equals(Constants.TestSessionStartMethodName)) { var testSessionStartArgs = (TestSessionStartArgs)methodArg; - testSessionStartArgs.Configuration = _configXml; + testSessionStartArgs.Configuration = _configXml!; methodInfo?.Invoke(_dataCollectorObject, new object[] { testSessionStartArgs }); } else diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/Interfaces/IDataCollectionLauncher.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/Interfaces/IDataCollectionLauncher.cs index a13b40ebb3..eefde514bb 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/Interfaces/IDataCollectionLauncher.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/Interfaces/IDataCollectionLauncher.cs @@ -27,5 +27,5 @@ internal interface IDataCollectionLauncher /// /// The . /// - int LaunchDataCollector(IDictionary? environmentVariables, IList commandLineArguments); + int LaunchDataCollector(IDictionary? environmentVariables, IList commandLineArguments); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs index 52bbc709ed..f0c671b15e 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs @@ -189,7 +189,7 @@ public DataCollectionParameters BeforeTestRunStart( ITestMessageEventHandler? runEventsHandler) { var areTestCaseLevelEventsRequired = false; - IDictionary environmentVariables = new Dictionary(); + IDictionary environmentVariables = new Dictionary(); var dataCollectionEventsPort = 0; InvokeDataCollectionServiceAction( diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs index 7df4ee456c..d6a0e8d90d 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/IPathConverter.cs @@ -18,15 +18,15 @@ internal interface IPathConverter TestCase UpdateTestCase(TestCase testCase, PathConversionDirection updateDirection); - IEnumerable UpdateTestCases(IEnumerable testCases, PathConversionDirection updateDirection); + IEnumerable UpdateTestCases(IEnumerable? testCases, PathConversionDirection updateDirection); TestRunCompleteEventArgs UpdateTestRunCompleteEventArgs(TestRunCompleteEventArgs testRunCompleteEventArgs, PathConversionDirection updateDirection); - TestRunChangedEventArgs UpdateTestRunChangedEventArgs(TestRunChangedEventArgs testRunChangedArgs, PathConversionDirection updateDirection); + TestRunChangedEventArgs UpdateTestRunChangedEventArgs(TestRunChangedEventArgs? testRunChangedArgs, PathConversionDirection updateDirection); Collection UpdateAttachmentSets(Collection attachmentSets, PathConversionDirection updateDirection); - ICollection UpdateAttachmentSets(ICollection attachmentSets, PathConversionDirection updateDirection); + ICollection UpdateAttachmentSets(ICollection? attachmentSets, PathConversionDirection updateDirection); DiscoveryCriteria UpdateDiscoveryCriteria(DiscoveryCriteria discoveryCriteria, PathConversionDirection updateDirection); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs index 1db65b3bbb..9460f19b08 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/NullPathConverter.cs @@ -20,7 +20,7 @@ private NullPathConverter() { } Collection IPathConverter.UpdateAttachmentSets(Collection attachmentSets, PathConversionDirection _) => attachmentSets; - ICollection IPathConverter.UpdateAttachmentSets(ICollection attachmentSets, PathConversionDirection _) => attachmentSets; + ICollection IPathConverter.UpdateAttachmentSets(ICollection? attachmentSets, PathConversionDirection _) => attachmentSets!; DiscoveryCriteria IPathConverter.UpdateDiscoveryCriteria(DiscoveryCriteria discoveryCriteria, PathConversionDirection _) => discoveryCriteria; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs index bcf270600c..03cccc0025 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs @@ -83,11 +83,11 @@ public TestCase UpdateTestCase(TestCase testCase, PathConversionDirection update return testCase; } - public IEnumerable UpdateTestCases(IEnumerable testCases, PathConversionDirection updateDirection) + public IEnumerable UpdateTestCases(IEnumerable? testCases, PathConversionDirection updateDirection) { ValidateArg.NotNull(testCases, nameof(testCases)); - testCases.ToList().ForEach(tc => UpdateTestCase(tc, updateDirection)); - return testCases; + testCases!.ToList().ForEach(tc => UpdateTestCase(tc, updateDirection)); + return testCases!; } public TestRunCompleteEventArgs UpdateTestRunCompleteEventArgs(TestRunCompleteEventArgs testRunCompleteEventArgs, PathConversionDirection updateDirection) @@ -97,10 +97,10 @@ public TestRunCompleteEventArgs UpdateTestRunCompleteEventArgs(TestRunCompleteEv return testRunCompleteEventArgs; } - public TestRunChangedEventArgs UpdateTestRunChangedEventArgs(TestRunChangedEventArgs testRunChangedArgs, PathConversionDirection updateDirection) + public TestRunChangedEventArgs UpdateTestRunChangedEventArgs(TestRunChangedEventArgs? testRunChangedArgs, PathConversionDirection updateDirection) { ValidateArg.NotNull(testRunChangedArgs, nameof(testRunChangedArgs)); - UpdateTestResults(testRunChangedArgs.NewTestResults, updateDirection); + UpdateTestResults(testRunChangedArgs!.NewTestResults!, updateDirection); UpdateTestCases(testRunChangedArgs.ActiveTests, updateDirection); return testRunChangedArgs; } @@ -112,11 +112,11 @@ public Collection UpdateAttachmentSets(Collection return attachmentSets; } - public ICollection UpdateAttachmentSets(ICollection attachmentSets, PathConversionDirection updateDirection) + public ICollection UpdateAttachmentSets(ICollection? attachmentSets, PathConversionDirection updateDirection) { ValidateArg.NotNull(attachmentSets, nameof(attachmentSets)); - attachmentSets.ToList().ForEach(i => UpdateAttachmentSet(i, updateDirection)); - return attachmentSets; + attachmentSets!.ToList().ForEach(i => UpdateAttachmentSet(i, updateDirection)); + return attachmentSets!; } private AttachmentSet UpdateAttachmentSet(AttachmentSet attachmentSet, PathConversionDirection updateDirection) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestCaseEventsHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestCaseEventsHandler.cs index 42c0213cd0..6c55b35885 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestCaseEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestCaseEventsHandler.cs @@ -53,7 +53,7 @@ public void SendTestResult(TestResult result) } /// - public void SendSessionStart(IDictionary properties) + public void SendSessionStart(IDictionary properties) { SessionStart.SafeInvoke(this, new SessionStartEventArgs(properties), "TestCaseEventsHandler.RaiseSessionStart"); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs index 6085055b78..eabc5032ce 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs @@ -166,7 +166,7 @@ public void Close() } /// - public void SendTestCases(IEnumerable discoveredTestCases) + public void SendTestCases(IEnumerable? discoveredTestCases) { var updatedTestCases = _pathConverter.UpdateTestCases(discoveredTestCases, PathConversionDirection.Send); var data = _dataSerializer.SerializePayload(MessageType.TestCasesFound, updatedTestCases, _protocolVersion); @@ -174,7 +174,7 @@ public void SendTestCases(IEnumerable discoveredTestCases) } /// - public void SendTestRunStatistics(TestRunChangedEventArgs testRunChangedArgs) + public void SendTestRunStatistics(TestRunChangedEventArgs? testRunChangedArgs) { var updatedTestRunChangedEventArgs = _pathConverter.UpdateTestRunChangedEventArgs(testRunChangedArgs, PathConversionDirection.Send); var data = _dataSerializer.SerializePayload(MessageType.TestRunStatsChange, updatedTestRunChangedEventArgs, _protocolVersion); @@ -182,7 +182,7 @@ public void SendTestRunStatistics(TestRunChangedEventArgs testRunChangedArgs) } /// - public void SendLog(TestMessageLevel messageLevel, string message) + public void SendLog(TestMessageLevel messageLevel, string? message) { var data = _dataSerializer.SerializePayload( MessageType.TestMessage, @@ -194,9 +194,9 @@ public void SendLog(TestMessageLevel messageLevel, string message) /// public void SendExecutionComplete( TestRunCompleteEventArgs testRunCompleteArgs, - TestRunChangedEventArgs lastChunkArgs, - ICollection runContextAttachments, - ICollection executorUris) + TestRunChangedEventArgs? lastChunkArgs, + ICollection? runContextAttachments, + ICollection? executorUris) { // When we abort the run we might have saved the error before we gave the handler the chance to abort // if the handler does not return with any new error we report the original one. diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs index 9673e2cfc5..3ddea6a197 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs @@ -682,7 +682,7 @@ private bool TryToRunInStaThread(Action action, bool waitForCompletion) EqtTrace.Warning("BaseRunTests.TryToRunInSTAThread: Failed to run in STA thread: {0}", ex); TestRunEventsHandler.HandleLogMessage( TestMessageLevel.Warning, - string.Format(CultureInfo.CurrentUICulture, CrossPlatEngineResources.ExecutionThreadApartmentStateNotSupportedForFramework, _runConfiguration.TargetFramework.ToString())); + string.Format(CultureInfo.CurrentUICulture, CrossPlatEngineResources.ExecutionThreadApartmentStateNotSupportedForFramework, _runConfiguration.TargetFramework!.ToString())); } return success; @@ -708,7 +708,7 @@ private ICollection UpdateTestResults(ICollection testRe { var updatedTestResult = _dataSerializer.Clone(testResult); TPDebug.Assert(updatedTestResult is not null, "updatedTestResult is null"); - updatedTestResult.TestCase.Source = package; + updatedTestResult.TestCase.Source = package!; updatedTestResults.Add(updatedTestResult); } @@ -727,7 +727,7 @@ private ICollection UpdateTestResults(ICollection testRe { var updatedTestCase = _dataSerializer.Clone(inProgressTestCase); TPDebug.Assert(updatedTestCase is not null, "updatedTestCase is null"); - updatedTestCase.Source = package; + updatedTestCase.Source = package!; updatedTestCases.Add(updatedTestCase); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs index 162441b0b0..844c15b150 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs @@ -221,7 +221,7 @@ protected override void SendSessionStart() return; } - var properties = new Dictionary + var properties = new Dictionary { { "TestSources", TestSourcesUtility.GetSources(_adapterSourceMap!)! } }; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs index b5026a8952..291e7a5671 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs @@ -103,7 +103,7 @@ protected override void SendSessionStart() return; } - var properties = new Dictionary + var properties = new Dictionary { { "TestSources", TestSourcesUtility.GetSources(_testCases)! } }; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs index a5950ceaac..686a83d0d0 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs @@ -25,7 +25,7 @@ public PostProcessingTestRunAttachmentsProcessingEventsHandler(IOutput consoleOu _consoleOutput = consoleOutput ?? throw new ArgumentNullException(nameof(consoleOutput)); } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { } public void HandleRawMessage(string rawMessage) @@ -48,7 +48,7 @@ public void HandleProcessedAttachmentsChunk(IEnumerable attachmen } } - public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable lastChunk) + public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable? lastChunk) { foreach (var attachment in lastChunk ?? Enumerable.Empty()) { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs index 74ae4a04c9..d65de6638d 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs @@ -76,7 +76,7 @@ public IProxyDiscoveryManager GetDiscoveryManager( // run or not. var parallelLevel = VerifyParallelSettingAndCalculateParallelLevel( discoveryCriteria.Sources.Count(), - discoveryCriteria.RunSettings); + discoveryCriteria.RunSettings!); var isParallelRun = parallelLevel > 1; @@ -85,12 +85,12 @@ public IProxyDiscoveryManager GetDiscoveryManager( requestData.MetricsCollection.Add(TelemetryDataConstants.TestSessionId, discoveryCriteria.TestSessionInfo?.Id.ToString() ?? string.Empty); // Get testhost managers by configuration, and either use it for in-process run. or for single source run. - List testHostManagers = GetTestRuntimeProvidersForUniqueConfigurations(discoveryCriteria.RunSettings, sourceToSourceDetailMap, warningLogger, out ITestRuntimeProvider? testHostManager); + List testHostManagers = GetTestRuntimeProvidersForUniqueConfigurations(discoveryCriteria.RunSettings!, sourceToSourceDetailMap, warningLogger, out ITestRuntimeProvider? testHostManager); // This is a big if that figures out if we can run in process. In process run is very restricted, it is non-parallel run // that has the same target framework as the current process, and it also must not be running in DesignMode (server mode / under IDE) // and more conditions. In all other cases we run in a separate testhost process. - if (ShouldRunInProcess(discoveryCriteria.RunSettings, isParallelRun, isDataCollectorEnabled: false, testHostManagers)) + if (ShouldRunInProcess(discoveryCriteria.RunSettings!, isParallelRun, isDataCollectorEnabled: false, testHostManagers)) { // We are running in process, so whatever the architecture and framework that was figured out is, it must be compatible. If we have more // changes that we want to do to runsettings in the future, based on SourceDetail then it will depend on those details. But in general @@ -120,9 +120,9 @@ public IProxyDiscoveryManager GetDiscoveryManager( var discoveryDataAggregator = new DiscoveryDataAggregator(); Func proxyDiscoveryManagerCreator = runtimeProviderInfo => { - var sources = runtimeProviderInfo.SourceDetails.Select(r => r.Source).ToList(); + var sources = runtimeProviderInfo.SourceDetails.Select(r => r.Source!).ToList(); var hostManager = _testHostProviderManager.GetTestHostManagerByRunConfiguration(runtimeProviderInfo.RunSettings, sources); - hostManager?.Initialize(TestSessionMessageLogger.Instance, runtimeProviderInfo.RunSettings); + hostManager?.Initialize(TestSessionMessageLogger.Instance, runtimeProviderInfo.RunSettings!); ThrowExceptionIfTestHostManagerIsNull(hostManager, runtimeProviderInfo.RunSettings); TPDebug.Assert(hostManager is not null, "hostManager is null"); @@ -156,7 +156,7 @@ public IProxyDiscoveryManager GetDiscoveryManager( proxyOperationManager = new ProxyOperationManager( requestData, - new TestRequestSender(requestData.ProtocolConfig, hostManager), + new TestRequestSender(requestData.ProtocolConfig!, hostManager), hostManager, // There is always at least one, and all of them have the same framework and architecture. runtimeProviderInfo.SourceDetails[0].Framework, @@ -175,7 +175,7 @@ public IProxyDiscoveryManager GetDiscoveryManager( discoveryDataAggregator) : new ProxyDiscoveryManager( requestData, - new TestRequestSender(requestData.ProtocolConfig, hostManager), + new TestRequestSender(requestData.ProtocolConfig!, hostManager), hostManager, // There is always at least one, and all of them have the same framework and architecture. runtimeProviderInfo.SourceDetails[0].Framework, @@ -263,17 +263,17 @@ internal IProxyExecutionManager CreateNonParallelExecutionManager(IRequestData r // specified in run settings. // Create a new host manager, to be associated with individual // ProxyExecutionManager(&POM) - var sources = runtimeProviderInfo.SourceDetails.Select(r => r.Source).ToList(); + var sources = runtimeProviderInfo.SourceDetails.Select(r => r.Source!).ToList(); var hostManager = _testHostProviderManager.GetTestHostManagerByRunConfiguration(runtimeProviderInfo.RunSettings, sources); ThrowExceptionIfTestHostManagerIsNull(hostManager, runtimeProviderInfo.RunSettings); - hostManager!.Initialize(TestSessionMessageLogger.Instance, runtimeProviderInfo.RunSettings); + hostManager!.Initialize(TestSessionMessageLogger.Instance, runtimeProviderInfo.RunSettings!); if (testRunCriteria.TestHostLauncher != null) { hostManager.SetCustomLauncher(testRunCriteria.TestHostLauncher); } - var requestSender = new TestRequestSender(requestData.ProtocolConfig, hostManager); + var requestSender = new TestRequestSender(requestData.ProtocolConfig!, hostManager); if (testRunCriteria.TestSessionInfo != null) { @@ -328,7 +328,7 @@ internal IProxyExecutionManager CreateNonParallelExecutionManager(IRequestData r requestSender, hostManager, // There is always at least one, and all of them have the same framework and architecture. - runtimeProviderInfo.SourceDetails[0].Framework, + runtimeProviderInfo.SourceDetails[0].Framework!, new ProxyDataCollectionManager( requestData, runtimeProviderInfo.RunSettings, @@ -338,7 +338,7 @@ internal IProxyExecutionManager CreateNonParallelExecutionManager(IRequestData r requestSender, hostManager, // There is always at least one, and all of them have the same framework and architecture. - runtimeProviderInfo.SourceDetails[0].Framework); + runtimeProviderInfo.SourceDetails[0].Framework!); } /// @@ -349,8 +349,8 @@ internal IProxyExecutionManager CreateNonParallelExecutionManager(IRequestData r IWarningLogger warningLogger) { var parallelLevel = VerifyParallelSettingAndCalculateParallelLevel( - testSessionCriteria.Sources.Count, - testSessionCriteria.RunSettings); + testSessionCriteria.Sources!.Count, + testSessionCriteria.RunSettings!); bool isParallelRun = parallelLevel > 1; requestData.MetricsCollection.Add( @@ -360,10 +360,10 @@ internal IProxyExecutionManager CreateNonParallelExecutionManager(IRequestData r var isDataCollectorEnabled = XmlRunSettingsUtilities.IsDataCollectionEnabled(testSessionCriteria.RunSettings); var isInProcDataCollectorEnabled = XmlRunSettingsUtilities.IsInProcDataCollectionEnabled(testSessionCriteria.RunSettings); - List testRuntimeProviders = GetTestRuntimeProvidersForUniqueConfigurations(testSessionCriteria.RunSettings, sourceToSourceDetailMap, warningLogger, out var _); + List testRuntimeProviders = GetTestRuntimeProvidersForUniqueConfigurations(testSessionCriteria.RunSettings!, sourceToSourceDetailMap, warningLogger, out var _); if (ShouldRunInProcess( - testSessionCriteria.RunSettings, + testSessionCriteria.RunSettings!, isParallelRun, isDataCollectorEnabled || isInProcDataCollectorEnabled, testRuntimeProviders)) @@ -375,17 +375,17 @@ internal IProxyExecutionManager CreateNonParallelExecutionManager(IRequestData r Func proxyCreator = testRuntimeProviderInfo => { - var sources = testRuntimeProviderInfo.SourceDetails.Select(x => x.Source).ToList(); + var sources = testRuntimeProviderInfo.SourceDetails.Select(x => x.Source!).ToList(); var hostManager = _testHostProviderManager.GetTestHostManagerByRunConfiguration(testRuntimeProviderInfo.RunSettings, sources); ThrowExceptionIfTestHostManagerIsNull(hostManager, testRuntimeProviderInfo.RunSettings); - hostManager!.Initialize(TestSessionMessageLogger.Instance, testRuntimeProviderInfo.RunSettings); + hostManager!.Initialize(TestSessionMessageLogger.Instance, testRuntimeProviderInfo.RunSettings!); if (testSessionCriteria.TestHostLauncher != null) { hostManager.SetCustomLauncher(testSessionCriteria.TestHostLauncher); } - var requestSender = new TestRequestSender(requestData.ProtocolConfig, hostManager) + var requestSender = new TestRequestSender(requestData.ProtocolConfig!, hostManager) { CloseConnectionOnOperationComplete = false }; @@ -418,7 +418,7 @@ internal IProxyExecutionManager CreateNonParallelExecutionManager(IRequestData r requestSender, hostManager, // There is always at least one, and all of them have the same framework and architecture. - testRuntimeProviderInfo.SourceDetails[0].Framework); + testRuntimeProviderInfo.SourceDetails[0].Framework!); }; // TODO: This condition should be returning the maxParallel level to avoid pre-starting way too many testhosts, because maxParallel level, @@ -444,7 +444,7 @@ private List GetTestRuntimeProvidersForUniqueConfigurat // It is okay to take the first (or any) source detail in the group. We are grouping to get the same source detail, so all architectures and frameworks are the same. var sourceDetail = runConfiguration.First(); var runsettingsXml = SourceDetailHelper.UpdateRunSettingsFromSourceDetail(runSettings, sourceDetail); - var sources = runConfiguration.Select(c => c.Source).ToList(); + var sources = runConfiguration.Select(c => c.Source!).ToList(); var testRuntimeProvider = _testHostProviderManager.GetTestHostManagerByRunConfiguration(runsettingsXml, sources); if (testRuntimeProvider != null) @@ -624,7 +624,7 @@ private bool ShouldRunInProcess( (runConfiguration.TargetPlatform == ObjectModel.Constants.DefaultPlatform || runConfiguration.TargetPlatform == Architecture.AnyCPU) && !runConfiguration.DisableAppDomain && !runConfiguration.DesignMode && - runConfiguration.TargetFramework.Name.IndexOf("netframework", StringComparison.OrdinalIgnoreCase) >= 0) + runConfiguration.TargetFramework!.Name.IndexOf("netframework", StringComparison.OrdinalIgnoreCase) >= 0) { EqtTrace.Info("TestEngine.ShouldRunInNoIsolation: running test in process(inside vstest.console.exe process)"); return true; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs index 2625711d80..522f4fab5e 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs @@ -85,7 +85,7 @@ public ProxyTestSessionManager( // Get dictionary from source -> runtimeProviderInfo, that has the type of runtime provider to create for this // source, and updated runsettings. _sourceToRuntimeProviderInfoMap = _runtimeProviders - .SelectMany(runtimeProviderInfo => runtimeProviderInfo.SourceDetails.Select(detail => new KeyValuePair(detail.Source, runtimeProviderInfo))) + .SelectMany(runtimeProviderInfo => runtimeProviderInfo.SourceDetails.Select(detail => new KeyValuePair(detail.Source!, runtimeProviderInfo))) .ToDictionary(pair => pair.Key, pair => pair.Value); } @@ -117,6 +117,7 @@ public virtual bool StartSession(ITestSessionEventsHandler eventsHandler, IReque { // This is similar to what we do in ProxyExecutionManager, and ProxyDiscoveryManager, we split // up the payload into multiple smaller pieces. Here it is one source per proxy. + TPDebug.Assert(_testSessionCriteria.Sources is not null, "_testSessionCriteria.Sources is null"); var source = _testSessionCriteria.Sources[i]; var sources = new List() { source }; var runtimeProviderInfo = _sourceToRuntimeProviderInfoMap[source]; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Utilities/SourceDetailHelper.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Utilities/SourceDetailHelper.cs index 81547143ad..4b01f23f09 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Utilities/SourceDetailHelper.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Utilities/SourceDetailHelper.cs @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Utilities; internal static class SourceDetailHelper { - internal static string? UpdateRunSettingsFromSourceDetail(string runSettings, SourceDetail sourceDetail) + internal static string UpdateRunSettingsFromSourceDetail(string runSettings, SourceDetail sourceDetail) { using var stream = new StringReader(runSettings); using var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings); @@ -20,10 +20,10 @@ internal static class SourceDetailHelper document.Load(reader); var navigator = document.CreateNavigator(); - InferRunSettingsHelper.UpdateTargetFramework(document, sourceDetail.Framework.ToString(), overwrite: true); + InferRunSettingsHelper.UpdateTargetFramework(document, sourceDetail.Framework!.ToString(), overwrite: true); InferRunSettingsHelper.UpdateTargetPlatform(document, sourceDetail.Architecture.ToString(), overwrite: true); - var updatedRunSettings = navigator?.OuterXml; + var updatedRunSettings = navigator!.OuterXml; return updatedRunSettings; } } diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BannedSymbols.txt b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BannedSymbols.txt index c3370ddb45..209d2ca894 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BannedSymbols.txt +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BannedSymbols.txt @@ -1,4 +1,4 @@ -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead -M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs index 4176ad160c..9bb9509ab7 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs @@ -110,13 +110,13 @@ public IEnumerable> GetTestExecutionEnvironmentVari /// A data collection sink for data transfer /// Data Collection Logger to send messages to the client /// Context of data collector environment - [MemberNotNull(nameof(_events), nameof(_dataCollectionSink), nameof(_context), nameof(_testSequence), nameof(_testObjectDictionary), nameof(_logger))] + [MemberNotNull(nameof(_events), nameof(_dataCollectionSink), nameof(_testSequence), nameof(_testObjectDictionary), nameof(_logger))] public override void Initialize( XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { _events = events; _dataCollectionSink = dataSink; @@ -419,8 +419,9 @@ private void EventsTestCaseStart(object? sender, TestCaseStartEventArgs e) TPDebug.Assert(_testSequence != null && _testObjectDictionary != null, "Initialize must be called before calling this method"); ResetInactivityTimer(); - EqtTrace.Info("Blame Collector : Test Case Start"); + EqtTrace.Info("BlameCollector.EventsTestCaseStart: Test Case Start"); + TPDebug.Assert(e.TestElement is not null, "e.TestElement is null"); var blameTestObject = new BlameTestObject(e.TestElement); // Add guid to list of test sequence to maintain the order. @@ -443,11 +444,12 @@ private void EventsTestCaseEnd(object? sender, TestCaseEndEventArgs e) TPDebug.Assert(_testObjectDictionary != null, "Initialize must be called before calling this method"); ResetInactivityTimer(); - EqtTrace.Info("Blame Collector: Test Case End"); + EqtTrace.Info("BlameCollector.EventsTestCaseEnd: Test Case End"); _testEndCount++; // Update the test object in the dictionary as the test has completed. + TPDebug.Assert(e.TestElement is not null, "e.TestElement is null"); if (_testObjectDictionary.ContainsKey(e.TestElement.Id)) { _testObjectDictionary[e.TestElement.Id].IsCompleted = true; diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/PublicAPI/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/PublicAPI/PublicAPI.Shipped.txt index 0247054e9f..c06ec39dd6 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/PublicAPI/PublicAPI.Shipped.txt @@ -80,4 +80,4 @@ Microsoft.TestPlatform.Extensions.BlameDataCollector.XmlReaderWriter Microsoft.TestPlatform.Extensions.BlameDataCollector.XmlReaderWriter.ReadTestSequence(string! filePath) -> System.Collections.Generic.List! Microsoft.TestPlatform.Extensions.BlameDataCollector.XmlReaderWriter.WriteTestSequence(System.Collections.Generic.List! testSequence, System.Collections.Generic.Dictionary! testObjectDictionary, string! filePath) -> string! Microsoft.TestPlatform.Extensions.BlameDataCollector.XmlReaderWriter.XmlReaderWriter(Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces.IFileHelper! fileHelper) -> void -override Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameCollector.Initialize(System.Xml.XmlElement? configurationElement, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEvents! events, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionSink! dataSink, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEnvironmentContext! environmentContext) -> void +override Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameCollector.Initialize(System.Xml.XmlElement? configurationElement, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEvents! events, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionSink! dataSink, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionLogger! logger, Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection.DataCollectionEnvironmentContext? environmentContext) -> void diff --git a/src/Microsoft.TestPlatform.Extensions.HtmlLogger/BannedSymbols.txt b/src/Microsoft.TestPlatform.Extensions.HtmlLogger/BannedSymbols.txt index c3370ddb45..209d2ca894 100644 --- a/src/Microsoft.TestPlatform.Extensions.HtmlLogger/BannedSymbols.txt +++ b/src/Microsoft.TestPlatform.Extensions.HtmlLogger/BannedSymbols.txt @@ -1,4 +1,4 @@ -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead -M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs index a1e15e6346..f0132c3ad8 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs @@ -22,7 +22,7 @@ namespace Microsoft.TestPlatform.Extensions.TrxLogger.ObjectModel; /// internal sealed class TestResultId : IXmlTestStore { - private Guid _runId; + private readonly Guid _runId; /// /// Initializes a new instance of the class. diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs index 12dfb6422a..8666c2c6be 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs @@ -83,7 +83,7 @@ internal TrxLogger(IFileHelper fileHelper, TrxFileHelper trxFileHelper) /// /// Parameters dictionary for logger. Ex: {"LogFileName":"TestResults.trx"}. /// - private Dictionary? _parametersDictionary; + private Dictionary? _parametersDictionary; /// /// Gets the directory under which default trx file and test results attachments should be saved. @@ -127,7 +127,7 @@ public void Initialize(TestLoggerEvents events, string testResultsDirPath) /// [MemberNotNull(nameof(_parametersDictionary))] - public void Initialize(TestLoggerEvents events, Dictionary parameters) + public void Initialize(TestLoggerEvents events, Dictionary parameters) { ValidateArg.NotNull(parameters, nameof(parameters)); if (parameters.Count == 0) @@ -148,7 +148,7 @@ public void Initialize(TestLoggerEvents events, Dictionary param } _parametersDictionary = parameters; - Initialize(events, _parametersDictionary[DefaultLoggerParameterNames.TestRunDirectory]); + Initialize(events, _parametersDictionary[DefaultLoggerParameterNames.TestRunDirectory]!); } #endregion @@ -610,7 +610,7 @@ private ITestElement GetOrCreateTestElement(Guid executionId, Guid parentExecuti Guid testId = _converter.GetTestId(testCase); // Scenario for inner test case when parent test element is not present. - var testName = testCase.DisplayName; + string? testName = testCase.DisplayName; var adapter = testCase.ExecutorUri.ToString(); if (adapter.Contains(TrxLoggerConstants.MstestAdapterString) && parentTestElement == null && @@ -629,7 +629,7 @@ private ITestElement GetOrCreateTestElement(Guid executionId, Guid parentExecuti // Create test element if (testElement == null) { - testElement = _converter.ToTestElement(testId, executionId, parentExecutionId, testName, testType, testCase); + testElement = _converter.ToTestElement(testId, executionId, parentExecutionId, testName!, testType, testCase); _testElements.TryAdd(testId, testElement); } diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs index f83afcbadc..4b7698e473 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs @@ -104,7 +104,7 @@ public ITestResult ToTestResult( TestRun testRun, VisualStudio.TestPlatform.ObjectModel.TestResult rockSteadyTestResult) { - var resultName = !string.IsNullOrEmpty(rockSteadyTestResult.DisplayName) ? rockSteadyTestResult.DisplayName : testName; + string resultName = !string.IsNullOrEmpty(rockSteadyTestResult.DisplayName) ? rockSteadyTestResult.DisplayName! : testName; var testResult = CreateTestResult(testRun.Id, testId, executionId, parentExecutionId, resultName, testOutcome, testType, testCategoryId); if (rockSteadyTestResult.ErrorMessage != null) @@ -239,7 +239,7 @@ private void UpdateResultMessages(TrxObjectModel.TestResult unitTestResult, Visu { if (TestResultMessage.AdditionalInfoCategory.Equals(message.Category, StringComparison.OrdinalIgnoreCase)) { - unitTestResult.AddTextMessage(message.Text); + unitTestResult.AddTextMessage(message.Text!); } else if (TestResultMessage.DebugTraceCategory.Equals(message.Category, StringComparison.OrdinalIgnoreCase)) { @@ -276,7 +276,7 @@ public List GetCustomPropertyValueFromTestCase(TestCase testCase, string if (customProperty != null) { - var cateogryValues = (string[])testCase.GetPropertyValue(customProperty); + var cateogryValues = (string[]?)testCase.GetPropertyValue(customProperty); return cateogryValues != null ? cateogryValues.ToList() : Enumerable.Empty().ToList(); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IDiscoveryContext.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IDiscoveryContext.cs index 3a88360d65..72b0886696 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IDiscoveryContext.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IDiscoveryContext.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.Adapter; /// @@ -13,5 +11,5 @@ public interface IDiscoveryContext /// /// Runsettings specified for this request. /// - IRunSettings RunSettings { get; } + IRunSettings? RunSettings { get; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle.cs index 62fd18ae49..96bebcabcc 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// @@ -29,5 +27,5 @@ public interface IFrameworkHandle : ITestExecutionRecorder, IMessageLogger /// Command line arguments the process should be launched with. /// Environment variables to be set in target process /// Process ID of the started process. - int LaunchProcessWithDebuggerAttached(string filePath, string workingDirectory, string arguments, IDictionary environmentVariables); + int LaunchProcessWithDebuggerAttached(string filePath, string workingDirectory, string arguments, IDictionary environmentVariables); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle2.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle2.cs index 0864a91e74..6dfe80fb9b 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle2.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IFrameworkHandle2.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.Adapter; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunContext.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunContext.cs index adc5053278..5046496188 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunContext.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunContext.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// @@ -38,15 +36,15 @@ public interface IRunContext : IDiscoveryContext /// It is used only with sources. With specific test cases it will always be null. /// If there is a parsing error or filter expression has unsupported properties, TestPlatformFormatException() is thrown. /// - ITestCaseFilterExpression GetTestCaseFilter(IEnumerable supportedProperties, Func propertyProvider); + ITestCaseFilterExpression? GetTestCaseFilter(IEnumerable? supportedProperties, Func propertyProvider); /// /// Directory which should be used for storing result files/deployment files etc. /// - string TestRunDirectory { get; } + string? TestRunDirectory { get; } /// /// Solution Directory. /// - string SolutionDirectory { get; } + string? SolutionDirectory { get; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunSettings.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunSettings.cs index e54158a16b..aec0559d0c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunSettings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/IRunSettings.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.Adapter; /// @@ -15,10 +13,10 @@ public interface IRunSettings /// /// Name of the settings section to get. /// The settings provider for the settings or null if one was not found. - ISettingsProvider GetSettings(string settingsName); + ISettingsProvider? GetSettings(string settingsName); /// /// Settings used for this run. /// - string SettingsXml { get; } + string? SettingsXml { get; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ISettingsProvider.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ISettingsProvider.cs index 93f40b16de..9e6615d11e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ISettingsProvider.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ISettingsProvider.cs @@ -3,8 +3,6 @@ using System.Xml; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseDiscoverySink.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseDiscoverySink.cs index 01639a283e..89ac6231ae 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseDiscoverySink.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseDiscoverySink.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.Adapter; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseFilterExpression.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseFilterExpression.cs index a44dbe327e..040e199b9f 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseFilterExpression.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestCaseFilterExpression.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestDiscoverer.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestDiscoverer.cs index 15f5144226..1083a71535 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestDiscoverer.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestDiscoverer.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor.cs index a7a5ab5e1a..d8e11ec408 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// @@ -22,7 +20,7 @@ public interface ITestExecutor /// Tests to be run. /// Context to use when executing the tests. /// Handle to the framework to record results and to do framework operations. - void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle); + void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle); /// /// Runs 'all' the tests present in the specified 'sources'. @@ -30,7 +28,7 @@ public interface ITestExecutor /// Path to test container files to look for tests in. /// Context to use when executing the tests. /// Handle to the framework to record results and to do framework operations. - void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle); + void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle); /// /// Cancel the execution of the tests. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor2.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor2.cs index 9563cde7df..cbe681f457 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor2.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestExecutor2.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// @@ -25,7 +23,7 @@ public interface ITestExecutor2 : ITestExecutor /// if the default test host process should be attached to, /// otherwise. /// - bool ShouldAttachToTestHost(IEnumerable sources, IRunContext runContext); + bool ShouldAttachToTestHost(IEnumerable? sources, IRunContext runContext); /// /// Indicates whether or not the default test host process should be attached to. @@ -36,5 +34,5 @@ public interface ITestExecutor2 : ITestExecutor /// if the default test host process should be attached to, /// otherwise. /// - bool ShouldAttachToTestHost(IEnumerable tests, IRunContext runContext); + bool ShouldAttachToTestHost(IEnumerable? tests, IRunContext runContext); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestLog.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestLog.cs index 4ed0be0741..ade77b32b8 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestLog.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/Interfaces/ITestLog.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestPlatformFormatException.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestPlatformFormatException.cs index 9ea7ad402c..004e0ebfa6 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestPlatformFormatException.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestPlatformFormatException.cs @@ -6,8 +6,6 @@ using System.Runtime.Serialization; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// @@ -31,7 +29,7 @@ public TestPlatformFormatException() /// Initializes with the message. /// /// Message for the exception. - public TestPlatformFormatException(string message) + public TestPlatformFormatException(string? message) : base(message) { } @@ -41,7 +39,7 @@ public TestPlatformFormatException(string message) /// /// Message for the exception. /// Filter expression. - public TestPlatformFormatException(string message, string filterValue) + public TestPlatformFormatException(string? message, string? filterValue) : base(message) { FilterValue = filterValue; @@ -52,7 +50,7 @@ public TestPlatformFormatException(string message, string filterValue) /// /// Message for the exception. /// The inner exception. - public TestPlatformFormatException(string message, Exception innerException) + public TestPlatformFormatException(string? message, Exception? innerException) : base(message, innerException) { } @@ -72,7 +70,7 @@ protected TestPlatformFormatException(SerializationInfo info, StreamingContext c /// /// Filter expression. /// - public string FilterValue + public string? FilterValue { get; private set; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestsCanceledException.cs b/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestsCanceledException.cs index b7e929af1d..f16c2f39ee 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestsCanceledException.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Adapter/TestsCanceledException.cs @@ -6,8 +6,6 @@ using System.Runtime.Serialization; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; /// @@ -30,7 +28,7 @@ public TestCanceledException() /// Initializes with the message. /// /// Message for the exception. - public TestCanceledException(string message) + public TestCanceledException(string? message) : base(message) { } @@ -40,7 +38,7 @@ public TestCanceledException(string message) /// /// Message for the exception. /// The inner exception. - public TestCanceledException(string message, Exception innerException) + public TestCanceledException(string? message, Exception? innerException) : base(message, innerException) { } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Architecture.cs b/src/Microsoft.TestPlatform.ObjectModel/Architecture.cs index 5783915c28..6c9b9bcde5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Architecture.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Architecture.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; public enum Architecture diff --git a/src/Microsoft.TestPlatform.ObjectModel/AttachmentSet.cs b/src/Microsoft.TestPlatform.ObjectModel/AttachmentSet.cs index 657fe59633..c35942e94e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/AttachmentSet.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/AttachmentSet.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -44,9 +42,7 @@ public AttachmentSet(Uri uri, string displayName) } public override string ToString() - { - return $"{nameof(Uri)}: {Uri.AbsoluteUri}, {nameof(DisplayName)}: {DisplayName}, {nameof(Attachments)}: [{string.Join(",", Attachments)}]"; - } + => $"{nameof(Uri)}: {Uri.AbsoluteUri}, {nameof(DisplayName)}: {DisplayName}, {nameof(Attachments)}: [{string.Join(",", Attachments)}]"; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs index 153dbc72a6..293a0fc82e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs @@ -6,8 +6,6 @@ using System.Linq; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -20,7 +18,9 @@ public class DiscoveryCriteria /// Initializes a new instance of the class. /// /// This constructor doesn't perform any parameter validation, it is meant to be used for serialization."/> +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public DiscoveryCriteria() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { // Parameterless constructor is used for Serialization. } @@ -40,7 +40,7 @@ public DiscoveryCriteria() public DiscoveryCriteria( IEnumerable sources, long frequencyOfDiscoveredTestsEvent, - string testSettings) + string? testSettings) : this( sources, frequencyOfDiscoveredTestsEvent, @@ -67,7 +67,7 @@ public DiscoveryCriteria( IEnumerable sources, long frequencyOfDiscoveredTestsEvent, TimeSpan discoveredTestEventTimeout, - string runSettings) + string? runSettings) : this( sources, frequencyOfDiscoveredTestsEvent, @@ -96,8 +96,8 @@ public DiscoveryCriteria( IEnumerable sources, long frequencyOfDiscoveredTestsEvent, TimeSpan discoveredTestEventTimeout, - string runSettings, - TestSessionInfo testSessionInfo) + string? runSettings, + TestSessionInfo? testSessionInfo) { ValidateArg.NotNullOrEmpty(sources, nameof(sources)); if (frequencyOfDiscoveredTestsEvent <= 0) @@ -140,7 +140,7 @@ public IEnumerable Sources /// Gets the test Containers (e.g. .appx, .appxrecipie) /// [DataMember] - public string Package { get; set; } + public string? Package { get; set; } /// /// Gets the test adapter and source map which would look like below: @@ -173,17 +173,17 @@ public IEnumerable Sources /// Gets the test settings used for the discovery request. /// [DataMember] - public string RunSettings { get; private set; } + public string? RunSettings { get; private set; } /// /// Gets or sets the criteria for filtering test cases. /// [DataMember] - public string TestCaseFilter { get; set; } + public string? TestCaseFilter { get; set; } /// /// Gets or sets the test session info object. /// [DataMember] - public TestSessionInfo TestSessionInfo { get; set; } + public TestSessionInfo? TestSessionInfo { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveredTestsEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveredTestsEventArgs.cs index df0b0d11c5..d25e45a9f7 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveredTestsEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveredTestsEventArgs.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -13,12 +11,12 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// public partial class DiscoveredTestsEventArgs : EventArgs { - public DiscoveredTestsEventArgs(IEnumerable discoveredTestCases) + public DiscoveredTestsEventArgs(IEnumerable? discoveredTestCases) { DiscoveredTestCases = discoveredTestCases; } /// /// Tests discovered in this discovery request /// - public IEnumerable DiscoveredTestCases { get; private set; } + public IEnumerable? DiscoveredTestCases { get; private set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryCompleteEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryCompleteEventArgs.cs index 92609a36ef..6631ccff15 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryCompleteEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryCompleteEventArgs.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -44,37 +42,37 @@ public DiscoveryCompleteEventArgs(long totalTests, bool isAborted) /// Metrics /// [DataMember] - public IDictionary Metrics { get; set; } + public IDictionary? Metrics { get; set; } /// /// Gets or sets the list of sources which were fully discovered. /// [DataMember] - public IList FullyDiscoveredSources { get; set; } = new List(); + public IList? FullyDiscoveredSources { get; set; } = new List(); /// /// Gets or sets the list of sources which were partially discovered (started discover tests, but then discovery aborted). /// [DataMember] // Added in protocol version 6. - public IList PartiallyDiscoveredSources { get; set; } = new List(); + public IList? PartiallyDiscoveredSources { get; set; } = new List(); /// /// Gets or sets the list of sources that were skipped during discovery. /// [DataMember] // Added in protocol version 7, for previous versions this is put into NotDiscoveredSources. - public IList SkippedDiscoveredSources { get; set; } = new List(); + public IList? SkippedDiscoveredSources { get; set; } = new List(); /// /// Gets or sets the list of sources which were not discovered at all. /// [DataMember] - public IList NotDiscoveredSources { get; set; } = new List(); + public IList? NotDiscoveredSources { get; set; } = new List(); /// /// Gets or sets the collection of discovered extensions. /// [DataMember] - public Dictionary> DiscoveredExtensions { get; set; } = new(); + public Dictionary>? DiscoveredExtensions { get; set; } = new(); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryStartEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryStartEventArgs.cs index 159df53dc4..1f6e8e3eb9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryStartEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/DiscoveryStartEventArgs.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StartTestSessionCompleteEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StartTestSessionCompleteEventArgs.cs index 2572ddd64c..011e714b7f 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StartTestSessionCompleteEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StartTestSessionCompleteEventArgs.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -19,11 +17,11 @@ public class StartTestSessionCompleteEventArgs : EventArgs /// Gets or sets the test session info. /// [DataMember] - public TestSessionInfo TestSessionInfo { get; set; } = null; + public TestSessionInfo? TestSessionInfo { get; set; } /// /// Gets or sets the metrics. /// [DataMember] - public IDictionary Metrics { get; set; } = null; + public IDictionary? Metrics { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StopTestSessionCompleteEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StopTestSessionCompleteEventArgs.cs index 2b906c1ec3..d5eaad8029 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StopTestSessionCompleteEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/StopTestSessionCompleteEventArgs.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -24,9 +22,9 @@ public StopTestSessionCompleteEventArgs() /// /// Creates an instance of the current class. /// - /// + /// /// The test session info. - public StopTestSessionCompleteEventArgs(TestSessionInfo testSessionInfo) + public StopTestSessionCompleteEventArgs(TestSessionInfo? testSessionInfo) { TestSessionInfo = testSessionInfo; } @@ -35,13 +33,13 @@ public StopTestSessionCompleteEventArgs(TestSessionInfo testSessionInfo) /// Gets or sets the test session info. /// [DataMember] - public TestSessionInfo TestSessionInfo { get; set; } = null; + public TestSessionInfo? TestSessionInfo { get; set; } /// /// Gets or sets the metrics. /// [DataMember] - public IDictionary Metrics { get; set; } = null; + public IDictionary? Metrics { get; set; } /// /// Gets or sets a value indicating if the session was successfully stopped or not. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingCompleteEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingCompleteEventArgs.cs index 97566f5698..308fbf8898 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingCompleteEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingCompleteEventArgs.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; [DataContract] @@ -17,7 +15,7 @@ public class TestRunAttachmentsProcessingCompleteEventArgs : EventArgs /// /// Specifies whether the attachments processing is canceled. /// Specifies the error encountered during the execution of the attachments processing. - public TestRunAttachmentsProcessingCompleteEventArgs(bool isCanceled, Exception error) + public TestRunAttachmentsProcessingCompleteEventArgs(bool isCanceled, Exception? error) { IsCanceled = isCanceled; Error = error; @@ -33,11 +31,11 @@ public TestRunAttachmentsProcessingCompleteEventArgs(bool isCanceled, Exception /// Gets the error encountered during the attachments processing of the test runs. Null if there is no error. /// [DataMember] - public Exception Error { get; private set; } + public Exception? Error { get; private set; } /// /// Get or Sets the Metrics (used for telemetry) /// [DataMember] - public IDictionary Metrics { get; set; } + public IDictionary? Metrics { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingProgressEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingProgressEventArgs.cs index a09e4251ab..8dd7ff3757 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingProgressEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunAttachmentsProcessingProgressEventArgs.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; [DataContract] diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunChangedEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunChangedEventArgs.cs index 9feb77f655..96e5e338ed 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunChangedEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunChangedEventArgs.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -21,7 +19,7 @@ public class TestRunChangedEventArgs : EventArgs /// The stats. /// The new test results. /// The active tests. - public TestRunChangedEventArgs(ITestRunStatistics stats, IEnumerable newTestResults, IEnumerable activeTests) + public TestRunChangedEventArgs(ITestRunStatistics? stats, IEnumerable? newTestResults, IEnumerable? activeTests) { TestRunStatistics = stats; NewTestResults = newTestResults; @@ -32,17 +30,17 @@ public TestRunChangedEventArgs(ITestRunStatistics stats, IEnumerable /// Gets the new test results. /// [DataMember] - public IEnumerable NewTestResults { get; private set; } + public IEnumerable? NewTestResults { get; private set; } /// /// Gets the test run statistics. /// [DataMember] - public ITestRunStatistics TestRunStatistics { get; private set; } + public ITestRunStatistics? TestRunStatistics { get; private set; } /// /// Gets the active tests. /// [DataMember] - public IEnumerable ActiveTests { get; private set; } + public IEnumerable? ActiveTests { get; private set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunCompleteEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunCompleteEventArgs.cs index f287f25e66..7284fad4ca 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunCompleteEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunCompleteEventArgs.cs @@ -6,8 +6,6 @@ using System.Collections.ObjectModel; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -18,7 +16,9 @@ public class TestRunCompleteEventArgs : EventArgs { // We have more than one ctor for backward-compatibility reason but we don't want to add dependency on Newtosoft([JsonConstructor]) // We want to fallback to the non-public default constructor https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_ConstructorHandling.htm during deserialization +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. private TestRunCompleteEventArgs() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { AttachmentSets = new Collection(); InvokedDataCollectors = new Collection(); @@ -34,10 +34,10 @@ private TestRunCompleteEventArgs() /// Attachment sets associated with the run. /// Time elapsed in just running tests public TestRunCompleteEventArgs( - ITestRunStatistics stats, + ITestRunStatistics? stats, bool isCanceled, bool isAborted, - Exception error, + Exception? error, Collection attachmentSets, TimeSpan elapsedTime) : this( @@ -61,12 +61,12 @@ public TestRunCompleteEventArgs( /// Invoked data collectors /// Time elapsed in just running tests public TestRunCompleteEventArgs( - ITestRunStatistics stats, + ITestRunStatistics? stats, bool isCanceled, bool isAborted, - Exception error, - Collection attachmentSets, - Collection invokedDataCollectors, + Exception? error, + Collection? attachmentSets, + Collection? invokedDataCollectors, TimeSpan elapsedTime) { TestRunStatistics = stats; @@ -84,7 +84,7 @@ public TestRunCompleteEventArgs( /// Gets the statistics on the state of the test run. /// [DataMember] - public ITestRunStatistics TestRunStatistics { get; private set; } + public ITestRunStatistics? TestRunStatistics { get; private set; } /// /// Gets a value indicating whether the test run is canceled or not. @@ -102,7 +102,7 @@ public TestRunCompleteEventArgs( /// Gets the error encountered during the execution of the test run. Null if there is no error. /// [DataMember] - public Exception Error { get; private set; } + public Exception? Error { get; private set; } /// /// Gets the attachment sets associated with the test run. @@ -127,11 +127,11 @@ public TestRunCompleteEventArgs( /// Get or Sets the Metrics /// [DataMember] - public IDictionary Metrics { get; set; } + public IDictionary? Metrics { get; set; } /// /// Gets or sets the collection of discovered extensions. /// [DataMember] - public Dictionary> DiscoveredExtensions { get; set; } + public Dictionary>? DiscoveredExtensions { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunStartEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunStartEventArgs.cs index a48626eec1..1e0d47f9bc 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunStartEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Events/TestRunStartEventArgs.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/FilterOptions.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/FilterOptions.cs index 9c9bdc41b1..33ed44163d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/FilterOptions.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/FilterOptions.cs @@ -5,8 +5,6 @@ using System.Runtime.Serialization; using System.Text; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -19,14 +17,14 @@ public class FilterOptions /// Gets or sets the regular expression that will be applied on the property before matching. /// [DataMember] - public string FilterRegEx { get; set; } + public string? FilterRegEx { get; set; } /// /// Gets or sets the optional regular expression replacement string. When this property is set, /// will be called upon property value instead of before matching. /// [DataMember] - public string FilterRegExReplacement { get; set; } + public string? FilterRegExReplacement { get; set; } /// public override string ToString() @@ -40,20 +38,20 @@ public override string ToString() return sb.ToString(); } - protected bool Equals(FilterOptions other) => + protected bool Equals(FilterOptions? other) => other != null && string.Equals(FilterRegEx, other.FilterRegEx) && string.Equals(FilterRegExReplacement, other.FilterRegExReplacement); /// - public override bool Equals(object obj) => Equals(obj as FilterOptions); + public override bool Equals(object? obj) => Equals(obj as FilterOptions); /// public override int GetHashCode() { unchecked { - var hashCode = FilterRegEx.GetHashCode(); + var hashCode = FilterRegEx?.GetHashCode() ?? 0; return (hashCode * 397) ^ (FilterRegExReplacement != null ? FilterRegExReplacement.GetHashCode() : 0); } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IBaseProxy.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IBaseProxy.cs index 8b7c9af6ea..c22857a2fc 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IBaseProxy.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IBaseProxy.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.Client; /// @@ -13,9 +11,9 @@ public interface IBaseProxy /// /// Updates the test process start info. /// - /// + /// /// The test process start info to be updated. - /// + /// /// The updated test process start info. TestProcessStartInfo UpdateTestProcessStartInfo(TestProcessStartInfo testProcessStartInfo); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IDiscoveryRequest.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IDiscoveryRequest.cs index 36d9292abd..88cddf8197 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IDiscoveryRequest.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IDiscoveryRequest.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IInternalTestRunEventsHandler.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IInternalTestRunEventsHandler.cs index a9054fa490..79ebd7cb84 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IInternalTestRunEventsHandler.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IInternalTestRunEventsHandler.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 - using System.Collections.Generic; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces; @@ -22,13 +20,13 @@ public interface IInternalTestRunEventsHandler : ITestMessageEventHandler /// Last set of test results /// Attachments of the test run /// ExecutorURIs of the adapters involved in test run - void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection runContextAttachments, ICollection executorUris); + void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs? lastChunkArgs, ICollection? runContextAttachments, ICollection? executorUris); /// /// Handle a change in TestRun i.e. new testresults and stats /// /// TestRunChanged Data - void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs); + void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs); /// /// Launches a process with a given process info under debugger diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IMetricsCollection.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IMetricsCollection.cs index c4a65e0355..08611192ec 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IMetricsCollection.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IMetricsCollection.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequest.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequest.cs index c55d6d7638..1e0528060a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequest.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequest.cs @@ -4,8 +4,6 @@ using System; using System.Threading; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequestData.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequestData.cs index fb59ab5109..e59657cd4c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequestData.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/IRequestData.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.Client; /// @@ -18,7 +16,7 @@ public interface IRequestData /// /// Gets or sets the ProtocolConfig /// - ProtocolConfig ProtocolConfig { get; set; } + ProtocolConfig? ProtocolConfig { get; set; } /// /// Gets or sets a value indicating whether is telemetry opted in. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler.cs index 08b59028ff..d65d2c8756 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -18,12 +16,12 @@ public interface ITestDiscoveryEventsHandler : ITestMessageEventHandler /// Total number of tests discovered. /// Last set of test cases discovered. /// True if the discovery operation is aborted. - void HandleDiscoveryComplete(long totalTests, IEnumerable lastChunk, bool isAborted); + void HandleDiscoveryComplete(long totalTests, IEnumerable? lastChunk, bool isAborted); /// /// Dispatch DiscoveredTest event to listeners. /// - /// Discovered test cases. - void HandleDiscoveredTests(IEnumerable discoveredTestCases); + /// Discovered test cases. + void HandleDiscoveredTests(IEnumerable? discoveredTestCases); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler2.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler2.cs index f4d887b848..a6583621d4 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler2.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestDiscoveryEventsHandler2.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -17,11 +15,11 @@ public interface ITestDiscoveryEventsHandler2 : ITestMessageEventHandler /// /// Discovery Complete Event Args /// Last set of test cases discovered. - void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable lastChunk); + void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable? lastChunk); /// /// Dispatch DiscoveredTest event to listeners. /// /// Discovered test cases. - void HandleDiscoveredTests(IEnumerable discoveredTestCases); + void HandleDiscoveredTests(IEnumerable? discoveredTestCases); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestHostLauncher.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestHostLauncher.cs index 0da872be6a..ca0f32162a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestHostLauncher.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestHostLauncher.cs @@ -3,8 +3,6 @@ using System.Threading; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatform.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatform.cs index 26d1074f71..edebdbce74 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatform.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatform.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -25,7 +23,7 @@ public interface ITestPlatform : IDisposable /// Flag indicating if we should skip the default adapters initialization. /// void UpdateExtensions( - IEnumerable pathToAdditionalExtensions, + IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters); /// @@ -45,7 +43,7 @@ void UpdateExtensions( IDiscoveryRequest CreateDiscoveryRequest( IRequestData requestData, DiscoveryCriteria discoveryCriteria, - TestPlatformOptions options, + TestPlatformOptions? options, Dictionary sourceToSourceDetailMap, IWarningLogger warningLogger); @@ -61,7 +59,7 @@ IDiscoveryRequest CreateDiscoveryRequest( ITestRunRequest CreateTestRunRequest( IRequestData requestData, TestRunCriteria testRunCriteria, - TestPlatformOptions options, + TestPlatformOptions? options, Dictionary sourceToSourceDetailMap, IWarningLogger warningLogger); diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatformCapabilities.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatformCapabilities.cs index 9b9876175b..381c47aed5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatformCapabilities.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestPlatformCapabilities.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.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunAttachmentsProcessingEventsHandler.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunAttachmentsProcessingEventsHandler.cs index db57453de1..c586949c2d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunAttachmentsProcessingEventsHandler.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunAttachmentsProcessingEventsHandler.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -17,7 +15,7 @@ public interface ITestRunAttachmentsProcessingEventsHandler : ITestMessageEventH /// /// AttachmentsProcessing Complete event args. /// Last set of processed attachment sets. - void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable lastChunk); + void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable? lastChunk); /// /// Dispatch ProcessedAttachmentsChunk event to listeners. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunConfiguration.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunConfiguration.cs index 8f991c8e2f..c61cedea6f 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunConfiguration.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunConfiguration.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler.cs index 1be21cdcd0..081151590e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -21,13 +19,13 @@ public interface ITestRunEventsHandler : ITestMessageEventHandler /// Last set of test results /// Attachments of the test run /// ExecutorURIs of the adapters involved in test run - void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection runContextAttachments, ICollection executorUris); + void HandleTestRunComplete(TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs? lastChunkArgs, ICollection? runContextAttachments, ICollection? executorUris); /// /// Handle a change in TestRun i.e. new testresults and stats /// /// TestRunChanged Data - void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs); + void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs); /// /// Launches a process with a given process info under debugger @@ -55,5 +53,5 @@ public interface ITestMessageEventHandler /// /// Message Level /// string message - void HandleLogMessage(TestMessageLevel level, string message); + void HandleLogMessage(TestMessageLevel level, string? message); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler2.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler2.cs index 22f4434170..7b389f7e4a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler2.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunEventsHandler2.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 - using System; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunRequest.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunRequest.cs index 675d80abd7..9d4990d26c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunRequest.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunRequest.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunStatistics.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunStatistics.cs index c45d8342ae..d2a0e165a5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunStatistics.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestRunStatistics.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -22,7 +20,7 @@ public interface ITestRunStatistics /// /// TestOutcome - Test count map /// - IDictionary Stats { get; } + IDictionary? Stats { get; } /// /// Number of tests that have been run. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestSessionEventsHandler.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestSessionEventsHandler.cs index cc47469c9d..d94638a2f8 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestSessionEventsHandler.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Interfaces/ITestSessionEventsHandler.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.Client; /// @@ -13,14 +11,14 @@ public interface ITestSessionEventsHandler : ITestMessageEventHandler /// /// Dispatch StartTestSession complete event to listeners. /// - /// + /// /// The event args. - void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs eventArgs); + void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs? eventArgs); /// /// Dispatch StopTestSession complete event to listeners. /// - /// + /// /// The event args. - void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs eventArgs); + void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs? eventArgs); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/CustomHostLaunchAckPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/CustomHostLaunchAckPayload.cs index f14c661a7f..7c6799b35d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/CustomHostLaunchAckPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/CustomHostLaunchAckPayload.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -22,5 +20,5 @@ public class CustomHostLaunchAckPayload /// ErrorMessage, in cases where custom launch fails /// [DataMember] - public string ErrorMessage { get; set; } + public string? ErrorMessage { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/DiscoveryRequestPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/DiscoveryRequestPayload.cs index a905f4e019..a7bd6b3fc5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/DiscoveryRequestPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/DiscoveryRequestPayload.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -18,19 +16,19 @@ public class DiscoveryRequestPayload /// Settings used for the discovery request. /// [DataMember] - public IEnumerable Sources { get; set; } + public IEnumerable? Sources { get; set; } /// /// Settings used for the discovery request. /// [DataMember] - public string RunSettings { get; set; } + public string? RunSettings { get; set; } /// /// Gets or sets the test platform options /// [DataMember] - public TestPlatformOptions TestPlatformOptions + public TestPlatformOptions? TestPlatformOptions { get; set; @@ -40,5 +38,5 @@ public TestPlatformOptions TestPlatformOptions /// Gets or sets the test session info. /// [DataMember] - public TestSessionInfo TestSessionInfo { get; set; } + public TestSessionInfo? TestSessionInfo { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/EditorAttachDebuggerAckPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/EditorAttachDebuggerAckPayload.cs index 676cdcc6a1..a18244e1b9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/EditorAttachDebuggerAckPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/EditorAttachDebuggerAckPayload.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -23,5 +21,5 @@ public class EditorAttachDebuggerAckPayload /// ErrorMessage, in cases where attaching the debugger fails. /// [DataMember] - public string ErrorMessage { get; set; } + public string? ErrorMessage { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionAckPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionAckPayload.cs index ab2a363997..6e3b892e26 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionAckPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionAckPayload.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Payloads; /// @@ -18,5 +16,5 @@ public class StartTestSessionAckPayload /// Gets or sets the event args. /// [DataMember] - public StartTestSessionCompleteEventArgs EventArgs { get; set; } = null; + public StartTestSessionCompleteEventArgs? EventArgs { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionPayload.cs index 8077b43b70..eef7d1cd37 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StartTestSessionPayload.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Payloads; /// @@ -19,13 +17,13 @@ public class StartTestSessionPayload /// Gets or sets the sources used for starting the test session. /// [DataMember] - public IList Sources { get; set; } + public IList? Sources { get; set; } /// /// Gets or sets the run settings used for starting the test session. /// [DataMember] - public string RunSettings { get; set; } + public string? RunSettings { get; set; } /// /// Gets or sets a flag indicating if debugging is enabled. @@ -43,5 +41,5 @@ public class StartTestSessionPayload /// Gets or sets the test platform options. /// [DataMember] - public TestPlatformOptions TestPlatformOptions { get; set; } + public TestPlatformOptions? TestPlatformOptions { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionAckPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionAckPayload.cs index d6eff0d7d6..fbc266aa78 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionAckPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionAckPayload.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Payloads; /// @@ -18,5 +16,5 @@ public class StopTestSessionAckPayload /// Gets or sets the event args. /// [DataMember] - public StopTestSessionCompleteEventArgs EventArgs { get; set; } = null; + public StopTestSessionCompleteEventArgs? EventArgs { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionPayload.cs index 7f9bbff2e2..c09f3be1ca 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/StopTestSessionPayload.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Payloads; /// @@ -18,11 +16,11 @@ public class StopTestSessionPayload /// Gets or sets the test session info. /// [DataMember] - public TestSessionInfo TestSessionInfo { get; set; } = null; + public TestSessionInfo? TestSessionInfo { get; set; } /// /// Gets or sets a flag indicating if metrics should be collected. /// [DataMember] - public bool CollectMetrics { get; set; } = false; + public bool CollectMetrics { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunAttachmentsProcessingPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunAttachmentsProcessingPayload.cs index e92657417e..2b3046024f 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunAttachmentsProcessingPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunAttachmentsProcessingPayload.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -17,19 +15,19 @@ public class TestRunAttachmentsProcessingPayload /// Collection of attachments. /// [DataMember] - public IEnumerable Attachments { get; set; } + public IEnumerable? Attachments { get; set; } /// /// Collection of the invoked data collectors. /// [DataMember] - public IEnumerable InvokedDataCollectors { get; set; } + public IEnumerable? InvokedDataCollectors { get; set; } /// /// Gets or sets the settings used for the test run request. /// [DataMember] - public string RunSettings { get; set; } + public string? RunSettings { get; set; } /// /// Gets or sets whether Metrics should be collected or not. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunRequestPayload.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunRequestPayload.cs index fa4749ec32..e162c89f7e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunRequestPayload.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/Payloads/TestRunRequestPayload.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -21,7 +19,7 @@ public class TestRunRequestPayload /// if a linq query outputs the IEnumerable. /// [DataMember] - public List Sources { get; set; } + public List? Sources { get; set; } /// /// Gets or sets the test cases for the test run request. @@ -31,13 +29,13 @@ public class TestRunRequestPayload /// if a linq query outputs the IEnumerable. /// [DataMember] - public List TestCases { get; set; } + public List? TestCases { get; set; } /// /// Gets or sets the settings used for the test run request. /// [DataMember] - public string RunSettings { get; set; } + public string? RunSettings { get; set; } /// /// Settings used for the Run request. @@ -55,11 +53,11 @@ public class TestRunRequestPayload /// Gets or sets the testplatform options /// [DataMember] - public TestPlatformOptions TestPlatformOptions { get; set; } + public TestPlatformOptions? TestPlatformOptions { get; set; } /// /// Gets or sets the test session info. /// [DataMember] - public TestSessionInfo TestSessionInfo { get; set; } + public TestSessionInfo? TestSessionInfo { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/ProtocolConfig.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/ProtocolConfig.cs index bb26d8f64f..f95227b186 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/ProtocolConfig.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/ProtocolConfig.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.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/StartTestSessionCriteria.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/StartTestSessionCriteria.cs index ede9cc1a43..2516ee4907 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/StartTestSessionCriteria.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/StartTestSessionCriteria.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -20,17 +18,17 @@ public class StartTestSessionCriteria /// Gets or sets the sources used for starting the test session. /// [DataMember] - public IList Sources { get; set; } + public IList? Sources { get; set; } /// /// Gets or sets the run settings used for starting the test session. /// [DataMember] - public string RunSettings { get; set; } + public string? RunSettings { get; set; } /// /// Gets or sets the test host launcher used for starting the test session. /// [DataMember] - public ITestHostLauncher TestHostLauncher { get; set; } + public ITestHostLauncher? TestHostLauncher { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/TestPlatformOptions.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/TestPlatformOptions.cs index 5016737c8c..d5f96d4fe7 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/TestPlatformOptions.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/TestPlatformOptions.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -16,22 +14,22 @@ public class TestPlatformOptions /// /// Gets or sets the filter criteria for test cases. /// - /// + /// /// /// This is only used when running tests with sources. /// [DataMember] - public string TestCaseFilter { get; set; } + public string? TestCaseFilter { get; set; } /// /// Gets or sets the filter options if there are any. /// - /// + /// /// /// This will be valid only if TestCase filter is present. /// [DataMember] - public FilterOptions FilterOptions { get; set; } + public FilterOptions? FilterOptions { get; set; } /// /// Gets or sets whether metrics should be collected or not. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs index ee564afeb0..95bf1fbbb8 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs @@ -526,10 +526,7 @@ public IEnumerable Sources [DataMember] public string TestCaseFilter { - get - { - return _testCaseFilter; - } + get => _testCaseFilter; private set { @@ -549,10 +546,7 @@ private set [DataMember] public FilterOptions FilterOptions { - get - { - return _filterOptions; - } + get => _filterOptions; private set { diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunState.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunState.cs index 46a2581a49..0d6fee2d6d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunState.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunState.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.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunStatistics.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunStatistics.cs index 4eb4a8aa3f..0050acb157 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunStatistics.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunStatistics.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -18,7 +16,9 @@ public class TestRunStatistics : ITestRunStatistics /// Initializes a new instance of the class. /// /// This constructor doesn't perform any parameter validation, it is meant to be used for serialization."/> +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public TestRunStatistics() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { // Default constructor for Serialization. } @@ -27,7 +27,7 @@ public TestRunStatistics() /// Initializes a new instance of the class. /// /// The stats. - public TestRunStatistics(IDictionary stats) + public TestRunStatistics(IDictionary? stats) { Stats = stats; } @@ -38,7 +38,7 @@ public TestRunStatistics(IDictionary stats) /// The executed tests. /// The stats. /// This constructor is only needed to reconstruct the object during deserialization. - public TestRunStatistics(long executedTests, IDictionary stats) + public TestRunStatistics(long executedTests, IDictionary? stats) { ExecutedTests = executedTests; Stats = stats; @@ -54,7 +54,7 @@ public TestRunStatistics(long executedTests, IDictionary stat /// Gets the test stats which is the test outcome versus its state. /// [DataMember] - public IDictionary Stats { get; private set; } + public IDictionary? Stats { get; private set; } /// /// Gets the number of tests with a specified outcome. @@ -65,7 +65,7 @@ public long this[TestOutcome testOutcome] { get { - return Stats.TryGetValue(testOutcome, out var count) ? count : 0; + return Stats?.TryGetValue(testOutcome, out var count) == true ? count : 0; } } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/TestSessionInfo.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/TestSessionInfo.cs index 0c98b991f6..8eed877a33 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/TestSessionInfo.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/TestSessionInfo.cs @@ -4,8 +4,6 @@ using System; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -32,7 +30,7 @@ public TestSessionInfo() /// /// Calculates the hash code for the current object. /// - /// + /// /// An integer representing the computed hashcode value. public override int GetHashCode() { @@ -42,11 +40,11 @@ public override int GetHashCode() /// /// Checks if the specified object is equal to the current instance. /// - /// + /// /// The object to be checked. - /// + /// /// True if the two objects are equal, false otherwise. - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as TestSessionInfo); } @@ -54,11 +52,11 @@ public override bool Equals(object obj) /// /// Checks if the specified session is equal to the current instance. /// - /// + /// /// The session to be checked. - /// + /// /// True if the two sessions are equal, false otherwise. - public bool Equals(TestSessionInfo other) + public bool Equals(TestSessionInfo? other) { return other != null && Id.Equals(other.Id); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/CodeCoverage/TestSDKAutoGeneratedCode.cs b/src/Microsoft.TestPlatform.ObjectModel/CodeCoverage/TestSDKAutoGeneratedCode.cs index a23cabcfa0..39cdc1b8e8 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/CodeCoverage/TestSDKAutoGeneratedCode.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/CodeCoverage/TestSDKAutoGeneratedCode.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfo.cs b/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfo.cs index 1fd5274494..bdf85b3a27 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfo.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfo.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; /// @@ -94,7 +92,7 @@ public TestHostConnectionInfo ConnectionInfo /// /// Gets or sets the diagnostics log file. /// - public string LogFile + public string? LogFile { get; set; diff --git a/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfoExtensions.cs b/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfoExtensions.cs index 89cf88794a..23adf2f3b8 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfoExtensions.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/ConnectionInfo/TestRunnerConnectionInfoExtensions.cs @@ -1,7 +1,7 @@ // 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 +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -17,8 +17,8 @@ public static class TestRunnerConnectionInfoExtensions /// Command line option string. public static string ToCommandLineOptions(this TestRunnerConnectionInfo connectionInfo) { - var options = "--port " + connectionInfo.Port + " --endpoint " + connectionInfo.ConnectionInfo.Endpoint + " --role " + (connectionInfo.ConnectionInfo.Role == ConnectionRole.Client ? "client" : "host") + " --parentprocessid " + connectionInfo.RunnerProcessId; - if (!string.IsNullOrEmpty(connectionInfo.LogFile)) + var options = $"--port {connectionInfo.Port} --endpoint {connectionInfo.ConnectionInfo.Endpoint} --role {(connectionInfo.ConnectionInfo.Role == ConnectionRole.Client ? "client" : "host")} --parentprocessid {connectionInfo.RunnerProcessId}"; + if (!StringUtils.IsNullOrEmpty(connectionInfo.LogFile)) { options += " --diag " + connectionInfo.LogFile; options += " --tracelevel " + connectionInfo.TraceLevel; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Constants.cs b/src/Microsoft.TestPlatform.ObjectModel/Constants.cs index 0cd1def08f..baae3c2e9a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Constants.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Constants.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorAttachmentProcessor.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorAttachmentProcessor.cs index 66f120b5ad..fdd9257d8a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorAttachmentProcessor.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorAttachmentProcessor.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorFriendlyNameAttribute.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorFriendlyNameAttribute.cs index 2dca49084d..9c6289f1ef 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorFriendlyNameAttribute.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorFriendlyNameAttribute.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorTypeUriAttribute.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorTypeUriAttribute.cs index 3d6e7c1022..296e2573cd 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorTypeUriAttribute.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Attributes/DataCollectorTypeUriAttribute.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/DataCollectorMessageLevel.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/DataCollectorMessageLevel.cs index 143d4437d6..03c6349e14 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/DataCollectorMessageLevel.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/DataCollectorMessageLevel.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.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/FileHelper.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/FileHelper.cs index 62f9e1851f..15cc946158 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/FileHelper.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/FileHelper.cs @@ -2,24 +2,23 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; internal sealed class FileHelper { - private static readonly Dictionary InvalidFileNameChars; + private static readonly Dictionary InvalidFileNameChars; private static readonly Regex ReservedFileNamesRegex = new(@"(?i:^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]|CLOCK\$)(\..*)?)$"); static FileHelper() { // Create a hash table of invalid chars. char[] invalidCharsArray = Path.GetInvalidFileNameChars(); - InvalidFileNameChars = new Dictionary(invalidCharsArray.Length); + InvalidFileNameChars = new(invalidCharsArray.Length); foreach (char c in invalidCharsArray) { InvalidFileNameChars.Add(c, null); @@ -35,7 +34,7 @@ private FileHelper() /// File name to check. /// Invalid characters which were found in the file name. /// True if the file name is valid and false if the filename contains invalid characters. - public static bool IsValidFileName(string fileName, out string invalidCharacters) + public static bool IsValidFileName(string fileName, out string? invalidCharacters) { bool result = true; //EqtAssert.StringNotNullOrEmpty(fileName, "fileName"); @@ -60,8 +59,7 @@ public static bool IsValidFileName(string fileName, out string invalidCharacters /// The name of the file. Note: only a file name, does not expect to contain directory separators. internal static bool IsReservedFileName(string fileName) { - Debug.Assert(!string.IsNullOrEmpty(fileName), "FileHelper.IsReservedFileName: the argument is null or empty string!"); - if (string.IsNullOrEmpty(fileName)) + if (fileName.IsNullOrEmpty()) { return false; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs index ec21eb6eb0..c907d958af 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs @@ -4,8 +4,6 @@ using System; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -45,7 +43,7 @@ internal RequestId(Guid id) /// /// The object to compare to /// True if equal, false otherwise - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) { @@ -57,7 +55,7 @@ public override bool Equals(object obj) return true; } - RequestId other = obj as RequestId; + RequestId? other = obj as RequestId; return other != null && Id == other.Id; } @@ -90,7 +88,7 @@ public override string ToString() /// /// The request ID to compare to /// True if equal, false otherwise - public bool Equals(RequestId other) + public bool Equals(RequestId? other) { return other != null && ( @@ -108,7 +106,7 @@ public bool Equals(RequestId other) /// /// The request ID to compare to /// An indication of the two request IDs' relative values - public int CompareTo(RequestId other) + public int CompareTo(RequestId? other) { return other == null ? 1 : Id.CompareTo(other.Id); } @@ -125,14 +123,14 @@ public int CompareTo(RequestId other) /// /// 'obj' is not null and not an instance of /// - public int CompareTo(object obj) + public int CompareTo(object? obj) { if (obj == null) { return 1; } - RequestId other = obj as RequestId; + RequestId? other = obj as RequestId; return other == null ? throw new ArgumentException(string.Format(Resources.Resources.Common_ObjectMustBeOfType, new object[] { typeof(RequestId).Name }), nameof(obj)) : Id.CompareTo(other.Id); @@ -150,7 +148,7 @@ public int CompareTo(object obj) /// The left-hand request ID /// The right-hand request ID /// True if equal, false otherwise - public static bool operator ==(RequestId left, RequestId right) + public static bool operator ==(RequestId? left, RequestId? right) { return ReferenceEquals(left, right) || @@ -165,7 +163,7 @@ right is not null && /// The left-hand request ID /// The right-hand request ID /// True if unequal, false otherwise - public static bool operator !=(RequestId left, RequestId right) + public static bool operator !=(RequestId? left, RequestId? right) { return !(left == right); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/Session.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/Session.cs index 4c01d7969b..d27fa87e0e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/Session.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/Session.cs @@ -4,8 +4,6 @@ using System; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -30,18 +28,9 @@ public SessionId(Guid id) [DataMember] public Guid Id { get; } - public override bool Equals(object obj) - { - return obj is SessionId sessionId && Id.Equals(sessionId.Id); - } + public override bool Equals(object? obj) => obj is SessionId sessionId && Id.Equals(sessionId.Id); - public override int GetHashCode() - { - return Id.GetHashCode(); - } + public override int GetHashCode() => Id.GetHashCode(); - public override string ToString() - { - return Id.ToString("B"); - } + public override string ToString() => Id.ToString("B"); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestCaseFailureType.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestCaseFailureType.cs index 33064ff7fc..63f2690e61 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestCaseFailureType.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestCaseFailureType.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.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestExecId.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestExecId.cs index c96c3d6e6e..219e97b210 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestExecId.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/TestExecId.cs @@ -4,8 +4,6 @@ using System; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -31,18 +29,9 @@ public TestExecId(Guid id) [DataMember] public Guid Id { get; } - public override bool Equals(object obj) - { - return obj is TestExecId testExecId && Id.Equals(testExecId.Id); - } + public override bool Equals(object? obj) => obj is TestExecId testExecId && Id.Equals(testExecId.Id); - public override int GetHashCode() - { - return Id.GetHashCode(); - } + public override int GetHashCode() => Id.GetHashCode(); - public override string ToString() - { - return Id.ToString("B"); - } + public override string ToString() => Id.ToString("B"); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionContext.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionContext.cs index fee39b65fd..8357d18063 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionContext.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionContext.cs @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -34,9 +33,12 @@ public class DataCollectionContext /// Constructs DataCollection Context for in process data collectors /// /// test case to identify the context - public DataCollectionContext(TestCase testCase) + public DataCollectionContext(TestCase? testCase) { TestCase = testCase; + // TODO: Comment says this ctor should never have been made public but it was added. + // This leaves a path where SessionId is null but the rest of the class doesn't handle it. + SessionId = null!; } /// @@ -45,7 +47,7 @@ public DataCollectionContext(TestCase testCase) /// /// The session under which the data collection occurs. Cannot be null. protected internal DataCollectionContext(SessionId sessionId) - : this(sessionId, (TestExecId)null) + : this(sessionId, (TestExecId?)null) { } @@ -56,7 +58,7 @@ protected internal DataCollectionContext(SessionId sessionId) /// The session under which the data collection occurs. Cannot be null. /// The test execution under which the data collection occurs, /// or null if no executing test case is in context - protected internal DataCollectionContext(SessionId sessionId, TestExecId testExecId) + protected internal DataCollectionContext(SessionId sessionId, TestExecId? testExecId) { //TODO //EqtAssert.ParameterNotNull(sessionId, "sessionId"); @@ -66,7 +68,8 @@ protected internal DataCollectionContext(SessionId sessionId, TestExecId testExe _hashCode = ComputeHashCode(); } - protected internal DataCollectionContext(SessionId sessionId, TestCase testCase) : this(sessionId, new TestExecId(testCase.Id)) + protected internal DataCollectionContext(SessionId sessionId, TestCase testCase) + : this(sessionId, new TestExecId(testCase.Id)) { TestCase = testCase; @@ -75,7 +78,7 @@ protected internal DataCollectionContext(SessionId sessionId, TestExecId testExe /// Gets test case. /// [DataMember] - public TestCase TestCase { get; private set; } + public TestCase? TestCase { get; private set; } /// /// Identifies the session under which the data collection occurs. Will not be null. @@ -88,30 +91,31 @@ protected internal DataCollectionContext(SessionId sessionId, TestExecId testExe /// or null if no such test exists. /// [DataMember] - public TestExecId TestExecId { get; } + public TestExecId? TestExecId { get; } /// /// Returns true if there is an executing test case associated with this context. /// [DataMember] + [MemberNotNullWhen(true, nameof(TestExecId))] public bool HasTestCase { get { return TestExecId != null; } } - public static bool operator ==(DataCollectionContext context1, DataCollectionContext context2) + public static bool operator ==(DataCollectionContext? context1, DataCollectionContext? context2) { return Equals(context1, context2); } - public static bool operator !=(DataCollectionContext context1, DataCollectionContext context2) + public static bool operator !=(DataCollectionContext? context1, DataCollectionContext? context2) { return !(context1 == context2); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - DataCollectionContext other = obj as DataCollectionContext; + DataCollectionContext? other = obj as DataCollectionContext; return other != null && SessionId.Equals(other.SessionId) diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionEnvironmentContext.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionEnvironmentContext.cs index 37cdc192d7..3f37e278cf 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionEnvironmentContext.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionEnvironmentContext.cs @@ -5,8 +5,6 @@ using System; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -18,14 +16,11 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; public sealed class DataCollectionEnvironmentContext { /// - /// DataCollectionContext for the session. - /// - - /// - /// Default Constructor + /// Serialization Constructor /// - internal DataCollectionEnvironmentContext() - : this(null) +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + private DataCollectionEnvironmentContext() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { } @@ -37,14 +32,13 @@ public DataCollectionEnvironmentContext(DataCollectionContext sessionDataCollect SessionDataCollectionContext = sessionDataCollectionContext; } - /// /// Creates an environment context for a local (hosted) agent and controller /// /// An environment context for a local (hosted) agent and controller public static DataCollectionEnvironmentContext CreateForLocalEnvironment() { - return CreateForLocalEnvironment(null); + return CreateForLocalEnvironment(null!); } /// @@ -54,8 +48,7 @@ public static DataCollectionEnvironmentContext CreateForLocalEnvironment() /// An environment context for a local (hosted) agent and controller public static DataCollectionEnvironmentContext CreateForLocalEnvironment(DataCollectionContext sessionDataCollectionContext) { - var dataCollectionEnvironmentContext = new DataCollectionEnvironmentContext(); - dataCollectionEnvironmentContext.SessionDataCollectionContext = sessionDataCollectionContext; + var dataCollectionEnvironmentContext = new DataCollectionEnvironmentContext(sessionDataCollectionContext); return dataCollectionEnvironmentContext; } @@ -63,6 +56,6 @@ public static DataCollectionEnvironmentContext CreateForLocalEnvironment(DataCol /// /// DataCollectionContext for the session. /// - public DataCollectionContext SessionDataCollectionContext { get; internal set; } + public DataCollectionContext SessionDataCollectionContext { get; private set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionLogger.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionLogger.cs index 73fd779138..83ca4f9d1e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionLogger.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionLogger.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionRunSettings.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionRunSettings.cs index a90c0de641..42f179557a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionRunSettings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectionRunSettings.cs @@ -7,8 +7,6 @@ using System.Linq; using System.Xml; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollector.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollector.cs index 29d4756e22..a6c4de91b9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollector.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollector.cs @@ -4,8 +4,6 @@ using System; using System.Xml; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -29,11 +27,11 @@ public abstract class DataCollector : IDisposable /// /// Provides contextual information about the agent environment public abstract void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext + DataCollectionEnvironmentContext? environmentContext ); /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectorSettings.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectorSettings.cs index 80545e7729..dbc436744d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectorSettings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/DataCollectorSettings.cs @@ -5,7 +5,7 @@ using System.Globalization; using System.Xml; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -17,7 +17,7 @@ public class DataCollectorSettings /// /// Gets or sets the uri. /// - public Uri Uri + public Uri? Uri { get; set; @@ -26,7 +26,7 @@ public Uri Uri /// /// Gets or sets the assembly qualified name. /// - public string AssemblyQualifiedName + public string? AssemblyQualifiedName { get; set; @@ -35,7 +35,7 @@ public string AssemblyQualifiedName /// /// Gets or sets the friendly name. /// - public string FriendlyName + public string? FriendlyName { get; set; @@ -53,7 +53,7 @@ public bool IsEnabled /// /// Gets or sets value CodeBase of collector DLL. The syntax is same as Code Base in AssemblyName class. /// - public string CodeBase + public string? CodeBase { get; set; @@ -62,7 +62,7 @@ public string CodeBase /// /// Gets or sets the configuration. /// - public XmlElement Configuration + public XmlElement? Configuration { get; set; @@ -78,11 +78,11 @@ public XmlElement ToXml() { XmlDocument doc = new(); XmlElement root = doc.CreateElement(Constants.DataCollectorSettingName); - AppendAttribute(doc, root, "uri", Uri.ToString()); + AppendAttribute(doc, root, "uri", Uri?.ToString()); AppendAttribute(doc, root, "assemblyQualifiedName", AssemblyQualifiedName); AppendAttribute(doc, root, "friendlyName", FriendlyName); - root.AppendChild(doc.ImportNode(Configuration, true)); + root.AppendChild(doc.ImportNode(Configuration!, true)); return root; } @@ -105,19 +105,19 @@ public XmlElement ToXml(string dataCollectorName) AppendAttribute(doc, root, "uri", Uri.ToString()); } - if (!string.IsNullOrWhiteSpace(AssemblyQualifiedName)) + if (!StringUtils.IsNullOrWhiteSpace(AssemblyQualifiedName)) { AppendAttribute(doc, root, "assemblyQualifiedName", AssemblyQualifiedName); } - if (!string.IsNullOrWhiteSpace(FriendlyName)) + if (!StringUtils.IsNullOrWhiteSpace(FriendlyName)) { AppendAttribute(doc, root, "friendlyName", FriendlyName); } AppendAttribute(doc, root, "enabled", IsEnabled.ToString()); - if (!string.IsNullOrWhiteSpace(CodeBase)) + if (!StringUtils.IsNullOrWhiteSpace(CodeBase)) { AppendAttribute(doc, root, "codebase", CodeBase); } @@ -224,7 +224,7 @@ internal static DataCollectorSettings FromXml(XmlReader reader) return settings; } - private static void AppendAttribute(XmlDocument doc, XmlElement owner, string attributeName, string attributeValue) + private static void AppendAttribute(XmlDocument doc, XmlElement owner, string attributeName, string? attributeValue) { XmlAttribute attribute = doc.CreateAttribute(attributeName); attribute.Value = attributeValue; diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEventArgs.cs index 1f4c7b78b8..3973402bb9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEventArgs.cs @@ -2,9 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Diagnostics; - -#nullable disable namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; @@ -19,8 +16,11 @@ public abstract class DataCollectionEventArgs : EventArgs /// /// Default constructor added for serialization/deserialization. /// +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public DataCollectionEventArgs() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { + // TODO: Make private } /// @@ -40,21 +40,4 @@ public DataCollectionContext Context get; internal set; } - - /// - /// Updates the data collection context stored by this instance. - /// - /// Context to update with. - /// - /// Generally the data collection context is known in advance, however there - /// are cases around custom notifications where it is not necessarily known - /// until the event is being sent. This is used for updating the context when - /// sending the event. - /// - internal void UpdateDataCollectionContext(DataCollectionContext context) - { - Debug.Assert(context != null, "'context' cannot be null."); - Context = context; - } - } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEvents.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEvents.cs index 5d59d6e75c..454389d6e8 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEvents.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/DataCollectionEvents.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -22,26 +20,26 @@ protected DataCollectionEvents() /// /// Raised when test host initialized /// - public abstract event EventHandler TestHostLaunched; + public abstract event EventHandler? TestHostLaunched; /// /// Raised when a session is starting /// - public abstract event EventHandler SessionStart; + public abstract event EventHandler? SessionStart; /// /// Raised when a session is ending /// - public abstract event EventHandler SessionEnd; + public abstract event EventHandler? SessionEnd; /// /// Raised when a test case is starting /// - public abstract event EventHandler TestCaseStart; + public abstract event EventHandler? TestCaseStart; /// /// Raised when a test case is ending /// - public abstract event EventHandler TestCaseEnd; + public abstract event EventHandler? TestCaseEnd; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs index 22d55f52f3..bd5cd80fb5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/SessionEvents.cs @@ -3,10 +3,9 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Runtime.Serialization; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; @@ -16,7 +15,7 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; [DataContract] public sealed class SessionStartEventArgs : DataCollectionEventArgs { - private readonly IDictionary _properties; + private readonly IDictionary _properties; /// /// Initializes a new instance of the class. @@ -26,7 +25,7 @@ public sealed class SessionStartEventArgs : DataCollectionEventArgs /// DataCollectionContext with empty session signifies that is it irrelevant in the current context. /// public SessionStartEventArgs() - : this(new DataCollectionContext(new SessionId(Guid.Empty)), new Dictionary()) + : this(new DataCollectionContext(new SessionId(Guid.Empty)), new Dictionary()) { } @@ -38,7 +37,7 @@ public SessionStartEventArgs() /// constructor with properties and default DataCollectionContext. /// DataCollectionContext with empty session signifies that is it irrelevant in the current context. /// - public SessionStartEventArgs(IDictionary properties) + public SessionStartEventArgs(IDictionary properties) : this(new DataCollectionContext(new SessionId(Guid.Empty)), properties) { @@ -50,17 +49,17 @@ public SessionStartEventArgs(IDictionary properties) /// /// Context information for the session /// - public SessionStartEventArgs(DataCollectionContext context, IDictionary properties) + public SessionStartEventArgs(DataCollectionContext context, IDictionary properties) : base(context) { _properties = properties; - Debug.Assert(!context.HasTestCase, "Session event has test a case context"); + TPDebug.Assert(!context.HasTestCase, "Session event has test a case context"); } /// /// Gets session start properties enumerator /// - public IEnumerator> GetProperties() + public IEnumerator> GetProperties() { return _properties.GetEnumerator(); } @@ -71,11 +70,11 @@ public IEnumerator> GetProperties() /// /// Property name /// - public T GetPropertyValue(string property) + public T? GetPropertyValue(string property) { ValidateArg.NotNullOrEmpty(property, nameof(property)); - return _properties.ContainsKey(property) ? (T)_properties[property] : default; + return _properties.ContainsKey(property) ? (T?)_properties[property] : default; } /// @@ -84,7 +83,7 @@ public T GetPropertyValue(string property) /// /// Property name /// - public object GetPropertyValue(string property) + public object? GetPropertyValue(string property) { ValidateArg.NotNullOrEmpty(property, nameof(property)); @@ -122,7 +121,7 @@ public SessionEndEventArgs() : this(new DataCollectionContext(new SessionId(Guid public SessionEndEventArgs(DataCollectionContext context) : base(context) { - Debug.Assert(!context.HasTestCase, "Session event has test a case context"); + TPDebug.Assert(!context.HasTestCase, "Session event has test a case context"); } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestCaseEvents.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestCaseEvents.cs index c65948701c..5313b1d5b5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestCaseEvents.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestCaseEvents.cs @@ -2,10 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Diagnostics; using System.Runtime.Serialization; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; @@ -18,8 +17,11 @@ public abstract class TestCaseEventArgs : DataCollectionEventArgs /// /// Default constructor added for serialization/deserialization. /// +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public TestCaseEventArgs() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { + // TODO: Make private } /// @@ -40,7 +42,7 @@ public TestCaseEventArgs() protected TestCaseEventArgs( DataCollectionContext context, Guid testCaseId, - string testCaseName, + string? testCaseName, bool isChildTestCase) : base(context) { @@ -114,7 +116,7 @@ public bool IsChildTestCase /// Gets test element of the test this event is for. /// [DataMember] - public TestCase TestElement + public TestCase? TestElement { get; internal set; @@ -191,7 +193,7 @@ internal TestCaseStartEventArgs( bool isChildTestCase) : base(context, testCaseId, testCaseName, isChildTestCase) { - Debug.Assert(context.HasTestCase, "Context is not for a test case"); + TPDebug.Assert(context.HasTestCase, "Context is not for a test case"); } } @@ -305,7 +307,7 @@ internal TestCaseEndEventArgs( TestOutcome testOutcome) : base(context, testCaseId, testCaseName, isChildTestCase) { - Debug.Assert(context.HasTestCase, "Context is not for a test case"); + TPDebug.Assert(context.HasTestCase, "Context is not for a test case"); TestOutcome = testOutcome; } @@ -329,8 +331,11 @@ public sealed class TestResultEventArgs : TestCaseEventArgs /// /// Default constructor for serialization/deserialization /// +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public TestResultEventArgs() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { + // TODO: Make private } /// @@ -399,7 +404,7 @@ internal TestResultEventArgs( TestResult testResult) : base(context, testCaseId, testCaseName, isChildTestCase) { - Debug.Assert(context.HasTestCase, "Context is not for a test case"); + TPDebug.Assert(context.HasTestCase, "Context is not for a test case"); TestResult = testResult; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestHostLaunchedEvent.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestHostLaunchedEvent.cs index 991a80016f..879abbac2a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestHostLaunchedEvent.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Events/TestHostLaunchedEvent.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectionSink.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectionSink.cs index 1a83ef5b88..1bdf537507 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectionSink.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectionSink.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.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachmentProcessor.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachmentProcessor.cs index 6d46965d97..f6876cb431 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachmentProcessor.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachmentProcessor.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// @@ -21,7 +19,7 @@ public interface IDataCollectorAttachmentProcessor /// /// Gets the attachments Uris, which are handled by attachment processor /// - IEnumerable GetExtensionUris(); + IEnumerable? GetExtensionUris(); /// /// Indicates whether attachment processor is supporting incremental processing of attachments @@ -34,7 +32,7 @@ public interface IDataCollectorAttachmentProcessor /// * `var result1 = await ProcessAttachmentSetsAsync([a1, a2, a3], ...);` when first 3 executions are done /// * `var result2 = await ProcessAttachmentSetsAsync(result1.Concat([a4]), ...);` when 4th execution is done /// * `var finalResult = await ProcessAttachmentSetsAsync(result2.Concat([a5]), ...);` when last test execution is done - /// + /// /// If `SupportsIncrementalProcessing` is `False` then Test Platform will wait for all test executions to finish and call `ProcessAttachmentSetsAsync` only once: /// * `var finalResult = await ProcessAttachmentSetsAsync([a1, a2, a3, a4, a5], ...);` /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachments.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachments.cs index 49980d4476..322c4d4878 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachments.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/IDataCollectorAttachments.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/ITestExecutionEnvironmentSpecifier.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/ITestExecutionEnvironmentSpecifier.cs index 375a0de7a9..c4b470d2f5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/ITestExecutionEnvironmentSpecifier.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/ITestExecutionEnvironmentSpecifier.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollectionArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollectionArgs.cs index 195ebdbe03..18159963c0 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollectionArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollectionArgs.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.DataCollector.InProcDataCollector; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollector.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollector.cs index 46a4d818c5..bdc7d6af00 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollector.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/InProcDataCollector.cs @@ -4,8 +4,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollector.InProcDataCollector; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.InProcDataCollector; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestCaseStartArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestCaseStartArgs.cs index 0e41f92814..ed6c8f1d46 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestCaseStartArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestCaseStartArgs.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.DataCollector.InProcDataCollector; /// @@ -16,7 +14,7 @@ public class TestCaseStartArgs : InProcDataCollectionArgs /// /// The test case. /// - public TestCaseStartArgs(TestCase testCase) + public TestCaseStartArgs(TestCase? testCase) { TestCase = testCase; } @@ -24,5 +22,5 @@ public TestCaseStartArgs(TestCase testCase) /// /// Gets the test case. /// - public TestCase TestCase { get; private set; } + public TestCase? TestCase { get; private set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestSessionStartArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestSessionStartArgs.cs index e7b5a43075..9fc75fa955 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestSessionStartArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/InProcDataCollector/TestSessionStartArgs.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollector.InProcDataCollector; @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollector.InProcDa /// public class TestSessionStartArgs : InProcDataCollectionArgs { - private readonly IDictionary _properties; + private readonly IDictionary? _properties; /// /// Initializes a new instance of the class. @@ -28,7 +28,7 @@ public TestSessionStartArgs() /// /// Properties. /// - public TestSessionStartArgs(IDictionary properties) + public TestSessionStartArgs(IDictionary properties) { Configuration = string.Empty; _properties = properties; @@ -48,13 +48,14 @@ public TestSessionStartArgs(string configuration) /// /// Gets or sets the configuration. /// - public string Configuration { get; set; } + public string? Configuration { get; set; } /// /// Gets session start properties enumerator /// - public IEnumerator> GetProperties() + public IEnumerator> GetProperties() { + TPDebug.Assert(_properties is not null, "_properties is null"); return _properties.GetEnumerator(); } @@ -64,11 +65,11 @@ public IEnumerator> GetProperties() /// /// Property name /// - public T GetPropertyValue(string property) + public T? GetPropertyValue(string property) { ValidateArg.NotNullOrEmpty(property, nameof(property)); - - return _properties.ContainsKey(property) ? (T)_properties[property] : default; + TPDebug.Assert(_properties is not null, "_properties is null"); + return _properties.ContainsKey(property) ? (T?)_properties[property] : default; } /// @@ -77,10 +78,10 @@ public T GetPropertyValue(string property) /// /// Property name /// - public object GetPropertyValue(string property) + public object? GetPropertyValue(string property) { ValidateArg.NotNullOrEmpty(property, nameof(property)); - + TPDebug.Assert(_properties is not null, "_properties is null"); _properties.TryGetValue(property, out var propertyValue); return propertyValue; diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/BaseTransferInformation.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/BaseTransferInformation.cs index d53c4e23fc..a4703adbb0 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/BaseTransferInformation.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/BaseTransferInformation.cs @@ -42,16 +42,11 @@ protected BasicTransferInformation(DataCollectionContext context) /// public string Description { - get - { - return _description; - } + get => _description; - set - { + set => // If we don't have a description, use an empty string. _description = value ?? string.Empty; - } } /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs index 79cf641efe..880622684d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/DefaultExecutorUriAttribute.cs b/src/Microsoft.TestPlatform.ObjectModel/DefaultExecutorUriAttribute.cs index 9c0170b6f2..754881f19a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DefaultExecutorUriAttribute.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DefaultExecutorUriAttribute.cs @@ -3,10 +3,6 @@ using System; -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources; - -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -21,11 +17,7 @@ public sealed class DefaultExecutorUriAttribute : Attribute /// The Uri of the executor public DefaultExecutorUriAttribute(string executorUri) { - if (string.IsNullOrWhiteSpace(executorUri)) - { - throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(executorUri)); - } - + ValidateArg.NotNullOrWhiteSpace(executorUri, nameof(executorUri)); ExecutorUri = executorUri; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/ExceptionConverter.cs b/src/Microsoft.TestPlatform.ObjectModel/ExceptionConverter.cs index 9c68f254a8..89d5246f46 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/ExceptionConverter.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/ExceptionConverter.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -15,12 +13,12 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; #endif public class TestPlatformException : Exception { - public TestPlatformException(string message) + public TestPlatformException(string? message) : base(message) { } - public TestPlatformException(string message, Exception innerException) + public TestPlatformException(string? message, Exception? innerException) : base(message, innerException) { } @@ -101,6 +99,6 @@ private static Exception ConvertException(string exceptionType, string message, #endif public class ProcessExitedException : TestPlatformException { - public ProcessExitedException(string message) : base(message) { } - public ProcessExitedException(string message, Exception inner) : base(message, inner) { } + public ProcessExitedException(string? message) : base(message) { } + public ProcessExitedException(string? message, Exception? inner) : base(message, inner) { } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/ExtensionUriAttribute.cs b/src/Microsoft.TestPlatform.ObjectModel/ExtensionUriAttribute.cs index 9eccc7f6a7..6c37cce362 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/ExtensionUriAttribute.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/ExtensionUriAttribute.cs @@ -3,10 +3,6 @@ using System; -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources; - -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -24,11 +20,7 @@ public sealed class ExtensionUriAttribute : Attribute /// The Uri of the extension public ExtensionUriAttribute(string extensionUri) { - if (string.IsNullOrWhiteSpace(extensionUri)) - { - throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(extensionUri)); - } - + ValidateArg.NotNullOrWhiteSpace(extensionUri, nameof(extensionUri)); ExtensionUri = extensionUri; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/FileExtensionAttribute.cs b/src/Microsoft.TestPlatform.ObjectModel/FileExtensionAttribute.cs index ab35e652ec..d66525d7f3 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/FileExtensionAttribute.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/FileExtensionAttribute.cs @@ -3,10 +3,6 @@ using System; -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources; - -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -25,11 +21,7 @@ public sealed class FileExtensionAttribute : Attribute /// The file extensions that the test discoverer can process tests from. public FileExtensionAttribute(string fileExtension) { - if (string.IsNullOrWhiteSpace(fileExtension)) - { - throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(fileExtension)); - } - + ValidateArg.NotNullOrWhiteSpace(fileExtension, nameof(fileExtension)); FileExtension = fileExtension; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Framework.cs b/src/Microsoft.TestPlatform.ObjectModel/Framework.cs index 516bd85e9d..711511fb70 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Framework.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Framework.cs @@ -1,14 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; + #if !NETSTANDARD1_0 + using NuGet.Frameworks; using static NuGet.Frameworks.FrameworkConstants; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -16,18 +17,21 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// public class Framework { +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. | Suppressed as we know values are set private Framework() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { } /// /// Default .Net target framework. /// - public static Framework DefaultFramework { get; } #if NETFRAMEWORK - = Framework.FromString(".NETFramework,Version=v4.0"); + public static Framework DefaultFramework { get; } = Framework.FromString(".NETFramework,Version=v4.0")!; #elif !NETSTANDARD1_0 - = Framework.FromString(".NETCoreApp,Version=v1.0"); + public static Framework DefaultFramework { get; } = Framework.FromString(".NETCoreApp,Version=v1.0")!; +#else + public static Framework? DefaultFramework { get; } #endif /// @@ -45,7 +49,7 @@ private Framework() /// /// Framework name /// A framework object - public static Framework FromString(string frameworkString) + public static Framework? FromString(string? frameworkString) { #if NETSTANDARD1_0 #pragma warning disable IDE1006 // Naming Styles @@ -60,7 +64,7 @@ public static Framework FromString(string frameworkString) }; #endif - if (string.IsNullOrWhiteSpace(frameworkString)) + if (frameworkString.IsNullOrWhiteSpace()) { return null; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/FrameworkVersion.cs b/src/Microsoft.TestPlatform.ObjectModel/FrameworkVersion.cs index 4ef3450415..0b4ca6d0ac 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/FrameworkVersion.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/FrameworkVersion.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; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/FriendlyNameAttribute.cs b/src/Microsoft.TestPlatform.ObjectModel/FriendlyNameAttribute.cs index 6e08fbe2e3..a48884122c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/FriendlyNameAttribute.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/FriendlyNameAttribute.cs @@ -3,10 +3,6 @@ using System; -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources; - -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -23,11 +19,7 @@ public sealed class FriendlyNameAttribute : Attribute /// The friendly name of the Logger public FriendlyNameAttribute(string friendlyName) { - if (string.IsNullOrWhiteSpace(friendlyName)) - { - throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(friendlyName)); - } - + ValidateArg.NotNullOrWhiteSpace(friendlyName, nameof(friendlyName)); FriendlyName = friendlyName; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRunTimeProvider.cs b/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRunTimeProvider.cs index 5862cc8c6d..f02b9562f0 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRunTimeProvider.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRunTimeProvider.cs @@ -7,11 +7,8 @@ using System.Threading.Tasks; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces; - using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Host; /// @@ -41,7 +38,7 @@ public interface ITestRuntimeProvider /// /// provide logger to runtimes /// provide runsettings to runtimes for initialization - void Initialize(IMessageLogger logger, string runsettingsXml); + void Initialize(IMessageLogger? logger, string runsettingsXml); /// /// Gets a value indicating whether the test host is specific to a test source. If yes, each test source @@ -53,7 +50,7 @@ public interface ITestRuntimeProvider /// /// The . /// - bool CanExecuteCurrentRunConfiguration(string runsettingsXml); + bool CanExecuteCurrentRunConfiguration(string? runsettingsXml); /// /// Sets a custom launcher @@ -83,7 +80,7 @@ public interface ITestRuntimeProvider /// Set of environment variables for the test host process. /// Set of connection parameters for the test host process to communicate with test runner. /// ProcessStartInfo of the test host. - TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary environmentVariables, TestRunnerConnectionInfo connectionInfo); + TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo); /// /// Gets paths of any additional extensions. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRuntimeProvider2.cs b/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRuntimeProvider2.cs index 537aadd76e..b46c03ac8c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRuntimeProvider2.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Host/ITestRuntimeProvider2.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.Host; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/InvokedDataCollector.cs b/src/Microsoft.TestPlatform.ObjectModel/InvokedDataCollector.cs index 5c7dbabb3b..89d8ef2b61 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/InvokedDataCollector.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/InvokedDataCollector.cs @@ -4,8 +4,6 @@ using System; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; public sealed class InvokedDataCollector : IEquatable @@ -61,22 +59,20 @@ public InvokedDataCollector(Uri uri, string friendlyName, string assemblyQualifi /// /// InvokedDataCollector instance /// True if objects are equal - public bool Equals(InvokedDataCollector other) - { - return other is not null - && HasAttachmentProcessor == other.HasAttachmentProcessor && - Uri.AbsoluteUri == other.Uri.AbsoluteUri && - FriendlyName == other.FriendlyName && - AssemblyQualifiedName == other.AssemblyQualifiedName && - FilePath == other.FilePath; - } + public bool Equals(InvokedDataCollector? other) + => other is not null + && HasAttachmentProcessor == other.HasAttachmentProcessor + && Uri.AbsoluteUri == other.Uri.AbsoluteUri + && FriendlyName == other.FriendlyName + && AssemblyQualifiedName == other.AssemblyQualifiedName + && FilePath == other.FilePath; /// /// Compares InvokedDataCollector instances for equality. /// /// InvokedDataCollector instance /// True if objects are equal - public override bool Equals(object obj) + public override bool Equals(object? obj) => Equals(obj as InvokedDataCollector); /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/LazyPropertyValue.cs b/src/Microsoft.TestPlatform.ObjectModel/LazyPropertyValue.cs index 03d973502b..594a5f8ed9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/LazyPropertyValue.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/LazyPropertyValue.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -24,8 +22,8 @@ internal interface ILazyPropertyValue /// The type of the value to be calculated public sealed class LazyPropertyValue : ILazyPropertyValue { - private T _value; private readonly Func _getValue; + private T? _value; private bool _isValueCreated; public LazyPropertyValue(Func getValue) @@ -48,7 +46,7 @@ public T Value _isValueCreated = true; } - return _value; + return _value!; } } @@ -56,7 +54,7 @@ object ILazyPropertyValue.Value { get { - return Value; + return Value!; } } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLogger.cs b/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLogger.cs index 21b81aada8..6dceecd957 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLogger.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLogger.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.Client; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLoggerWithParams.cs b/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLoggerWithParams.cs index 7f5296d20e..94d103b37f 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLoggerWithParams.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logger/ITestLoggerWithParams.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -19,5 +17,5 @@ public interface ITestLoggerWithParameters : ITestLogger /// /// Events that can be registered for. /// Collection of parameters - void Initialize(TestLoggerEvents events, Dictionary parameters); + void Initialize(TestLoggerEvents events, Dictionary parameters); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerRunSettings.cs b/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerRunSettings.cs index 90583cc6fd..d149a93b48 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerRunSettings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerRunSettings.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerSettings.cs b/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerSettings.cs index 1f35604fb8..c4892a15d5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerSettings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logger/LoggerSettings.cs @@ -5,7 +5,7 @@ using System.Globalization; using System.Xml; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -17,7 +17,7 @@ public class LoggerSettings /// /// Gets or sets the uri. /// - public Uri Uri + public Uri? Uri { get; set; @@ -26,7 +26,7 @@ public Uri Uri /// /// Gets or sets the assembly qualified name. /// - public string AssemblyQualifiedName + public string? AssemblyQualifiedName { get; set; @@ -35,7 +35,7 @@ public string AssemblyQualifiedName /// /// Gets or sets value CodeBase of logger DLL. The syntax is same as Code Base in AssemblyName class. /// - public string CodeBase + public string? CodeBase { get; set; @@ -44,7 +44,7 @@ public string CodeBase /// /// Gets or sets the friendly name. /// - public string FriendlyName + public string? FriendlyName { get; set; @@ -63,7 +63,7 @@ public bool IsEnabled /// /// Gets or sets the configuration. /// - public XmlElement Configuration + public XmlElement? Configuration { get; set; @@ -108,9 +108,9 @@ public XmlElement ToXml(string loggerName) return root; } - private static void AppendAttribute(XmlDocument doc, XmlElement owner, string attributeName, string attributeValue) + private static void AppendAttribute(XmlDocument doc, XmlElement owner, string attributeName, string? attributeValue) { - if (string.IsNullOrWhiteSpace(attributeValue)) + if (StringUtils.IsNullOrWhiteSpace(attributeValue)) { return; } @@ -186,9 +186,9 @@ internal static LoggerSettings FromXml(XmlReader reader) } // Check for required attributes. - if (string.IsNullOrWhiteSpace(settings.FriendlyName) && - string.IsNullOrWhiteSpace(settings.Uri?.ToString()) && - string.IsNullOrWhiteSpace(settings.AssemblyQualifiedName)) + if (StringUtils.IsNullOrWhiteSpace(settings.FriendlyName) && + StringUtils.IsNullOrWhiteSpace(settings.Uri?.ToString()) && + StringUtils.IsNullOrWhiteSpace(settings.AssemblyQualifiedName)) { throw new SettingsException( string.Format( @@ -210,8 +210,10 @@ internal static LoggerSettings FromXml(XmlReader reader) // Read inner elements. while (reader.NodeType == XmlNodeType.Element) { +#pragma warning disable IDE0066 // Convert switch statement to expression switch (reader.Name.ToLowerInvariant()) { +#pragma warning restore IDE0066 // Convert switch statement to expression #if !NETSTANDARD1_0 case Constants.LoggerConfigurationNameLower: var document = new XmlDocument(); diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logger/TestLoggerEvents.cs b/src/Microsoft.TestPlatform.ObjectModel/Logger/TestLoggerEvents.cs index 07f7a6dcc6..5a71f9c9d9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logger/TestLoggerEvents.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logger/TestLoggerEvents.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; /// @@ -24,41 +22,41 @@ protected TestLoggerEvents() /// /// Raised when a test message is received. /// - public abstract event EventHandler TestRunMessage; + public abstract event EventHandler? TestRunMessage; /// /// Raised when a test run starts. /// - public abstract event EventHandler TestRunStart; + public abstract event EventHandler? TestRunStart; /// /// Raised when a test result is received. /// - public abstract event EventHandler TestResult; + public abstract event EventHandler? TestResult; /// /// Raised when a test run is complete. /// - public abstract event EventHandler TestRunComplete; + public abstract event EventHandler? TestRunComplete; /// /// Raised when test discovery starts /// - public abstract event EventHandler DiscoveryStart; + public abstract event EventHandler? DiscoveryStart; /// /// Raised when a discovery message is received. /// - public abstract event EventHandler DiscoveryMessage; + public abstract event EventHandler? DiscoveryMessage; /// /// Raised when discovered tests are received /// - public abstract event EventHandler DiscoveredTests; + public abstract event EventHandler? DiscoveredTests; /// /// Raised when test discovery is complete /// - public abstract event EventHandler DiscoveryComplete; + public abstract event EventHandler? DiscoveryComplete; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/DataCollectionMessageEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/DataCollectionMessageEventArgs.cs index 192393ea9d..7d5f032afd 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/DataCollectionMessageEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/DataCollectionMessageEventArgs.cs @@ -4,8 +4,6 @@ using System; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; /// @@ -19,14 +17,15 @@ public class DataCollectionMessageEventArgs : TestRunMessageEventArgs /// /// Level at which message should be logged. /// Text message. - public DataCollectionMessageEventArgs(TestMessageLevel level, string message) : base(level, message) + public DataCollectionMessageEventArgs(TestMessageLevel level, string message) + : base(level, message) { } /// /// Friendly name of collector /// [DataMember] - public string FriendlyName + public string? FriendlyName { get; set; @@ -37,7 +36,7 @@ public string FriendlyName /// Uri of collector. /// [DataMember] - public Uri Uri + public Uri? Uri { get; set; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestResultEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestResultEventArgs.cs index 081d9615fa..a191282c5d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestResultEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestResultEventArgs.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunMessageEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunMessageEventArgs.cs index 5caf9174d0..de2e21bb5b 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunMessageEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunMessageEventArgs.cs @@ -4,10 +4,6 @@ using System; using System.Runtime.Serialization; -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources; - -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; /// @@ -23,10 +19,7 @@ public class TestRunMessageEventArgs : EventArgs /// The message. public TestRunMessageEventArgs(TestMessageLevel level, string message) { - if (string.IsNullOrWhiteSpace(message)) - { - throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(message)); - } + ValidateArg.NotNullOrWhiteSpace(message, nameof(message)); if (level is < TestMessageLevel.Informational or > TestMessageLevel.Error) { diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunStartedEventArgs.cs b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunStartedEventArgs.cs index 0bb67cd8b5..03ff39dabf 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunStartedEventArgs.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logging/Events/TestRunStartedEventArgs.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; /// @@ -22,7 +20,5 @@ public TestRunStartedEventArgs(int processId) } public override string ToString() - { - return "ProcessId = " + ProcessId; - } + => "ProcessId = " + ProcessId; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logging/Interfaces/IMessageLogger.cs b/src/Microsoft.TestPlatform.ObjectModel/Logging/Interfaces/IMessageLogger.cs index 27a4cf4160..92a7602612 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logging/Interfaces/IMessageLogger.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logging/Interfaces/IMessageLogger.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.Logging; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Logging/TestMessageLevel.cs b/src/Microsoft.TestPlatform.ObjectModel/Logging/TestMessageLevel.cs index 90b1c665e9..c60c6595d1 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Logging/TestMessageLevel.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Logging/TestMessageLevel.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.Logging; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaNavigationData.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaNavigationData.cs index fa820eabec..e82645a884 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaNavigationData.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaNavigationData.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -12,13 +10,13 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// public class DiaNavigationData : INavigationData { - public string FileName { get; set; } + public string? FileName { get; set; } public int MinLineNumber { get; set; } public int MaxLineNumber { get; set; } - public DiaNavigationData(string fileName, int minLineNumber, int maxLineNumber) + public DiaNavigationData(string? fileName, int minLineNumber, int maxLineNumber) { FileName = fileName; MinLineNumber = minLineNumber; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs index 8ea8c96aa6..9a7a27f3a2 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -48,12 +46,12 @@ public DiaSession(string binaryPath) /// /// search path. /// - public DiaSession(string binaryPath, string searchPath) + public DiaSession(string binaryPath, string? searchPath) : this(binaryPath, searchPath, GetSymbolReader(binaryPath)) { } - internal DiaSession(string binaryPath, string searchPath, ISymbolReader symbolReader) + internal DiaSession(string binaryPath, string? searchPath, ISymbolReader symbolReader) { _symbolReader = symbolReader; ValidateArg.NotNullOrEmpty(binaryPath, nameof(binaryPath)); @@ -75,9 +73,9 @@ public void Dispose() /// The method name. /// The for that method. /// Leaving this method in place to preserve back compatibility. - public DiaNavigationData GetNavigationData(string declaringTypeName, string methodName) + public DiaNavigationData? GetNavigationData(string declaringTypeName, string methodName) { - return (DiaNavigationData)GetNavigationDataForMethod(declaringTypeName, methodName); + return (DiaNavigationData?)GetNavigationDataForMethod(declaringTypeName, methodName); } /// @@ -86,7 +84,7 @@ public DiaNavigationData GetNavigationData(string declaringTypeName, string meth /// The declaring type name. /// The method name. /// The for that method. - public INavigationData GetNavigationDataForMethod(string declaringTypeName, string methodName) + public INavigationData? GetNavigationDataForMethod(string declaringTypeName, string methodName) { ValidateArg.NotNullOrEmpty(declaringTypeName, nameof(declaringTypeName)); ValidateArg.NotNullOrEmpty(methodName, nameof(methodName)); @@ -94,23 +92,18 @@ public INavigationData GetNavigationDataForMethod(string declaringTypeName, stri return _symbolReader.GetNavigationData(declaringTypeName, methodName); } - private static ISymbolReader GetSymbolReader(string binaryPath) + private static ISymbolReader GetSymbolReader(string? binaryPath) { var pdbFilePath = Path.ChangeExtension(binaryPath, ".pdb"); // For remote scenario, also look for pdb in current directory, (esp for UWP) // The alternate search path should be an input from Adapters, but since it is not so currently adding a HACK - pdbFilePath = !File.Exists(pdbFilePath) ? Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(pdbFilePath)) : pdbFilePath; + pdbFilePath = !File.Exists(pdbFilePath) ? Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(pdbFilePath)!) : pdbFilePath; if (File.Exists(pdbFilePath)) { using var stream = new FileHelper().GetStream(pdbFilePath, FileMode.Open, FileAccess.Read); - if (PortablePdbReader.IsPortable(stream)) - { - return new PortableSymbolReader(); - } - - return new FullSymbolReader(); + return PortablePdbReader.IsPortable(stream) ? new PortableSymbolReader() : new FullSymbolReader(); } else { diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs index c45155c9d8..1d551bc62e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs @@ -3,11 +3,10 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; @@ -21,13 +20,13 @@ internal class FullSymbolReader : ISymbolReader /// private bool _isDisposed; - private IDiaDataSource _source; - private IDiaSession _session; + private IDiaDataSource? _source; + private IDiaSession? _session; /// /// Holds type symbols available in the source. /// - private Dictionary _typeSymbols = new(); + private readonly Dictionary _typeSymbols = new(); /// /// Holds method symbols for all types in the source. @@ -35,7 +34,7 @@ internal class FullSymbolReader : ISymbolReader /// Bug: Method overrides in same type are not handled (not a regression) /// ToDo(Solution): Use method token along with as identifier, this will always give unique method.The adapters would need to send this token to us to correct the behavior. /// - private Dictionary> _methodSymbols = new(); + private readonly Dictionary> _methodSymbols = new(); /// /// dispose caches @@ -58,7 +57,7 @@ public void Dispose() /// /// search path. /// - public void CacheSymbols(string binaryPath, string searchPath) + public void CacheSymbols(string binaryPath, string? searchPath) { try { @@ -87,11 +86,11 @@ public void CacheSymbols(string binaryPath, string searchPath) /// . /// Returns INavigationData which contains filename and line number. /// - public INavigationData GetNavigationData(string declaringTypeName, string methodName) + public INavigationData? GetNavigationData(string declaringTypeName, string methodName) { - INavigationData navigationData = null; - IDiaSymbol typeSymbol = GetTypeSymbol(declaringTypeName, SymTagEnum.SymTagCompiland); - IDiaSymbol methodSymbol; + INavigationData? navigationData = null; + IDiaSymbol? typeSymbol = GetTypeSymbol(declaringTypeName, SymTagEnum.SymTagCompiland); + IDiaSymbol? methodSymbol; if (typeSymbol != null) { methodSymbol = GetMethodSymbol(typeSymbol, methodName); @@ -113,7 +112,7 @@ public INavigationData GetNavigationData(string declaringTypeName, string method return navigationData; } - private bool OpenSession(string filename, string searchPath) + private bool OpenSession(string filename, string? searchPath) { try { @@ -129,7 +128,7 @@ private bool OpenSession(string filename, string searchPath) if (!Path.IsPathRooted(filename)) { filename = Path.Combine(Directory.GetCurrentDirectory(), filename); - if (string.IsNullOrEmpty(searchPath)) + if (StringUtils.IsNullOrEmpty(searchPath)) { searchPath = Directory.GetCurrentDirectory(); } @@ -169,7 +168,7 @@ private DiaNavigationData GetSymbolNavigationData(IDiaSymbol symbol) DiaNavigationData navigationData = new(null, int.MaxValue, int.MinValue); - IDiaEnumLineNumbers lines = null; + IDiaEnumLineNumbers? lines = null; try { @@ -191,18 +190,19 @@ private DiaNavigationData GetSymbolNavigationData(IDiaSymbol symbol) return navigationData; } + TPDebug.Assert(_session is not null, "_session is null"); _session.FindLinesByAddress(section, offset, (uint)length, out lines); while (true) { - lines.GetNext(1, out IDiaLineNumber lineNumber, out uint celt); + lines.GetNext(1, out IDiaLineNumber? lineNumber, out uint celt); if (celt != 1) { break; } - IDiaSourceFile sourceFile = null; + IDiaSourceFile? sourceFile = null; try { lineNumber.GetSourceFile(out sourceFile); @@ -244,10 +244,11 @@ private DiaNavigationData GetSymbolNavigationData(IDiaSymbol symbol) private void PopulateCacheForTypeAndMethodSymbols() { - IDiaEnumSymbols enumTypeSymbols = null; - IDiaSymbol global = null; + IDiaEnumSymbols? enumTypeSymbols = null; + IDiaSymbol? global = null; try { + TPDebug.Assert(_session is not null, "_session is null"); _session.GetGlobalScope(out global); global.FindChildren(SymTagEnum.SymTagCompiland, null, 0, out enumTypeSymbols); @@ -260,7 +261,7 @@ private void PopulateCacheForTypeAndMethodSymbols() typeSymbol.GetName(out var name); _typeSymbols[name] = typeSymbol; - IDiaEnumSymbols enumMethodSymbols = null; + IDiaEnumSymbols? enumMethodSymbols = null; try { Dictionary methodSymbolsForType = new(); @@ -302,13 +303,13 @@ private void PopulateCacheForTypeAndMethodSymbols() } } - private IDiaSymbol GetTypeSymbol(string typeName, SymTagEnum symTag) + private IDiaSymbol? GetTypeSymbol(string typeName, SymTagEnum symTag) { ValidateArg.NotNullOrEmpty(typeName, nameof(typeName)); - IDiaEnumSymbols enumSymbols = null; - IDiaSymbol typeSymbol = null; - IDiaSymbol global = null; + IDiaEnumSymbols? enumSymbols = null; + IDiaSymbol? typeSymbol = null; + IDiaSymbol? global = null; try { @@ -318,6 +319,7 @@ private IDiaSymbol GetTypeSymbol(string typeName, SymTagEnum symTag) return _typeSymbols[typeName]; } + TPDebug.Assert(_session is not null, "_session is null"); _session.GetGlobalScope(out global); global.FindChildren(symTag, typeName, 0, out enumSymbols); @@ -326,7 +328,7 @@ private IDiaSymbol GetTypeSymbol(string typeName, SymTagEnum symTag) #if DEBUG if (typeSymbol == null) { - IDiaEnumSymbols enumAllSymbols = null; + IDiaEnumSymbols? enumAllSymbols = null; try { global.FindChildren(symTag, null, 0, out enumAllSymbols); @@ -334,7 +336,7 @@ private IDiaSymbol GetTypeSymbol(string typeName, SymTagEnum symTag) while (true) { - enumAllSymbols.GetNext(1, out IDiaSymbol childSymbol, out uint fetchedCount); + enumAllSymbols.GetNext(1, out IDiaSymbol? childSymbol, out uint fetchedCount); if (fetchedCount == 0 || childSymbol == null) { break; @@ -345,7 +347,7 @@ private IDiaSymbol GetTypeSymbol(string typeName, SymTagEnum symTag) ReleaseComObject(ref childSymbol); } - Debug.Assert(children.Count > 0); + TPDebug.Assert(children.Count > 0); } finally { @@ -369,13 +371,13 @@ private IDiaSymbol GetTypeSymbol(string typeName, SymTagEnum symTag) return typeSymbol; } - private IDiaSymbol GetMethodSymbol(IDiaSymbol typeSymbol, string methodName) + private IDiaSymbol? GetMethodSymbol(IDiaSymbol typeSymbol, string methodName) { ValidateArg.NotNull(typeSymbol, nameof(typeSymbol)); ValidateArg.NotNullOrEmpty(methodName, nameof(methodName)); - IDiaEnumSymbols enumSymbols = null; - IDiaSymbol methodSymbol = null; + IDiaEnumSymbols? enumSymbols = null; + IDiaSymbol? methodSymbol = null; Dictionary methodSymbolsForType; try @@ -402,7 +404,7 @@ private IDiaSymbol GetMethodSymbol(IDiaSymbol typeSymbol, string methodName) #if DEBUG if (methodSymbol == null) { - IDiaEnumSymbols enumAllSymbols = null; + IDiaEnumSymbols? enumAllSymbols = null; try { typeSymbol.FindChildren(SymTagEnum.SymTagFunction, null, 0, out enumAllSymbols); @@ -410,7 +412,7 @@ private IDiaSymbol GetMethodSymbol(IDiaSymbol typeSymbol, string methodName) while (true) { - enumAllSymbols.GetNext(1, out IDiaSymbol childSymbol, out uint fetchedCount); + enumAllSymbols.GetNext(1, out IDiaSymbol? childSymbol, out uint fetchedCount); if (fetchedCount == 0 || childSymbol == null) { break; @@ -421,7 +423,7 @@ private IDiaSymbol GetMethodSymbol(IDiaSymbol typeSymbol, string methodName) ReleaseComObject(ref childSymbol); } - Debug.Assert(children.Count > 0); + TPDebug.Assert(children.Count > 0); } finally { @@ -449,13 +451,13 @@ private IDiaSymbol GetMethodSymbol(IDiaSymbol typeSymbol, string methodName) /// private static void UpdateMethodSymbolCache(string methodName, IDiaSymbol methodSymbol, Dictionary methodSymbolCache) { - Debug.Assert(!string.IsNullOrEmpty(methodName), "MethodName cannot be empty."); - Debug.Assert(methodSymbol != null, "Method symbol cannot be null."); - Debug.Assert(methodSymbolCache != null, "Method symbol cache cannot be null."); + TPDebug.Assert(!StringUtils.IsNullOrEmpty(methodName), "MethodName cannot be empty."); + TPDebug.Assert(methodSymbol != null, "Method symbol cannot be null."); + TPDebug.Assert(methodSymbolCache != null, "Method symbol cache cannot be null."); // #827589, In case a type has overloaded methods, then there could be a method already in the // cache which should be disposed. - if (methodSymbolCache.TryGetValue(methodName, out IDiaSymbol oldSymbol)) + if (methodSymbolCache.TryGetValue(methodName, out IDiaSymbol? oldSymbol)) { ReleaseComObject(ref oldSymbol); } @@ -463,7 +465,7 @@ private static void UpdateMethodSymbolCache(string methodName, IDiaSymbol method methodSymbolCache[methodName] = methodSymbol; } - private static void ReleaseComObject(ref T obj) + private static void ReleaseComObject(ref T? obj) where T : class { if (obj != null) @@ -483,7 +485,7 @@ private void Dispose(bool disposing) { foreach (IDiaSymbol methodSymbol in methodSymbolsForType.Values) { - IDiaSymbol symToRelease = methodSymbol; + IDiaSymbol? symToRelease = methodSymbol; ReleaseComObject(ref symToRelease); } @@ -491,15 +493,13 @@ private void Dispose(bool disposing) } _methodSymbols.Clear(); - _methodSymbols = null; foreach (IDiaSymbol typeSymbol in _typeSymbols.Values) { - IDiaSymbol symToRelease = typeSymbol; + IDiaSymbol? symToRelease = typeSymbol; ReleaseComObject(ref symToRelease); } _typeSymbols.Clear(); - _typeSymbols = null; ReleaseComObject(ref _session); ReleaseComObject(ref _source); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationData.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationData.cs index b239029751..564751b6a2 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationData.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationData.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.Navigation; /// @@ -13,7 +11,7 @@ public interface INavigationData /// /// Gets or sets the file name of the file containing the method being navigated. /// - string FileName { get; set; } + string? FileName { get; set; } /// /// Gets or sets the min line number of the method being navigated in the file. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationSession.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationSession.cs index 5472d70f5b..70e2f26706 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationSession.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/INavigationSession.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; /// @@ -18,5 +16,5 @@ public interface INavigationSession : IDisposable /// The declaring type name. /// The method name. /// The to get to the method. - INavigationData GetNavigationDataForMethod(string declaringTypeName, string methodName); + INavigationData? GetNavigationDataForMethod(string declaringTypeName, string methodName); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/ISymbolReader.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/ISymbolReader.cs index 41f60f8b5e..286a5baa3b 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/ISymbolReader.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/ISymbolReader.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; /// @@ -21,7 +19,7 @@ internal interface ISymbolReader : IDisposable /// /// search path. /// - void CacheSymbols(string binaryPath, string searchPath); + void CacheSymbols(string binaryPath, string? searchPath); /// /// Gets Navigation data from caches @@ -36,5 +34,5 @@ internal interface ISymbolReader : IDisposable /// . /// Returns INavigationData which contains file name and line number. /// - INavigationData GetNavigationData(string declaringTypeName, string methodName); + INavigationData? GetNavigationData(string declaringTypeName, string methodName); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs index 91898fcf29..8835fce075 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; internal static class HResult @@ -390,7 +388,7 @@ internal interface IDiaSymbol int Stub82(); [PreserveSig] - int FindChildren(SymTagEnum tag, string str, int flags, out IDiaEnumSymbols symbol); + int FindChildren(SymTagEnum tag, string? str, int flags, out IDiaEnumSymbols symbol); int Stub84(); @@ -557,7 +555,7 @@ internal static class DiaSourceObject [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hReservedNull, int dwFlags); - public static IDiaDataSource GetDiaSourceObject() + public static IDiaDataSource? GetDiaSourceObject() { var nativeDllDirectory = new ProcessHelper().GetNativeDllDirectory(); @@ -581,7 +579,7 @@ public static IDiaDataSource GetDiaSourceObject() private interface IClassFactory { void CreateInstance( - [MarshalAs(UnmanagedType.Interface)] object aggregator, + [MarshalAs(UnmanagedType.Interface)] object? aggregator, ref Guid refiid, [MarshalAs(UnmanagedType.Interface)] out object createdObject); @@ -611,7 +609,7 @@ internal interface IDiaDataSource [PreserveSig] int LoadDataForExe( [MarshalAs(UnmanagedType.LPWStr)] string executable, - [MarshalAs(UnmanagedType.LPWStr)] string searchPath, + [MarshalAs(UnmanagedType.LPWStr)] string? searchPath, IntPtr callback); int Stub5(); diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortablePdbReader.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortablePdbReader.cs index cb5801455a..7b0e8ddad9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortablePdbReader.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortablePdbReader.cs @@ -7,8 +7,6 @@ using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; /// @@ -20,19 +18,19 @@ internal class PortablePdbReader : IDisposable /// Use to get method token /// private static readonly PropertyInfo MethodInfoMethodTokenProperty = - typeof(MethodInfo).GetProperty("MetadataToken"); + typeof(MethodInfo).GetProperty("MetadataToken")!; /// /// Metadata reader provider from portable pdb stream /// To get Metadata reader /// - private MetadataReaderProvider _provider; + private readonly MetadataReaderProvider _provider; /// /// Metadata reader from portable pdb stream /// To get method debug info from method info /// - private MetadataReader _reader; + private readonly MetadataReader _reader; /// /// Initializes a new instance of the class. @@ -71,8 +69,6 @@ public PortablePdbReader(MetadataReaderProvider metadataReaderProvider) public void Dispose() { _provider?.Dispose(); - _provider = null; - _reader = null; } /// @@ -84,7 +80,7 @@ public void Dispose() /// /// The . /// - public DiaNavigationData GetDiaNavigationData(MethodInfo methodInfo) + public DiaNavigationData? GetDiaNavigationData(MethodInfo? methodInfo) { if (methodInfo == null) { @@ -118,7 +114,7 @@ internal static bool IsPortable(Stream stream) internal static MethodDebugInformationHandle GetMethodDebugInformationHandle(MethodInfo methodInfo) { - var methodToken = (int)MethodInfoMethodTokenProperty.GetValue(methodInfo); + var methodToken = (int)MethodInfoMethodTokenProperty.GetValue(methodInfo)!; var handle = ((MethodDefinitionHandle)MetadataTokens.Handle(methodToken)).ToDebugInformationHandle(); return handle; } @@ -144,14 +140,14 @@ private static void GetMethodMinAndMaxLineNumber( } } - private DiaNavigationData GetDiaNavigationData(MethodDebugInformationHandle handle) + private DiaNavigationData? GetDiaNavigationData(MethodDebugInformationHandle handle) { if (_reader == null) { throw new ObjectDisposedException(nameof(PortablePdbReader)); } - DiaNavigationData diaNavigationData = null; + DiaNavigationData? diaNavigationData = null; try { var methodDebugDefinition = _reader.GetMethodDebugInformation(handle); diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs index 2f7c437282..41b2689916 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs @@ -5,14 +5,12 @@ using System.Collections.Generic; using System.IO; using System.Reflection; -using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Navigation; /// @@ -24,8 +22,7 @@ internal class PortableSymbolReader : ISymbolReader /// Key in first dict is Type FullName /// Key in second dict is method name /// - private Dictionary> _methodsNavigationDataForType = - new(); + private readonly Dictionary> _methodsNavigationDataForType = new(); /// /// The cache symbols. @@ -36,7 +33,7 @@ internal class PortableSymbolReader : ISymbolReader /// /// The search path. /// - public void CacheSymbols(string binaryPath, string searchPath) + public void CacheSymbols(string binaryPath, string? searchPath) { PopulateCacheForTypeAndMethodSymbols(binaryPath); } @@ -52,7 +49,6 @@ public void Dispose() } _methodsNavigationDataForType.Clear(); - _methodsNavigationDataForType = null; } /// @@ -67,9 +63,9 @@ public void Dispose() /// /// The . /// - public INavigationData GetNavigationData(string declaringTypeName, string methodName) + public INavigationData? GetNavigationData(string declaringTypeName, string methodName) { - INavigationData navigationData = null; + INavigationData? navigationData = null; if (_methodsNavigationDataForType.ContainsKey(declaringTypeName)) { var methodDict = _methodsNavigationDataForType[declaringTypeName]; @@ -141,7 +137,7 @@ private void PopulateCacheForTypeAndMethodSymbols(string binaryPath) if (methodsNavigationData.Count != 0) { - _methodsNavigationDataForType[type.FullName] = methodsNavigationData; + _methodsNavigationDataForType[type.FullName!] = methodsNavigationData; } } } @@ -166,7 +162,7 @@ private static PortablePdbReader CreatePortablePdbReaderFromPEData(string binary using var dllStream = new FileStream(binaryPath, FileMode.Open, FileAccess.Read); using var peReader = new PEReader(dllStream); - var hasPdb = peReader.TryOpenAssociatedPortablePdb(binaryPath, pdbPath => new FileStream(pdbPath, FileMode.Open, FileAccess.Read), out MetadataReaderProvider mp, pdbPath: out _); + var hasPdb = peReader.TryOpenAssociatedPortablePdb(binaryPath, pdbPath => new FileStream(pdbPath, FileMode.Open, FileAccess.Read), out var mp, pdbPath: out _); // The out parameters don't give additional info about the pdbFile in case it is not found. So we have few reasons to fail: if (!hasPdb) @@ -178,6 +174,7 @@ private static PortablePdbReader CreatePortablePdbReaderFromPEData(string binary + "\n- Additionally if your dll is built with full, see FullPdbReader instead."); } + TPDebug.Assert(mp is not null, "mp is null"); return new PortablePdbReader(mp); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Shipped.txt deleted file mode 100644 index 5f282702bb..0000000000 --- a/src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Shipped.txt +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Unshipped.txt b/src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Unshipped.txt deleted file mode 100644 index 5f282702bb..0000000000 --- a/src/Microsoft.TestPlatform.ObjectModel/PublicAPI/net6.0/PublicAPI.Unshipped.txt +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/Microsoft.TestPlatform.ObjectModel/RegistryFreeActivationContext.cs b/src/Microsoft.TestPlatform.ObjectModel/RegistryFreeActivationContext.cs index 58d75fc9c2..5c9a4ece6d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/RegistryFreeActivationContext.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/RegistryFreeActivationContext.cs @@ -8,8 +8,6 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs index 19b6279053..15b05ead7c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs @@ -2,14 +2,14 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Xml; +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -32,7 +32,7 @@ public class RunConfiguration : TestRunSettings /// /// .Net framework which rocksteady should use for discovery/execution /// - private Framework _framework; + private Framework? _framework; /// /// Specifies the frequency of the runStats/discoveredTests event @@ -47,7 +47,7 @@ public class RunConfiguration : TestRunSettings /// /// Paths at which rocksteady should look for test adapters /// - private string _testAdaptersPaths; + private string? _testAdaptersPaths; /// /// Indication to adapters to disable app domain. @@ -97,7 +97,7 @@ public RunConfiguration() : base(Constants.RunConfigurationSettingsName) /// /// Gets or sets the solution directory. /// - public string SolutionDirectory + public string? SolutionDirectory { get; set; @@ -108,10 +108,7 @@ public string SolutionDirectory /// public string ResultsDirectory { - get - { - return _resultsDirectory; - } + get => _resultsDirectory; set { @@ -125,10 +122,7 @@ public string ResultsDirectory /// public int MaxCpuCount { - get - { - return _maxCpuCount; - } + get => _maxCpuCount; set { _maxCpuCount = value; @@ -141,10 +135,7 @@ public int MaxCpuCount /// public long BatchSize { - get - { - return _batchSize; - } + get => _batchSize; set { _batchSize = value; @@ -162,10 +153,7 @@ public long BatchSize /// public bool DesignMode { - get - { - return _designMode; - } + get => _designMode; set { @@ -184,10 +172,7 @@ public bool DesignMode /// public bool ShouldCollectSourceInformation { - get - { - return (CollectSourceInformationSet) ? _shouldCollectSourceInformation : _designMode; - } + get => (CollectSourceInformationSet) ? _shouldCollectSourceInformation : _designMode; set { @@ -201,10 +186,7 @@ public bool ShouldCollectSourceInformation /// public bool DisableAppDomain { - get - { - return _disableAppDomain; - } + get => _disableAppDomain; set { @@ -223,10 +205,7 @@ public bool DisableAppDomain /// public bool DisableParallelization { - get - { - return _disableParallelization; - } + get => _disableParallelization; set { @@ -240,10 +219,7 @@ public bool DisableParallelization /// public Architecture TargetPlatform { - get - { - return _platform; - } + get => _platform; set { @@ -257,10 +233,7 @@ public Architecture TargetPlatform /// public Architecture? DefaultPlatform { - get - { - return _defaultPlatform; - } + get => _defaultPlatform; set { @@ -272,12 +245,9 @@ public Architecture? DefaultPlatform /// /// Gets or sets the target Framework this run is targeting. /// - public Framework TargetFramework + public Framework? TargetFramework { - get - { - return _framework; - } + get => _framework; set { @@ -300,7 +270,7 @@ public bool TreatNoTestsAsError [Obsolete("Use TargetFramework instead")] public FrameworkVersion TargetFrameworkVersion { - get => (_framework?.Name) switch + get => _framework?.Name switch { Constants.DotNetFramework35 => FrameworkVersion.Framework35, Constants.DotNetFramework40 => FrameworkVersion.Framework40, @@ -320,17 +290,14 @@ public FrameworkVersion TargetFrameworkVersion /// /// Gets or sets the target device IP. For Phone this value is Device, for emulators "Mobile Emulator 10.0.15063.0 WVGA 4 inch 1GB" /// - public string TargetDevice { get; set; } + public string? TargetDevice { get; set; } /// /// Gets or sets the paths used for test adapters lookup in test platform. /// - public string TestAdaptersPaths + public string? TestAdaptersPaths { - get - { - return _testAdaptersPaths; - } + get => _testAdaptersPaths; set { @@ -433,6 +400,7 @@ public bool TargetFrameworkSet /// /// Gets a value indicating whether test adapters paths set. /// + [MemberNotNullWhen(true, nameof(TestAdaptersPaths))] public bool TestAdaptersPathsSet { get; @@ -451,7 +419,7 @@ public bool ResultsDirectorySet /// /// Gets the binaries root. /// - public string BinariesRoot { get; private set; } + public string? BinariesRoot { get; private set; } /// /// Collect source information @@ -461,11 +429,11 @@ public bool ResultsDirectorySet /// /// Default filter to use to filter tests /// - public string TestCaseFilter { get; private set; } + public string? TestCaseFilter { get; private set; } /// Path to dotnet executable to be used to invoke testhost.dll. Specifying this will skip looking up testhost.exe and will force usage of the testhost.dll. /// - public string DotnetHostPath { get; private set; } + public string? DotnetHostPath { get; private set; } #if !NETSTANDARD1_0 /// @@ -486,7 +454,7 @@ public override XmlElement ToXml() if (DefaultPlatform != null) { XmlElement defaultPlatform = doc.CreateElement("DefaultPlatform"); - defaultPlatform.InnerXml = DefaultPlatform.ToString(); + defaultPlatform.InnerXml = DefaultPlatform.ToString()!; root.AppendChild(defaultPlatform); } @@ -523,7 +491,7 @@ public override XmlElement ToXml() root.AppendChild(disableParallelization); XmlElement targetFrameworkVersion = doc.CreateElement("TargetFrameworkVersion"); - targetFrameworkVersion.InnerXml = TargetFramework.ToString(); + targetFrameworkVersion.InnerXml = TargetFramework?.ToString()!; root.AppendChild(targetFrameworkVersion); XmlElement executionThreadApartmentState = doc.CreateElement("ExecutionThreadApartmentState"); @@ -555,21 +523,21 @@ public override XmlElement ToXml() root.AppendChild(binariesRoot); } - if (!string.IsNullOrEmpty(TargetDevice)) + if (!StringUtils.IsNullOrEmpty(TargetDevice)) { XmlElement targetDevice = doc.CreateElement("TargetDevice"); targetDevice.InnerXml = TargetDevice; root.AppendChild(targetDevice); } - if (!string.IsNullOrEmpty(TestCaseFilter)) + if (!StringUtils.IsNullOrEmpty(TestCaseFilter)) { XmlElement testCaseFilter = doc.CreateElement(nameof(TestCaseFilter)); testCaseFilter.InnerXml = TestCaseFilter; root.AppendChild(testCaseFilter); } - if (!string.IsNullOrEmpty(DotnetHostPath)) + if (!StringUtils.IsNullOrEmpty(DotnetHostPath)) { XmlElement dotnetHostPath = doc.CreateElement(nameof(DotnetHostPath)); dotnetHostPath.InnerXml = DotnetHostPath; @@ -614,7 +582,7 @@ public static RunConfiguration FromXml(XmlReader reader) XmlRunSettingsUtilities.ThrowOnHasAttributes(reader); string resultsDir = reader.ReadElementContentAsString(); - if (string.IsNullOrEmpty(resultsDir)) + if (StringUtils.IsNullOrEmpty(resultsDir)) { throw new SettingsException( string.Format( @@ -802,7 +770,7 @@ public static RunConfiguration FromXml(XmlReader reader) case "TargetFrameworkVersion": XmlRunSettingsUtilities.ThrowOnHasAttributes(reader); - Framework frameworkType; + Framework? frameworkType; value = reader.ReadElementContentAsString(); try { @@ -874,13 +842,13 @@ public static RunConfiguration FromXml(XmlReader reader) case "SolutionDirectory": XmlRunSettingsUtilities.ThrowOnHasAttributes(reader); - string solutionDirectory = reader.ReadElementContentAsString(); + string? solutionDirectory = reader.ReadElementContentAsString(); #if !NETSTANDARD1_0 solutionDirectory = Environment.ExpandEnvironmentVariables(solutionDirectory); #endif - if (string.IsNullOrEmpty(solutionDirectory) + if (StringUtils.IsNullOrEmpty(solutionDirectory) #if !NETSTANDARD1_0 || !System.IO.Directory.Exists(solutionDirectory) #endif diff --git a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsException.cs b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsException.cs index 7a37d09ebc..31dc838ff9 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsException.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsException.cs @@ -6,8 +6,6 @@ using System.Runtime.Serialization; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -30,7 +28,7 @@ public SettingsException() : base() /// Initializes with the message. /// /// Message for the exception. - public SettingsException(string message) + public SettingsException(string? message) : base(message) { } @@ -40,7 +38,7 @@ public SettingsException(string message) /// /// Message for the exception. /// The inner exception. - public SettingsException(string message, Exception innerException) + public SettingsException(string? message, Exception? innerException) : base(message, innerException) { } diff --git a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsNameAttribute.cs b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsNameAttribute.cs index 5325acd881..fc49e6dfcd 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsNameAttribute.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/SettingsNameAttribute.cs @@ -3,10 +3,6 @@ using System; -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources; - -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -22,11 +18,7 @@ public sealed class SettingsNameAttribute : Attribute /// Name of the settings public SettingsNameAttribute(string settingsName) { - if (string.IsNullOrWhiteSpace(settingsName)) - { - throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(settingsName)); - } - + ValidateArg.NotNullOrWhiteSpace(settingsName, nameof(settingsName)); SettingsName = settingsName; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunParameters.cs b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunParameters.cs index e603975941..a23e28101d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunParameters.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunParameters.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -27,49 +25,51 @@ internal static Dictionary FromXml(XmlReader reader) { var testParameters = new Dictionary(); - if (!reader.IsEmptyElement) + if (reader.IsEmptyElement) { - XmlRunSettingsUtilities.ThrowOnHasAttributes(reader); - reader.Read(); + return testParameters; + } + + XmlRunSettingsUtilities.ThrowOnHasAttributes(reader); + reader.Read(); - while (reader.NodeType == XmlNodeType.Element) + while (reader.NodeType == XmlNodeType.Element) + { + string elementName = reader.Name; + switch (elementName) { - string elementName = reader.Name; - switch (elementName) - { - case "Parameter": - string paramName = null; - string paramValue = null; - for (int attIndex = 0; attIndex < reader.AttributeCount; attIndex++) + case "Parameter": + string? paramName = null; + string? paramValue = null; + for (int attIndex = 0; attIndex < reader.AttributeCount; attIndex++) + { + reader.MoveToAttribute(attIndex); + if (string.Equals(reader.Name, "Name", StringComparison.OrdinalIgnoreCase)) { - reader.MoveToAttribute(attIndex); - if (string.Equals(reader.Name, "Name", StringComparison.OrdinalIgnoreCase)) - { - paramName = reader.Value; - } - else if (string.Equals(reader.Name, "Value", StringComparison.OrdinalIgnoreCase)) - { - paramValue = reader.Value; - } + paramName = reader.Value; } - - if (paramName != null && paramValue != null) + else if (string.Equals(reader.Name, "Value", StringComparison.OrdinalIgnoreCase)) { - testParameters[paramName] = paramValue; + paramValue = reader.Value; } + } - break; - default: - throw new SettingsException( - string.Format( - CultureInfo.CurrentCulture, - Resources.Resources.InvalidSettingsXmlElement, - Constants.TestRunParametersName, - reader.Name)); - } + if (paramName != null && paramValue != null) + { + testParameters[paramName] = paramValue; + } - reader.Read(); + break; + default: + throw new SettingsException( + string.Format( + CultureInfo.CurrentCulture, + Resources.Resources.InvalidSettingsXmlElement, + Constants.TestRunParametersName, + reader.Name)); } + + reader.Read(); } return testParameters; diff --git a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunSettings.cs b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunSettings.cs index 36a3e5e0d1..280aeebade 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunSettings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/TestRunSettings.cs @@ -5,8 +5,6 @@ using System.Xml; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -21,7 +19,6 @@ public abstract class TestRunSettings protected TestRunSettings(string name) { ValidateArg.NotNullOrEmpty(name, nameof(name)); - Name = name; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/SourceDetail.cs b/src/Microsoft.TestPlatform.ObjectModel/SourceDetail.cs index 4270aa9518..cba8b66872 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/SourceDetail.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/SourceDetail.cs @@ -1,13 +1,11 @@ // 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; public class SourceDetail { - public string Source { get; internal set; } + public string? Source { get; internal set; } public Architecture Architecture { get; internal set; } - public Framework Framework { get; internal set; } + public Framework? Framework { get; internal set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestAdapterLoadingStrategy.cs b/src/Microsoft.TestPlatform.ObjectModel/TestAdapterLoadingStrategy.cs index b2137251e1..904b40ea10 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestAdapterLoadingStrategy.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestAdapterLoadingStrategy.cs @@ -12,20 +12,20 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; internal enum TestAdapterLoadingStrategy { /// - /// A strategy not defined, Test Platform will load adapters normally. + /// A strategy not defined, Test Platform will load adapters normally. /// Default = 0, /// - /// Test Platform will only load adapters specified by /TestAdapterPath (or RunConfiguration.TestAdaptersPaths node). - /// If a specific adapter path is provided, adapter will be loaded; if a directory path is provided adapters directly in that folder will be loaded. + /// Test Platform will only load adapters specified by /TestAdapterPath (or RunConfiguration.TestAdaptersPaths node). + /// If a specific adapter path is provided, adapter will be loaded; if a directory path is provided adapters directly in that folder will be loaded. /// If no adapter path is specified, test run will fail. /// This will imply /InIsolation switch and force the tests to be run in an isolated process. /// Explicit = 1, /// - /// Load adapters next to source. + /// Load adapters next to source. /// NextToSource = 2, diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs b/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs index 3e96a5089d..5de3ce721a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs @@ -7,10 +7,9 @@ using System.Linq; using System.Runtime.Serialization; +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -21,7 +20,7 @@ public sealed class TestCase : TestObject { private Guid _defaultId = Guid.Empty; private Guid _id; - private string _displayName; + private string? _displayName; private string _fullyQualifiedName; private string _source; @@ -29,8 +28,11 @@ public sealed class TestCase : TestObject /// Initializes a new instance of the class. /// /// This constructor doesn't perform any parameter validation, it is meant to be used for serialization."/> +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public TestCase() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { + // TODO: Make private // Default constructor for Serialization. } @@ -51,16 +53,17 @@ public TestCase(string fullyQualifiedName, Uri executorUri, string source) ValidateArg.NotNullOrEmpty(fullyQualifiedName, nameof(fullyQualifiedName)); ValidateArg.NotNullOrEmpty(source, nameof(source)); - FullyQualifiedName = fullyQualifiedName; + _fullyQualifiedName = fullyQualifiedName; ExecutorUri = executorUri ?? throw new ArgumentNullException(nameof(executorUri)); - Source = source; + _source = source; LineNumber = -1; + _defaultId = Guid.Empty; } /// /// LocalExtensionData which can be used by Adapter developers for local transfer of extended properties. /// Note that this data is available only for in-Proc execution, and may not be available for OutProc executors /// - public object LocalExtensionData { get; set; } + public object? LocalExtensionData { get; set; } /// /// Gets or sets the id of the test case. @@ -83,10 +86,7 @@ public Guid Id return _id; } - set - { - _id = value; - } + set => _id = value; } /// @@ -107,14 +107,8 @@ public string FullyQualifiedName [DataMember] public string DisplayName { - get - { - return string.IsNullOrEmpty(_displayName) ? GetFullyQualifiedName() : _displayName; - } - set - { - _displayName = value; - } + get => _displayName.IsNullOrEmpty() ? GetFullyQualifiedName() : _displayName; + set => _displayName = value; } /// @@ -132,10 +126,7 @@ public Uri ExecutorUri [DataMember] public string Source { - get - { - return _source; - } + get => _source; set { _source = value; @@ -149,7 +140,7 @@ public string Source /// Gets or sets the source code file path of the test. /// [DataMember] - public string CodeFilePath + public string? CodeFilePath { get; set; } @@ -228,7 +219,7 @@ private void SetPropertyAndResetId(TestProperty property, T value) /// Return TestProperty's value /// /// - protected override object ProtectedGetPropertyValue(TestProperty property, object defaultValue) + protected override object? ProtectedGetPropertyValue(TestProperty property, object? defaultValue) { ValidateArg.NotNull(property, nameof(property)); return property.Id switch @@ -248,7 +239,7 @@ protected override object ProtectedGetPropertyValue(TestProperty property, objec /// /// Set TestProperty's value /// - protected override void ProtectedSetPropertyValue(TestProperty property, object value) + protected override void ProtectedSetPropertyValue(TestProperty property, object? value) { ValidateArg.NotNull(property, nameof(property)); switch (property.Id) @@ -258,27 +249,27 @@ protected override void ProtectedSetPropertyValue(TestProperty property, object return; case "TestCase.DisplayName": - DisplayName = value as string; + DisplayName = (value as string)!; return; case "TestCase.ExecutorUri": - ExecutorUri = value as Uri ?? new Uri(value as string); + ExecutorUri = value as Uri ?? new Uri((value as string)!); return; case "TestCase.FullyQualifiedName": - FullyQualifiedName = value as string; + FullyQualifiedName = (value as string)!; return; case "TestCase.Id": - Id = value is Guid guid ? guid : Guid.Parse(value as string); + Id = value is Guid guid ? guid : Guid.Parse((value as string)!); return; case "TestCase.LineNumber": - LineNumber = (int)value; + LineNumber = (int)value!; return; case "TestCase.Source": - Source = value as string; + Source = (value as string)!; return; } @@ -286,18 +277,18 @@ protected override void ProtectedSetPropertyValue(TestProperty property, object base.ProtectedSetPropertyValue(property, value); } - private static readonly TestProperty ManagedTypeProperty = TestProperty.Register("TestCase.ManagedType", "ManagedType", string.Empty, string.Empty, typeof(string), o => !string.IsNullOrWhiteSpace(o as string), TestPropertyAttributes.Hidden, typeof(TestCase)); - private static readonly TestProperty ManagedMethodProperty = TestProperty.Register("TestCase.ManagedMethod", "ManagedMethod", string.Empty, string.Empty, typeof(string), o => !string.IsNullOrWhiteSpace(o as string), TestPropertyAttributes.Hidden, typeof(TestCase)); + private static readonly TestProperty ManagedTypeProperty = TestProperty.Register("TestCase.ManagedType", "ManagedType", string.Empty, string.Empty, typeof(string), o => !StringUtils.IsNullOrWhiteSpace(o as string), TestPropertyAttributes.Hidden, typeof(TestCase)); + private static readonly TestProperty ManagedMethodProperty = TestProperty.Register("TestCase.ManagedMethod", "ManagedMethod", string.Empty, string.Empty, typeof(string), o => !StringUtils.IsNullOrWhiteSpace(o as string), TestPropertyAttributes.Hidden, typeof(TestCase)); - private bool ContainsManagedMethodAndType => !string.IsNullOrWhiteSpace(ManagedMethod) && !string.IsNullOrWhiteSpace(ManagedType); + private bool ContainsManagedMethodAndType => !StringUtils.IsNullOrWhiteSpace(ManagedMethod) && !StringUtils.IsNullOrWhiteSpace(ManagedType); - private string ManagedType + private string? ManagedType { get => GetPropertyValue(ManagedTypeProperty, null); set => SetPropertyAndResetId(ManagedTypeProperty, value); } - private string ManagedMethod + private string? ManagedMethod { get => GetPropertyValue(ManagedMethodProperty, null); set => SetPropertyAndResetId(ManagedMethodProperty, value); @@ -345,32 +336,34 @@ public static class TestCaseProperties Source }; - private static bool ValidateName(object value) + private static bool ValidateName(object? value) { - return !string.IsNullOrWhiteSpace((string)value); + return !StringUtils.IsNullOrWhiteSpace((string?)value); } - private static bool ValidateDisplay(object value) + private static bool ValidateDisplay(object? value) { // only check for null and pass the rest up to UI for validation return value != null; } - private static bool ValidateExecutorUri(object value) + private static bool ValidateExecutorUri(object? value) { return value != null; } - private static bool ValidateGuid(object value) + private static bool ValidateGuid(object? value) { - try + if (value?.ToString() is not string sValue) { - _ = new Guid(value.ToString()); - return true; + return false; } - catch (ArgumentNullException) + + // TODO: Replace with TryParse? + try { - return false; + _ = new Guid(sValue); + return true; } catch (FormatException) { diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestObject.cs b/src/Microsoft.TestPlatform.ObjectModel/TestObject.cs index 26cde7689f..01ab01827d 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestObject.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestObject.cs @@ -4,12 +4,13 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -25,7 +26,7 @@ public abstract class TestObject /// /// The store for all the properties registered. /// - private readonly Dictionary _store; + private readonly Dictionary _store; /// /// Property used for Json (de)serialization of store dictionary. Serialization of dictionaries @@ -33,12 +34,9 @@ public abstract class TestObject /// other hand provides a clean Key, Value entries for TestProperty and it's value. /// [DataMember(Name = "Properties")] - private List> StoreKeyValuePairs + private List> StoreKeyValuePairs { - get - { - return _store.ToList(); - } + get => _store.ToList(); set { @@ -63,14 +61,14 @@ private List> StoreKeyValuePairs } } - public IEnumerable> GetProperties() + public IEnumerable> GetProperties() { return _store; } protected TestObject() { - _store = new Dictionary(); + _store = new Dictionary(); } [OnSerializing] @@ -84,8 +82,8 @@ public void CacheLazyValuesOnSerializing(StreamingContext context) foreach (var kvp in lazyValues) { - var lazyValue = (ILazyPropertyValue)kvp.Value; - var value = lazyValue.Value; + var lazyValue = (ILazyPropertyValue?)kvp.Value; + var value = lazyValue?.Value; _store.Remove(kvp.Key); if (value != null) @@ -108,10 +106,10 @@ public virtual IEnumerable Properties /// /// TestObject's TestProperty /// property value - public object GetPropertyValue(TestProperty property) + public object? GetPropertyValue(TestProperty property) { ValidateArg.NotNull(property, nameof(property)); - object defaultValue = null; + object? defaultValue = null; var valueType = property.GetValueType(); if (valueType != null && valueType.GetTypeInfo().IsValueType) @@ -129,7 +127,8 @@ public object GetPropertyValue(TestProperty property) /// TestObject's TestProperty /// default property value if property is not present /// property value - public T GetPropertyValue(TestProperty property, T defaultValue) + [return: NotNullIfNotNull("defaultValue")] + public T? GetPropertyValue(TestProperty property, T? defaultValue) { return GetPropertyValue(property, defaultValue, CultureInfo.InvariantCulture); } @@ -161,7 +160,7 @@ public void SetPropertyValue(TestProperty property, LazyPropertyValue valu /// /// TestObject's TestProperty /// value to be set - public void SetPropertyValue(TestProperty property, object value) + public void SetPropertyValue(TestProperty property, object? value) { ProtectedSetPropertyValue(property, value); } @@ -183,11 +182,12 @@ public void RemovePropertyValue(TestProperty property) /// Returns TestProperty's value /// /// property's value. default value is returned if the property is not present - public T GetPropertyValue(TestProperty property, T defaultValue, CultureInfo culture) + [return: NotNullIfNotNull("defaultValue")] + public T? GetPropertyValue(TestProperty property, T? defaultValue, CultureInfo culture) { ValidateArg.NotNull(property, nameof(property)); ValidateArg.NotNull(culture, nameof(culture)); - object objValue = ProtectedGetPropertyValue(property, defaultValue); + object? objValue = ProtectedGetPropertyValue(property, defaultValue); return ConvertPropertyTo(property, culture, objValue); } @@ -199,7 +199,7 @@ public void SetPropertyValue(TestProperty property, T value, CultureInfo cult { ValidateArg.NotNull(property, nameof(property)); ValidateArg.NotNull(culture, nameof(culture)); - object objValue = ConvertPropertyFrom(property, culture, value); + object? objValue = ConvertPropertyFrom(property, culture, value); ProtectedSetPropertyValue(property, objValue); } @@ -211,7 +211,7 @@ public void SetPropertyValue(TestProperty property, LazyPropertyValue valu { ValidateArg.NotNull(property, nameof(property)); ValidateArg.NotNull(culture, nameof(culture)); - object objValue = ConvertPropertyFrom(property, culture, value); + object? objValue = ConvertPropertyFrom(property, culture, value); ProtectedSetPropertyValue(property, objValue); } @@ -220,7 +220,8 @@ public void SetPropertyValue(TestProperty property, LazyPropertyValue valu /// Return TestProperty's value /// /// - protected virtual object ProtectedGetPropertyValue(TestProperty property, object defaultValue) + [return: NotNullIfNotNull("defaultValue")] + protected virtual object? ProtectedGetPropertyValue(TestProperty property, object? defaultValue) { ValidateArg.NotNull(property, nameof(property)); if (!_store.TryGetValue(property, out var value) || value == null) @@ -234,7 +235,7 @@ protected virtual object ProtectedGetPropertyValue(TestProperty property, object /// /// Set TestProperty's value /// - protected virtual void ProtectedSetPropertyValue(TestProperty property, object value) + protected virtual void ProtectedSetPropertyValue(TestProperty property, object? value) { ValidateArg.NotNull(property, nameof(property)); _store[property] = property.ValidateValueCallback == null || property.ValidateValueCallback(value) @@ -246,7 +247,7 @@ protected virtual void ProtectedSetPropertyValue(TestProperty property, object v /// Convert passed in value from TestProperty's specified value type. /// /// Converted object - private static object ConvertPropertyFrom(TestProperty property, CultureInfo culture, object value) + private static object? ConvertPropertyFrom(TestProperty property, CultureInfo culture, object? value) { ValidateArg.NotNull(property, nameof(property)); ValidateArg.NotNull(culture, nameof(culture)); @@ -263,15 +264,16 @@ private static object ConvertPropertyFrom(TestProperty property, CultureInfo // Traits are KeyValuePair based. Use the custom converter in that case. if (valueType == typeof(KeyValuePair[])) { - return KeyValueConverter.ConvertFrom(null, culture, (string)value); + return KeyValueConverter.ConvertFrom(null, culture, (string?)value); } // Use a custom string array converter for string[] types. if (valueType == typeof(string[])) { - return StringArrayConverter.ConvertFrom(null, culture, (string)value); + return StringArrayConverter.ConvertFrom(null, culture, (string?)value); } + TPDebug.Assert(valueType is not null, "valueType is null"); TypeConverter converter = TypeDescriptor.GetConverter(valueType); if (converter == null) { @@ -280,7 +282,7 @@ private static object ConvertPropertyFrom(TestProperty property, CultureInfo try { - return converter.ConvertFrom(null, culture, value); + return converter.ConvertFrom(null, culture, value!); } catch (FormatException) { @@ -297,7 +299,8 @@ private static object ConvertPropertyFrom(TestProperty property, CultureInfo /// Convert passed in value into the specified type when property is registered. /// /// Converted object - private static T ConvertPropertyTo(TestProperty property, CultureInfo culture, object value) + [return: NotNullIfNotNull("value")] + private static T? ConvertPropertyTo(TestProperty property, CultureInfo culture, object? value) { ValidateArg.NotNull(property, nameof(property)); ValidateArg.NotNull(culture, nameof(culture)); @@ -312,7 +315,7 @@ private static T ConvertPropertyTo(TestProperty property, CultureInfo culture } else if (value is LazyPropertyValue lazyValue) { - return lazyValue.Value; + return lazyValue.Value!; } var valueType = property.GetValueType(); @@ -326,7 +329,7 @@ private static T ConvertPropertyTo(TestProperty property, CultureInfo culture try { - return (T)converter.ConvertTo(null, culture, value, typeof(T)); + return (T?)converter.ConvertTo(null, culture, value, typeof(T))!; } catch (FormatException) { @@ -339,7 +342,7 @@ private static T ConvertPropertyTo(TestProperty property, CultureInfo culture } } - private TraitCollection _traits; + private TraitCollection? _traits; public TraitCollection Traits { diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestOutcome.cs b/src/Microsoft.TestPlatform.ObjectModel/TestOutcome.cs index b68c91d976..9d4e924c4c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestOutcome.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestOutcome.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; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestOutcomeHelper.cs b/src/Microsoft.TestPlatform.ObjectModel/TestOutcomeHelper.cs index 5f94335f53..680499b897 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestOutcomeHelper.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestOutcomeHelper.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -19,28 +17,15 @@ public static class TestOutcomeHelper /// The localized outcome string. public static string GetOutcomeString(TestOutcome outcome) { - string result; - switch (outcome) + string result = outcome switch { - case TestOutcome.None: - result = Resources.Resources.TestOutcomeNone; - break; - case TestOutcome.Passed: - result = Resources.Resources.TestOutcomePassed; - break; - case TestOutcome.Failed: - result = Resources.Resources.TestOutcomeFailed; - break; - case TestOutcome.Skipped: - result = Resources.Resources.TestOutcomeSkipped; - break; - case TestOutcome.NotFound: - result = Resources.Resources.TestOutcomeNotFound; - break; - default: - throw new ArgumentOutOfRangeException(nameof(outcome)); - } - + TestOutcome.None => Resources.Resources.TestOutcomeNone, + TestOutcome.Passed => Resources.Resources.TestOutcomePassed, + TestOutcome.Failed => Resources.Resources.TestOutcomeFailed, + TestOutcome.Skipped => Resources.Resources.TestOutcomeSkipped, + TestOutcome.NotFound => Resources.Resources.TestOutcomeNotFound, + _ => throw new ArgumentOutOfRangeException(nameof(outcome)), + }; return result; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProcessStartInfo.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProcessStartInfo.cs index 50e73951c6..0260e63194 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProcessStartInfo.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProcessStartInfo.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -18,30 +16,30 @@ public class TestProcessStartInfo /// The name of the test runner exe /// [DataMember] - public string FileName { get; set; } + public string? FileName { get; set; } /// /// The arguments for the test runner /// [DataMember] - public string Arguments { get; set; } + public string? Arguments { get; set; } /// /// The working directory for the test runner /// [DataMember] - public string WorkingDirectory { get; set; } + public string? WorkingDirectory { get; set; } /// /// The associated environment variables /// [DataMember] - public IDictionary EnvironmentVariables { get; set; } + public IDictionary? EnvironmentVariables { get; set; } /// /// Any additional custom properties that might be required for the launch /// For example - emulator ID, remote machine details etc. /// [DataMember] - public IDictionary CustomProperties { get; set; } + public IDictionary? CustomProperties { get; set; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs index 3098d1ef4c..b1baf611a5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs @@ -10,8 +10,6 @@ using System.Text; using System.Runtime.Serialization.Json; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// @@ -22,13 +20,13 @@ internal class CustomKeyValueConverter : TypeConverter private readonly DataContractJsonSerializer _serializer = new(typeof(TraitObject[])); /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string); } /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { return value is KeyValuePair[] keyValuePairs ? keyValuePairs @@ -36,9 +34,9 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul } /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object? value) { - // KeyValuePairs are used for traits. + // KeyValuePairs are used for traits. if (value is string data) { // PERF: The values returned here can possibly be cached, but the benefits are very small speed wise, @@ -47,7 +45,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c using var stream = new MemoryStream(Encoding.Unicode.GetBytes(data)); // Converting Json data to array of KeyValuePairs with duplicate keys. var listOfTraitObjects = _serializer.ReadObject(stream) as TraitObject[]; - return listOfTraitObjects?.Select(i => new KeyValuePair(i.Key, i.Value)).ToArray() ?? new KeyValuePair[0]; + return listOfTraitObjects?.Select(trait => new KeyValuePair(trait.Key, trait.Value)).ToArray() ?? new KeyValuePair[0]; } return null; @@ -57,9 +55,9 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c private class TraitObject { [System.Runtime.Serialization.DataMember(Name = "Key")] - public string Key { get; set; } + public string? Key { get; set; } [System.Runtime.Serialization.DataMember(Name = "Value")] - public string Value { get; set; } + public string? Value { get; set; } } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs index 2799f2a982..423d46efd4 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs @@ -8,8 +8,6 @@ using System.Runtime.Serialization.Json; using System.Text; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; internal class CustomStringArrayConverter : TypeConverter @@ -17,19 +15,19 @@ internal class CustomStringArrayConverter : TypeConverter private readonly DataContractJsonSerializer _serializer = new(typeof(string[])); /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string); } /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { return value is string[] strings ? strings : base.ConvertTo(context, culture, value, destinationType); } /// - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object? value) { // PERF: The strings returned here can possibly be cached, but the benefits are not huge speed wise, // and it is unclear how many distinct strings we get, and how much memory this would consume. I was seeing around 200ms improvement on 10k tests. diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestProperty.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestProperty.cs index e9ee329b44..fa204d0664 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestProperty.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestProperty.cs @@ -11,11 +11,9 @@ using Microsoft.VisualStudio.TestPlatform.Utilities; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; -public delegate bool ValidateValueCallback(object value); +public delegate bool ValidateValueCallback(object? value); [DataContract] public class TestProperty : IEquatable @@ -34,12 +32,14 @@ public class TestProperty : IEquatable /// /// Initializes a new instance of the class. /// +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. private TestProperty() +#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { // Default constructor for Serialization. } - private TestProperty(string id, string label, string category, string description, Type valueType, ValidateValueCallback validateValueCallback, TestPropertyAttributes attributes) + private TestProperty(string id, string label, string category, string description, Type valueType, ValidateValueCallback? validateValueCallback, TestPropertyAttributes attributes) { ValidateArg.NotNullOrEmpty(id, nameof(id)); ValidateArg.NotNull(label, nameof(label)); @@ -55,7 +55,7 @@ private TestProperty(string id, string label, string category, string descriptio else if (valueType == typeof(string) || valueType == typeof(Uri) || valueType == typeof(string[]) - || valueType.AssemblyQualifiedName.Contains("System.Private") + || valueType.AssemblyQualifiedName!.Contains("System.Private") || valueType.AssemblyQualifiedName.Contains("mscorlib")) { // This comparison is a check to ensure assembly information is not embedded in data. @@ -63,7 +63,7 @@ private TestProperty(string id, string label, string category, string descriptio // are different in desktop and coreclr. Thus AQN in coreclr includes System.Private.CoreLib which // is not available on the desktop. // Note that this doesn't handle generic types. Such types will fail during serialization. - ValueType = valueType.FullName; + ValueType = valueType.FullName!; } else if (valueType.GetTypeInfo().IsValueType) { @@ -114,7 +114,7 @@ private TestProperty(string id, string label, string category, string descriptio /// /// This property is not required at the client side. [IgnoreDataMember] - public ValidateValueCallback ValidateValueCallback { get; } + public ValidateValueCallback? ValidateValueCallback { get; } /// /// Gets or sets the attributes for this property. @@ -128,7 +128,6 @@ private TestProperty(string id, string label, string category, string descriptio [DataMember] public string ValueType { get; set; } - #region IEquatable /// @@ -138,13 +137,13 @@ public override int GetHashCode() } /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { return base.Equals(obj as TestProperty); } /// - public bool Equals(TestProperty other) + public bool Equals(TestProperty? other) { return (other != null) && (Id == other.Id); } @@ -181,7 +180,7 @@ private Type GetType(string typeName) return t; } - Type type = null; + Type? type = null; try { @@ -280,11 +279,11 @@ public static void ClearRegisteredProperties() } } - public static TestProperty Find(string id) + public static TestProperty? Find(string id) { ValidateArg.NotNull(id, nameof(id)); - TestProperty result = null; + TestProperty? result = null; lock (Properties) { @@ -317,7 +316,7 @@ public static TestProperty Register(string id, string label, Type valueType, Tes return Register(id, label, string.Empty, string.Empty, valueType, null, attributes, owner); } - public static TestProperty Register(string id, string label, string category, string description, Type valueType, ValidateValueCallback validateValueCallback, TestPropertyAttributes attributes, Type owner) + public static TestProperty Register(string id, string label, string category, string description, Type valueType, ValidateValueCallback? validateValueCallback, TestPropertyAttributes attributes, Type owner) { ValidateArg.NotNullOrEmpty(id, nameof(id)); ValidateArg.NotNull(label, nameof(label)); diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestPropertyAttributes.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestPropertyAttributes.cs index a88e8ca5db..c01aac3e74 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestPropertyAttributes.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/TestPropertyAttributes.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; [Flags] diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs b/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs index 00ae27a551..8f363e4d8a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs @@ -9,7 +9,7 @@ using System.Runtime.Serialization; using System.Text; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -57,19 +57,19 @@ public TestResult(TestCase testCase) /// Gets or sets the exception message. /// [DataMember] - public string ErrorMessage { get; set; } + public string? ErrorMessage { get; set; } /// /// Gets or sets the exception stack trace. /// [DataMember] - public string ErrorStackTrace { get; set; } + public string? ErrorStackTrace { get; set; } /// /// Gets or sets the TestResult Display name. Used for Data Driven Test (i.e. Data Driven Test. E.g. InlineData in xUnit) /// [DataMember] - public string DisplayName { get; set; } + public string? DisplayName { get; set; } /// /// Gets the test messages. @@ -81,7 +81,7 @@ public TestResult(TestCase testCase) /// Gets or sets test result ComputerName. /// [DataMember] - public string ComputerName { get; set; } + public string? ComputerName { get; set; } /// /// Gets or sets the test result Duration. @@ -132,7 +132,7 @@ public override string ToString() result.AppendFormat(CultureInfo.CurrentUICulture, Resources.Resources.TestFailureMessageFormat, ErrorMessage); // Add stack trace if we have one. - if (!string.IsNullOrWhiteSpace(ErrorStackTrace)) + if (!StringUtils.IsNullOrWhiteSpace(ErrorStackTrace)) { result.AppendLine(); result.AppendFormat( @@ -148,7 +148,7 @@ public override string ToString() StringBuilder testMessages = new(); foreach (TestResultMessage message in Messages) { - if (!string.IsNullOrEmpty(message?.Category) && !string.IsNullOrEmpty(message.Text)) + if (!StringUtils.IsNullOrEmpty(message?.Category) && !StringUtils.IsNullOrEmpty(message.Text)) { testMessages.AppendFormat( CultureInfo.CurrentUICulture, @@ -172,7 +172,7 @@ public override string ToString() /// Return TestProperty's value /// /// - protected override object ProtectedGetPropertyValue(TestProperty property, object defaultValue) + protected override object? ProtectedGetPropertyValue(TestProperty property, object? defaultValue) { ValidateArg.NotNull(property, nameof(property)); return property.Id switch @@ -192,27 +192,27 @@ protected override object ProtectedGetPropertyValue(TestProperty property, objec /// /// Set TestProperty's value /// - protected override void ProtectedSetPropertyValue(TestProperty property, object value) + protected override void ProtectedSetPropertyValue(TestProperty property, object? value) { ValidateArg.NotNull(property, nameof(property)); switch (property.Id) { case "TestResult.ComputerName": - ComputerName = (string)value; return; + ComputerName = (string?)value; return; case "TestResult.DisplayName": - DisplayName = (string)value; return; + DisplayName = (string?)value; return; case "TestResult.Duration": - Duration = (TimeSpan)value; return; + Duration = (TimeSpan)value!; return; case "TestResult.EndTime": - EndTime = (DateTimeOffset)value; return; + EndTime = (DateTimeOffset)value!; return; case "TestResult.ErrorMessage": - ErrorMessage = (string)value; return; + ErrorMessage = (string?)value; return; case "TestResult.ErrorStackTrace": - ErrorStackTrace = (string)value; return; + ErrorStackTrace = (string?)value; return; case "TestResult.Outcome": - Outcome = (TestOutcome)value; return; + Outcome = (TestOutcome)value!; return; case "TestResult.StartTime": - StartTime = (DateTimeOffset)value; return; + StartTime = (DateTimeOffset)value!; return; } base.ProtectedSetPropertyValue(property, value); } @@ -253,7 +253,7 @@ public class TestResultMessage /// /// Category of the message. /// Text of the message. - public TestResultMessage(string category, string text) + public TestResultMessage(string category, string? text) { Category = category; Text = text; @@ -273,7 +273,7 @@ public string Category /// Gets the message text /// [DataMember] - public string Text + public string? Text { get; private set; @@ -331,8 +331,8 @@ public static class TestResultProperties StartTime }; - private static bool ValidateOutcome(object value) + private static bool ValidateOutcome(object? value) { - return (TestOutcome)value is <= TestOutcome.NotFound and >= TestOutcome.None; + return value is TestOutcome testOutcome && testOutcome <= TestOutcome.NotFound && testOutcome >= TestOutcome.None; } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestServiceLocator.cs b/src/Microsoft.TestPlatform.ObjectModel/TestServiceLocator.cs index de124b766d..eb72662489 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestServiceLocator.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestServiceLocator.cs @@ -34,7 +34,7 @@ public static void Register(string name, TRegistration instance) } #if !NETSTANDARD1_0 - Resolves.Add(new Resolve(name, typeof(TRegistration).FullName, Environment.StackTrace)); + Resolves.Add(new Resolve(name, typeof(TRegistration).FullName!, Environment.StackTrace)); #endif return (TRegistration)instance; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Trait.cs b/src/Microsoft.TestPlatform.ObjectModel/Trait.cs index dafc167734..578611c814 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Trait.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Trait.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/TraitCollection.cs b/src/Microsoft.TestPlatform.ObjectModel/TraitCollection.cs index 2cb348e888..40be3a5e2a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TraitCollection.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TraitCollection.cs @@ -6,8 +6,6 @@ using System.Collections.Generic; using System.Linq; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/UapConstants.cs b/src/Microsoft.TestPlatform.ObjectModel/UapConstants.cs index 321dc164da..2c9b2e21b2 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/UapConstants.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/UapConstants.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; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyHelper.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyHelper.cs index 973c85b380..935aa04816 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyHelper.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyHelper.cs @@ -4,18 +4,16 @@ using System; using System.Collections.Generic; #if NETFRAMEWORK -using System.Diagnostics; using System.IO; #endif using System.Linq; using System.Reflection; #if NETFRAMEWORK +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; /// @@ -52,13 +50,13 @@ public static class AssemblyHelper // assemblies that have been added to the global assembly cache. setupInfo.LoaderOptimization = LoaderOptimization.MultiDomainHost; - AppDomain ad = null; + AppDomain? ad = null; try { ad = AppDomain.CreateDomain("Dependency finder domain", null, setupInfo); var assemblyLoadWorker = typeof(AssemblyLoadWorker); - AssemblyLoadWorker worker = null; + AssemblyLoadWorker? worker = null; if (assemblyLoadWorker.Assembly.GlobalAssemblyCache) { worker = (AssemblyLoadWorker)ad.CreateInstanceAndUnwrap( @@ -108,13 +106,13 @@ public static KeyValuePair GetFrameworkVersionAn var setupInfo = new AppDomainSetup(); setupInfo.ApplicationBase = sourceDirectory; setupInfo.LoaderOptimization = LoaderOptimization.MultiDomainHost; - AppDomain ad = null; + AppDomain? ad = null; try { ad = AppDomain.CreateDomain("Multiargeting settings domain", null, setupInfo); Type assemblyLoadWorker = typeof(AssemblyLoadWorker); - AssemblyLoadWorker worker = null; + AssemblyLoadWorker? worker = null; // This has to be LoadFrom, otherwise we will have to use AssemblyResolver to find self. worker = (AssemblyLoadWorker)ad.CreateInstanceFromAndUnwrap( @@ -154,9 +152,9 @@ public static KeyValuePair GetFrameworkVersionAn /// Returns null on failure and an empty array if there is no reference in the project. /// /// Full path to the assembly to get dependencies for. - public static string[] GetReferencedAssemblies(string source) + public static string[]? GetReferencedAssemblies(string source) { - Debug.Assert(!string.IsNullOrEmpty(source)); + TPDebug.Assert(!StringUtils.IsNullOrEmpty(source)); var setupInfo = new AppDomainSetup(); setupInfo.ApplicationBase = Path.GetDirectoryName(Path.GetFullPath(source)); @@ -168,13 +166,13 @@ public static string[] GetReferencedAssemblies(string source) // assemblies that have been added to the global assembly cache. setupInfo.LoaderOptimization = LoaderOptimization.MultiDomainHost; - AppDomain ad = null; + AppDomain? ad = null; try { ad = AppDomain.CreateDomain("Dependency finder domain", null, setupInfo); var assemblyLoadWorker = typeof(AssemblyLoadWorker); - AssemblyLoadWorker worker = null; + AssemblyLoadWorker? worker = null; if (assemblyLoadWorker.Assembly.GlobalAssemblyCache) { worker = (AssemblyLoadWorker)ad.CreateInstanceAndUnwrap( @@ -230,7 +228,7 @@ public static void SetAppDomainFrameworkVersionBasedOnTestSource(AppDomainSetup /// String representation of the target dot net framework e.g. .NETFramework,Version=v4.0 internal static string GetTargetFrameworkVersionString(string path) { - Debug.Assert(!string.IsNullOrEmpty(path)); + TPDebug.Assert(!StringUtils.IsNullOrEmpty(path)); var setupInfo = new AppDomainSetup(); setupInfo.ApplicationBase = Path.GetDirectoryName(Path.GetFullPath(path)); @@ -242,45 +240,45 @@ internal static string GetTargetFrameworkVersionString(string path) // assemblies that have been added to the global assembly cache. setupInfo.LoaderOptimization = LoaderOptimization.MultiDomainHost; - if (File.Exists(path)) + if (!File.Exists(path)) { - AppDomain ad = null; - try - { - ad = AppDomain.CreateDomain("Framework Version String Domain", null, setupInfo); + return string.Empty; + } - var assemblyLoadWorker = typeof(AssemblyLoadWorker); - AssemblyLoadWorker worker = null; - if (assemblyLoadWorker.Assembly.GlobalAssemblyCache) - { - worker = (AssemblyLoadWorker)ad.CreateInstanceAndUnwrap( - assemblyLoadWorker.Assembly.FullName, - assemblyLoadWorker.FullName, - false, BindingFlags.Default, null, - null, null, null); - } - else - { - // This has to be LoadFrom, otherwise we will have to use AssemblyResolver to find self. - worker = (AssemblyLoadWorker)ad.CreateInstanceFromAndUnwrap( - assemblyLoadWorker.Assembly.Location, - assemblyLoadWorker.FullName, - false, BindingFlags.Default, null, - null, null, null); - } + AppDomain? ad = null; + try + { + ad = AppDomain.CreateDomain("Framework Version String Domain", null, setupInfo); - return worker.GetTargetFrameworkVersionStringFromPath(path); + var assemblyLoadWorker = typeof(AssemblyLoadWorker); + AssemblyLoadWorker? worker = null; + if (assemblyLoadWorker.Assembly.GlobalAssemblyCache) + { + worker = (AssemblyLoadWorker)ad.CreateInstanceAndUnwrap( + assemblyLoadWorker.Assembly.FullName, + assemblyLoadWorker.FullName, + false, BindingFlags.Default, null, + null, null, null); } - finally + else { - if (ad != null) - { - AppDomain.Unload(ad); - } + // This has to be LoadFrom, otherwise we will have to use AssemblyResolver to find self. + worker = (AssemblyLoadWorker)ad.CreateInstanceFromAndUnwrap( + assemblyLoadWorker.Assembly.Location, + assemblyLoadWorker.FullName, + false, BindingFlags.Default, null, + null, null, null); } - } - return string.Empty; + return worker.GetTargetFrameworkVersionStringFromPath(path); + } + finally + { + if (ad != null) + { + AppDomain.Unload(ad); + } + } } /// @@ -307,9 +305,9 @@ internal static void SetNETFrameworkCompatiblityMode(AppDomainSetup setup, IRunC { try { - RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runContext.RunSettings.SettingsXml); + RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runContext.RunSettings?.SettingsXml); if (null != runConfiguration && (Equals(runConfiguration.TargetFramework, FrameworkVersion.Framework40) || - string.Equals(runConfiguration.TargetFramework.ToString(), Constants.DotNetFramework40, StringComparison.OrdinalIgnoreCase))) + string.Equals(runConfiguration.TargetFramework?.ToString(), Constants.DotNetFramework40, StringComparison.OrdinalIgnoreCase))) { EqtTrace.Verbose("AssemblyHelper.SetNETFrameworkCompatiblityMode: setting .NetFramework,Version=v4.0 compatibility mode."); setup.TargetFrameworkName = Constants.DotNetFramework40; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs index 8f2357d718..04ff3106ac 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs @@ -3,12 +3,11 @@ #if NETFRAMEWORK using System; -using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; @@ -77,11 +76,11 @@ internal static string GetTargetFrameworkStringFromAssembly(Assembly assembly) /// Returns null on failure and an empty array if there is no reference in the project. /// /// Path to the assembly file to load from. - public string[] GetReferencedAssemblies(string path) + public string[]? GetReferencedAssemblies(string path) { - Debug.Assert(!string.IsNullOrEmpty(path)); + TPDebug.Assert(!StringUtils.IsNullOrEmpty(path)); - Assembly a = null; + Assembly? a = null; try { // ReflectionOnlyLoadFrom does not use the probing paths and loads from the @@ -93,7 +92,7 @@ public string[] GetReferencedAssemblies(string path) { return null; } - Debug.Assert(a != null); + TPDebug.Assert(a != null); AssemblyName[] assemblies = a.GetReferencedAssemblies(); return assemblies == null || assemblies.Length == 0 @@ -115,7 +114,7 @@ public string[] GetReferencedAssemblies(string path) // Assembly a = Assembly.ReflectionOnlyLoadFrom(path); - Debug.Assert(a != null); + TPDebug.Assert(a != null); AssemblyName[] assemblies = a.GetReferencedAssemblies(); @@ -175,7 +174,7 @@ public void GetPlatformAndFrameworkSettings(string path, out string procArchType // in the loaded context. var a = Assembly.ReflectionOnlyLoadFrom(path); - Debug.Assert(a != null); + TPDebug.Assert(a != null); a.ManifestModule.GetPEKind(out var peKind, out var machine); // conversion to string type is needed for below reason @@ -210,7 +209,7 @@ public void GetPlatformAndFrameworkSettings(string path, out string procArchType } } - if (string.IsNullOrEmpty(procArchType)) + if (StringUtils.IsNullOrEmpty(procArchType)) { EqtTrace.Verbose("Unable to find the platform type for image:{0} with PEKind:{1}, Machine:{2}. Returning Default:{3}", path, peKindString, machineTypeString, "AnyCPU"); procArchType = "AnyCPU"; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/EqtHash.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/EqtHash.cs index 4ecd0ea2ed..ef595cffb5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/EqtHash.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/EqtHash.cs @@ -2,9 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Diagnostics; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; @@ -20,7 +19,7 @@ public static class EqtHash /// public static Guid GuidFromString(string data) { - Debug.Assert(data != null); + TPDebug.Assert(data != null); // Do NOT change the algorithm ever as this will have compat implications // TC-TA team has a feature in VS where workitems are associated based on TestCase Ids @@ -31,7 +30,7 @@ public static Guid GuidFromString(string data) byte[] hash = Sha1Helper.ComputeSha1(System.Text.Encoding.Unicode.GetBytes(data)); // Guid is always 16 bytes - Debug.Assert(Guid.Empty.ToByteArray().Length == 16, "Expected Guid to be 16 bytes"); + TPDebug.Assert(Guid.Empty.ToByteArray().Length == 16, "Expected Guid to be 16 bytes"); byte[] toGuid = new byte[16]; Array.Copy(hash, toGuid, 16); diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs index 7d305c0081..7056264d71 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs @@ -6,8 +6,6 @@ using System.Globalization; using System.Text; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; public static class FilterHelper diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs index 3e49eab004..0d457ae7c3 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs @@ -6,8 +6,6 @@ using System.Security.Cryptography; #endif -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; /// @@ -163,7 +161,7 @@ public byte[] ComputeHash(byte[] message) return digest; } - private void PadMessage(ref byte[] message) + private static void PadMessage(ref byte[] message) { var length = message.Length; var paddingBytes = BlockBytes - (length % BlockBytes); diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/StringUtilities.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/StringUtilities.cs index 05d3fb10cd..54983817e5 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/StringUtilities.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/StringUtilities.cs @@ -3,7 +3,7 @@ using System; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; @@ -18,10 +18,10 @@ public static class StringUtilities /// /// The input string. /// The string that is prepared for output. - public static string PrepareForOutput(string input) + public static string PrepareForOutput(string? input) { - string result = input; - if (input == null) + string? result = input; + if (result == null) { result = Resources.Resources.NullString; } @@ -36,13 +36,13 @@ public static string PrepareForOutput(string input) /// /// string to check /// True if string is null or a whitespace, false otherwise - public static bool IsNullOrWhiteSpace(string input) + public static bool IsNullOrWhiteSpace(string? input) { if (input != null) { input = input.Trim(); } - return string.IsNullOrEmpty(input); + return input.IsNullOrEmpty(); } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/SuspendCodeCoverage.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/SuspendCodeCoverage.cs index 5915237206..aa9bd91d86 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/SuspendCodeCoverage.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/SuspendCodeCoverage.cs @@ -4,8 +4,6 @@ #if NETFRAMEWORK using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; /// @@ -18,7 +16,7 @@ public class SuspendCodeCoverage : IDisposable private const string SuspendCodeCoverageEnvVarName = "__VANGUARD_SUSPEND_INSTRUMENT__"; private const string SuspendCodeCoverageEnvVarTrueValue = "TRUE"; - private readonly string _prevEnvValue; + private readonly string? _prevEnvValue; /// /// Whether the object is disposed or not. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs index b2d3a35bdb..69f1866829 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs @@ -4,8 +4,6 @@ using System.Globalization; using System.Xml; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; /// diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs index d278209ea1..6f5ef2fa57 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs @@ -7,6 +7,8 @@ using System.IO; using System.Xml; +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; + #if !NETSTANDARD1_0 using System.Xml.XPath; #endif @@ -15,8 +17,6 @@ using ObjectModelResources = Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources.Resources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; /// @@ -69,7 +69,7 @@ public static bool ContainsDataCollector(IXPathNavigable runSettingDocument, str ValidateArg.NotNull(dataCollectorUri, nameof(dataCollectorUri)); var navigator = runSettingDocument.CreateNavigator(); - var nodes = navigator.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); + var nodes = navigator!.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); foreach (XPathNavigator dataCollectorNavigator in nodes) { @@ -91,7 +91,7 @@ public static bool ContainsDataCollector(IXPathNavigable runSettingDocument, str public static IList GetDataCollectorsFriendlyName(string runsettingsXml) { var friendlyNameList = new List(); - if (!string.IsNullOrWhiteSpace(runsettingsXml)) + if (!StringUtils.IsNullOrWhiteSpace(runsettingsXml)) { using var stream = new StringReader(runsettingsXml); using var reader = XmlReader.Create(stream, ReaderSettings); @@ -99,7 +99,7 @@ public static IList GetDataCollectorsFriendlyName(string runsettingsXml) document.Load(reader); var runSettingsNavigator = document.CreateNavigator(); - var nodes = runSettingsNavigator.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); + var nodes = runSettingsNavigator!.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); foreach (XPathNavigator dataCollectorNavigator in nodes) { @@ -121,11 +121,11 @@ public static void InsertDataCollectorsNode(IXPathNavigable runSettingDocument, ValidateArg.NotNull(runSettingDocument, nameof(runSettingDocument)); ValidateArg.NotNull(settings, nameof(settings)); - var navigator = runSettingDocument.CreateNavigator(); + var navigator = runSettingDocument.CreateNavigator()!; MoveToDataCollectorsNode(ref navigator); var settingsXml = settings.ToXml(); - var dataCollectorNode = settingsXml.CreateNavigator(); + var dataCollectorNode = settingsXml.CreateNavigator()!; dataCollectorNode.MoveToRoot(); navigator.AppendChild(dataCollectorNode); @@ -137,7 +137,7 @@ public static void InsertDataCollectorsNode(IXPathNavigable runSettingDocument, /// /// The run settings. /// The RunConfiguration node as defined in the settings xml. - public static RunConfiguration GetRunConfigurationNode(string settingsXml) + public static RunConfiguration GetRunConfigurationNode(string? settingsXml) { var nodeValue = GetNodeValue(settingsXml, Constants.RunConfigurationSettingsName, RunConfiguration.FromXml); if (nodeValue == default(RunConfiguration)) @@ -155,7 +155,7 @@ public static RunConfiguration GetRunConfigurationNode(string settingsXml) /// The run settings xml. /// The test run parameters defined in the run settings. /// If there is no test run parameters section defined in the settings xml a blank dictionary is returned. - public static Dictionary GetTestRunParameters(string settingsXml) + public static Dictionary GetTestRunParameters(string? settingsXml) { var nodeValue = GetNodeValue(settingsXml, Constants.TestRunParametersName, TestRunParameters.FromXml); if (nodeValue == default(Dictionary)) @@ -205,7 +205,7 @@ public static XmlDocument CreateDefaultRunSettings() /// /// The run Settings Xml. /// True if data collection is enabled. - public static bool IsDataCollectionEnabled(string runSettingsXml) + public static bool IsDataCollectionEnabled(string? runSettingsXml) { var dataCollectionRunSettings = GetDataCollectionRunSettings(runSettingsXml); @@ -217,7 +217,7 @@ public static bool IsDataCollectionEnabled(string runSettingsXml) /// /// The run Settings Xml. /// True if data collection is enabled. - public static bool IsInProcDataCollectionEnabled(string runSettingsXml) + public static bool IsInProcDataCollectionEnabled(string? runSettingsXml) { var dataCollectionRunSettings = GetInProcDataCollectionRunSettings(runSettingsXml); @@ -229,10 +229,10 @@ public static bool IsInProcDataCollectionEnabled(string runSettingsXml) /// /// The run Settings Xml. /// The . - public static DataCollectionRunSettings GetDataCollectionRunSettings(string runSettingsXml) + public static DataCollectionRunSettings? GetDataCollectionRunSettings(string? runSettingsXml) { // use XmlReader to avoid loading of the plugins in client code (mainly from VS). - if (string.IsNullOrWhiteSpace(runSettingsXml)) + if (runSettingsXml.IsNullOrWhiteSpace()) { return null; } @@ -274,10 +274,10 @@ public static DataCollectionRunSettings GetDataCollectionRunSettings(string runS /// The run Settings Xml. /// /// Data collection run settings. - public static DataCollectionRunSettings GetInProcDataCollectionRunSettings(string runSettingsXml) + public static DataCollectionRunSettings? GetInProcDataCollectionRunSettings(string? runSettingsXml) { // use XmlReader to avoid loading of the plugins in client code (mainly from VS). - if (string.IsNullOrWhiteSpace(runSettingsXml)) + if (runSettingsXml.IsNullOrWhiteSpace()) { return null; } @@ -313,7 +313,7 @@ public static DataCollectionRunSettings GetInProcDataCollectionRunSettings(strin /// /// The run Settings Xml. /// The . - public static LoggerRunSettings GetLoggerRunSettings(string runSettings) + public static LoggerRunSettings? GetLoggerRunSettings(string? runSettings) { return GetNodeValue( runSettings, @@ -355,41 +355,43 @@ internal static void ThrowOnNoAttributes(XmlReader reader) reader.Name)); } - private static T GetNodeValue(string settingsXml, string nodeName, Func nodeParser) + private static T? GetNodeValue(string? settingsXml, string nodeName, Func nodeParser) { // use XmlReader to avoid loading of the plugins in client code (mainly from VS). - if (!string.IsNullOrWhiteSpace(settingsXml)) + if (settingsXml.IsNullOrWhiteSpace()) { - try + return default; + } + + try + { + using var stringReader = new StringReader(settingsXml); + XmlReader reader = XmlReader.Create(stringReader, ReaderSettings); + + // read to the fist child + XmlReaderUtilities.ReadToRootNode(reader); + reader.ReadToNextElement(); + + // Read till we reach nodeName element or reach EOF + while (!string.Equals(reader.Name, nodeName, StringComparison.OrdinalIgnoreCase) + && + !reader.EOF) { - using var stringReader = new StringReader(settingsXml); - XmlReader reader = XmlReader.Create(stringReader, ReaderSettings); - - // read to the fist child - XmlReaderUtilities.ReadToRootNode(reader); - reader.ReadToNextElement(); - - // Read till we reach nodeName element or reach EOF - while (!string.Equals(reader.Name, nodeName, StringComparison.OrdinalIgnoreCase) - && - !reader.EOF) - { - reader.SkipToNextElement(); - } - - if (!reader.EOF) - { - // read nodeName element. - return nodeParser(reader); - } + reader.SkipToNextElement(); } - catch (XmlException ex) + + if (!reader.EOF) { - throw new SettingsException( - string.Format(CultureInfo.CurrentCulture, "{0} {1}", Resources.CommonResources.MalformedRunSettingsFile, ex.Message), - ex); + // read nodeName element. + return nodeParser(reader); } } + catch (XmlException ex) + { + throw new SettingsException( + string.Format(CultureInfo.CurrentCulture, "{0} {1}", Resources.CommonResources.MalformedRunSettingsFile, ex.Message), + ex); + } return default; } diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/System/IProcessHelper.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/System/IProcessHelper.cs index 242a3b767d..28e99e1d99 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/System/IProcessHelper.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/System/IProcessHelper.cs @@ -22,7 +22,7 @@ public interface IProcessHelper /// Call back for on process exit /// Call back for on process output /// The process created. - object LaunchProcess(string processPath, string arguments, string workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack); + object LaunchProcess(string processPath, string? arguments, string? workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack); /// /// Gets the current process file path. diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs index 7969c3b50f..8faa2a2dce 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs @@ -23,7 +23,7 @@ bool DoNotInitialize /// /// Trace level. /// The message to add to trace. - void WriteLine(PlatformTraceLevel level, string message); + void WriteLine(PlatformTraceLevel level, string? message); /// /// Initializes the verbose tracing with custom log file diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt index b7b0acdf31..0e3aafffc6 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt @@ -8,7 +8,7 @@ Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.InitializeTrac Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.InitializeVerboseTrace(string? customLogFile) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.SetTraceLevel(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel value) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.ShouldTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool -Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.DoNotInitialize.get -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.DoNotInitialize.set -> void @@ -51,7 +51,7 @@ Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelp Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.GetProcessId(object? process) -> int Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.GetProcessName(int processId) -> string! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.GetTestEngineDirectory() -> string? -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.SetExitCallback(int processId, System.Action? callbackAction) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.TerminateProcess(object? process) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces.IProcessHelper.TryGetExitCode(object? process, out int exitCode) -> bool diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt index 0fcd69c201..0d7e7074c9 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt @@ -5,7 +5,7 @@ Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupListener(System.Diagnostics.TraceListener? listener) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupRemoteEqtTraceListeners(System.AppDomain? childDomain) -> void -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RemoteEqtTrace Microsoft.VisualStudio.TestPlatform.ObjectModel.RemoteEqtTrace.RemoteEqtTrace() -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RemoteEqtTrace.TraceLevel.get -> System.Diagnostics.TraceLevel @@ -15,7 +15,7 @@ Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Rolling Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.Dispose(bool disposing) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.~PlatformAssemblyResolver() -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int processId, System.Action? callbackAction) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessStartInfoExtensions override Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Dispose(bool disposing) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt index 0fcd69c201..0d7e7074c9 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt @@ -5,7 +5,7 @@ Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupListener(System.Diagnostics.TraceListener? listener) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupRemoteEqtTraceListeners(System.AppDomain? childDomain) -> void -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RemoteEqtTrace Microsoft.VisualStudio.TestPlatform.ObjectModel.RemoteEqtTrace.RemoteEqtTrace() -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RemoteEqtTrace.TraceLevel.get -> System.Diagnostics.TraceLevel @@ -15,7 +15,7 @@ Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Rolling Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.Dispose(bool disposing) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.~PlatformAssemblyResolver() -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int processId, System.Action? callbackAction) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessStartInfoExtensions override Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Dispose(bool disposing) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt index eca93b34d1..ba9b53b0b7 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt @@ -1,13 +1,13 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.RollingFileTraceListener(string! fileName, string! name, int rollSizeKB) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.Dispose(bool disposing) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.~PlatformAssemblyResolver() -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int processId, System.Action? callbackAction) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessStartInfoExtensions override Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Dispose(bool disposing) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt index eca93b34d1..ba9b53b0b7 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt @@ -1,13 +1,13 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.RollingFileTraceListener(string! fileName, string! name, int rollSizeKB) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.Dispose(bool disposing) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.~PlatformAssemblyResolver() -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int processId, System.Action? callbackAction) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessStartInfoExtensions override Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Dispose(bool disposing) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt index eca93b34d1..ba9b53b0b7 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt @@ -1,13 +1,13 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.RollingFileTraceListener(string! fileName, string! name, int rollSizeKB) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.Dispose(bool disposing) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.~PlatformAssemblyResolver() -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int processId, System.Action? callbackAction) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessStartInfoExtensions override Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Dispose(bool disposing) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt index 354151a095..ccdad87559 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt @@ -1,7 +1,7 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel, string? message) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState platformApartmentState, bool waitForCompletion) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.GetProcessById(int processId) -> object! -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int parentProcessId, System.Action? callbackAction) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt index 354151a095..ccdad87559 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt @@ -1,7 +1,7 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel, string? message) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState platformApartmentState, bool waitForCompletion) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.GetProcessById(int processId) -> object! -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int parentProcessId, System.Action? callbackAction) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt index eca93b34d1..ba9b53b0b7 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt @@ -1,13 +1,13 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.RollingFileTraceListener(string! fileName, string! name, int rollSizeKB) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.Dispose(bool disposing) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformAssemblyResolver.~PlatformAssemblyResolver() -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int processId, System.Action? callbackAction) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessStartInfoExtensions override Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener.Dispose(bool disposing) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt index 9a6c07b4ee..d396faaefd 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt @@ -1,9 +1,9 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string? message) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.GetProcessById(int processId) -> object! -Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string! arguments, string! workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! +Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.LaunchProcess(string! processPath, string? arguments, string? workingDirectory, System.Collections.Generic.IDictionary? envVariables, System.Action? errorCallback, System.Action? exitCallBack, System.Action? outputCallBack) -> object! Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.SetExitCallback(int parentProcessId, System.Action? callbackAction) -> void static Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.LogFile.get -> string? static Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.LogFile.set -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs index 38acfd2a33..79c69169a7 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs @@ -26,7 +26,7 @@ public partial class ProcessHelper : IProcessHelper private readonly Process _currentProcess = Process.GetCurrentProcess(); /// - public object LaunchProcess(string processPath, string arguments, string workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack) + public object LaunchProcess(string processPath, string? arguments, string? workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack) { if (!File.Exists(processPath)) { diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs index 5997cd5a6f..4a3a2a4939 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs @@ -214,10 +214,10 @@ public bool ShouldTrace(PlatformTraceLevel traceLevel) } /// - public void WriteLine(PlatformTraceLevel level, string message) + public void WriteLine(PlatformTraceLevel level, string? message) { - Debug.Assert(message != null, "message != null"); - Debug.Assert(!string.IsNullOrEmpty(ProcessName), "!string.IsNullOrEmpty(ProcessName)"); + TPDebug.Assert(message != null, "message != null"); + TPDebug.Assert(!string.IsNullOrEmpty(ProcessName), "!string.IsNullOrEmpty(ProcessName)"); if (EnsureTraceIsInitialized()) { @@ -302,7 +302,7 @@ internal static void SetupRemoteListeners(TraceListener? listener) /// The exception to log. private static void LogIgnoredException(Exception e) { - Debug.Assert(e != null, "e != null"); + TPDebug.Assert(e != null, "e != null"); try { diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/net451/Tracing/PlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/net451/Tracing/PlatformEqtTrace.cs index 34921bb73c..75f21c34db 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/net451/Tracing/PlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/net451/Tracing/PlatformEqtTrace.cs @@ -32,7 +32,7 @@ public partial class PlatformEqtTrace : IPlatformEqtTrace /// Child AppDomain. public void SetupRemoteEqtTraceListeners(AppDomain? childDomain) { - Debug.Assert(childDomain != null, "domain"); + TPDebug.Assert(childDomain != null, "domain"); if (childDomain == null) { return; diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/System/ProcessHelper.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/System/ProcessHelper.cs index 71f48e6bf8..4105394a18 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/System/ProcessHelper.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/System/ProcessHelper.cs @@ -16,7 +16,7 @@ namespace Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; public class ProcessHelper : IProcessHelper { /// - public object LaunchProcess(string processPath, string arguments, string workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack) + public object LaunchProcess(string processPath, string? arguments, string? workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack) { throw new NotImplementedException(); } diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs index 46fb0e76e6..8dd37b469f 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs @@ -29,7 +29,7 @@ public class PlatformEqtTrace : IPlatformEqtTrace public bool DoNotInitialize { get; set; } - public void WriteLine(PlatformTraceLevel traceLevel, string message) + public void WriteLine(PlatformTraceLevel traceLevel, string? message) { if (!ShouldTrace(traceLevel)) { diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/System/ProcessHelper.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/System/ProcessHelper.cs index 36d8066537..4661959451 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/System/ProcessHelper.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/System/ProcessHelper.cs @@ -17,7 +17,7 @@ namespace Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; public partial class ProcessHelper : IProcessHelper { /// - public object LaunchProcess(string processPath, string arguments, string workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack) + public object LaunchProcess(string processPath, string? arguments, string? workingDirectory, IDictionary? envVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallBack) { throw new NotImplementedException(); } diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs index 94849beceb..65f253efa3 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs @@ -43,7 +43,7 @@ public bool DoNotInitialize private static PlatformTraceLevel TraceLevel { get; set; } /// - public void WriteLine(PlatformTraceLevel level, string message) + public void WriteLine(PlatformTraceLevel level, string? message) { if (TraceInitialized() && TraceLevel > PlatformTraceLevel.Off) { diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/UnitTestEventSource.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/UnitTestEventSource.cs index 90871a160b..07cfc77aee 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/UnitTestEventSource.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/UnitTestEventSource.cs @@ -12,31 +12,31 @@ internal sealed class UnitTestEventSource : EventSource public static UnitTestEventSource Log { get; } = new UnitTestEventSource(); [Event(1, Level = EventLevel.Verbose)] - public void Verbose(string message) + public void Verbose(string? message) { WriteEvent(1, message); } [Event(2, Level = EventLevel.Informational)] - public void Info(string message) + public void Info(string? message) { WriteEvent(2, message); } [Event(3, Level = EventLevel.Warning)] - public void Warn(string message) + public void Warn(string? message) { WriteEvent(3, message); } [Event(4, Level = EventLevel.Error)] - public void Error(string message) + public void Error(string? message) { WriteEvent(4, message); } [Event(5, Level = EventLevel.Critical)] - public void Critical(string message) + public void Critical(string? message) { WriteEvent(5, message); } diff --git a/src/Microsoft.TestPlatform.TestHostProvider/BannedSymbols.txt b/src/Microsoft.TestPlatform.TestHostProvider/BannedSymbols.txt index c3370ddb45..209d2ca894 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/BannedSymbols.txt +++ b/src/Microsoft.TestPlatform.TestHostProvider/BannedSymbols.txt @@ -1,4 +1,4 @@ -M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'TPDebug.Assert' instead -M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean); Use 'TPDebug.Assert' instead +M:System.Diagnostics.TPDebug.Assert(System.Boolean,System.String); Use 'TPDebug.Assert' instead M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead diff --git a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs index 6b9a56e853..c6a008be58 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs +++ b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs @@ -156,7 +156,7 @@ public Task LaunchTestHostAsync(TestProcessStartInfo testHostStartInfo, Ca /// public virtual TestProcessStartInfo GetTestHostProcessStartInfo( IEnumerable sources, - IDictionary? environmentVariables, + IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo) { TPDebug.Assert(IsInitialized, "Initialize must have been called before GetTestHostProcessStartInfo"); @@ -203,7 +203,7 @@ public virtual TestProcessStartInfo GetTestHostProcessStartInfo( { FileName = launcherPath, Arguments = argumentsString, - EnvironmentVariables = environmentVariables ?? new Dictionary(), + EnvironmentVariables = environmentVariables ?? new Dictionary(), WorkingDirectory = processWorkingDirectory }; } @@ -312,21 +312,20 @@ public IEnumerable GetTestSources(IEnumerable sources) } /// - public bool CanExecuteCurrentRunConfiguration(string runsettingsXml) + public bool CanExecuteCurrentRunConfiguration(string? runsettingsXml) { var config = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); var framework = config.TargetFramework; // This is expected to be called once every run so returning a new instance every time. - return framework.Name.IndexOf("NETFramework", StringComparison.OrdinalIgnoreCase) >= 0; + return framework!.Name.IndexOf("NETFramework", StringComparison.OrdinalIgnoreCase) >= 0; } [MemberNotNullWhen(true, nameof(_messageLogger), nameof(_targetFramework))] private bool IsInitialized { get; set; } /// - [MemberNotNull(nameof(_messageLogger), nameof(_targetFramework))] - public void Initialize(IMessageLogger logger, string runsettingsXml) + public void Initialize(IMessageLogger? logger, string runsettingsXml) { var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); @@ -487,7 +486,7 @@ private bool LaunchHost(TestProcessStartInfo testHostStartInfo, CancellationToke EqtTrace.Verbose("DefaultTestHostManager: Starting process '{0}' with command line '{1}'", testHostStartInfo.FileName, testHostStartInfo.Arguments); cancellationToken.ThrowIfCancellationRequested(); _testHostProcess = _processHelper.LaunchProcess( - testHostStartInfo.FileName, + testHostStartInfo.FileName!, testHostStartInfo.Arguments, testHostStartInfo.WorkingDirectory, testHostStartInfo.EnvironmentVariables, diff --git a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs index 1a4f787198..f9c53dd18f 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs +++ b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs @@ -172,8 +172,7 @@ private set }; /// - [MemberNotNull(nameof(_targetFramework), nameof(_dotnetHostPath))] - public void Initialize(IMessageLogger logger, string runsettingsXml) + public void Initialize(IMessageLogger? logger, string runsettingsXml) { _hostExitedEventRaised = false; @@ -207,7 +206,7 @@ public Task LaunchTestHostAsync(TestProcessStartInfo testHostStartInfo, Ca /// public virtual TestProcessStartInfo GetTestHostProcessStartInfo( IEnumerable sources, - IDictionary? environmentVariables, + IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo) { TPDebug.Assert(_targetFramework is not null, "_targetFramework is null"); @@ -465,7 +464,7 @@ public virtual TestProcessStartInfo GetTestHostProcessStartInfo( // G:\nuget-package-path\microsoft.testplatform.testhost\version\**\testhost.dll // G:\tmp\netcore-test\bin\Debug\netcoreapp1.0\netcore-test.dll startInfo.Arguments = args; - startInfo.EnvironmentVariables = environmentVariables ?? new Dictionary(); + startInfo.EnvironmentVariables = environmentVariables ?? new Dictionary(); // If we're running using custom apphost we need to set DOTNET_ROOT/DOTNET_ROOT(x86) // We're setting it inside SDK to support private install scenario. @@ -614,7 +613,7 @@ bool IsNativeModule(string modulePath) } EqtTrace.Verbose($"DotnetTestHostmanager.LaunchTestHostAsync: Found '{vstestDotnetRootEnvName}' in env variables, value '{vstestDotnetRootEnvValue}', forwarding to '{dotnetRootEnvName}' (target framework is {_targetFramework.Name}, Version={_targetFramework.Version})."); - startInfo.EnvironmentVariables.Add(dotnetRootEnvName, vstestDotnetRootEnvValue); + startInfo.EnvironmentVariables!.Add(dotnetRootEnvName, vstestDotnetRootEnvValue); } /// @@ -639,13 +638,13 @@ public IEnumerable GetTestSources(IEnumerable sources) } /// - public bool CanExecuteCurrentRunConfiguration(string runsettingsXml) + public bool CanExecuteCurrentRunConfiguration(string? runsettingsXml) { var config = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); var framework = config.TargetFramework; // This is expected to be called once every run so returning a new instance every time. - return framework.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 + return framework!.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 || framework.Name.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) >= 0 || framework.Name.IndexOf("net5", StringComparison.OrdinalIgnoreCase) >= 0; } @@ -728,7 +727,7 @@ private bool LaunchHost(TestProcessStartInfo testHostStartInfo, CancellationToke cancellationToken.ThrowIfCancellationRequested(); _testHostProcess = _processHelper.LaunchProcess( - testHostStartInfo.FileName, + testHostStartInfo.FileName!, testHostStartInfo.Arguments, testHostStartInfo.WorkingDirectory, testHostStartInfo.EnvironmentVariables, diff --git a/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs b/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs index 4c20e33a65..fdc77923f3 100644 --- a/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs +++ b/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs @@ -164,7 +164,7 @@ public static void UpdateRunSettingsWithUserProvidedSwitches(XmlDocument runSett var shouldUpdatePlatform = true; TryGetPlatformXml(runSettingsNavigator, out var nodeXml); - if (!string.IsNullOrEmpty(nodeXml)) + if (!nodeXml.IsNullOrEmpty()) { architecture = (Architecture)Enum.Parse(typeof(Architecture), nodeXml, true); shouldUpdatePlatform = false; @@ -174,9 +174,11 @@ public static void UpdateRunSettingsWithUserProvidedSwitches(XmlDocument runSett var shouldUpdateFramework = true; TryGetFrameworkXml(runSettingsNavigator, out nodeXml); - if (!string.IsNullOrEmpty(nodeXml)) + if (!nodeXml.IsNullOrEmpty()) { - framework = Framework.FromString(nodeXml); + var fwkFromString = Framework.FromString(nodeXml); + TPDebug.Assert(fwkFromString is not null, "fwkFromString is null"); + framework = fwkFromString; shouldUpdateFramework = false; } diff --git a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/DiscoveryEventsHandleConverter.cs b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/DiscoveryEventsHandleConverter.cs index 693f8e0a08..e665c6e41c 100644 --- a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/DiscoveryEventsHandleConverter.cs +++ b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/DiscoveryEventsHandleConverter.cs @@ -42,7 +42,7 @@ public void HandleRawMessage(string rawMessage) /// /// /// - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { _testDiscoveryEventsHandler.HandleLogMessage(level, message); } diff --git a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleRequestSender.cs b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleRequestSender.cs index 7619acd83d..d63225ebb9 100644 --- a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleRequestSender.cs +++ b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleRequestSender.cs @@ -446,7 +446,7 @@ await SendMessageAndListenAndReportTestResultsAsync( var ackPayload = _dataSerializer.DeserializePayload(message); TPDebug.Assert(ackPayload is not null, "ackPayload is null"); eventsHandler?.HandleStartTestSessionComplete(ackPayload.EventArgs); - return ackPayload.EventArgs.TestSessionInfo; + return ackPayload.EventArgs!.TestSessionInfo; case MessageType.CustomTestHostLaunch: HandleCustomHostLaunch(testHostLauncher, message); @@ -527,7 +527,7 @@ await SendMessageAndListenAndReportTestResultsAsync( Sources = sources, RunSettings = runSettings, HasCustomHostLauncher = testHostLauncher != null, - IsDebuggingEnabled = (testHostLauncher != null) && testHostLauncher.IsDebug, + IsDebuggingEnabled = testHostLauncher != null && testHostLauncher.IsDebug, TestPlatformOptions = options }; @@ -546,7 +546,7 @@ await SendMessageAndListenAndReportTestResultsAsync( var ackPayload = _dataSerializer.DeserializePayload(message); TPDebug.Assert(ackPayload is not null, "ackPayload is null"); eventsHandler?.HandleStartTestSessionComplete(ackPayload.EventArgs); - return ackPayload.EventArgs.TestSessionInfo; + return ackPayload.EventArgs!.TestSessionInfo; case MessageType.CustomTestHostLaunch: HandleCustomHostLaunch(testHostLauncher, message); @@ -642,7 +642,7 @@ public bool StopTestSession( var payload = _dataSerializer.DeserializePayload(message); TPDebug.Assert(payload is not null, "payload is null"); eventsHandler?.HandleStopTestSessionComplete(payload.EventArgs); - return payload.EventArgs.IsStopped; + return payload.EventArgs!.IsStopped; case MessageType.TestMessage: var testMessagePayload = _dataSerializer.DeserializePayload(message); @@ -732,7 +732,7 @@ public async Task StopTestSessionAsync( var payload = _dataSerializer.DeserializePayload(message); TPDebug.Assert(payload is not null, "payload is null"); eventsHandler?.HandleStopTestSessionComplete(payload.EventArgs); - return payload.EventArgs.IsStopped; + return payload.EventArgs!.IsStopped; case MessageType.TestMessage: var testMessagePayload = _dataSerializer.DeserializePayload(message); @@ -1146,7 +1146,7 @@ private void SendMessageAndListenAndReportTestResults( .DeserializePayload(message); TPDebug.Assert(testRunCompletePayload is not null, "testRunCompletePayload is null"); eventHandler.HandleTestRunComplete( - testRunCompletePayload.TestRunCompleteArgs, + testRunCompletePayload.TestRunCompleteArgs!, testRunCompletePayload.LastRunTests, testRunCompletePayload.RunAttachments, testRunCompletePayload.ExecutorUris); @@ -1227,7 +1227,7 @@ private async Task SendMessageAndListenAndReportTestResultsAsync( .DeserializePayload(message); TPDebug.Assert(testRunCompletePayload is not null, "testRunCompletePayload is null"); eventHandler.HandleTestRunComplete( - testRunCompletePayload.TestRunCompleteArgs, + testRunCompletePayload.TestRunCompleteArgs!, testRunCompletePayload.LastRunTests, testRunCompletePayload.RunAttachments, testRunCompletePayload.ExecutorUris); @@ -1319,7 +1319,7 @@ private async Task SendMessageAndListenAndReportAttachmentsProcessingResultAsync TPDebug.Assert(testRunAttachmentsProcessingCompletePayload is not null, "testRunAttachmentsProcessingCompletePayload is null"); eventHandler.HandleTestRunAttachmentsProcessingComplete( - testRunAttachmentsProcessingCompletePayload.AttachmentsProcessingCompleteEventArgs, + testRunAttachmentsProcessingCompletePayload.AttachmentsProcessingCompleteEventArgs!, testRunAttachmentsProcessingCompletePayload.Attachments); isTestRunAttachmentsProcessingComplete = true; } @@ -1332,7 +1332,7 @@ private async Task SendMessageAndListenAndReportAttachmentsProcessingResultAsync TPDebug.Assert(testRunAttachmentsProcessingProgressPayload is not null, "testRunAttachmentsProcessingProgressPayload is null"); eventHandler.HandleTestRunAttachmentsProcessingProgress( - testRunAttachmentsProcessingProgressPayload.AttachmentsProcessingProgressEventArgs); + testRunAttachmentsProcessingProgressPayload.AttachmentsProcessingProgressEventArgs!); } else if (string.Equals(MessageType.TestMessage, message.MessageType)) { @@ -1400,11 +1400,10 @@ private void HandleCustomHostLaunch(ITestHostLauncher? customHostLauncher, Messa try { - var testProcessStartInfo = _dataSerializer - .DeserializePayload(message); + var testProcessStartInfo = _dataSerializer.DeserializePayload(message); ackPayload.HostProcessId = customHostLauncher != null - ? customHostLauncher.LaunchTestHost(testProcessStartInfo) + ? customHostLauncher.LaunchTestHost(testProcessStartInfo!) : -1; } catch (Exception ex) diff --git a/src/testhost.x86/DefaultEngineInvoker.cs b/src/testhost.x86/DefaultEngineInvoker.cs index fc8a797ee3..61c2201d27 100644 --- a/src/testhost.x86/DefaultEngineInvoker.cs +++ b/src/testhost.x86/DefaultEngineInvoker.cs @@ -249,7 +249,7 @@ private static TestHostConnectionInfo GetConnectionInfo(IDictionary? sources, out IDictionary sources, out IDictionary sourceToFrameworkMap, out bool conflictInFxIdentifier) + private Framework? DetermineFramework(IEnumerable sources, out IDictionary sourceToFrameworkMap, out bool conflictInFxIdentifier) { sourceToFrameworkMap = new Dictionary(); @@ -191,7 +191,7 @@ private Framework DetermineFramework(IEnumerable sources, out IDictiona } } - sourceToFrameworkMap.Add(source, Framework.FromString(fx.FullName)); + sourceToFrameworkMap.Add(source, Framework.FromString(fx.FullName)!); if (finalFx == null) { diff --git a/src/vstest.console/Internal/ConsoleLogger.cs b/src/vstest.console/Internal/ConsoleLogger.cs index 0aa1da5214..58b52de982 100644 --- a/src/vstest.console/Internal/ConsoleLogger.cs +++ b/src/vstest.console/Internal/ConsoleLogger.cs @@ -194,7 +194,7 @@ public void Initialize(TestLoggerEvents events, string testRunDirectory) // events.DiscoveredTests += DiscoveredTestsHandler; } - public void Initialize(TestLoggerEvents events, Dictionary parameters) + public void Initialize(TestLoggerEvents events, Dictionary parameters) { ValidateArg.NotNull(parameters, nameof(parameters)); diff --git a/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs b/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs index b9e0e63b0c..fa4596dfce 100644 --- a/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs +++ b/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs @@ -220,7 +220,7 @@ private void UpdateFrameworkAndPlatform(string key, string value) { if (key.Equals(FrameworkArgumentExecutor.RunSettingsPath)) { - Framework framework = Framework.FromString(value); + Framework? framework = Framework.FromString(value); if (framework != null) { _commandLineOptions.TargetFrameworkVersion = framework; diff --git a/src/vstest.console/Processors/CollectArgumentProcessor.cs b/src/vstest.console/Processors/CollectArgumentProcessor.cs index c795a2f530..167b7dd622 100644 --- a/src/vstest.console/Processors/CollectArgumentProcessor.cs +++ b/src/vstest.console/Processors/CollectArgumentProcessor.cs @@ -228,7 +228,7 @@ private static bool DoesDataCollectorSettingsExist(string friendlyName, dataCollectorSettings = null; foreach (var dataCollectorSetting in dataCollectionRunSettings.DataCollectorSettingsList) { - if (dataCollectorSetting.FriendlyName.Equals(friendlyName, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(dataCollectorSetting.FriendlyName, friendlyName, StringComparison.OrdinalIgnoreCase)) { dataCollectorSettings = dataCollectorSetting; return true; diff --git a/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs b/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs index 35774c9f20..c474d0f4bd 100644 --- a/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs @@ -242,7 +242,7 @@ private void InitializeBlame(bool enableCrashDump, bool enableHangDump, Dictiona // Add blame configuration element to blame collector. foreach (var item in dataCollectionRunSettings.DataCollectorSettingsList) { - if (item.FriendlyName.Equals(BlameFriendlyName)) + if (string.Equals(item.FriendlyName, BlameFriendlyName)) { item.Configuration = outernode; } @@ -257,20 +257,22 @@ private void InitializeBlame(bool enableCrashDump, bool enableHangDump, Dictiona /// /// Settings xml. /// Results directory. - private string? GetResultsDirectory(string? settings) + private static string? GetResultsDirectory(string? settings) { string? resultsDirectory = null; - if (settings != null) + if (settings == null) { - try - { - RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(settings); - resultsDirectory = RunSettingsUtilities.GetTestResultsDirectory(runConfiguration); - } - catch (SettingsException se) - { - EqtTrace.Error("EnableBlameArgumentProcessor: Unable to get the test results directory: Error {0}", se); - } + return resultsDirectory; + } + + try + { + RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(settings); + resultsDirectory = RunSettingsUtilities.GetTestResultsDirectory(runConfiguration); + } + catch (SettingsException se) + { + EqtTrace.Error("EnableBlameArgumentProcessor: Unable to get the test results directory: Error {0}", se); } return resultsDirectory; diff --git a/src/vstest.console/Processors/ListTestsArgumentProcessor.cs b/src/vstest.console/Processors/ListTestsArgumentProcessor.cs index 49e45f7492..bce24c3e08 100644 --- a/src/vstest.console/Processors/ListTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/ListTestsArgumentProcessor.cs @@ -210,10 +210,10 @@ public void UnregisterDiscoveryEvents(IDiscoveryRequest discoveryRequest) discoveryRequest.OnDiscoveredTests -= DiscoveryRequest_OnDiscoveredTests; } - private void DiscoveryRequest_OnDiscoveredTests(Object sender, DiscoveredTestsEventArgs args) + private void DiscoveryRequest_OnDiscoveredTests(object sender, DiscoveredTestsEventArgs args) { // List out each of the tests. - foreach (var test in args.DiscoveredTestCases) + foreach (var test in args.DiscoveredTestCases!) { _output.WriteLine(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.AvailableTestsFormat, diff --git a/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs b/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs index dfa5ba8e3b..62597c2c6a 100644 --- a/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs @@ -135,7 +135,7 @@ public void Initialize(string? argument) private void ExtractFrameworkAndPlatform() { var framworkStr = _runSettingsManager.QueryRunSettingsNode(FrameworkArgumentExecutor.RunSettingsPath); - Framework framework = Framework.FromString(framworkStr); + Framework? framework = Framework.FromString(framworkStr); if (framework != null) { _commandLineOptions.TargetFrameworkVersion = framework; diff --git a/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs b/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs index 3799927b25..5291bc7dff 100644 --- a/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs @@ -274,7 +274,7 @@ private void DiscoveryRequest_OnDiscoveredTests(object sender, DiscoveredTestsEv TPDebug.Assert(_selectedTestNames != null, "Initialize should have been called"); _discoveredTestCount += args.DiscoveredTestCases.Count(); - foreach (var testCase in args.DiscoveredTestCases) + foreach (var testCase in args.DiscoveredTestCases!) { foreach (var nameCriteria in _selectedTestNames) { diff --git a/src/vstest.console/Processors/RunTestsArgumentProcessor.cs b/src/vstest.console/Processors/RunTestsArgumentProcessor.cs index 27fe174735..555c6e98de 100644 --- a/src/vstest.console/Processors/RunTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunTestsArgumentProcessor.cs @@ -215,8 +215,8 @@ private void TestRunRequest_OnRunCompletion(object sender, TestRunCompleteEventA // we need to check if there are any tests executed - to try show some help info to user to check for installed vsix extensions if (!e.IsAborted && !e.IsCanceled) { - s_numberOfExecutedTests = e.TestRunStatistics.ExecutedTests; - var testsFoundInAnySource = e.TestRunStatistics != null && (e.TestRunStatistics.ExecutedTests > 0); + var testsFoundInAnySource = e.TestRunStatistics != null && e.TestRunStatistics.ExecutedTests > 0; + s_numberOfExecutedTests = e.TestRunStatistics!.ExecutedTests; // Indicate the user to use test adapter path command if there are no tests found if (!testsFoundInAnySource && !CommandLineOptions.Instance.TestAdapterPathsSet && _commandLineOptions.TestCaseFilterValue == null) diff --git a/src/vstest.console/Publisher/TextFileTelemetryPublisher.cs b/src/vstest.console/Publisher/TextFileTelemetryPublisher.cs index b4cea58e80..1a0da9bded 100644 --- a/src/vstest.console/Publisher/TextFileTelemetryPublisher.cs +++ b/src/vstest.console/Publisher/TextFileTelemetryPublisher.cs @@ -7,7 +7,6 @@ using System.Linq; using Microsoft.VisualStudio.TestPlatform.ObjectModel; - using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; diff --git a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs index 956da011f4..6c2728f719 100644 --- a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs +++ b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -187,7 +188,7 @@ public void DiscoverTests( Source = source, Architecture = sourceToArchitectureMap[source], Framework = sourceToFrameworkMap[source], - }).ToDictionary(k => k.Source); + }).ToDictionary(k => k.Source!); var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettings); var batchSize = runConfiguration.BatchSize; @@ -253,7 +254,7 @@ public void DiscoverTests( // Posts the discovery complete event. _metricsPublisher.Result.PublishMetrics( TelemetryDataConstants.TestDiscoveryCompleteEvent, - requestData.MetricsCollection.Metrics); + requestData.MetricsCollection.Metrics!); } } } @@ -279,7 +280,7 @@ public void RunTests( var sources = GetSources(testRunRequestPayload); if (UpdateRunSettingsIfRequired( - runsettings, + runsettings!, sources!, testRunEventsRegistrar, out string updatedRunsettings, @@ -294,7 +295,7 @@ public void RunTests( Source = source, Architecture = sourceToArchitectureMap[source!], Framework = sourceToFrameworkMap[source!], - }).ToDictionary(k => k.Source); + }).ToDictionary(k => k.Source!); if (InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings(runsettings)) { @@ -304,6 +305,7 @@ public void RunTests( runsettings)); } + TPDebug.Assert(runsettings is not null, "runSettings is null"); var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettings); var batchSize = runConfiguration.BatchSize; @@ -391,7 +393,7 @@ public void RunTests( // Post the run complete event _metricsPublisher.Result.PublishMetrics( TelemetryDataConstants.TestExecutionCompleteEvent, - requestData.MetricsCollection.Metrics); + requestData.MetricsCollection.Metrics!); } } @@ -421,7 +423,7 @@ public void ProcessTestRunAttachments( Task task = _attachmentsProcessingManager.ProcessTestRunAttachmentsAsync( attachmentsProcessingPayload.RunSettings, requestData, - attachmentsProcessingPayload.Attachments, + attachmentsProcessingPayload.Attachments!, attachmentsProcessingPayload.InvokedDataCollectors, attachmentsProcessingEventsHandler, _currentAttachmentsProcessingCancellationTokenSource.Token); @@ -441,7 +443,7 @@ public void ProcessTestRunAttachments( // Post the attachments processing complete event. _metricsPublisher.Result.PublishMetrics( TelemetryDataConstants.TestAttachmentsProcessingCompleteEvent, - requestData.MetricsCollection.Metrics); + requestData.MetricsCollection.Metrics!); } } } @@ -479,7 +481,7 @@ public void StartTestSession( Source = source, Architecture = sourceToArchitectureMap[source], Framework = sourceToFrameworkMap[source], - }).ToDictionary(k => k.Source); + }).ToDictionary(k => k.Source!); if (InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings(payload.RunSettings)) { @@ -524,7 +526,7 @@ public void StartTestSession( // Post the attachments processing complete event. _metricsPublisher.Result.PublishMetrics( TelemetryDataConstants.StartTestSessionCompleteEvent, - requestData.MetricsCollection.Metrics); + requestData.MetricsCollection.Metrics!); } } } @@ -547,7 +549,7 @@ public void StopTestSession( EqtTrace.Info("TestRequestManager.StopTestSession: Synchronization context taken."); _testPlatformEventSource.StopTestSessionStart(); - var stopped = TestSessionPool.Instance.KillSession(payload.TestSessionInfo, requestData); + var stopped = TestSessionPool.Instance.KillSession(payload.TestSessionInfo!, requestData); eventsHandler.HandleStopTestSessionComplete( new() { @@ -569,7 +571,7 @@ public void StopTestSession( // Post the attachments processing complete event. _metricsPublisher.Result.PublishMetrics( TelemetryDataConstants.StopTestSessionCompleteEvent, - requestData.MetricsCollection.Metrics); + requestData.MetricsCollection.Metrics!); } } } @@ -681,7 +683,7 @@ private bool UpdateRunSettingsIfRequired( navigator, sources!, registrar, - out Framework chosenFramework, + out Framework? chosenFramework, out sourceToFrameworkMap); settingsUpdated |= frameworkWasAutodetected; @@ -702,7 +704,7 @@ private bool UpdateRunSettingsIfRequired( // run, so we will run via .NET testhost.exe, and not via dotnet testhost.dll. Architecture defaultArchitecture = Architecture.X86; if (!disableMultiTfm - || chosenFramework.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 + || chosenFramework!.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 || chosenFramework.Name.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) >= 0 // This is a special case for 1 version of Nuget.Frameworks that was shipped with using identifier NET5 instead of NETCoreApp5 for .NET 5. || chosenFramework.Name.IndexOf("net5", StringComparison.OrdinalIgnoreCase) >= 0) @@ -767,7 +769,7 @@ private bool UpdateRunSettingsIfRequired( if (disableMultiTfm || (!disableMultiTfm && (platformSetByRunsettings || frameworkSetByRunsettings))) { CheckSourcesForCompatibility( - chosenFramework, + chosenFramework!, chosenPlatform, defaultArchitecture, sourceToArchitectureMap, @@ -793,7 +795,7 @@ private bool UpdateRunSettingsIfRequired( var keys = sourceToFrameworkMap.Keys.ToList(); foreach (var key in keys) { - sourceToFrameworkMap[key] = chosenFramework; + sourceToFrameworkMap[key] = chosenFramework!; } } @@ -1005,7 +1007,7 @@ private bool UpdateFrameworkInRunSettingsIfRequired( XPathNavigator navigator, IList? sources, IBaseTestEventsRegistrar? registrar, - out Framework commonFramework, + [NotNullWhen(true)] out Framework? commonFramework, out IDictionary sourceToFrameworkMap) { bool frameworkSetByRunsettings = IsFrameworkSetByRunSettings(navigator, out commonFramework); @@ -1042,11 +1044,11 @@ private bool UpdateFrameworkInRunSettingsIfRequired( return true; } - private static void WriteWarningForNetFramework35IsUnsupported(IBaseTestEventsRegistrar? registrar, Framework commonFramework) + private static void WriteWarningForNetFramework35IsUnsupported(IBaseTestEventsRegistrar? registrar, Framework? commonFramework) { // Raise warnings for unsupported frameworks. // TODO: Look at the sourceToFrameworkMap, and report paths to the sources that use that framework, rather than the chosen framework - if (ObjectModel.Constants.DotNetFramework35.Equals(commonFramework.Name)) + if (string.Equals(ObjectModel.Constants.DotNetFramework35, commonFramework?.Name)) { EqtTrace.Warning("TestRequestManager.UpdateRunSettingsIfRequired: throw warning on /Framework:Framework35 option."); registrar?.LogWarning(Resources.Resources.Framework35NotSupported); @@ -1173,14 +1175,13 @@ private void RunTests( /// private bool IsFrameworkSetByRunSettings( XPathNavigator navigator, - out Framework chosenFramework) + out Framework? chosenFramework) { if (_commandLineOptions.IsDesignMode) { bool isValidFrameworkXml = InferRunSettingsHelper.TryGetFrameworkXml(navigator, out var frameworkXml); - var runSettingsHaveValidFramework = isValidFrameworkXml && !frameworkXml.IsNullOrWhiteSpace(); - if (runSettingsHaveValidFramework) + if (isValidFrameworkXml && !frameworkXml.IsNullOrWhiteSpace()) { // TODO: this should just ask the runsettings to give that value so we always parse it the same way chosenFramework = Framework.FromString(frameworkXml); @@ -1250,7 +1251,7 @@ private static void CollectMetrics(IRequestData requestData, RunConfiguration ru // Collecting Target Framework. requestData.MetricsCollection.Add( TelemetryDataConstants.TargetFramework, - runConfiguration.TargetFramework.Name); + runConfiguration.TargetFramework!.Name); // Collecting Target Platform. requestData.MetricsCollection.Add( @@ -1289,7 +1290,7 @@ private static void CollectMetrics(IRequestData requestData, RunConfiguration ru // Collecting TestPlatform version. requestData.MetricsCollection.Add( TelemetryDataConstants.TestPlatformVersion, - Product.Version); + Product.Version!); // Collecting TargetOS. requestData.MetricsCollection.Add( diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs index 8195658cf7..2328fd2e84 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs @@ -287,7 +287,7 @@ public void TestSessionEndEventShouldWriteEventLogEntriesAndSendFile() var eventLogDataCollector = new EventLogDataCollector(); eventLogDataCollector.Initialize(null, _mockDataCollectionEvents.Object, _mockDataCollectionSink, _mockDataCollectionLogger.Object, _dataCollectionEnvironmentContext); var testcase = new TestCase() { Id = Guid.NewGuid() }; - _mockDataCollectionEvents.Raise(x => x.SessionStart += null, new SessionStartEventArgs(_dataCollectionEnvironmentContext.SessionDataCollectionContext, new Dictionary())); + _mockDataCollectionEvents.Raise(x => x.SessionStart += null, new SessionStartEventArgs(_dataCollectionEnvironmentContext.SessionDataCollectionContext, new Dictionary())); _mockDataCollectionEvents.Raise(x => x.SessionEnd += null, new SessionEndEventArgs(_dataCollectionEnvironmentContext.SessionDataCollectionContext)); Assert.IsTrue(_mockDataCollectionSink.IsSendFileAsyncInvoked); } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/DebugAssertTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/DebugAssertTests.cs index 7db7ead909..4d7db654f2 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/DebugAssertTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/DebugAssertTests.cs @@ -10,11 +10,11 @@ namespace Microsoft.TestPlatform.AcceptanceTests; public class DebugAssertTests : AcceptanceTestBase { [TestMethod] - // this is core only, there is nothing we can do about Debug.Assert crashing the process on framework + // this is core only, there is nothing we can do about TPDebug.Assert crashing the process on framework [NetCoreTargetFrameworkDataSource(useDesktopRunner: false)] public void RunningTestWithAFailingDebugAssertDoesNotCrashTheHostingProcess(RunnerInfo runnerInfo) { - // when debugging this test in case it starts failing, be aware that the default behavior of Debug.Assert + // when debugging this test in case it starts failing, be aware that the default behavior of TPDebug.Assert // is to not crash the process when we are running in debug, and debugger is attached SetTestEnvironment(_testEnvironment, runnerInfo); @@ -23,7 +23,7 @@ public void RunningTestWithAFailingDebugAssertDoesNotCrashTheHostingProcess(Runn InvokeVsTest(arguments); // this will have failed tests when our trace listener works and crash the testhost process when it does not - // because crashing processes is what a failed Debug.Assert does by default, unless you have a debugger attached + // because crashing processes is what a failed TPDebug.Assert does by default, unless you have a debugger attached ValidateSummaryStatus(passed: 4, failed: 4, 0); StringAssert.Contains(StdOut, "threw exception: Microsoft.VisualStudio.TestPlatform.TestHost.DebugAssertException:"); } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CodeCoverageTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CodeCoverageTests.cs index bf19a566b2..e3a2a80a3f 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CodeCoverageTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CodeCoverageTests.cs @@ -169,7 +169,7 @@ await _vstestConsoleWrapper.ProcessTestRunAttachmentsAsync( } } - Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.AttachmentsProcessingState]); + Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics![TelemetryDataConstants.AttachmentsProcessingState]); Assert.AreEqual(2L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsSentForProcessing]); Assert.AreEqual(1L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsAfterProcessing]); Assert.IsTrue(_testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics.ContainsKey(TelemetryDataConstants.TimeTakenInSecForAttachmentsProcessing)); @@ -278,7 +278,7 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingModuleDuplicate } } - Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.AttachmentsProcessingState]); + Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics![TelemetryDataConstants.AttachmentsProcessingState]); Assert.AreEqual(3L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsSentForProcessing]); Assert.AreEqual(1L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsAfterProcessing]); Assert.IsTrue(_testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics.ContainsKey(TelemetryDataConstants.TimeTakenInSecForAttachmentsProcessing)); @@ -335,7 +335,7 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingSameReportForma } } - Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.AttachmentsProcessingState]); + Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics![TelemetryDataConstants.AttachmentsProcessingState]); Assert.AreEqual(2L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsSentForProcessing]); Assert.AreEqual(1L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsAfterProcessing]); Assert.IsTrue(_testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics.ContainsKey(TelemetryDataConstants.TimeTakenInSecForAttachmentsProcessing)); @@ -398,7 +398,7 @@ public async Task TestRunWithCodeCoverageAndAttachmentsProcessingDifferentReport } } - Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.AttachmentsProcessingState]); + Assert.AreEqual("Completed", _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics![TelemetryDataConstants.AttachmentsProcessingState]); Assert.AreEqual(4L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsSentForProcessing]); Assert.AreEqual(1L, _testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics[TelemetryDataConstants.NumberOfAttachmentsAfterProcessing]); Assert.IsTrue(_testRunAttachmentsProcessingEventHandler.CompleteArgs.Metrics.ContainsKey(TelemetryDataConstants.TimeTakenInSecForAttachmentsProcessing)); diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CustomTestHostTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CustomTestHostTests.cs index d711ef7964..a05cfda9b5 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CustomTestHostTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/CustomTestHostTests.cs @@ -226,8 +226,8 @@ public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo) public int LaunchTestHost(TestProcessStartInfo defaultTestHostStartInfo, CancellationToken cancellationToken) { var processInfo = new ProcessStartInfo( - defaultTestHostStartInfo.FileName, - defaultTestHostStartInfo.Arguments) + defaultTestHostStartInfo.FileName!, + defaultTestHostStartInfo.Arguments!) { WorkingDirectory = defaultTestHostStartInfo.WorkingDirectory }; diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/DiscoveryEventHandler.cs b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/DiscoveryEventHandler.cs index 2423e8ae25..0c3936c0b6 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/DiscoveryEventHandler.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/DiscoveryEventHandler.cs @@ -24,7 +24,7 @@ public DiscoveryEventHandler() DiscoveredTestCases = new List(); } - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { if (discoveredTestCases != null) { @@ -32,7 +32,7 @@ public void HandleDiscoveredTests(IEnumerable discoveredTestCases) } } - public void HandleDiscoveryComplete(long totalTests, IEnumerable lastChunk, bool isAborted) + public void HandleDiscoveryComplete(long totalTests, IEnumerable? lastChunk, bool isAborted) { if (lastChunk != null) { @@ -40,7 +40,7 @@ public void HandleDiscoveryComplete(long totalTests, IEnumerable lastC } } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { // No Op } @@ -54,9 +54,9 @@ public void HandleRawMessage(string rawMessage) public struct TestMessage { public TestMessageLevel TestMessageLevel; - public string Message; + public string? Message; - public TestMessage(TestMessageLevel testMessageLevel, string message) + public TestMessage(TestMessageLevel testMessageLevel, string? message) { TestMessageLevel = testMessageLevel; Message = message; @@ -94,12 +94,12 @@ public void HandleRawMessage(string rawMessage) // No Op } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { TestMessages.Add(new TestMessage(level, message)); } - public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable lastChunk) + public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable? lastChunk) { if (lastChunk != null) { @@ -113,7 +113,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete SkippedDiscoveredSources = discoveryCompleteEventArgs.SkippedDiscoveredSources; } - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { if (discoveredTestCases != null) { @@ -145,7 +145,7 @@ public void HandleRawMessage(string rawMessage) // No Op } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { if (level == TestMessageLevel.Error) { @@ -153,7 +153,7 @@ public void HandleLogMessage(TestMessageLevel level, string message) }; } - public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable lastChunk) + public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable? lastChunk) { if (lastChunk != null) { @@ -161,7 +161,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete } } - public void HandleDiscoveryComplete(long totalTests, IEnumerable lastChunk, bool isAborted) + public void HandleDiscoveryComplete(long totalTests, IEnumerable? lastChunk, bool isAborted) { if (lastChunk != null) { @@ -169,7 +169,7 @@ public void HandleDiscoveryComplete(long totalTests, IEnumerable lastC } } - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { if (discoveredTestCases != null && discoveredTestCases.Any()) { diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/RunEventHandler.cs b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/RunEventHandler.cs index c23a89f294..f61c3e9d94 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/RunEventHandler.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/RunEventHandler.cs @@ -39,7 +39,7 @@ public class RunEventHandler : ITestRunEventsHandler /// public string? LogMessage { get; private set; } - public List Errors { get; set; } + public List Errors { get; set; } /// /// Gets the test message level. @@ -49,7 +49,7 @@ public class RunEventHandler : ITestRunEventsHandler public RunEventHandler() { TestResults = new List(); - Errors = new List(); + Errors = new List(); Attachments = new List(); InvokedDataCollectors = new List(); } @@ -62,7 +62,7 @@ public void EnsureSuccess() } } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { LogMessage = message; TestMessageLevel = level; @@ -74,9 +74,9 @@ public void HandleLogMessage(TestMessageLevel level, string message) public void HandleTestRunComplete( TestRunCompleteEventArgs testRunCompleteArgs, - TestRunChangedEventArgs lastChunkArgs, - ICollection runContextAttachments, - ICollection executorUris) + TestRunChangedEventArgs? lastChunkArgs, + ICollection? runContextAttachments, + ICollection? executorUris) { if (lastChunkArgs != null && lastChunkArgs.NewTestResults != null) { @@ -96,7 +96,7 @@ public void HandleTestRunComplete( Metrics = testRunCompleteArgs.Metrics; } - public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) + public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs) { if (testRunChangedArgs != null && testRunChangedArgs.NewTestResults != null) { diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/TestRunAttachmentsProcessingEventHandler.cs b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/TestRunAttachmentsProcessingEventHandler.cs index bb5fe8e374..ca3b598f8d 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/TestRunAttachmentsProcessingEventHandler.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/TranslationLayerTests/EventHandler/TestRunAttachmentsProcessingEventHandler.cs @@ -25,7 +25,7 @@ public class TestRunAttachmentsProcessingEventHandler : ITestRunAttachmentsProce /// public string? LogMessage { get; private set; } - public List Errors { get; set; } + public List Errors { get; set; } /// /// Gets the test message level. @@ -34,7 +34,7 @@ public class TestRunAttachmentsProcessingEventHandler : ITestRunAttachmentsProce public TestRunAttachmentsProcessingEventHandler() { - Errors = new List(); + Errors = new(); Attachments = new List(); ProgressArgs = new List(); } @@ -47,7 +47,7 @@ public void EnsureSuccess() } } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { LogMessage = message; TestMessageLevel = level; @@ -82,7 +82,7 @@ public void HandleTestRunAttachmentsProcessingComplete(ICollection lastChunk) + public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable? lastChunk) { if (lastChunk != null) { diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/FindMethodExtensions.cs b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/FindMethodExtensions.cs index aee24c0d47..d20d4f2ef0 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/FindMethodExtensions.cs +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/FindMethodExtensions.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Reflection; @@ -51,7 +50,7 @@ internal static IMethodSymbol FindMethod( candidates = candidates.Where(m => m.Parameters.Select(p => p.Type).SequenceEqual(methodParameterTypes)); } - Debug.Assert(candidates.Any() && !candidates.Skip(1).Any()); + TPDebug.Assert(candidates.Any() && !candidates.Skip(1).Any()); return candidates.Single(); } @@ -82,7 +81,7 @@ internal static IMethodSymbol FindMethod( candidates = candidates.Where(selector); - Debug.Assert(candidates.Any() && !candidates.Skip(1).Any()); + TPDebug.Assert(candidates.Any() && !candidates.Skip(1).Any()); return candidates.Single(); } diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/Microsoft.TestPlatform.AdapterUtilities.UnitTests.csproj b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/Microsoft.TestPlatform.AdapterUtilities.UnitTests.csproj index d69a372fc5..544d949dc6 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/Microsoft.TestPlatform.AdapterUtilities.UnitTests.csproj +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/Microsoft.TestPlatform.AdapterUtilities.UnitTests.csproj @@ -31,5 +31,16 @@ + + + NullableHelpers.cs + TextTemplatingFileGenerator + + + + + + + diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs index 9e62fcbffd..ebd79426ab 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/DesignMode/DesignModeClientTests.cs @@ -541,7 +541,7 @@ public void DesignModeClientConnectShouldReturnNullSessionWhenStartTestSessionTh .Callback((string _, object actualPayload) => { _completeEvent.Set(); - Assert.IsNull(((StartTestSessionAckPayload)actualPayload).EventArgs.TestSessionInfo); + Assert.IsNull(((StartTestSessionAckPayload)actualPayload).EventArgs!.TestSessionInfo); }); _mockCommunicationManager.Setup( cm => cm.DeserializePayload( @@ -592,8 +592,8 @@ public void DesignModeClientConnectShouldReturnFalseWhenStopTestSessionThrows() { _completeEvent.Set(); - Assert.AreEqual(((StopTestSessionAckPayload)actualPayload).EventArgs.TestSessionInfo, testSessionInfo); - Assert.IsFalse(((StopTestSessionAckPayload)actualPayload).EventArgs.IsStopped); + Assert.AreEqual(((StopTestSessionAckPayload)actualPayload).EventArgs!.TestSessionInfo, testSessionInfo); + Assert.IsFalse(((StopTestSessionAckPayload)actualPayload).EventArgs!.IsStopped); }); _mockCommunicationManager.Setup( diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs index 7af18fc64f..3e39370534 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs @@ -263,9 +263,9 @@ public void HandleTestRunStatsChangeShouldInvokeListenersWithTestRunChangedEvent Assert.IsNotNull(receivedArgs); Assert.AreEqual(testRunChangedEventArgs.TestRunStatistics, receivedArgs.TestRunStatistics); CollectionAssert.AreEqual( - testRunChangedEventArgs.NewTestResults.ToList(), - receivedArgs.NewTestResults.ToList()); - CollectionAssert.AreEqual(testRunChangedEventArgs.ActiveTests.ToList(), receivedArgs.ActiveTests.ToList()); + testRunChangedEventArgs.NewTestResults!.ToList(), + receivedArgs.NewTestResults!.ToList()); + CollectionAssert.AreEqual(testRunChangedEventArgs.ActiveTests!.ToList(), receivedArgs.ActiveTests!.ToList()); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs index 4821050ff3..0608e0fd99 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginDiscovererTests.cs @@ -183,12 +183,12 @@ public void Cancel() throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } @@ -202,12 +202,12 @@ public void Cancel() throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } @@ -221,12 +221,12 @@ public void Cancel() throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } @@ -301,11 +301,11 @@ public void Load(XmlReader reader) public class InvalidDataCollector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } } @@ -325,11 +325,11 @@ public class ADataCollectorInheritingFromAnotherDataCollector : InvalidDataColle public class ValidDataCollector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs index d057f27cac..dc97e8fc40 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginManagerTests.cs @@ -139,12 +139,12 @@ public void DiscoverTests(IEnumerable sources, IDiscoveryContext discove throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs index d7e4575f31..e6831cf97b 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/RunSettingsProviderExtensionsTests.cs @@ -66,7 +66,7 @@ public void AddDefaultRunSettingsShouldSetDefaultSettingsForEmptySettings() var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings!.SettingsXml); Assert.AreEqual(runConfiguration.ResultsDirectory, Constants.DefaultResultsDirectory); - Assert.AreEqual(runConfiguration.TargetFramework.ToString(), Framework.DefaultFramework.ToString()); + Assert.AreEqual(runConfiguration.TargetFramework!.ToString(), Framework.DefaultFramework.ToString()); Assert.AreEqual(runConfiguration.TargetPlatform, Constants.DefaultPlatform); } @@ -85,7 +85,7 @@ public void AddDefaultRunSettingsShouldAddUnspecifiedSettings() var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(_runSettingsProvider.ActiveRunSettings!.SettingsXml); Assert.AreEqual(runConfiguration.ResultsDirectory, Constants.DefaultResultsDirectory); - Assert.AreEqual(runConfiguration.TargetFramework.ToString(), Framework.DefaultFramework.ToString()); + Assert.AreEqual(runConfiguration.TargetFramework!.ToString(), Framework.DefaultFramework.ToString()); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostProviderManagerTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostProviderManagerTests.cs index 9904266e30..8648d497c6 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostProviderManagerTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Hosting/TestHostProviderManagerTests.cs @@ -160,17 +160,17 @@ private class CustomTestHost : ITestRuntimeProvider public bool Shared { get; private set; } - public bool CanExecuteCurrentRunConfiguration(string runsettingsXml) + public bool CanExecuteCurrentRunConfiguration(string? runsettingsXml) { var config = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); var framework = config.TargetFramework; Shared = !config.DisableAppDomain; // This is expected to be called once every run so returning a new instance every time. - return framework.Name.IndexOf("netframework", StringComparison.OrdinalIgnoreCase) >= 0; + return framework!.Name.IndexOf("netframework", StringComparison.OrdinalIgnoreCase) >= 0; } - public TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary environmentVariables, TestRunnerConnectionInfo connectionInfo) + public TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo) { throw new NotImplementedException(); } @@ -185,7 +185,7 @@ public IEnumerable GetTestSources(IEnumerable sources) return sources; } - public void Initialize(IMessageLogger logger, string runsettingsXml) + public void Initialize(IMessageLogger? logger, string runsettingsXml) { var config = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); Shared = !config.DisableAppDomain; @@ -232,18 +232,18 @@ private class TestableTestHostManager : ITestRuntimeProvider public bool Shared { get; private set; } - public bool CanExecuteCurrentRunConfiguration(string runsettingsXml) + public bool CanExecuteCurrentRunConfiguration(string? runsettingsXml) { var config = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); var framework = config.TargetFramework; Shared = !config.DisableAppDomain; // This is expected to be called once every run so returning a new instance every time. - return framework.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 + return framework!.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 || framework.Name.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) >= 0; } - public TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary environmentVariables, TestRunnerConnectionInfo connectionInfo) + public TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo) { throw new NotImplementedException(); } @@ -253,7 +253,7 @@ public IEnumerable GetTestPlatformExtensions(IEnumerable sources throw new NotImplementedException(); } - public void Initialize(IMessageLogger logger, string runsettingsXml) + public void Initialize(IMessageLogger? logger, string runsettingsXml) { var config = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); Shared = !config.DisableAppDomain; diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs index 0d94e142a1..a3b2a51f8f 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs @@ -56,7 +56,7 @@ public void FakesDataCollectorSettingsShouldBeOverridden() IsEnabled = true, Configuration = doc.FirstChild as XmlElement }; - XmlRunSettingsUtilities.InsertDataCollectorsNode(doc.CreateNavigator(), dataCollectorNode); + XmlRunSettingsUtilities.InsertDataCollectorsNode(doc.CreateNavigator()!, dataCollectorNode); var dataCollectorNode2 = new DataCollectorSettings() { diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs index 854314992f..75e7afbefb 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs @@ -352,8 +352,8 @@ public void ProcessRequestShouldCallSessionStartWithCorrectTestSources() _requestHandler.ProcessRequests(); _mockDataCollectionManager.Verify(x => x.SessionStarted(It.Is( - y => y.GetPropertyValue>("TestSources").Contains("test1.dll") && - y.GetPropertyValue>("TestSources").Contains("test2.dll")))); + y => y.GetPropertyValue>("TestSources")!.Contains("test1.dll") && + y.GetPropertyValue>("TestSources")!.Contains("test2.dll")))); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs index 810012e9fb..bd581840d7 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs @@ -39,7 +39,7 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachments() var displayName = "CustomDataCollector"; var attachment = new AttachmentSet(datacollectorUri, displayName); attachment.Attachments.Add(new UriDataAttachment(attachmentUri, "filename.txt")); - var invokedDataCollector = new InvokedDataCollector(datacollectorUri, displayName, typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false); + var invokedDataCollector = new InvokedDataCollector(datacollectorUri, displayName, typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false); _mockDataSerializer.Setup(x => x.DeserializePayload(It.IsAny())).Returns( new AfterTestRunEndResult(new Collection() { attachment }, new Collection() { invokedDataCollector }, new Dictionary())); _mockCommunicationManager.Setup(x => x.ReceiveMessage()).Returns(new Message() { MessageType = MessageType.AfterTestRunEndResult, Payload = null }); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs index 77cb64f2fd..70a7a7cf80 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/Serialization/TestObjectConverterTests.cs @@ -99,7 +99,7 @@ public void TestObjectShouldDeserializeNullValueForProperty() var properties = test.Properties.ToArray(); Assert.AreEqual(1, properties.Length); - Assert.IsTrue(string.IsNullOrEmpty(test.GetPropertyValue(properties[0]).ToString())); + Assert.IsTrue(string.IsNullOrEmpty(test.GetPropertyValue(properties[0])!.ToString())); } [TestMethod] @@ -111,7 +111,7 @@ public void TestObjectShouldDeserializeStringArrayValueForProperty() var properties = test.Properties.ToArray(); Assert.AreEqual(1, properties.Length); - CollectionAssert.AreEqual(new[] { "val1", "val2" }, (string[])test.GetPropertyValue(properties[0])); + CollectionAssert.AreEqual(new[] { "val1", "val2" }, (string[])test.GetPropertyValue(properties[0])!); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs index 1e044b0f48..caeab456e1 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs @@ -200,11 +200,11 @@ public void DataCollectorAttachmentProcessorAppDomain_ShouldReportFailureDuringE public class AppDomainSampleDataCollector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } @@ -257,11 +257,11 @@ public async Task> ProcessAttachmentSetsAsync(XmlElem public class AppDomainSampleDataCollectorFailure : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs index 05253660c9..3dd8696dd5 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs @@ -44,9 +44,9 @@ public void Create_ShouldReturnListOfAttachmentProcessors() // arrange List invokedDataCollectors = new() { - new InvokedDataCollector(new Uri("datacollector://Sample"), "Sample", typeof(SampleDataCollector).AssemblyQualifiedName, typeof(SampleDataCollector).Assembly.Location, true), - new InvokedDataCollector(new Uri("datacollector://SampleData2"), "SampleData2", typeof(SampleData2Collector).AssemblyQualifiedName, typeof(SampleData2Collector).Assembly.Location, true), - new InvokedDataCollector(new Uri("datacollector://SampleData3"), "SampleData3", typeof(SampleData3Collector).AssemblyQualifiedName, typeof(SampleData3Collector).Assembly.Location, true) + new InvokedDataCollector(new Uri("datacollector://Sample"), "Sample", typeof(SampleDataCollector).AssemblyQualifiedName!, typeof(SampleDataCollector).Assembly.Location, true), + new InvokedDataCollector(new Uri("datacollector://SampleData2"), "SampleData2", typeof(SampleData2Collector).AssemblyQualifiedName!, typeof(SampleData2Collector).Assembly.Location, true), + new InvokedDataCollector(new Uri("datacollector://SampleData3"), "SampleData3", typeof(SampleData3Collector).AssemblyQualifiedName!, typeof(SampleData3Collector).Assembly.Location, true) }; // act var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -82,7 +82,7 @@ public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() // arrange List invokedDataCollectors = new() { - new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", typeof(SampleData4Collector).AssemblyQualifiedName, typeof(SampleData4Collector).Assembly.Location, true) + new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", typeof(SampleData4Collector).AssemblyQualifiedName!, typeof(SampleData4Collector).Assembly.Location, true) }; // act @@ -99,7 +99,7 @@ public void Create_ShouldAddTwoTimeCodeCoverageDataAttachmentsHandler() // arrange List invokedDataCollectors = new() { - new InvokedDataCollector(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "SampleData5", typeof(SampleData5Collector).AssemblyQualifiedName, typeof(SampleData5Collector).Assembly.Location, true) + new InvokedDataCollector(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "SampleData5", typeof(SampleData5Collector).AssemblyQualifiedName!, typeof(SampleData5Collector).Assembly.Location, true) }; // act @@ -170,11 +170,11 @@ private static string GetTestAssetsFolder() public class SampleDataCollector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } @@ -186,11 +186,11 @@ public override void Initialize( public class SampleData2Collector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } @@ -202,11 +202,11 @@ public override void Initialize( public class SampleData3Collector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } @@ -218,11 +218,11 @@ public override void Initialize( public class SampleData4Collector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } @@ -234,11 +234,11 @@ public override void Initialize( public class SampleData5Collector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs index 324c3532b0..48f4ee7f9a 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs @@ -343,8 +343,8 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachment new AttachmentSet(new Uri(Uri2), "uri2_output") }; - _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(null, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler1); - _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(null, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler2); + _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler1); + _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler2); // act await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _mockEventsHandler.Object, _cancellationTokenSource.Token); @@ -580,7 +580,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProperlySendProgres } }); - _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(null, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) + _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns((XmlElement configurationElement, ICollection i1, IProgress progress, IMessageLogger logger, CancellationToken cancellation) => { progress.Report(25); @@ -591,7 +591,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProperlySendProgres return Task.FromResult(outputAttachments1); }); - _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(null, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) + _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())) .Returns((XmlElement configurationElement, ICollection i1, IProgress progress, IMessageLogger logger, CancellationToken cancellation) => { progress.Report(50); @@ -666,7 +666,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldFlowCorrectDataCollectorC List invokedDataCollectors = new() { - new InvokedDataCollector(new Uri(Uri1), withConfig ? "friendlyNameA" : "friendlyNameB", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false) + new InvokedDataCollector(new Uri(Uri1), withConfig ? "friendlyNameA" : "friendlyNameB", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) }; string runSettingsXml = diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs index b4f7216bfe..ba0151d135 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs @@ -110,7 +110,7 @@ public void StartTestRunShouldUpdateTestCaseSourceIfTestCaseSourceDiffersFromTes var inputSource = new List { "inputPackage.appxrecipe" }; var testRunCriteria = new TestRunCriteria( - new List { new TestCase("A.C.M", new Uri("excutor://dummy"), inputSource.FirstOrDefault()) }, + new List { new TestCase("A.C.M", new Uri("excutor://dummy"), inputSource.First()) }, frequencyOfRunStatsChangeEvent: 10); var manualResetEvent = new ManualResetEvent(false); @@ -134,7 +134,7 @@ public void StartTestRunShouldNotUpdateTestCaseSourceIfTestCaseSourceDiffersFrom { var actualSources = new List { "actualSource.dll" }; var testRunCriteria = new TestRunCriteria( - new List { new TestCase("A.C.M", new Uri("excutor://dummy"), actualSources.FirstOrDefault()) }, + new List { new TestCase("A.C.M", new Uri("excutor://dummy"), actualSources.First()) }, frequencyOfRunStatsChangeEvent: 10); var manualResetEvent = new ManualResetEvent(false); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs index 2d398e9a7f..39e8a6a119 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs @@ -399,10 +399,10 @@ public void StartTestRunShouldAggregateRunData() Assert.IsTrue(completeArgs.IsAborted, "Aborted value must be OR of all values"); Assert.IsTrue(completeArgs.IsCanceled, "Canceled value must be OR of all values"); - Assert.AreEqual(10, completeArgs.TestRunStatistics.ExecutedTests, + Assert.AreEqual(10, completeArgs.TestRunStatistics!.ExecutedTests, "Stats must be aggregated properly"); - Assert.AreEqual(6, completeArgs.TestRunStatistics.Stats[TestOutcome.Passed], + Assert.AreEqual(6, completeArgs.TestRunStatistics.Stats![TestOutcome.Passed], "Stats must be aggregated properly"); Assert.AreEqual(4, completeArgs.TestRunStatistics.Stats[TestOutcome.Failed], "Stats must be aggregated properly"); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs index 38e28b51b6..381fe0220d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs @@ -94,14 +94,14 @@ public void AggregateShouldAggregateInvokedCollectorsCorrectly() var invokedDataCollectors = new Collection() { - new InvokedDataCollector(new Uri("datacollector://sample"),"sample", typeof(string).AssemblyQualifiedName,typeof(string).Assembly.Location,false) + new InvokedDataCollector(new Uri("datacollector://sample"),"sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location,false) }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, null, invokedDataCollectors, null); Assert.AreEqual(1, aggregator.InvokedDataCollectors.Count, "InvokedDataCollectors List must have data."); var invokedDataCollectors2 = new Collection() { - new InvokedDataCollector(new Uri("datacollector://sample2"),"sample2", typeof(int).AssemblyQualifiedName,typeof(int).Assembly.Location,false) + new InvokedDataCollector(new Uri("datacollector://sample2"),"sample2", typeof(int).AssemblyQualifiedName!, typeof(int).Assembly.Location,false) }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, null, invokedDataCollectors2, null); Assert.AreEqual(2, aggregator.InvokedDataCollectors.Count, "InvokedDataCollectors List must have aggregated data."); @@ -256,7 +256,7 @@ public void AggregateShouldAggregateRunStatsCorrectly() runStats = aggregator.GetAggregatedRunStats(); Assert.AreEqual(12, runStats.ExecutedTests, "RunStats must have aggregated data."); - Assert.AreEqual(2, runStats.Stats[TestOutcome.Passed], "RunStats must have aggregated data."); + Assert.AreEqual(2, runStats.Stats![TestOutcome.Passed], "RunStats must have aggregated data."); Assert.AreEqual(3, runStats.Stats[TestOutcome.Failed], "RunStats must have aggregated data."); Assert.AreEqual(1, runStats.Stats[TestOutcome.Skipped], "RunStats must have aggregated data."); Assert.AreEqual(4, runStats.Stats[TestOutcome.NotFound], "RunStats must have aggregated data."); @@ -276,7 +276,7 @@ public void AggregateShouldAggregateRunStatsCorrectly() runStats = aggregator.GetAggregatedRunStats(); Assert.AreEqual(23, runStats.ExecutedTests, "RunStats must have aggregated data."); - Assert.AreEqual(5, runStats.Stats[TestOutcome.Passed], "RunStats must have aggregated data."); + Assert.AreEqual(5, runStats.Stats![TestOutcome.Passed], "RunStats must have aggregated data."); Assert.AreEqual(5, runStats.Stats[TestOutcome.Failed], "RunStats must have aggregated data."); Assert.AreEqual(3, runStats.Stats[TestOutcome.Skipped], "RunStats must have aggregated data."); Assert.AreEqual(5, runStats.Stats[TestOutcome.NotFound], "RunStats must have aggregated data."); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs index 63b59edee8..00ca31373c 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs @@ -55,7 +55,7 @@ public ProxyBaseManagerTests() _mockTestHostManager.Setup( m => m.GetTestHostProcessStartInfo( It.IsAny>(), - It.IsAny>(), + It.IsAny>(), It.IsAny())) .Returns(new TestProcessStartInfo()); _mockTestHostManager.Setup(tmh => tmh.LaunchTestHostAsync(It.IsAny(), It.IsAny())) diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs index defc2bcedc..910d1b9bd1 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs @@ -93,7 +93,7 @@ public void StartTestRunShouldUpdateTestCaseSourceIfTestCaseSourceDiffersFromTes var inputSource = new List { "inputPackage.appxrecipe" }; var testRunCriteria = new TestRunCriteria( - new List { new TestCase("A.C.M", new Uri("excutor://dummy"), inputSource.FirstOrDefault()) }, + new List { new TestCase("A.C.M", new Uri("excutor://dummy"), inputSource.First()) }, frequencyOfRunStatsChangeEvent: 10); _mockTestHostManager.Setup(hm => hm.GetTestSources(inputSource)).Returns(actualSources); @@ -115,7 +115,7 @@ public void StartTestRunShouldNotUpdateTestCaseSourceIfTestCaseSourceDoNotDiffer var inputSource = new List { "actualSource.dll" }; var testRunCriteria = new TestRunCriteria( - new List { new TestCase("A.C.M", new Uri("excutor://dummy"), inputSource.FirstOrDefault()) }, + new List { new TestCase("A.C.M", new Uri("excutor://dummy"), inputSource.First()) }, frequencyOfRunStatsChangeEvent: 10); _mockTestHostManager.Setup(hm => hm.GetTestSources(inputSource)).Returns(actualSources); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs index 0a466824fa..7f9a084eec 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerWithDataCollectionTests.cs @@ -164,7 +164,7 @@ public void LaunchProcessWithDebuggerAttachedShouldUpdateEnvironmentVariables() var testProcessStartInfo = new TestProcessStartInfo { Arguments = string.Empty, - EnvironmentVariables = new Dictionary + EnvironmentVariables = new Dictionary { {"variable1", "value1" }, {"variable2", "value2" } @@ -179,7 +179,7 @@ public void LaunchProcessWithDebuggerAttachedShouldUpdateEnvironmentVariables() Assert.IsTrue(launchedStartInfo != null, "Failed to get the start info"); foreach (var envVaribale in testProcessStartInfo.EnvironmentVariables) { - Assert.AreEqual(envVaribale.Value, launchedStartInfo.EnvironmentVariables[envVaribale.Key], $"Expected environment variable {envVaribale.Key} : {envVaribale.Value} not found"); + Assert.AreEqual(envVaribale.Value, launchedStartInfo.EnvironmentVariables![envVaribale.Key], $"Expected environment variable {envVaribale.Key} : {envVaribale.Value} not found"); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs index f64cc5c876..85303d523b 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs @@ -71,7 +71,7 @@ public void SetupChannelShouldLaunchTestHost() var expectedStartInfo = new TestProcessStartInfo(); _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); _mockTestHostManager.Setup( - th => th.GetTestHostProcessStartInfo(Enumerable.Empty(), It.IsAny>(), It.IsAny())) + th => th.GetTestHostProcessStartInfo(Enumerable.Empty(), It.IsAny>(), It.IsAny())) .Returns(expectedStartInfo); _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); @@ -91,9 +91,9 @@ public void SetupChannelShouldCreateTimestampedLogFileForHost() th => th.GetTestHostProcessStartInfo( It.IsAny>(), - It.IsAny>(), + It.IsAny>(), It.Is( - t => t.LogFile.Contains("log.host." + DateTime.Now.ToString("yy-MM-dd")) + t => t.LogFile!.Contains("log.host." + DateTime.Now.ToString("yy-MM-dd")) && t.LogFile.Contains("_" + Environment.CurrentManagedThreadId + ".txt")))); #if NETFRAMEWORK EqtTrace.TraceLevel = TraceLevel.Off; @@ -121,7 +121,7 @@ public void SetupChannelShouldAddRunnerProcessIdForTestHost() th => th.GetTestHostProcessStartInfo( It.IsAny>(), - It.IsAny>(), + It.IsAny>(), It.Is(t => t.RunnerProcessId.Equals(pid)))); } @@ -141,7 +141,7 @@ public void SetupChannelShouldAddCorrectTraceLevelForTestHost() th => th.GetTestHostProcessStartInfo( It.IsAny>(), - It.IsAny>(), + It.IsAny>(), It.Is(t => t.TraceLevel == (int)PlatformTraceLevel.Info))); } @@ -446,7 +446,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgTrueIfTelem testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); // Verify. - Assert.IsTrue(receivedTestProcessInfo.Arguments.Contains("--telemetryoptedin true")); + Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin true")); } [TestMethod] @@ -469,7 +469,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgFalseIfTele testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); // Verify. - Assert.IsTrue(receivedTestProcessInfo.Arguments.Contains("--telemetryoptedin false")); + Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin false")); } [MemberNotNull(nameof(_mockProcessHelper), nameof(_mockFileHelper), nameof(_mockEnvironment), nameof(_mockRunsettingHelper), nameof(_mockWindowsRegistry), nameof(_mockEnvironmentVariableHelper))] @@ -489,7 +489,7 @@ private void SetUpMocksForDotNetTestHost() It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny>(), + It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>())) @@ -548,7 +548,7 @@ public TestableDotnetTestHostManager( public override TestProcessStartInfo GetTestHostProcessStartInfo( IEnumerable sources, - IDictionary? environmentVariables, + IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo) { return new TestProcessStartInfo(); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs index 91cb8983e1..6a73de9005 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs @@ -132,7 +132,7 @@ public void StartSessionShouldSucceedIfCalledOnlyOnce() // First call to StartSession should succeed. Assert.IsTrue(proxyManager.StartSession(_mockEventsHandler.Object, _mockRequestData.Object)); mockProxyOperationManager.Verify(pom => pom.SetupChannel( - testSessionCriteria.Sources, + testSessionCriteria.Sources!, testSessionCriteria.RunSettings), Times.Once); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( @@ -142,7 +142,7 @@ public void StartSessionShouldSucceedIfCalledOnlyOnce() // Second call to StartSession should fail. Assert.IsFalse(proxyManager.StartSession(_mockEventsHandler.Object, _mockRequestData.Object)); mockProxyOperationManager.Verify(pom => pom.SetupChannel( - testSessionCriteria.Sources, + testSessionCriteria.Sources!, testSessionCriteria.RunSettings), Times.Once); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( @@ -248,7 +248,7 @@ public void StartSessionShouldFailIfAddSessionFails() // Call to StartSession should fail because AddSession fails. Assert.IsFalse(proxyManager.StartSession(_mockEventsHandler.Object, _mockRequestData.Object)); mockProxyOperationManager.Verify(pom => pom.SetupChannel( - testSessionCriteria.Sources, + testSessionCriteria.Sources!, testSessionCriteria.RunSettings), Times.Once); mockProxyOperationManager.Verify(pom => pom.Close(), Times.Once); @@ -271,7 +271,7 @@ public void StopSessionShouldSucceedIfCalledOnlyOnce() // StartSession should succeed. Assert.IsTrue(proxyManager.StartSession(_mockEventsHandler.Object, _mockRequestData.Object)); mockProxyOperationManager.Verify(pom => pom.SetupChannel( - testSessionCriteria.Sources, + testSessionCriteria.Sources!, testSessionCriteria.RunSettings), Times.Once); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( @@ -309,7 +309,7 @@ public void StopSessionShouldSucceedWhenCalledWithMultipleSources() mockProxyOperationManager.Verify(pom => pom.SetupChannel( It.IsAny>(), testSessionCriteria.RunSettings), - Times.Exactly(testSessionCriteria.Sources.Count)); + Times.Exactly(testSessionCriteria.Sources!.Count)); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( It.IsAny()), Times.Once); @@ -337,7 +337,7 @@ public void DequeueProxyShouldSucceedIfIdentificationCriteriaAreMet() mockProxyOperationManager.Verify(pom => pom.SetupChannel( It.IsAny>(), testSessionCriteria.RunSettings), - Times.Exactly(testSessionCriteria.Sources.Count)); + Times.Exactly(testSessionCriteria.Sources!.Count)); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( It.IsAny()), Times.Once); @@ -379,7 +379,7 @@ public void DequeueProxyTwoConsecutiveTimesWithEnqueueShouldBeSuccessful() mockProxyOperationManager.Verify(pom => pom.SetupChannel( It.IsAny>(), testSessionCriteria.RunSettings), - Times.Exactly(testSessionCriteria.Sources.Count)); + Times.Exactly(testSessionCriteria.Sources!.Count)); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( It.IsAny()), Times.Once); @@ -414,7 +414,7 @@ public void DequeueProxyShouldFailIfRunSettingsMatchingFails() mockProxyOperationManager.Verify(pom => pom.SetupChannel( It.IsAny>(), testSessionCriteria.RunSettings), - Times.Exactly(testSessionCriteria.Sources.Count)); + Times.Exactly(testSessionCriteria.Sources!.Count)); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( It.IsAny()), Times.Once); @@ -440,7 +440,7 @@ public void DequeueProxyShouldFailIfRunSettingsMatchingFailsFor2EnvVariables() mockProxyOperationManager.Verify(pom => pom.SetupChannel( It.IsAny>(), testSessionCriteria.RunSettings), - Times.Exactly(testSessionCriteria.Sources.Count)); + Times.Exactly(testSessionCriteria.Sources!.Count)); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( It.IsAny()), Times.Once); @@ -466,7 +466,7 @@ public void DequeueProxyShouldFailIfRunSettingsMatchingFailsForDataCollectors() mockProxyOperationManager.Verify(pom => pom.SetupChannel( It.IsAny>(), testSessionCriteria.RunSettings), - Times.Exactly(testSessionCriteria.Sources.Count)); + Times.Exactly(testSessionCriteria.Sources!.Count)); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( It.IsAny()), Times.Once); @@ -496,7 +496,7 @@ public void EnqueueProxyShouldSucceedIfIdentificationCriteriaAreMet() mockProxyOperationManager.Verify(pom => pom.SetupChannel( It.IsAny>(), testSessionCriteria.RunSettings), - Times.Exactly(testSessionCriteria.Sources.Count)); + Times.Exactly(testSessionCriteria.Sources!.Count)); _mockEventsHandler.Verify(eh => eh.HandleStartTestSessionComplete( It.IsAny()), Times.Once); @@ -512,7 +512,7 @@ public void EnqueueProxyShouldSucceedIfIdentificationCriteriaAreMet() Assert.IsTrue(proxyManager.EnqueueProxy(0)); } - private StartTestSessionCriteria CreateTestSession(IList sources, string runSettings) + private static StartTestSessionCriteria CreateTestSession(IList sources, string runSettings) { return new StartTestSessionCriteria() { @@ -531,7 +531,7 @@ private ProxyTestSessionManager CreateProxy( typeof(ITestRuntimeProvider), shared: false, runSettings, - testSessionCriteria.Sources.Select(s => new SourceDetail + testSessionCriteria.Sources!.Select(s => new SourceDetail { Source = s, Architecture = Architecture.X86, @@ -542,7 +542,7 @@ private ProxyTestSessionManager CreateProxy( var runtimeProviders = new List { runtimeProviderInfo }; return new ProxyTestSessionManager( testSessionCriteria, - testSessionCriteria.Sources.Count, + testSessionCriteria.Sources!.Count, _ => proxyOperationManager, runtimeProviders ); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs index 68c8be5313..8d38db20db 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs @@ -48,7 +48,7 @@ public void HandleRawMessageShouldSendMessageToBaseTestRunEventsHandler() { _mockDataSerializer.Setup(x => x.DeserializeMessage(It.IsAny())).Returns(new Message() { MessageType = MessageType.BeforeTestRunStart }); _testRunEventHandler.HandleRawMessage(null!); - _baseTestRunEventsHandler.Verify(th => th.HandleRawMessage(null), Times.AtLeast(1)); + _baseTestRunEventsHandler.Verify(th => th.HandleRawMessage(null!), Times.AtLeast(1)); } [TestMethod] @@ -110,7 +110,7 @@ public void HandleRawMessageShouldInvokeAfterTestRunEndAndReturnInvokedDataColle { var invokedDataCollectors = new Collection { - new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, true) + new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, true) }; var testRunCompleteEventArgs = new TestRunCompleteEventArgs(null, false, false, null, new Collection(), new Collection(), new TimeSpan()); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs index a194d98525..0d1dd747b1 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs @@ -41,7 +41,7 @@ public void LaunchDataCollectorShouldLaunchDataCollectorProcess() List arguments = new(); _dataCollectionLauncher.LaunchDataCollector(null, arguments); - _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); + _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); } [TestMethod] @@ -53,7 +53,7 @@ public void LaunchDataCollectorShouldAppendDoubleQuoteForDataCollectorDllPath() List arguments = new(); _dataCollectionLauncher.LaunchDataCollector(null, arguments); - _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), string.Format("{0} \"{1}\" {2} ", "exec", dataCollectorAssemblyPath, string.Join(" ", arguments)), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); + _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), string.Format("{0} \"{1}\" {2} ", "exec", dataCollectorAssemblyPath, string.Join(" ", arguments)), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); } [TestMethod] @@ -64,6 +64,6 @@ public void LaunchDataCollectorShouldLaunchDataCollectorProcessWithCurrecntWorki string currentWorkingDirectory = Directory.GetCurrentDirectory(); - _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), It.IsAny(), currentWorkingDirectory, It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); + _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), It.IsAny(), currentWorkingDirectory, It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); } } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs index 875f74aadd..769617af26 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs @@ -203,7 +203,7 @@ public void InProcDataCollectionExtensionManagerWillNotEnableDataCollectionForIn [TestMethod] public void TriggerSessionStartShouldBeCalledWithCorrectTestSources() { - var properties = new Dictionary + var properties = new Dictionary { { "TestSources", new List() { "testsource1.dll", "testsource2.dll" } } }; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionSinkTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionSinkTests.cs index 656dceb413..d3b85388af 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionSinkTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionSinkTests.cs @@ -42,7 +42,7 @@ public void SendDataShouldThrowArgumentExceptionIfKeyIsNull() _testCase.SetPropertyValue(TestCaseProperties.Id, Guid.NewGuid()); Assert.ThrowsException( - () => _dataCollectionSink.SendData(_dataCollectionContext, null, "DummyValue")); + () => _dataCollectionSink.SendData(_dataCollectionContext, null!, "DummyValue")); } [TestMethod] @@ -51,7 +51,7 @@ public void SendDataShouldThrowArgumentExceptionIfValueIsNull() _testCase.SetPropertyValue(TestCaseProperties.Id, Guid.NewGuid()); Assert.ThrowsException( - () => _dataCollectionSink.SendData(_dataCollectionContext, "DummyKey", null)); + () => _dataCollectionSink.SendData(_dataCollectionContext, "DummyKey", null!)); } //[TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs index 7e46fa96b3..30d35aae84 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs @@ -61,7 +61,7 @@ public void InitializeShouldInitializeCommunication() _mockDataCollectionRequestSender.Setup(x => x.WaitForRequestHandlerConnection(EnvironmentHelper.DefaultConnectionTimeout * 1000)).Returns(true); _proxyDataCollectionManager.Initialize(); - _mockDataCollectionLauncher.Verify(x => x.LaunchDataCollector(It.IsAny>(), It.IsAny>()), Times.Once); + _mockDataCollectionLauncher.Verify(x => x.LaunchDataCollector(It.IsAny>(), It.IsAny>()), Times.Once); _mockDataCollectionRequestSender.Verify(x => x.WaitForRequestHandlerConnection(EnvironmentHelper.DefaultConnectionTimeout * 1000), Times.Once); } @@ -122,7 +122,7 @@ public void InitializeShouldPassDiagArgumentsIfDiagIsEnabled() _mockDataCollectionLauncher.Verify( x => x.LaunchDataCollector( - It.IsAny>(), + It.IsAny>(), It.Is>(list => list.Contains("--diag") && list.Contains("--tracelevel") && list.Contains(expectedTraceLevel.ToString()))), Times.Once); } @@ -154,7 +154,7 @@ public void BeforeTestRunStartShouldPassRunSettingsWithExtensionsFolderUpdatedAs _proxyDataCollectionManager = new ProxyDataCollectionManager(_mockRequestData.Object, runsettings, sourceList, _mockDataCollectionRequestSender.Object, _mockProcessHelper.Object, _mockDataCollectionLauncher.Object); _mockRequestData.Setup(r => r.IsTelemetryOptedIn).Returns(true); - BeforeTestRunStartResult res = new(new Dictionary(), 123); + BeforeTestRunStartResult res = new(new Dictionary(), 123); _mockDataCollectionRequestSender.Setup(x => x.SendBeforeTestRunStartAndGetResult(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())).Returns(res); var result = _proxyDataCollectionManager.BeforeTestRunStart(true, true, null); @@ -168,7 +168,7 @@ public void BeforeTestRunStartShouldPassRunSettingsWithExtensionsFolderUpdatedAs [TestMethod] public void BeforeTestRunStartShouldReturnDataCollectorParameters() { - BeforeTestRunStartResult res = new(new Dictionary(), 123); + BeforeTestRunStartResult res = new(new Dictionary(), 123); var sourceList = new List() { "testsource1.dll" }; _mockDataCollectionRequestSender.Setup(x => x.SendBeforeTestRunStartAndGetResult(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())).Returns(res); @@ -203,7 +203,7 @@ public void SendBeforeTestRunStartAndGetResultShouldBeInvokedWithCorrectTestSour var testSources = new List() { "abc.dll", "efg.dll" }; _proxyDataCollectionManager = new ProxyDataCollectionManager(_mockRequestData.Object, string.Empty, testSources, _mockDataCollectionRequestSender.Object, _mockProcessHelper.Object, _mockDataCollectionLauncher.Object); - BeforeTestRunStartResult res = new(new Dictionary(), 123); + BeforeTestRunStartResult res = new(new Dictionary(), 123); _mockDataCollectionRequestSender.Setup(x => x.SendBeforeTestRunStartAndGetResult(string.Empty, testSources, It.IsAny(), It.IsAny())).Returns(res); var result = _proxyDataCollectionManager.BeforeTestRunStart(true, true, null); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs index 04c8f56615..1207f87706 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs @@ -501,11 +501,11 @@ public void RunTestsShouldRaiseTestRunComplete() Assert.IsNotNull(_receivedRunCompleteArgs); Assert.IsNull(_receivedRunCompleteArgs.Error); Assert.IsFalse(_receivedRunCompleteArgs.IsAborted); - Assert.AreEqual(_runTestsInstance.GetTestRunCache.TestRunStatistics.ExecutedTests, _receivedRunCompleteArgs.TestRunStatistics.ExecutedTests); + Assert.AreEqual(_runTestsInstance.GetTestRunCache.TestRunStatistics.ExecutedTests, _receivedRunCompleteArgs.TestRunStatistics!.ExecutedTests); // Test run changed event assertions Assert.IsNotNull(_receivedRunStatusArgs); - Assert.AreEqual(_runTestsInstance.GetTestRunCache.TestRunStatistics.ExecutedTests, _receivedRunStatusArgs.TestRunStatistics.ExecutedTests); + Assert.AreEqual(_runTestsInstance.GetTestRunCache.TestRunStatistics.ExecutedTests, _receivedRunStatusArgs.TestRunStatistics!.ExecutedTests); Assert.IsNotNull(_receivedRunStatusArgs.NewTestResults); Assert.IsTrue(_receivedRunStatusArgs.NewTestResults.Any()); Assert.IsTrue(_receivedRunStatusArgs.ActiveTests == null || !_receivedRunStatusArgs.ActiveTests.Any()); @@ -596,7 +596,7 @@ public void RunTestsShouldCloneTheTestResultsObjectsIfTestSourceIsPackage() _runTestsInstance.RunTests(); Assert.IsNotNull(_receivedRunStatusArgs?.NewTestResults); - Assert.AreEqual(1, _receivedRunStatusArgs.ActiveTests.Count()); + Assert.AreEqual(1, _receivedRunStatusArgs.ActiveTests!.Count()); _mockDataSerializer.Verify(d => d.Clone(It.IsAny()), Times.Exactly(2)); } @@ -999,7 +999,7 @@ protected override void SendSessionEnd() protected override void SendSessionStart() { - _testCaseEventsHandler?.SendSessionStart(new Dictionary { { "TestSources", new List() { "1.dll" } } }); + _testCaseEventsHandler?.SendSessionStart(new Dictionary { { "TestSources", new List() { "1.dll" } } }); } protected override bool ShouldAttachDebuggerToTestHost( @@ -1018,11 +1018,11 @@ public void Cancel() { } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { } } @@ -1035,12 +1035,12 @@ public void Cancel() throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs index 828831a659..7dfec2e75a 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs @@ -166,7 +166,7 @@ public void StartTestRunShouldRunTestsInTheProvidedSources() "A.C.M", new Uri("e://d/"), "A.dll")); - fh.RecordResult(tr); + fh!.RecordResult(tr); }; _executionManager.StartTestRun(adapterSourceMap, null, null, _testExecutionContext, null, mockTestRunEventsHandler.Object); @@ -204,7 +204,7 @@ public void StartTestRunShouldRunTestsForTheProvidedTests() "A.C.M", new Uri(RunTestsWithSourcesTestsExecutorUri), "A.dll")); - fh.RecordResult(tr); + fh!.RecordResult(tr); }; TestPluginCacheHelper.SetupMockExtensions(new string[] { assemblyLocation }, () => { }); @@ -318,12 +318,12 @@ public void Cancel() throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } @@ -337,12 +337,12 @@ public void Cancel() throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } @@ -356,12 +356,12 @@ public void Cancel() throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { throw new NotImplementedException(); } @@ -436,11 +436,11 @@ public void Load(XmlReader reader) public class InvalidDataCollector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } @@ -460,11 +460,11 @@ public class ADataCollectorInheritingFromAnotherDataCollector : InvalidDataColle public class ValidDataCollector : DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs index 719726a4e2..d8d1ce9be2 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs @@ -279,10 +279,10 @@ public void SendSessionStartShouldCallSessionStartWithCorrectTestSources() _runTestsInstance.CallSendSessionStart(); - mockTestCaseEventsHandler.Verify(x => x.SendSessionStart(It.Is>( + mockTestCaseEventsHandler.Verify(x => x.SendSessionStart(It.Is>( y => y.ContainsKey("TestSources") - && ((IEnumerable)y["TestSources"]).Contains("1.dll") - && ((IEnumerable)y["TestSources"]).Contains("2.dll") + && ((IEnumerable)y["TestSources"]!).Contains("1.dll") + && ((IEnumerable)y["TestSources"]!).Contains("2.dll") ))); } @@ -395,20 +395,20 @@ public void DiscoverTests(IEnumerable sources, IDiscoveryContext discove [ExtensionUri(RunTestsWithSourcesTestsExecutorUri)] internal class RunTestWithSourcesExecutor : ITestExecutor { - public static Action, IRunContext, IFrameworkHandle>? RunTestsWithSourcesCallback { get; set; } - public static Action, IRunContext, IFrameworkHandle>? RunTestsWithTestsCallback { get; set; } + public static Action?, IRunContext?, IFrameworkHandle?>? RunTestsWithSourcesCallback { get; set; } + public static Action?, IRunContext?, IFrameworkHandle?>? RunTestsWithTestsCallback { get; set; } public void Cancel() { throw new NotImplementedException(); } - public void RunTests(IEnumerable sources, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? sources, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { RunTestsWithSourcesCallback?.Invoke(sources, runContext, frameworkHandle); } - public void RunTests(IEnumerable tests, IRunContext runContext, IFrameworkHandle frameworkHandle) + public void RunTests(IEnumerable? tests, IRunContext? runContext, IFrameworkHandle? frameworkHandle) { RunTestsWithTestsCallback?.Invoke(tests, runContext, frameworkHandle); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithTestsTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithTestsTests.cs index 723d8704ba..0dcaa9b75c 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithTestsTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithTestsTests.cs @@ -158,9 +158,9 @@ public void SendSessionStartShouldCallSessionStartWithCorrectTestSources() _runTestsInstance.CallSendSessionStart(); - mockTestCaseEventsHandler.Verify(x => x.SendSessionStart(It.Is>( + mockTestCaseEventsHandler.Verify(x => x.SendSessionStart(It.Is>( y => y.ContainsKey("TestSources") - && ((IEnumerable)y["TestSources"]).Contains("s.dll") + && ((IEnumerable)y["TestSources"]!).Contains("s.dll") ))); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs index 355d2eb76e..4292a53b3d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/TestRunCacheTests.cs @@ -132,7 +132,7 @@ public void OnNewTestResultShouldUpdateRunStats() } Assert.AreEqual(2, cache.TestRunStatistics.ExecutedTests); - Assert.AreEqual(2, cache.TestRunStatistics.Stats[TestOutcome.Passed]); + Assert.AreEqual(2, cache.TestRunStatistics.Stats![TestOutcome.Passed]); } [TestMethod] @@ -358,7 +358,7 @@ public void TestRunStatsShouldReturnCurrentStats() var stats = cache.TestRunStatistics; Assert.AreEqual(cacheSize, stats.ExecutedTests); - Assert.AreEqual(5, stats.Stats[TestOutcome.Passed]); + Assert.AreEqual(5, stats.Stats![TestOutcome.Passed]); Assert.AreEqual(5, stats.Stats[TestOutcome.Failed]); } @@ -383,14 +383,14 @@ private class TestCacheTester public int TotalInProgressTestsReceived { get; set; } - public void CacheHitOnSize(TestRunStatistics stats, ICollection results, ICollection tests) + public void CacheHitOnSize(TestRunStatistics _, ICollection results, ICollection tests) { Assert.AreEqual(ExpectedCacheSize, results.Count + tests.Count); CacheHitCount++; TotalInProgressTestsReceived += tests.Count; } - public void CacheHitOnTimerLimit(ICollection results, ICollection tests) + public void CacheHitOnTimerLimit(ICollection _, ICollection tests) { CacheHitCount++; TotalInProgressTestsReceived += tests.Count; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs index 89342d6e8d..30f7074573 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs @@ -1650,7 +1650,7 @@ public void Initialize(TestLoggerEvents events, string testRunDirectory) [FriendlyName("TestLoggerWithParameterExtension")] private class ValidLoggerWithParameters : ITestLoggerWithParameters { - public static Dictionary? Parameters; + public static Dictionary? Parameters; public static int Counter; public void Initialize(TestLoggerEvents events, string testRunDirectory) @@ -1658,7 +1658,7 @@ public void Initialize(TestLoggerEvents events, string testRunDirectory) Counter += 2; } - public void Initialize(TestLoggerEvents events, Dictionary parameters) + public void Initialize(TestLoggerEvents events, Dictionary parameters) { Counter++; Parameters = parameters; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestableImplementations/TestableRuntimeProvider.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestableImplementations/TestableRuntimeProvider.cs index f63ce5bfc0..6d11d7673c 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestableImplementations/TestableRuntimeProvider.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestableImplementations/TestableRuntimeProvider.cs @@ -26,17 +26,17 @@ public TestableRuntimeProvider(bool shared) Shared = shared; } - public event EventHandler? HostLaunched; + public event EventHandler? HostLaunched; - public event EventHandler? HostExited; + public event EventHandler? HostExited; public bool Shared { get; } - public void Initialize(IMessageLogger logger, string runsettingsXml) + public void Initialize(IMessageLogger? logger, string runsettingsXml) { } - public bool CanExecuteCurrentRunConfiguration(string runsettingsXml) + public bool CanExecuteCurrentRunConfiguration(string? runsettingsXml) { return true; } @@ -52,16 +52,16 @@ public TestHostConnectionInfo GetTestHostConnectionInfo() public Task LaunchTestHostAsync(TestProcessStartInfo testHostStartInfo, CancellationToken cancellationToken) { - HostLaunched?.Invoke(this, null); + HostLaunched?.Invoke(this, null!); return Task.FromResult(true); } - public TestProcessStartInfo? GetTestHostProcessStartInfo( + public TestProcessStartInfo GetTestHostProcessStartInfo( IEnumerable sources, - IDictionary environmentVariables, + IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo) { - return default; + return default!; } public IEnumerable GetTestPlatformExtensions(IEnumerable sources, IEnumerable extensions) @@ -76,7 +76,7 @@ public IEnumerable GetTestSources(IEnumerable sources) public Task CleanTestHostAsync(CancellationToken cancellationToken) { - HostExited?.Invoke(this, null); + HostExited?.Invoke(this, null!); return Task.FromResult(true); } } diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs index bb7cae86b9..5dad48094e 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs @@ -36,7 +36,7 @@ public class TrxLoggerTests private static readonly string DefaultLogFileNameParameterValue = "logfilevalue.trx"; private readonly Mock _events; - private readonly Dictionary _parameters; + private readonly Dictionary _parameters; private TestableTrxLogger _testableTrxLogger; @@ -45,7 +45,7 @@ public TrxLoggerTests() _events = new Mock(); _testableTrxLogger = new TestableTrxLogger(); - _parameters = new Dictionary(2) + _parameters = new Dictionary(2) { [DefaultLoggerParameterNames.TestRunDirectory] = DefaultTestRunDirectory, [TrxLoggerConstants.LogFileNameKey] = DefaultLogFileNameParameterValue @@ -99,7 +99,7 @@ public void InitializeShouldNotThrowExceptionIfTestRunDirectoryIsNeitherEmptyNor public void InitializeShouldThrowExceptionIfParametersAreEmpty() { var events = new Mock(); - Assert.ThrowsException(() => _testableTrxLogger.Initialize(events.Object, new Dictionary())); + Assert.ThrowsException(() => _testableTrxLogger.Initialize(events.Object, new Dictionary())); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs b/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs index 552a9c0541..386fdab9eb 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs @@ -38,7 +38,7 @@ public void GetNavigationDataShouldReturnCorrectFileNameAndLineNumber() var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var diaSession = new DiaSession(assemblyPath); - DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "PassingTest"); + DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "PassingTest"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); StringAssert.EndsWith(diaNavigationData.FileName, @"\SimpleClassLibrary\Class1.cs"); @@ -56,7 +56,7 @@ public void GetNavigationDataShouldReturnCorrectDataForAsyncMethod() var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var diaSession = new DiaSession(assemblyPath); - DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1+d__1", "MoveNext"); + DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1+d__1", "MoveNext"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); StringAssert.EndsWith(diaNavigationData.FileName, @"\SimpleClassLibrary\Class1.cs"); @@ -74,7 +74,7 @@ public void GetNavigationDataShouldReturnCorrectDataForOverLoadedMethod() var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var diaSession = new DiaSession(assemblyPath); - DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "OverLoadedMethod"); + DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "OverLoadedMethod"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); StringAssert.EndsWith(diaNavigationData.FileName, @"\SimpleClassLibrary\Class1.cs"); @@ -95,7 +95,7 @@ public void GetNavigationDataShouldReturnNullForNotExistMethodNameOrNotExistType var diaSession = new DiaSession(assemblyPath); // Not exist method name - DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "NotExistMethod"); + DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "NotExistMethod"); Assert.IsNull(diaNavigationData); // Not Exist Type name @@ -113,7 +113,7 @@ public void DiaSessionPerfTest() var watch = Stopwatch.StartNew(); var diaSession = new DiaSession(assemblyPath); - DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.HugeMethodSet", "MSTest_D1_01"); + DiaNavigationData? diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.HugeMethodSet", "MSTest_D1_01"); watch.Stop(); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs index 6f239fd489..ac0fec5c8a 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs @@ -15,7 +15,7 @@ public class SessionEventsTests public SessionEventsTests() { - var properties = new Dictionary + var properties = new Dictionary { { "property1", 1 }, { "property2", 2 } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/FrameworkTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/FrameworkTests.cs index f5ecd13f21..018c64d1c7 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/FrameworkTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/FrameworkTests.cs @@ -31,26 +31,26 @@ public void FrameworkFromStringShouldReturnNullForInvalidString() [TestMethod] public void FrameworkFromStringShouldIgnoreCase() { - var fx = Framework.FromString("framework35"); + var fx = Framework.FromString("framework35")!; Assert.AreEqual(".NETFramework,Version=v3.5", fx.Name); - fx = Framework.FromString("FRAMEWORK40"); + fx = Framework.FromString("FRAMEWORK40")!; Assert.AreEqual(".NETFramework,Version=v4.0", fx.Name); - fx = Framework.FromString("Framework45"); + fx = Framework.FromString("Framework45")!; Assert.AreEqual(".NETFramework,Version=v4.5", fx.Name); - fx = Framework.FromString("frameworKcore10"); + fx = Framework.FromString("frameworKcore10")!; Assert.AreEqual(".NETCoreApp,Version=v1.0", fx.Name); - fx = Framework.FromString("frameworkUAP10"); + fx = Framework.FromString("frameworkUAP10")!; Assert.AreEqual("UAP,Version=v10.0", fx.Name); } [TestMethod] public void FrameworkFromStringShouldTrimSpacesAroundFrameworkString() { - var fx = Framework.FromString(" Framework35"); + var fx = Framework.FromString(" Framework35")!; Assert.AreEqual(".NETFramework,Version=v3.5", fx.Name); Assert.AreEqual("3.5.0.0", fx.Version); @@ -59,11 +59,11 @@ public void FrameworkFromStringShouldTrimSpacesAroundFrameworkString() [TestMethod] public void FrameworkFromStringShouldWorkForShortNames() { - var fx = Framework.FromString("net451"); + var fx = Framework.FromString("net451")!; Assert.AreEqual(".NETFramework,Version=v4.5.1", fx.Name); Assert.AreEqual("4.5.1.0", fx.Version); - var corefx = Framework.FromString("netcoreapp2.0"); + var corefx = Framework.FromString("netcoreapp2.0")!; Assert.AreEqual(".NETCoreApp,Version=v2.0", corefx.Name); Assert.AreEqual("2.0.0.0", corefx.Version); } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs index 6a8b472c36..e81bf05e38 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs @@ -88,9 +88,9 @@ public void RunConfigurationReadsValuesCorrectlyFromXml() // Verify Default Assert.AreEqual(Architecture.X64, runConfiguration.TargetPlatform); - var expectedFramework = Framework.FromString("FrameworkCore10"); + var expectedFramework = Framework.FromString("FrameworkCore10")!; _ = runConfiguration.TargetFramework; - Assert.AreEqual(expectedFramework.Name, runConfiguration.TargetFramework.Name); + Assert.AreEqual(expectedFramework.Name, runConfiguration.TargetFramework!.Name); Assert.AreEqual(expectedFramework.Version, runConfiguration.TargetFramework.Version); Assert.AreEqual("TestResults", runConfiguration.ResultsDirectory); @@ -118,23 +118,23 @@ public void SetTargetFrameworkVersionShouldSetTargetFramework() { var runConfiguration = new RunConfiguration(); runConfiguration.TargetFrameworkVersion = FrameworkVersion.Framework35; - Equals(Framework.FromString("Framework35").Name, runConfiguration.TargetFramework.Name); + Equals(Framework.FromString("Framework35")!.Name, runConfiguration.TargetFramework!.Name); Assert.AreEqual(FrameworkVersion.Framework35, runConfiguration.TargetFrameworkVersion); runConfiguration.TargetFrameworkVersion = FrameworkVersion.Framework40; - Equals(Framework.FromString("Framework40").Name, runConfiguration.TargetFramework.Name); + Equals(Framework.FromString("Framework40")!.Name, runConfiguration.TargetFramework.Name); Assert.AreEqual(FrameworkVersion.Framework40, runConfiguration.TargetFrameworkVersion); runConfiguration.TargetFrameworkVersion = FrameworkVersion.Framework45; - Equals(Framework.FromString("Framework45").Name, runConfiguration.TargetFramework.Name); + Equals(Framework.FromString("Framework45")!.Name, runConfiguration.TargetFramework.Name); Assert.AreEqual(FrameworkVersion.Framework45, runConfiguration.TargetFrameworkVersion); runConfiguration.TargetFrameworkVersion = FrameworkVersion.FrameworkCore10; - Equals(Framework.FromString("FrameworkCore10").Name, runConfiguration.TargetFramework.Name); + Equals(Framework.FromString("FrameworkCore10")!.Name, runConfiguration.TargetFramework.Name); Assert.AreEqual(FrameworkVersion.FrameworkCore10, runConfiguration.TargetFrameworkVersion); runConfiguration.TargetFrameworkVersion = FrameworkVersion.FrameworkUap10; - Equals(Framework.FromString("FrameworkUap10").Name, runConfiguration.TargetFramework.Name); + Equals(Framework.FromString("FrameworkUap10")!.Name, runConfiguration.TargetFramework.Name); Assert.AreEqual(FrameworkVersion.FrameworkUap10, runConfiguration.TargetFrameworkVersion); } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunSettingsTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunSettingsTests.cs index bdb1deae21..3477a0d302 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunSettingsTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunSettingsTests.cs @@ -26,14 +26,14 @@ public ChildRunSettings() : base("SomeName") { } - public override XmlElement? ToXml() + public override XmlElement ToXml() { var document = new XmlDocument(); using (XmlWriter writer = document.CreateNavigator()!.AppendChild()) { new XmlSerializer(typeof(ChildRunSettings)).Serialize(writer, this); } - return document.DocumentElement; + return document.DocumentElement!; } } } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs index 2af3bc89a3..51278d94ea 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/TestObjectTests.cs @@ -37,7 +37,7 @@ public void TestCaseIdShouldReturnGuidWhenTestPropertiesIdIsSet() public void GetPropertiesShouldReturnListOfPropertiesInStore() { TestProperty tp = TestProperty.Register("dummyId", "dummyLabel", typeof(int), typeof(TestObjectTests)); - var kvp = new KeyValuePair(tp, 123); + var kvp = new KeyValuePair(tp, 123); TestCase.SetPropertyValue(kvp.Key, kvp.Value); var properties = TestCase.GetProperties().ToList(); diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/FilterHelperTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/FilterHelperTests.cs index 217ca2b934..b167362632 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/FilterHelperTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/FilterHelperTests.cs @@ -17,8 +17,8 @@ public class FilterHelpersTests [TestMethod] public void EscapeUnescapeNullThrowsArgumentNullException() { - Assert.ThrowsException(() => FilterHelper.Escape(null)); - Assert.ThrowsException(() => FilterHelper.Unescape(null)); + Assert.ThrowsException(() => FilterHelper.Escape(null!)); + Assert.ThrowsException(() => FilterHelper.Unescape(null!)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs index 43087eab09..4d39ae246d 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs @@ -430,7 +430,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithCorrectFriendlyName() "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingFriendlyName); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingFriendlyName)!; Assert.AreEqual("TestLoggerWithParameterExtension", loggerRunSettings.LoggerSettingsList.First().FriendlyName); } @@ -449,7 +449,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithCorrectUri() "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingUri); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingUri)!; Assert.IsTrue(new Uri("testlogger://logger").Equals(loggerRunSettings.LoggerSettingsList.First().Uri)); } @@ -501,7 +501,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithCorrectAssemblyQualifiedNa "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingAssemblyQualifiedName); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingAssemblyQualifiedName)!; Assert.AreEqual("Sample.Sample.Sample.SampleLogger, Sample.Sample.Logger, Version=0.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx", loggerRunSettings.LoggerSettingsList.First().AssemblyQualifiedName); } @@ -520,7 +520,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithCorrectCodeBase() "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingAssemblyQualifiedName); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingAssemblyQualifiedName)!; Assert.AreEqual(@"C:\Sample\Sample.TestLogger.dll", loggerRunSettings.LoggerSettingsList.First().CodeBase); } @@ -539,7 +539,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithCorrectEnabledAttributeVal "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingEnabledAttribute); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingEnabledAttribute)!; Assert.IsFalse(loggerRunSettings.LoggerSettingsList.First().IsEnabled); } @@ -558,7 +558,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithEnabledFalseIfInvalidEnabl "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingInvalidEnabledValue); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingInvalidEnabledValue)!; Assert.IsFalse(loggerRunSettings.LoggerSettingsList.First().IsEnabled); } @@ -577,7 +577,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerAsEnabledWhenEnabledAttributeN "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingEnabledAttribute); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingEnabledAttribute)!; Assert.IsTrue(loggerRunSettings.LoggerSettingsList.First().IsEnabled); } @@ -625,7 +625,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithCorrectValuesWhenMultipleA "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingMultipleAttributes); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingMultipleAttributes)!; Assert.AreEqual("TestLoggerWithParameterExtension", loggerRunSettings.LoggerSettingsList.First().FriendlyName); Assert.IsTrue(new Uri("testlogger://logger").Equals(loggerRunSettings.LoggerSettingsList.First().Uri)); Assert.AreEqual("Sample.Sample.Sample.SampleLogger, Sample.Sample.Logger, Version=0.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx", loggerRunSettings.LoggerSettingsList.First().AssemblyQualifiedName); @@ -648,7 +648,7 @@ public void GetLoggerRunSettingsShouldReturnLoggerWithCorrectValuesWhenCaseSensi "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingAttributesWithRandomCasing); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithLoggerHavingAttributesWithRandomCasing)!; Assert.AreEqual("TestLoggerWithParameterExtension", loggerRunSettings.LoggerSettingsList.First().FriendlyName); Assert.IsTrue(new Uri("testlogger://logger").Equals(loggerRunSettings.LoggerSettingsList.First().Uri)); Assert.AreEqual("Sample.Sample.Sample.SampleLogger, Sample.Sample.Logger, Version=0.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx", loggerRunSettings.LoggerSettingsList.First().AssemblyQualifiedName); @@ -729,7 +729,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggerRunSettingsWhenLoggerRunS "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggerRunSettingsNode); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggerRunSettingsNode)!; Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); } @@ -744,7 +744,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggerRunSettingsWhenLoggerRunS "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggerRunSettingsNode); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggerRunSettingsNode)!; Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); } @@ -826,7 +826,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggersWhenLoggersIsEmpty() "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggersNode); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggersNode)!; Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); } @@ -843,7 +843,7 @@ public void GetLoggerRunSettingsShouldReturnEmptyLoggersWhenLoggersIsSelfEnding( "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggersNode); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithEmptyLoggersNode)!; Assert.AreEqual(0, loggerRunSettings.LoggerSettingsList.Count); } @@ -931,14 +931,14 @@ public void GetLoggerRunSettingsShouldReturnConfigurationElementIfPresentInLogge "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithConfigurationElementInLoggerNode); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithConfigurationElementInLoggerNode)!; var expectedConfigurationElement = new XmlDocument().CreateElement("ConfiGUration"); expectedConfigurationElement.InnerXml = "Value1Value2"; Assert.AreEqual(expectedConfigurationElement.Name, - loggerRunSettings.LoggerSettingsList.First().Configuration.Name); + loggerRunSettings.LoggerSettingsList.First().Configuration!.Name); Assert.AreEqual(expectedConfigurationElement.InnerXml, - loggerRunSettings.LoggerSettingsList.First().Configuration.InnerXml); + loggerRunSettings.LoggerSettingsList.First().Configuration!.InnerXml); } [TestMethod] @@ -1043,7 +1043,7 @@ public void GetLoggerRunSettingsShouldReturnMultipleLoggersIfPresent() "; var loggerRunSettings = - XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithMultipleLoggers); + XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithMultipleLoggers)!; Assert.AreEqual(3, loggerRunSettings.LoggerSettingsList.Count); @@ -1054,12 +1054,12 @@ public void GetLoggerRunSettingsShouldReturnMultipleLoggersIfPresent() Assert.IsTrue(string.IsNullOrWhiteSpace(loggerFirst.AssemblyQualifiedName)); Assert.IsTrue(string.IsNullOrWhiteSpace(loggerFirst.CodeBase)); Assert.IsTrue(loggerFirst.IsEnabled); - Assert.AreEqual("Value1Value2", loggerFirst.Configuration.InnerXml); + Assert.AreEqual("Value1Value2", loggerFirst.Configuration!.InnerXml); // 2nd logger var loggerSecond = loggerRunSettings.LoggerSettingsList[1]; Assert.AreEqual("TestLogger", loggerSecond.FriendlyName); - Assert.AreEqual(new Uri("testlogger://logger").ToString(), loggerSecond.Uri.ToString()); + Assert.AreEqual(new Uri("testlogger://logger").ToString(), loggerSecond.Uri!.ToString()); Assert.AreEqual("Sample.Sample.Sample.SampleLogger, Sample.Sample.Logger, Version=0.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx", loggerSecond.AssemblyQualifiedName); Assert.AreEqual(@"C:\Sample\Sample.TestLogger.dll", loggerSecond.CodeBase); Assert.IsFalse(loggerSecond.IsEnabled); @@ -1068,11 +1068,11 @@ public void GetLoggerRunSettingsShouldReturnMultipleLoggersIfPresent() // 3rd logger var loggerThird = loggerRunSettings.LoggerSettingsList[2]; Assert.IsTrue(string.IsNullOrWhiteSpace(loggerThird.FriendlyName)); - Assert.AreEqual(new Uri("testlogger://loggerTemp").ToString(), loggerThird.Uri.ToString()); + Assert.AreEqual(new Uri("testlogger://loggerTemp").ToString(), loggerThird.Uri!.ToString()); Assert.IsTrue(string.IsNullOrWhiteSpace(loggerThird.AssemblyQualifiedName)); Assert.IsTrue(string.IsNullOrWhiteSpace(loggerThird.CodeBase)); Assert.IsTrue(loggerThird.IsEnabled); - Assert.AreEqual("Value3Value4", loggerThird.Configuration.InnerXml); + Assert.AreEqual("Value3Value4", loggerThird.Configuration!.InnerXml); } [TestMethod] @@ -1094,7 +1094,7 @@ public void GetLoggerRunSettingsShouldReturnLoggersWhenLoggerHasSelfEndingTag() "; var loggerRunSettings = - XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithSelfEndingLoggers); + XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithSelfEndingLoggers)!; Assert.AreEqual(3, loggerRunSettings.LoggerSettingsList.Count); Assert.AreEqual("TestLoggerWithParameterExtension", loggerRunSettings.LoggerSettingsList[0].FriendlyName); @@ -1127,14 +1127,14 @@ public void GetLoggerRunSettingsShouldReturnLastConfigurationElementIfMultiplePr "; - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithMultipleConfigurationElements); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runSettingsWithMultipleConfigurationElements)!; var expectedConfigurationElement = new XmlDocument().CreateElement("ConfiGUration"); expectedConfigurationElement.InnerXml = "Value3Value4"; Assert.AreEqual(expectedConfigurationElement.Name, - loggerRunSettings.LoggerSettingsList.First().Configuration.Name); + loggerRunSettings.LoggerSettingsList.First().Configuration!.Name); Assert.AreEqual(expectedConfigurationElement.InnerXml, - loggerRunSettings.LoggerSettingsList.First().Configuration.InnerXml); + loggerRunSettings.LoggerSettingsList.First().Configuration!.InnerXml); } #endregion diff --git a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs index c743b7838e..e96b41e84d 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs @@ -45,7 +45,7 @@ public void DiscoverTests(string projectName, double expectedNumberOfTests) vstestConsoleWrapper.DiscoverTests(assetPath, GetDefaultRunSettings(), options, discoveryEventHandler2); vstestConsoleWrapper.EndSession(); } - Assert.AreEqual(expectedNumberOfTests, discoveryEventHandler2.Metrics[TelemetryDataConstants.TotalTestsDiscovered]); + Assert.AreEqual(expectedNumberOfTests, discoveryEventHandler2.Metrics![TelemetryDataConstants.TotalTestsDiscovered]); PostTelemetry(discoveryEventHandler2.Metrics, perfAnalyzer, projectName); } @@ -88,7 +88,7 @@ public void DiscoverTestsWithDefaultAdaptersSkipped(string projectName, double e vstestConsoleWrapper.EndSession(); } - Assert.AreEqual(expectedNumberOfTests, discoveryEventHandler2.Metrics[TelemetryDataConstants.TotalTestsDiscovered]); + Assert.AreEqual(expectedNumberOfTests, discoveryEventHandler2.Metrics![TelemetryDataConstants.TotalTestsDiscovered]); PostTelemetry(discoveryEventHandler2.Metrics, perfAnalyzer, projectName); } } diff --git a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/DiscoveryEventHandler.cs b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/DiscoveryEventHandler.cs index bc609dc574..3c086ff3b7 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/DiscoveryEventHandler.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/DiscoveryEventHandler.cs @@ -20,19 +20,19 @@ public class DiscoveryEventHandler2 : ITestDiscoveryEventsHandler2 /// /// Gets the metrics. /// - public IDictionary Metrics { get; private set; } = new Dictionary(); + public IDictionary? Metrics { get; private set; } = new Dictionary(); public void HandleRawMessage(string rawMessage) { // No Op } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { // No Op } - public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable lastChunk) + public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable? lastChunk) { if (lastChunk != null) { @@ -42,7 +42,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete Metrics = discoveryCompleteEventArgs.Metrics; } - public void HandleDiscoveredTests(IEnumerable discoveredTestCases) + public void HandleDiscoveredTests(IEnumerable? discoveredTestCases) { if (discoveredTestCases != null) { diff --git a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/RunEventHandler.cs b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/RunEventHandler.cs index 3f7746d29c..3dff609130 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/RunEventHandler.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/EventHandler/RunEventHandler.cs @@ -20,7 +20,7 @@ public class RunEventHandler : ITestRunEventsHandler /// /// Gets the metrics. /// - public IDictionary Metrics { get; private set; } = new Dictionary(); + public IDictionary? Metrics { get; private set; } = new Dictionary(); /// /// Gets the log message. @@ -32,16 +32,16 @@ public RunEventHandler() TestResults = new List(); } - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { LogMessages.Add($"[{level.ToString().ToUpperInvariant()}]: {message}"); } public void HandleTestRunComplete( TestRunCompleteEventArgs testRunCompleteArgs, - TestRunChangedEventArgs lastChunkArgs, - ICollection runContextAttachments, - ICollection executorUris) + TestRunChangedEventArgs? lastChunkArgs, + ICollection? runContextAttachments, + ICollection? executorUris) { if (lastChunkArgs != null && lastChunkArgs.NewTestResults != null) { @@ -55,7 +55,7 @@ public void HandleTestRunComplete( } } - public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs) + public void HandleTestRunStatsChange(TestRunChangedEventArgs? testRunChangedArgs) { if (testRunChangedArgs != null && testRunChangedArgs.NewTestResults != null) { diff --git a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs index d0c09ec27a..77886038e2 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs @@ -46,7 +46,7 @@ public void RunTests(string projectName, double expectedNumberOfTests) vstestConsoleWrapper.EndSession(); } - Assert.AreEqual(expectedNumberOfTests, runEventHandler.Metrics[TelemetryDataConstants.TotalTestsRun]); + Assert.AreEqual(expectedNumberOfTests, runEventHandler.Metrics![TelemetryDataConstants.TotalTestsRun]); PostTelemetry(runEventHandler.Metrics, perfAnalyzer, projectName); } @@ -87,7 +87,7 @@ public void RunTestsWithDefaultAdaptersSkipped(string projectName, double expect vstestConsoleWrapper.EndSession(); } - Assert.AreEqual(expectedNumberOfTests, runEventHandler.Metrics[TelemetryDataConstants.TotalTestsRun]); + Assert.AreEqual(expectedNumberOfTests, runEventHandler.Metrics![TelemetryDataConstants.TotalTestsRun]); PostTelemetry(runEventHandler.Metrics, perfAnalyzer, projectName); } } diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs index ccbd93865e..3ffd03908e 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs @@ -87,7 +87,7 @@ public void GetTestHostProcessStartInfoShouldIncludeFileNameFromSubFolderTestHos var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); - Assert.IsTrue(startInfo.FileName.EndsWith(Path.Combine(subFoler, "testhost.exe"))); + Assert.IsTrue(startInfo.FileName!.EndsWith(Path.Combine(subFoler, "testhost.exe"))); } [TestMethod] @@ -120,13 +120,13 @@ public void GetTestHostConnectionInfoShouldIncludeEndpointRoleAndChannelType() [TestMethod] public void GetTestHostProcessStartInfoShouldIncludeEmptyEnvironmentVariables() { - Assert.AreEqual(0, _startInfo.EnvironmentVariables.Count); + Assert.AreEqual(0, _startInfo.EnvironmentVariables!.Count); } [TestMethod] public void GetTestHostProcessStartInfoShouldIncludeEnvironmentVariables() { - var environmentVariables = new Dictionary { { "k1", "v1" } }; + var environmentVariables = new Dictionary { { "k1", "v1" } }; var info = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), environmentVariables, default); @@ -185,7 +185,7 @@ public void GetTestHostProcessStartInfoShouldNotUseMonoAsHostOnNonWindowsIfStart default); StringAssert.Contains(info.FileName, "TestHost" + Path.DirectorySeparatorChar + "testhost.exe"); - Assert.IsFalse(info.Arguments.Contains("TestHost" + Path.DirectorySeparatorChar + "testhost.exe")); + Assert.IsFalse(info.Arguments!.Contains("TestHost" + Path.DirectorySeparatorChar + "testhost.exe")); } [TestMethod] @@ -326,7 +326,7 @@ public void LaunchTestHostShouldReturnTestHostProcessId() It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny>(), + It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>())).Returns(Process.GetCurrentProcess()); @@ -553,7 +553,7 @@ private void ErrorCallBackTestHelper(string errorMessage, int exitCode) It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny>(), + It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>())) @@ -587,7 +587,7 @@ private void ExitCallBackTestHelper(int exitCode) It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny>(), + It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>())) diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs index 2dd103de21..8aee09f72e 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs @@ -176,7 +176,7 @@ public void GetTestHostProcessStartInfoShouldNotAddRuntimeConfigJsonIfNotExists( var startInfo = GetDefaultStartInfo(); - Assert.IsFalse(startInfo.Arguments.Contains("--runtimeconfig \"test.runtimeconfig.json\"")); + Assert.IsFalse(startInfo.Arguments!.Contains("--runtimeconfig \"test.runtimeconfig.json\"")); } [TestMethod] @@ -198,7 +198,7 @@ public void GetTestHostProcessStartInfoShouldNotAddDepsFileJsonIfNotExists() var startInfo = GetDefaultStartInfo(); - Assert.IsFalse(startInfo.Arguments.Contains("--depsfile \"test.deps.json\"")); + Assert.IsFalse(startInfo.Arguments!.Contains("--depsfile \"test.deps.json\"")); } [TestMethod] @@ -225,7 +225,7 @@ public void GetTestHostConnectionInfoShouldIncludeEndpointRoleAndChannelType() [TestMethod] public void GetTestHostProcessStartInfoShouldIncludeEnvironmentVariables() { - var environmentVariables = new Dictionary { { "k1", "v1" }, { "k2", "v2" } }; + var environmentVariables = new Dictionary { { "k1", "v1" }, { "k2", "v2" } }; _mockFileHelper.Setup(ph => ph.Exists("testhost.dll")).Returns(true); var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(_testSource, environmentVariables, _defaultConnectionInfo); @@ -482,7 +482,7 @@ public void LaunchTestHostAsyncShouldNotStartHostProcessIfCancellationTokenIsSet [TestMethod] public void LaunchTestHostShouldLaunchProcessWithEnvironmentVariables() { - var variables = new Dictionary { { "k1", "v1" }, { "k2", "v2" } }; + var variables = new Dictionary { { "k1", "v1" }, { "k2", "v2" } }; var startInfo = new TestProcessStartInfo { EnvironmentVariables = variables }; _dotnetHostManager.SetCustomLauncher(_mockTestHostLauncher.Object); @@ -492,7 +492,7 @@ public void LaunchTestHostShouldLaunchProcessWithEnvironmentVariables() processId.Wait(); Assert.IsTrue(processId.Result); - _mockTestHostLauncher.Verify(thl => thl.LaunchTestHost(It.Is(x => x.EnvironmentVariables.Equals(variables)), It.IsAny()), Times.Once); + _mockTestHostLauncher.Verify(thl => thl.LaunchTestHost(It.Is(x => x.EnvironmentVariables!.Equals(variables)), It.IsAny()), Times.Once); } [TestMethod] @@ -591,7 +591,7 @@ public async Task LaunchTestHostShouldLaunchProcessWithConnectionInfo() _dotnetHostManager.SetCustomLauncher(_mockTestHostLauncher.Object); await _dotnetHostManager.LaunchTestHostAsync(_defaultTestProcessStartInfo, CancellationToken.None); - _mockTestHostLauncher.Verify(thl => thl.LaunchTestHost(It.Is(x => x.Arguments.Equals(expectedArgs)), It.IsAny()), Times.Once); + _mockTestHostLauncher.Verify(thl => thl.LaunchTestHost(It.Is(x => x.Arguments!.Equals(expectedArgs)), It.IsAny()), Times.Once); } [TestMethod] @@ -705,7 +705,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathFromSourceDirect var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments.Contains(expectedTestHostPath)); + Assert.IsTrue(startInfo.Arguments!.Contains(expectedTestHostPath)); } [TestMethod] @@ -770,7 +770,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathFromDepsFile() var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments.Contains(testHostFullPath)); + Assert.IsTrue(startInfo.Arguments!.Contains(testHostFullPath)); } [TestMethod] @@ -837,7 +837,7 @@ public void GetTestHostProcessStartInfoShouldIncludeTestHostPathFromSourceDirect var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments.Contains(testHostPath)); + Assert.IsTrue(startInfo.Arguments!.Contains(testHostPath)); } [TestMethod] @@ -903,7 +903,7 @@ public void GetTestHostProcessStartInfoShouldSkipInvalidAdditionalProbingPaths() var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(new[] { sourcePath }, null, _defaultConnectionInfo); - Assert.IsTrue(startInfo.Arguments.Contains(testHostFullPath)); + Assert.IsTrue(startInfo.Arguments!.Contains(testHostFullPath)); } [TestMethod] @@ -921,13 +921,13 @@ public void GetTestHostProcessStartInfoShouldForwardDOTNET_ROOTEnvVarsForAppHost var startInfo = _dotnetHostManager.GetTestHostProcessStartInfo(_testSource, null, _defaultConnectionInfo); if (!string.IsNullOrEmpty(expectedValue)) { - Assert.AreEqual(1, startInfo.EnvironmentVariables.Count); + Assert.AreEqual(1, startInfo.EnvironmentVariables!.Count); Assert.IsNotNull(startInfo.EnvironmentVariables[envVar]); Assert.AreEqual(startInfo.EnvironmentVariables[envVar], expectedValue); } else { - Assert.AreEqual(0, startInfo.EnvironmentVariables.Count); + Assert.AreEqual(0, startInfo.EnvironmentVariables!.Count); } } @@ -1043,7 +1043,7 @@ public void ForwardDotnetRootEnvironmentVariableWhenTargetFrameworkIsLessThanNet """; _dotnetHostManager.Initialize(_mockMessageLogger.Object, runSettingsXml); - var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; + var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; // Sanity check Assert.AreEqual(0, startInfo.EnvironmentVariables.Count); @@ -1082,7 +1082,7 @@ public void ForwardDotnetRootEnvironmentVariableWhenIncorrectEnvVarDoesNothing(s """; _dotnetHostManager.Initialize(_mockMessageLogger.Object, runSettingsXml); - var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; + var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; // Act _dotnetHostManager.ForwardDotnetRootEnvironmentVariable(startInfo); @@ -1112,7 +1112,7 @@ public void ForwardDotnetRootEnvironmentVariableWhenTargetFrameworkIsGreaterOrEq """; _dotnetHostManager.Initialize(_mockMessageLogger.Object, runSettingsXml); - var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; + var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; // Sanity check Assert.AreEqual(0, startInfo.EnvironmentVariables.Count); @@ -1151,7 +1151,7 @@ public void ForwardDotnetRootEnvironmentVariableWhenTargetFrameworkIsGreaterOrEq """; _dotnetHostManager.Initialize(_mockMessageLogger.Object, runSettingsXml); - var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; + var startInfo = new TestProcessStartInfo { EnvironmentVariables = new Dictionary() }; // Sanity check Assert.AreEqual(0, startInfo.EnvironmentVariables.Count); @@ -1189,7 +1189,7 @@ private void ErrorCallBackTestHelper(string errorMessage, int exitCode) It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny>(), + It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>())) @@ -1213,7 +1213,7 @@ private void ExitCallBackTestHelper(int exitCode) It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny>(), + It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>())) diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs index c0e6c8292b..889e1d4aa7 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs @@ -23,9 +23,9 @@ public class InferRunSettingsHelperTests { private readonly IDictionary _sourceArchitectures; private readonly IDictionary _sourceFrameworks; - private readonly Framework _frameworkNet45 = Framework.FromString(".NETFramework,Version=4.5"); - private readonly Framework _frameworkNet46 = Framework.FromString(".NETFramework,Version=4.6"); - private readonly Framework _frameworkNet47 = Framework.FromString(".NETFramework,Version=4.7"); + private readonly Framework _frameworkNet45 = Framework.FromString(".NETFramework,Version=4.5")!; + private readonly Framework _frameworkNet46 = Framework.FromString(".NETFramework,Version=4.6")!; + private readonly Framework _frameworkNet47 = Framework.FromString(".NETFramework,Version=4.7")!; private const string MultiTargettingForwardLink = @"https://aka.ms/tp/vstest/multitargetingdoc?view=vs-2019"; public InferRunSettingsHelperTests() diff --git a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs index cc1d9ecb15..063ef2b0ae 100644 --- a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs +++ b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs @@ -894,7 +894,7 @@ public void StartTestRunShouldCompleteWithSingleTestAndMessage() mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -946,7 +946,7 @@ public async Task StartTestRunAsyncShouldCompleteWithSingleTestAndMessage() mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -1003,7 +1003,7 @@ public void StartTestRunShouldIncludeFilterInRequestPayload() // Assert. Assert.IsNotNull(receivedRequest); CollectionAssert.AreEqual(sources, receivedRequest.Sources); - Assert.AreEqual(filter, receivedRequest.TestPlatformOptions.TestCaseFilter, "The run request message should include test case filter"); + Assert.AreEqual(filter, receivedRequest.TestPlatformOptions!.TestCaseFilter, "The run request message should include test case filter"); } [TestMethod] @@ -1045,7 +1045,7 @@ public void StartTestRunWithCustomHostShouldComplete() mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -1106,7 +1106,7 @@ public async Task StartTestRunAsyncWithCustomHostShouldComplete() mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -1268,7 +1268,7 @@ public void StartTestRunWithCustomHostShouldIncludeFilterInRequestPayload() // Assert. Assert.IsNotNull(receivedRequest); CollectionAssert.AreEqual(sources, receivedRequest.Sources); - Assert.AreEqual(filter, receivedRequest.TestPlatformOptions.TestCaseFilter, "The run request message should include test case filter"); + Assert.AreEqual(filter, receivedRequest.TestPlatformOptions!.TestCaseFilter, "The run request message should include test case filter"); } [TestMethod] @@ -1361,7 +1361,7 @@ public void StartTestRunWithSelectedTestsShouldCompleteWithSingleTestAndMessage( mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -1412,7 +1412,7 @@ public async Task StartTestRunAsyncWithSelectedTestsShouldCompleteWithSingleTest mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -1471,10 +1471,10 @@ public void StartTestRunWithSelectedTestsHavingTraitsShouldReturnTestRunComplete _requestSender.StartTestRun(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedChangeEventArgs); - Assert.IsTrue(receivedChangeEventArgs.NewTestResults.Any()); + Assert.IsTrue(receivedChangeEventArgs.NewTestResults!.Any()); // Verify that the traits are passed through properly. - var traits = receivedChangeEventArgs.NewTestResults.ToArray()[0].TestCase.Traits; + var traits = receivedChangeEventArgs.NewTestResults!.ToArray()[0].TestCase.Traits; Assert.IsNotNull(traits); Assert.AreEqual("a", traits.ToArray()[0].Name); Assert.AreEqual("b", traits.ToArray()[0].Value); @@ -1524,10 +1524,10 @@ public async Task StartTestRunAsyncWithSelectedTestsHavingTraitsShouldReturnTest await _requestSender.StartTestRunAsync(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedChangeEventArgs); - Assert.IsTrue(receivedChangeEventArgs.NewTestResults.Any()); + Assert.IsTrue(receivedChangeEventArgs.NewTestResults!.Any()); // Verify that the traits are passed through properly. - var traits = receivedChangeEventArgs.NewTestResults.ToArray()[0].TestCase.Traits; + var traits = receivedChangeEventArgs.NewTestResults!.ToArray()[0].TestCase.Traits; Assert.IsNotNull(traits); Assert.AreEqual("a", traits.ToArray()[0].Name); Assert.AreEqual("b", traits.ToArray()[0].Value); @@ -1581,10 +1581,10 @@ public void StartTestRunWithSelectedTestsHavingTraitsShouldReturnTestRunStatsWit _requestSender.StartTestRun(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedChangeEventArgs); - Assert.IsTrue(receivedChangeEventArgs.NewTestResults.Any()); + Assert.IsTrue(receivedChangeEventArgs.NewTestResults!.Any()); // Verify that the traits are passed through properly. - var traits = receivedChangeEventArgs.NewTestResults.ToArray()[0].TestCase.Traits; + var traits = receivedChangeEventArgs.NewTestResults!.ToArray()[0].TestCase.Traits; Assert.IsNotNull(traits); Assert.AreEqual("a", traits.ToArray()[0].Name); Assert.AreEqual("b", traits.ToArray()[0].Value); @@ -1638,10 +1638,10 @@ public async Task StartTestRunAsyncWithSelectedTestsHavingTraitsShouldReturnTest await _requestSender.StartTestRunAsync(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); Assert.IsNotNull(receivedChangeEventArgs); - Assert.IsTrue(receivedChangeEventArgs.NewTestResults.Any()); + Assert.IsTrue(receivedChangeEventArgs.NewTestResults!.Any()); // Verify that the traits are passed through properly. - var traits = receivedChangeEventArgs.NewTestResults.ToArray()[0].TestCase.Traits; + var traits = receivedChangeEventArgs.NewTestResults!.ToArray()[0].TestCase.Traits; Assert.IsNotNull(traits); Assert.AreEqual("a", traits.ToArray()[0].Name); Assert.AreEqual("b", traits.ToArray()[0].Value); @@ -1684,7 +1684,7 @@ public void StartTestRunWithCustomHostWithSelectedTestsComplete() mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -1743,7 +1743,7 @@ public async Task StartTestRunWithCustomHostAsyncWithSelectedTestsShouldComplete mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { - Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); + Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults!.Any(), "TestResults must be passed properly"); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); @@ -1789,7 +1789,7 @@ public void StartTestRunWithCustomHostInParallelShouldCallCustomHostMultipleTime mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())) .Callback((startInfo) => { - if (startInfo.FileName.Equals(p1.FileName)) + if (startInfo.FileName!.Equals(p1.FileName)) { _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message2)); } @@ -1828,7 +1828,7 @@ public async Task StartTestRunWithCustomHostAsyncInParallelShouldCallCustomHostM mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())) .Callback((startInfo) => { - if (startInfo.FileName.Equals(p1.FileName)) + if (startInfo.FileName!.Equals(p1.FileName)) { _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message2)); } @@ -1964,12 +1964,12 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithZeroAttachment _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); - Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors.Count()); + Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors!.Count()); }); await _requestSender.ProcessTestRunAttachmentsAsync( new List { new AttachmentSet(new Uri("http://www.bing.com"), "a") }, - new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false) }, + new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) }, Constants.EmptyRunSettings, true, mockHandler.Object, @@ -2003,12 +2003,12 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachment( _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); - Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors.Count()); + Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors!.Count()); }); await _requestSender.ProcessTestRunAttachmentsAsync( new List { new AttachmentSet(new Uri("http://www.bing.com"), "a") }, - new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false) }, + new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) }, Constants.EmptyRunSettings, true, mockHandler.Object, @@ -2046,14 +2046,14 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachmentA _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); - Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors.Count()); + Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors!.Count()); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete))); await _requestSender.ProcessTestRunAttachmentsAsync( new List { new AttachmentSet(new Uri("http://www.bing.com"), "a") }, - new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false) }, + new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) }, Constants.EmptyRunSettings, false, mockHandler.Object, @@ -2098,7 +2098,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachmentA _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); - Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors.Count()); + Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors!.Count()); }); mockHandler.Setup(mh => mh.HandleTestRunAttachmentsProcessingProgress(It.IsAny())).Callback( @@ -2106,7 +2106,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachmentA await _requestSender.ProcessTestRunAttachmentsAsync( new List { new AttachmentSet(new Uri("http://www.bing.com"), "a") }, - new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false) }, + new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) }, Constants.EmptyRunSettings, false, mockHandler.Object, @@ -2145,7 +2145,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldSendCancelMessageIfCancell _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); - Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors.Count()); + Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors!.Count()); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback(() => { @@ -2155,7 +2155,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldSendCancelMessageIfCancell await _requestSender.ProcessTestRunAttachmentsAsync( new List { new AttachmentSet(new Uri("http://www.bing.com"), "a") }, - new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false) }, + new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) }, Constants.EmptyRunSettings, false, mockHandler.Object, @@ -2191,12 +2191,12 @@ public async Task ProcessTestRunAttachmentsAsyncShouldSendCancelMessageIfCancell _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); - Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors.Count()); + Assert.AreEqual(1, ((TestRunAttachmentsProcessingPayload)o).InvokedDataCollectors!.Count()); }); await _requestSender.ProcessTestRunAttachmentsAsync( new List { new AttachmentSet(new Uri("http://www.bing.com"), "a") }, - new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, false) }, + new List() { new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) }, Constants.EmptyRunSettings, true, mockHandler.Object, diff --git a/test/datacollector.PlatformTests/CustomDataCollector.cs b/test/datacollector.PlatformTests/CustomDataCollector.cs index f4723e1296..b1b9bf90d5 100644 --- a/test/datacollector.PlatformTests/CustomDataCollector.cs +++ b/test/datacollector.PlatformTests/CustomDataCollector.cs @@ -18,11 +18,11 @@ public class CustomDataCollector : ObjectModel.DataCollection.DataCollector, ITe private DataCollectionLogger? _logger; public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { _dataCollectionSink = dataSink; _context = environmentContext; diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index 86d6cd1cb7..19c995e71a 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -496,9 +496,9 @@ internal TestableDataCollectionManager(IDataCollectionAttachmentManager datacoll { } - protected override bool TryGetUriFromFriendlyName(string friendlyName, out string dataCollectorUri) + protected override bool TryGetUriFromFriendlyName(string? friendlyName, out string dataCollectorUri) { - if (friendlyName.Equals("CustomDataCollector")) + if (friendlyName!.Equals("CustomDataCollector")) { dataCollectorUri = "my://custom/datacollector"; return true; diff --git a/test/datacollector.UnitTests/DummyDataCollectors.cs b/test/datacollector.UnitTests/DummyDataCollectors.cs index 442c35df5b..614631d156 100644 --- a/test/datacollector.UnitTests/DummyDataCollectors.cs +++ b/test/datacollector.UnitTests/DummyDataCollectors.cs @@ -17,17 +17,17 @@ public class CustomDataCollector : ObjectModel.DataCollection.DataCollector, ITe public DataCollectionSink? DataSink { get; set; } public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } - public IEnumerable>? GetTestExecutionEnvironmentVariables() + public IEnumerable> GetTestExecutionEnvironmentVariables() { - return default; + return default!; } } @@ -35,11 +35,11 @@ public override void Initialize( public class CustomDataCollectorWithoutUri : ObjectModel.DataCollection.DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } } @@ -48,11 +48,11 @@ public override void Initialize( public class CustomDataCollectorWithoutFriendlyName : ObjectModel.DataCollection.DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } } @@ -62,11 +62,11 @@ public override void Initialize( public class CustomDataCollectorWithEmptyFriendlyName : ObjectModel.DataCollection.DataCollector { public override void Initialize( - XmlElement configurationElement, + XmlElement? configurationElement, DataCollectionEvents events, DataCollectionSink dataSink, DataCollectionLogger logger, - DataCollectionEnvironmentContext environmentContext) + DataCollectionEnvironmentContext? environmentContext) { } } diff --git a/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs b/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs index 33be9826db..21c42bef50 100644 --- a/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs +++ b/test/datacollector.UnitTests/TestPlatformDataCollectionEventsTests.cs @@ -37,7 +37,7 @@ public void RaiseEventsShouldRaiseEventsIfSessionStartEventArgsIsPassed() _context = new DataCollectionContext(testCase); _events.SessionStart += SessionStartMessageHandler; - var eventArgs = new SessionStartEventArgs(_context, new Dictionary()); + var eventArgs = new SessionStartEventArgs(_context, new Dictionary()); _events.RaiseEvent(eventArgs); Assert.IsTrue(_isEventRaised); @@ -50,7 +50,7 @@ public void RaiseEventsShouldNotRaiseEventsIfEventIsNotRegisterd() var testCase = new TestCase(); _context = new DataCollectionContext(testCase); - var eventArgs = new SessionStartEventArgs(_context, new Dictionary()); + var eventArgs = new SessionStartEventArgs(_context, new Dictionary()); _events.RaiseEvent(eventArgs); Assert.IsFalse(_isEventRaised); @@ -65,7 +65,7 @@ public void RaiseEventsShouldNotRaiseEventsIfEventIsUnRegisterd() _events.SessionStart += SessionStartMessageHandler; _events.SessionStart -= SessionStartMessageHandler; - var eventArgs = new SessionStartEventArgs(_context, new Dictionary()); + var eventArgs = new SessionStartEventArgs(_context, new Dictionary()); _events.RaiseEvent(eventArgs); Assert.IsFalse(_isEventRaised); diff --git a/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs b/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs index 9ad86673d9..dd6e706cd5 100644 --- a/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs +++ b/test/datacollector.UnitTests/TestPlatformDataCollectionLoggerTests.cs @@ -37,7 +37,7 @@ public void LogErrorShouldThrowExceptionIfContextIsNull() { Assert.ThrowsException(() => _logger.LogError(null!, string.Empty)); - Assert.ThrowsException(() => _logger.LogError(null, new Exception())); + Assert.ThrowsException(() => _logger.LogError(null!, new Exception())); Assert.ThrowsException(() => _logger.LogError(null!, string.Empty, new Exception())); } @@ -53,7 +53,7 @@ public void LogErrorShouldThrowExceptionIfTextIsNull() [TestMethod] public void LogErrorShouldThrowExceptionIfExceptionIsNull() { - Assert.ThrowsException(() => _logger.LogError(_context, (Exception?)null)); + Assert.ThrowsException(() => _logger.LogError(_context, (Exception?)null!)); Assert.ThrowsException(() => _logger.LogError(_context, string.Empty, null!)); } diff --git a/test/testhost.UnitTests/NullableHelpers.cs b/test/testhost.UnitTests/NullableHelpers.cs new file mode 100644 index 0000000000..9bf63d5169 --- /dev/null +++ b/test/testhost.UnitTests/NullableHelpers.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// This code is auto-generated. Changes to this file will be lost! +// This T4 file is copied in various projects because inclusion as link or through shared project +// doesn't allow to generate the C# file locally. If some modification is required, please update +// all instances. +// + +#nullable enable + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace testhost.UnitTests; + +internal static class StringUtils +{ + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrEmpty(value); + + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrWhiteSpace(value); +} + +[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] +internal static class TPDebug +{ + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b) + => Debug.Assert(b); + + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b, string message) + => Debug.Assert(b, message); +} diff --git a/test/testhost.UnitTests/NullableHelpers.tt b/test/testhost.UnitTests/NullableHelpers.tt new file mode 100644 index 0000000000..7e3d8e7270 --- /dev/null +++ b/test/testhost.UnitTests/NullableHelpers.tt @@ -0,0 +1,45 @@ +<#@ template debug="true" hostspecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ assembly name="System.Core" #> +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// This code is auto-generated. Changes to this file will be lost! +// This T4 file is copied in various projects because inclusion as link or through shared project +// doesn't allow to generate the C# file locally. If some modification is required, please update +// all instances. +// + +#nullable enable + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace <#= System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint") #>; + +internal static class StringUtils +{ + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrEmpty(value); + + /// + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrWhiteSpace(value); +} + +[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] +internal static class TPDebug +{ + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b) + => Debug.Assert(b); + + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b, string message) + => Debug.Assert(b, message); +} diff --git a/test/testhost.UnitTests/TestHostTraceListenerTests.cs b/test/testhost.UnitTests/TestHostTraceListenerTests.cs index b2413e1353..bc35350598 100644 --- a/test/testhost.UnitTests/TestHostTraceListenerTests.cs +++ b/test/testhost.UnitTests/TestHostTraceListenerTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -// define trace and debug to trigger the Debug.Assert calls even when we build in Release +// define trace and debug to trigger the TPDebug.Assert calls even when we build in Release #define DEBUG #if NETCOREAPP diff --git a/test/testhost.UnitTests/testhost.UnitTests.csproj b/test/testhost.UnitTests/testhost.UnitTests.csproj index 843ee2e344..5ab93eee41 100644 --- a/test/testhost.UnitTests/testhost.UnitTests.csproj +++ b/test/testhost.UnitTests/testhost.UnitTests.csproj @@ -20,5 +20,24 @@ + + + + + + NullableHelpers.cs + TextTemplatingFileGenerator + + + + + + + + True + True + NullableHelpers.tt + + diff --git a/test/vstest.ProgrammerTests/Fakes/FakeOutput.cs b/test/vstest.ProgrammerTests/Fakes/FakeOutput.cs index 0118b3f950..cfbbb41b2f 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeOutput.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeOutput.cs @@ -13,13 +13,13 @@ internal class FakeOutput : IOutput public StringBuilder CurrentLine { get; } = new(); public List Lines { get; } = new(); - public void Write(string message, OutputLevel level) + public void Write(string? message, OutputLevel level) { Messages.Add(new OutputMessage(message, level, isNewLine: false)); CurrentLine.Append(message); } - public void WriteLine(string message, OutputLevel level) + public void WriteLine(string? message, OutputLevel level) { Lines.Add(CurrentLine + message); CurrentLine.Clear(); diff --git a/test/vstest.ProgrammerTests/Fakes/FakeProcess.cs b/test/vstest.ProgrammerTests/Fakes/FakeProcess.cs index cde1a8024b..adce51bfc4 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeProcess.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeProcess.cs @@ -13,7 +13,7 @@ internal class FakeProcess public string Path { get; } public string? Arguments { get; set; } public string WorkingDirectory { get; } - public IDictionary EnvironmentVariables { get; } + public IDictionary EnvironmentVariables { get; } // TODO: Throw if already set public Action? ErrorCallback { get; set; } // TODO: Throw if already set @@ -28,14 +28,14 @@ internal class FakeProcess public bool Exited { get; private set; } public TestProcessStartInfo TestProcessStartInfo { get; internal set; } - public FakeProcess(FakeErrorAggregator fakeErrorAggregator, string path, string? arguments = null, string? workingDirectory = null, IDictionary? environmentVariables = null, Action? errorCallback = null, Action? exitCallBack = null, Action? outputCallback = null) + public FakeProcess(FakeErrorAggregator fakeErrorAggregator, string path, string? arguments = null, string? workingDirectory = null, IDictionary? environmentVariables = null, Action? errorCallback = null, Action? exitCallBack = null, Action? outputCallback = null) { FakeErrorAggregator = fakeErrorAggregator; Path = path; Name = System.IO.Path.GetFileName(path); Arguments = arguments; WorkingDirectory = workingDirectory ?? System.IO.Path.GetDirectoryName(path) ?? throw new InvalidOperationException($"Path {path} does not have a parent directory."); - EnvironmentVariables = environmentVariables ?? new Dictionary(); + EnvironmentVariables = environmentVariables ?? new Dictionary(); ErrorCallback = errorCallback; ExitCallback = exitCallBack; OutputCallback = outputCallback; diff --git a/test/vstest.ProgrammerTests/Fakes/FakeProcessHelper.cs b/test/vstest.ProgrammerTests/Fakes/FakeProcessHelper.cs index 596848899e..4729970c96 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeProcessHelper.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeProcessHelper.cs @@ -80,7 +80,7 @@ public string GetTestEngineDirectory() throw new NotImplementedException(); } - public object LaunchProcess(string processPath, string arguments, string workingDirectory, IDictionary? environmentVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallback) + public object LaunchProcess(string processPath, string? arguments, string? workingDirectory, IDictionary? environmentVariables, Action? errorCallback, Action? exitCallBack, Action? outputCallback) { // TODO: Throw if setting says we can't start new processes; var process = new FakeProcess(FakeErrorAggregator, processPath, arguments, workingDirectory, environmentVariables, errorCallback, exitCallBack, outputCallback); diff --git a/test/vstest.ProgrammerTests/Fakes/FakeTestRuntimeProvider.cs b/test/vstest.ProgrammerTests/Fakes/FakeTestRuntimeProvider.cs index 0aa36d4629..266095e8f9 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeTestRuntimeProvider.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeTestRuntimeProvider.cs @@ -51,15 +51,12 @@ public FakeTestRuntimeProvider(FakeProcessHelper fakeProcessHelper, FakeProcess // TODO: Validate the process we are passed is actually the same as TestHostProcess // TODO: Validate we already started the process. var process = (FakeProcess)p; - if (HostExited != null) - { - // TODO: When we exit, eventually there are no subscribers, maybe we should review if we don't lose the error output sometimes, in unnecessary way - HostExited(this, new HostProviderEventArgs(process.ErrorOutput, process.ExitCode, process.Id)); - } + // TODO: When we exit, eventually there are no subscribers, maybe we should review if we don't lose the error output sometimes, in unnecessary way + HostExited?.Invoke(this, new HostProviderEventArgs(process.ErrorOutput!, process.ExitCode, process.Id)); }; } - public bool CanExecuteCurrentRunConfiguration(string runsettingsXml) + public bool CanExecuteCurrentRunConfiguration(string? runsettingsXml) { // x86 // Framework40 @@ -80,7 +77,7 @@ public TestHostConnectionInfo GetTestHostConnectionInfo() return FakeCommunicationEndpoint.TestHostConnectionInfo; } - public TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary environmentVariables, TestRunnerConnectionInfo connectionInfo) + public TestProcessStartInfo GetTestHostProcessStartInfo(IEnumerable sources, IDictionary? environmentVariables, TestRunnerConnectionInfo connectionInfo) { // TODO: do we need to do more here? How to link testhost to the fake one we "start"? return TestHostProcess.TestProcessStartInfo; @@ -99,7 +96,7 @@ public IEnumerable GetTestSources(IEnumerable sources) return sources; } - public void Initialize(IMessageLogger logger, string runsettingsXml) + public void Initialize(IMessageLogger? logger, string runsettingsXml) { // TODO: this is called twice, is that okay? // TODO: and also by HandlePartialRunComplete after the test run has completed and we aborted because the client disconnected @@ -113,11 +110,8 @@ public Task LaunchTestHostAsync(TestProcessStartInfo testHostStartInfo, Ca throw new InvalidOperationException($"Tried to start a different process than the one associated with this provider: File name is {testHostStartInfo.FileName} is not the same as the fake process associated with this provider {TestHostProcess.TestProcessStartInfo.FileName}."); FakeProcessHelper.StartFakeProcess(TestHostProcess); + HostLaunched?.Invoke(this, new HostProviderEventArgs("Fake testhost launched", 0, TestHostProcess.Id)); - if (HostLaunched != null) - { - HostLaunched(this, new HostProviderEventArgs("Fake testhost launched", 0, TestHostProcess.Id)); - } return Task.FromResult(true); } diff --git a/test/vstest.ProgrammerTests/Fakes/FakeTestSessionEventsHandler.cs b/test/vstest.ProgrammerTests/Fakes/FakeTestSessionEventsHandler.cs index a1791e77a4..616c6aa966 100644 --- a/test/vstest.ProgrammerTests/Fakes/FakeTestSessionEventsHandler.cs +++ b/test/vstest.ProgrammerTests/Fakes/FakeTestSessionEventsHandler.cs @@ -15,13 +15,13 @@ public FakeTestSessionEventsHandler(FakeErrorAggregator fakeErrorAggregator) _fakeErrorAggregator = fakeErrorAggregator; } - public List AllEvents { get; } = new(); + public List AllEvents { get; } = new(); public List LoggedMessages { get; } = new(); public List RawMessages { get; } = new(); - public List StartTestSessionCompleteEvents { get; } = new(); - public List StopTestSessionCompleteEvents { get; } = new(); + public List StartTestSessionCompleteEvents { get; } = new(); + public List StopTestSessionCompleteEvents { get; } = new(); - public void HandleLogMessage(TestMessageLevel level, string message) + public void HandleLogMessage(TestMessageLevel level, string? message) { var msg = new TestMessage(level, message); AllEvents.Add(msg); @@ -34,13 +34,13 @@ public void HandleRawMessage(string rawMessage) RawMessages.Add(rawMessage); } - public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs eventArgs) + public void HandleStartTestSessionComplete(StartTestSessionCompleteEventArgs? eventArgs) { AllEvents.Add(eventArgs); StartTestSessionCompleteEvents.Add(eventArgs); } - public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs eventArgs) + public void HandleStopTestSessionComplete(StopTestSessionCompleteEventArgs? eventArgs) { AllEvents.Add(eventArgs); StopTestSessionCompleteEvents.Add(eventArgs); diff --git a/test/vstest.ProgrammerTests/Fakes/Fixture.cs b/test/vstest.ProgrammerTests/Fakes/Fixture.cs index afddd891d9..3a073442c2 100644 --- a/test/vstest.ProgrammerTests/Fakes/Fixture.cs +++ b/test/vstest.ProgrammerTests/Fakes/Fixture.cs @@ -40,8 +40,8 @@ internal class Fixture : IDisposable public TestRequestManager? TestRequestManager { get; private set; } public ProtocolConfig ProtocolConfig { get; internal set; } - public List ExecutedTests => TestRunEventsRegistrar.RunChangedEvents.SelectMany(er => er.Data.NewTestResults).ToList(); - public List DiscoveredTests => TestDiscoveryEventsRegistrar.DiscoveredTestsEvents.SelectMany(er => er.Data.DiscoveredTestCases).ToList(); + public List ExecutedTests => TestRunEventsRegistrar.RunChangedEvents.SelectMany(er => er.Data.NewTestResults!).ToList(); + public List DiscoveredTests => TestDiscoveryEventsRegistrar.DiscoveredTestsEvents.SelectMany(er => er.Data.DiscoveredTestCases!).ToList(); public List LoggedWarnings => TestRunEventsRegistrar.LoggedWarnings.Concat(TestDiscoveryEventsRegistrar.LoggedWarnings).ToList(); diff --git a/test/vstest.ProgrammerTests/Fakes/OutputMessage.cs b/test/vstest.ProgrammerTests/Fakes/OutputMessage.cs index 0fac9f619d..694539e202 100644 --- a/test/vstest.ProgrammerTests/Fakes/OutputMessage.cs +++ b/test/vstest.ProgrammerTests/Fakes/OutputMessage.cs @@ -7,14 +7,14 @@ namespace vstest.ProgrammerTests.Fakes; internal class OutputMessage { - public OutputMessage(string message, OutputLevel level, bool isNewLine) + public OutputMessage(string? message, OutputLevel level, bool isNewLine) { Message = message; Level = level; IsNewLine = isNewLine; } - public string Message { get; } + public string? Message { get; } public OutputLevel Level { get; } public bool IsNewLine { get; } } diff --git a/test/vstest.ProgrammerTests/Fakes/TestMessage.cs b/test/vstest.ProgrammerTests/Fakes/TestMessage.cs index 9a9ca99dcb..926fbfb485 100644 --- a/test/vstest.ProgrammerTests/Fakes/TestMessage.cs +++ b/test/vstest.ProgrammerTests/Fakes/TestMessage.cs @@ -7,12 +7,12 @@ namespace vstest.ProgrammerTests.Fakes; internal class TestMessage { - public TestMessage(TestMessageLevel level, string message) + public TestMessage(TestMessageLevel level, string? message) { Level = level; Message = message; } public TestMessageLevel Level { get; } - public string Message { get; } + public string? Message { get; } } diff --git a/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs b/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs index 8905e5fa6d..3dfc252bee 100644 --- a/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs +++ b/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs @@ -501,7 +501,7 @@ public async Task E() await testRequestManager.ExecuteWithAbort(tm => tm.StartTestSession(startTestSessionPayload, testHostLauncher: null, fixture.TestSessionEventsHandler, fixture.ProtocolConfig)); // You need to pass this on, otherwise it will ignore the test session that you just started. This is a by product of being able to start multiple test sessions. - var testSessionInfo = fixture.TestSessionEventsHandler.StartTestSessionCompleteEvents.Single().TestSessionInfo; + var testSessionInfo = fixture.TestSessionEventsHandler.StartTestSessionCompleteEvents.Single()!.TestSessionInfo; var testRunRequestPayload = new TestRunRequestPayload { diff --git a/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs b/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs index df27595f0a..dfce3d50e2 100644 --- a/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs +++ b/test/vstest.console.UnitTests/CommandLine/InferHelperTests.cs @@ -20,11 +20,11 @@ public class InferHelperTests private readonly InferHelper _inferHelper; private readonly Framework _defaultFramework = Framework.DefaultFramework; private readonly Architecture _defaultArchitecture = Architecture.X64; - private readonly Framework _frameworkNet45 = Framework.FromString(".NETFramework,Version=4.5"); - private readonly Framework _frameworkNet46 = Framework.FromString(".NETFramework,Version=4.6"); - private readonly Framework _frameworkNet47 = Framework.FromString(".NETFramework,Version=4.7"); - private readonly Framework _frameworkCore10 = Framework.FromString(".NETCoreApp,Version=1.0"); - private readonly Framework _frameworkCore11 = Framework.FromString(".NETCoreApp,Version=1.1"); + private readonly Framework _frameworkNet45 = Framework.FromString(".NETFramework,Version=4.5")!; + private readonly Framework _frameworkNet46 = Framework.FromString(".NETFramework,Version=4.6")!; + private readonly Framework _frameworkNet47 = Framework.FromString(".NETFramework,Version=4.7")!; + private readonly Framework _frameworkCore10 = Framework.FromString(".NETCoreApp,Version=1.0")!; + private readonly Framework _frameworkCore11 = Framework.FromString(".NETCoreApp,Version=1.1")!; public InferHelperTests() { @@ -190,7 +190,7 @@ public void AutoDetectFrameworkShouldReturnFramework46On46Sources() [TestMethod] public void AutoDetectFrameworkShouldReturnFrameworkUap10ForAppxFiles() { - var fx = Framework.FromString(Constants.DotNetFrameworkUap10); + var fx = Framework.FromString(Constants.DotNetFrameworkUap10)!; var assemblyName = "uwp10.appx"; SetupAndValidateForSingleAssembly(assemblyName, fx, false); } @@ -198,7 +198,7 @@ public void AutoDetectFrameworkShouldReturnFrameworkUap10ForAppxFiles() [TestMethod] public void AutoDetectFrameworkShouldReturnFrameworkUap10ForMsixFiles() { - var fx = Framework.FromString(Constants.DotNetFrameworkUap10); + var fx = Framework.FromString(Constants.DotNetFrameworkUap10)!; var assemblyName = "uwp10.msix"; SetupAndValidateForSingleAssembly(assemblyName, fx, false); } @@ -206,7 +206,7 @@ public void AutoDetectFrameworkShouldReturnFrameworkUap10ForMsixFiles() [TestMethod] public void AutoDetectFrameworkShouldReturnFrameworkUap10ForAppxrecipeFiles() { - var fx = Framework.FromString(Constants.DotNetFrameworkUap10); + var fx = Framework.FromString(Constants.DotNetFrameworkUap10)!; var assemblyName = "uwp10.appxrecipe"; SetupAndValidateForSingleAssembly(assemblyName, fx, false); } @@ -214,7 +214,7 @@ public void AutoDetectFrameworkShouldReturnFrameworkUap10ForAppxrecipeFiles() [TestMethod] public void AutoDetectFrameworkShouldReturnDefaultFullFrameworkForJsFiles() { - var fx = Framework.FromString(Constants.DotNetFramework40); + var fx = Framework.FromString(Constants.DotNetFramework40)!; var assemblyName = "vstests.js"; SetupAndValidateForSingleAssembly(assemblyName, fx, false); } diff --git a/test/vstest.console.UnitTests/ExecutorUnitTests.cs b/test/vstest.console.UnitTests/ExecutorUnitTests.cs index e20cad635e..5d5fc9787d 100644 --- a/test/vstest.console.UnitTests/ExecutorUnitTests.cs +++ b/test/vstest.console.UnitTests/ExecutorUnitTests.cs @@ -74,7 +74,7 @@ public void ExecutorShouldNotPrintsSplashScreenIfNoLogoPassed() // Just check first 20 characters - don't need to check whole thing as assembly version is variable Assert.IsFalse( mockOutput.Messages.First() - .Message.Contains(CommandLineResources.MicrosoftCommandLineTitle.Substring(0, 20)), + .Message!.Contains(CommandLineResources.MicrosoftCommandLineTitle.Substring(0, 20)), "First Printed message must be Microsoft Copyright"); } @@ -86,7 +86,7 @@ public void ExecutorShouldSanitizeNoLogoInput() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message.Contains(CommandLineResources.NoArgumentsProvided))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(CommandLineResources.NoArgumentsProvided))); } /// @@ -100,7 +100,7 @@ public void ExecutorEmptyArgsPrintsErrorAndHelpMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message.Contains(CommandLineResources.NoArgumentsProvided))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(CommandLineResources.NoArgumentsProvided))); } [TestMethod] @@ -112,7 +112,7 @@ public void ExecutorWithInvalidArgsShouldPrintErrorMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); } [TestMethod] @@ -124,7 +124,7 @@ public void ExecutorWithInvalidArgsShouldPrintHowToUseHelpOption() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); } [TestMethod] @@ -136,7 +136,7 @@ public void ExecutorWithInvalidArgsAndValueShouldPrintErrorMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); } /// @@ -149,7 +149,7 @@ public void ExecuteShouldInitializeDefaultRunsettings() _ = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(null); RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(RunSettingsManager.Instance.ActiveRunSettings.SettingsXml); Assert.AreEqual(Constants.DefaultResultsDirectory, runConfiguration.ResultsDirectory); - Assert.AreEqual(Framework.DefaultFramework.ToString(), runConfiguration.TargetFramework.ToString()); + Assert.AreEqual(Framework.DefaultFramework.ToString(), runConfiguration.TargetFramework!.ToString()); Assert.AreEqual(Constants.DefaultPlatform, runConfiguration.TargetPlatform); } @@ -179,7 +179,7 @@ public void ExecuteShouldExitWithErrorOnResponseFileException() var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); - var errorMessageCount = mockOutput.Messages.Count(msg => msg.Level == OutputLevel.Error && msg.Message.Contains( + var errorMessageCount = mockOutput.Messages.Count(msg => msg.Level == OutputLevel.Error && msg.Message!.Contains( string.Format(CultureInfo.CurrentCulture, CommandLineResources.OpenResponseFileError, args[0].Substring(1)))); Assert.AreEqual(1, errorMessageCount, "Response File Exception should display error."); Assert.AreEqual(1, exitCode, "Response File Exception execution should exit with error."); @@ -214,7 +214,7 @@ public void ExecuteShouldNotThrowSettingsExceptionButLogOutput() var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); - var result = mockOutput.Messages.Any(o => o.Level == OutputLevel.Error && o.Message.Contains("Invalid settings 'Logger'. Unexpected XmlAttribute: 'invalidName'.")); + var result = mockOutput.Messages.Any(o => o.Level == OutputLevel.Error && o.Message!.Contains("Invalid settings 'Logger'. Unexpected XmlAttribute: 'invalidName'.")); Assert.IsTrue(result, "expecting error message : Invalid settings 'Logger'.Unexpected XmlAttribute: 'invalidName'."); } finally @@ -287,7 +287,7 @@ public void ExecutorShouldShowRightErrorMessage() var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); - var result = mockOutput.Messages.Any(o => o.Level == OutputLevel.Error && o.Message.Contains("Invalid setting 'RunConfiguration'. Invalid value 'Invalid' specified for 'TargetPlatform'.")); + var result = mockOutput.Messages.Any(o => o.Level == OutputLevel.Error && o.Message!.Contains("Invalid setting 'RunConfiguration'. Invalid value 'Invalid' specified for 'TargetPlatform'.")); Assert.AreEqual(1, exitCode, "Exit code should be one because it throws exception"); Assert.IsTrue(result, "expecting error message : Invalid setting 'RunConfiguration'. Invalid value 'Invalid' specified for 'TargetPlatform'."); } @@ -334,20 +334,20 @@ public void ExecutorShouldPrintRunnerArchitecture() var assemblyVersion = typeof(Executor).GetTypeInfo().Assembly.GetCustomAttribute()!.InformationalVersion; Assert.AreEqual(4, mockOutput.Messages.Count); - Assert.IsTrue(Regex.IsMatch(mockOutput.Messages[0].Message, @"Microsoft \(R\) Test Execution Command Line Tool Version .* \(x64\)")); - Assert.IsFalse(mockOutput.Messages.Any(message => message.Message.Contains("vstest.console.exe is running in emulated mode"))); + Assert.IsTrue(Regex.IsMatch(mockOutput.Messages[0].Message!, @"Microsoft \(R\) Test Execution Command Line Tool Version .* \(x64\)")); + Assert.IsFalse(mockOutput.Messages.Any(message => message.Message!.Contains("vstest.console.exe is running in emulated mode"))); } private class MockOutput : IOutput { public List Messages { get; set; } = new List(); - public void Write(string message, OutputLevel level) + public void Write(string? message, OutputLevel level) { Messages.Add(new OutputMessage() { Message = message, Level = level }); } - public void WriteLine(string message, OutputLevel level) + public void WriteLine(string? message, OutputLevel level) { Messages.Add(new OutputMessage() { Message = message, Level = level }); } @@ -355,7 +355,7 @@ public void WriteLine(string message, OutputLevel level) private class OutputMessage { - public string Message { get; set; } = ""; + public string? Message { get; set; } = ""; public OutputLevel Level { get; set; } } } diff --git a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs index f7ab28faad..1757bb95a0 100644 --- a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs +++ b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs @@ -72,7 +72,7 @@ public void InitializeShouldNotThrowExceptionIfEventsIsNotNull() [TestMethod] public void InitializeWithParametersShouldThrowExceptionIfEventsIsNull() { - var parameters = new Dictionary + var parameters = new Dictionary { { "param1", "value" }, }; @@ -83,19 +83,19 @@ public void InitializeWithParametersShouldThrowExceptionIfEventsIsNull() [TestMethod] public void InitializeWithParametersShouldThrowExceptionIfParametersIsEmpty() { - Assert.ThrowsException(() => _consoleLogger.Initialize(new Mock().Object, new Dictionary())); + Assert.ThrowsException(() => _consoleLogger.Initialize(new Mock().Object, new Dictionary())); } [TestMethod] public void InitializeWithParametersShouldThrowExceptionIfParametersIsNull() { - Assert.ThrowsException(() => _consoleLogger.Initialize(new Mock().Object, (Dictionary)null!)); + Assert.ThrowsException(() => _consoleLogger.Initialize(new Mock().Object, (Dictionary)null!)); } [TestMethod] public void InitializeWithParametersShouldSetVerbosityLevel() { - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "minimal" }, { DefaultLoggerParameterNames.TargetFramework , "net451"} @@ -108,7 +108,7 @@ public void InitializeWithParametersShouldSetVerbosityLevel() [TestMethod] public void InitializeWithParametersShouldDefaultToNormalVerbosityLevelForInvalidVerbosity() { - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "" }, }; @@ -125,7 +125,7 @@ public void InitializeWithParametersShouldDefaultToNormalVerbosityLevelForInvali [TestMethod] public void InitializeWithParametersShouldSetPrefixValue() { - var parameters = new Dictionary + var parameters = new Dictionary { { "prefix", "true" }, }; @@ -140,7 +140,7 @@ public void InitializeWithParametersShouldSetPrefixValue() [TestMethod] public void InitializeWithParametersShouldSetNoProgress() { - var parameters = new Dictionary(); + var parameters = new Dictionary(); Assert.IsFalse(ConsoleLogger.EnableProgress); @@ -216,7 +216,7 @@ private void SetupForTestMessageHandler(out InternalTestLoggerEvents loggerEvent { loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -241,7 +241,7 @@ public void TestResultHandlerShouldShowStdOutMessagesBannerIfStdOutIsNotEmpty() var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -272,7 +272,7 @@ public void NormalVerbosityShowNotStdOutMessagesForPassedTests() // Setup var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -301,7 +301,7 @@ public void DetailedVerbosityShowStdOutMessagesForPassedTests() // Setup var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "detailed" } }; @@ -333,7 +333,7 @@ public void TestRunErrorMessageShowShouldTestRunFailed() // Setup var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "detailed" } }; @@ -357,7 +357,7 @@ public void InQuietModeTestErrorMessageShouldShowTestRunFailed() // Setup var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "quiet" }, { DefaultLoggerParameterNames.TargetFramework , "abc" } @@ -381,7 +381,7 @@ public void InQuietModeTestWarningMessageShouldNotShow() // Setup var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "quiet" }, { DefaultLoggerParameterNames.TargetFramework , "abc" } @@ -405,7 +405,7 @@ public void InNormalModeTestWarningAndErrorMessagesShouldShow() // Setup var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -431,7 +431,7 @@ public void TestResultHandlerShouldNotShowStdOutMessagesBannerIfStdOutIsEmpty() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -456,7 +456,7 @@ public void TestResultHandlerShouldShowStdErrMessagesBannerIfStdErrIsNotEmpty() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -483,7 +483,7 @@ public void TestResultHandlerShouldNotShowStdErrMessagesBannerIfStdErrIsEmpty() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -508,7 +508,7 @@ public void TestResultHandlerShouldShowAdditionalInfoBannerIfAdditionalInfoIsNot { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -535,7 +535,7 @@ public void TestResultHandlerShouldNotShowAdditionalInfoBannerIfAdditionalInfoIs { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -562,7 +562,7 @@ public void TestResultHandlerShouldShowPassedTestsForNormalVebosity() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -593,7 +593,7 @@ public void TestResultHandlerShouldShowFailedTestsAndPassedTestsForQuietVebosity { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", verbosityLevel }, { DefaultLoggerParameterNames.TargetFramework , framework} @@ -645,7 +645,7 @@ public void TestResultHandlerShouldNotShowformattedFailedTestsAndPassedTestsForO { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", verbosityLevel }, { DefaultLoggerParameterNames.TargetFramework , "net451"} @@ -674,7 +674,7 @@ public void TestResultHandlerShouldNotShowNotStdOutMsgOfPassedTestIfVerbosityIsN { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -701,7 +701,7 @@ public void TestResultHandlerShouldNotShowDbgTrcMsg() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -728,7 +728,7 @@ public void TestResultHandlerShouldWriteToConsoleButSkipPassedTestsForMinimalVer { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "minimal" }, { DefaultLoggerParameterNames.TargetFramework , "net451"} @@ -754,7 +754,7 @@ public void TestResultHandlerShouldWriteToNoTestResultForQuietVerbosity() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "quiet" }, { DefaultLoggerParameterNames.TargetFramework , "net451"} @@ -785,7 +785,7 @@ public void TestResultHandlerForTestResultWithDurationShouldPrintDurationInfo(st { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -808,7 +808,7 @@ public void TestResultHandlerForTestResultWithDurationLessThanOneMsShouldPrintDu { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -831,7 +831,7 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsPass() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -856,7 +856,7 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsFail() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -880,7 +880,7 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsCanceled() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -904,7 +904,7 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsCanceledWithoutRunn { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -920,7 +920,7 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsAborted() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -941,7 +941,7 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsAbortedWithoutRunni { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -967,7 +967,7 @@ public void TestRunStartHandlerShouldWriteNumberOfTestSourcesDiscoveredOnConsole CommandLineOptions.Instance.AddSource(testFilePath); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -999,7 +999,7 @@ public void TestRunStartHandlerShouldWriteTestSourcesDiscoveredOnConsoleIfVerbos CommandLineOptions.Instance.AddSource(testFilePath); CommandLineOptions.Instance.AddSource(testFilePath2); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "detailed" } }; @@ -1033,7 +1033,7 @@ public void TestRunStartHandlerShouldNotWriteTestSourcesDiscoveredOnConsoleIfVer CommandLineOptions.Instance.AddSource(testFilePath); CommandLineOptions.Instance.AddSource(testFilePath2); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -1053,7 +1053,7 @@ public void PrintTimeHandlerShouldPrintElapsedTimeOnConsole() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -1080,7 +1080,7 @@ public void DisplayFullInformationShouldWriteErrorMessageAndStackTraceToConsole( { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -1106,7 +1106,7 @@ public void DisplayFullInformationShouldWriteStdMessageWithNewLine() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "detailed" } }; @@ -1132,7 +1132,7 @@ public void GetTestMessagesShouldWriteMessageAndStackTraceToConsole() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; @@ -1169,7 +1169,7 @@ public void AttachmentInformationShouldBeWrittenToConsoleIfAttachmentsArePresent { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", verbosityLevel } }; @@ -1195,7 +1195,7 @@ public void ResultsInHeirarchichalOrderShouldReportCorrectCount() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary + var parameters = new Dictionary { { "verbosity", "normal" } }; diff --git a/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs index 4c6b0f01ed..b13df6dfb9 100644 --- a/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs @@ -99,7 +99,7 @@ public void InitializeShouldCreateEntryForCodeCoverageInRunSettingsIfNotAlreadyP Assert.IsNotNull(_settingsProvider.ActiveRunSettings); var dataCollectorsFriendlyNames = XmlRunSettingsUtilities.GetDataCollectorsFriendlyName(_settingsProvider.ActiveRunSettings - .SettingsXml); + .SettingsXml!); Assert.IsTrue(dataCollectorsFriendlyNames.Contains("Code Coverage"), "Code coverage setting in not available in runsettings"); } diff --git a/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs index 5c27c16534..333d6ece1c 100644 --- a/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/HelpArgumentProcessorTests.cs @@ -82,19 +82,19 @@ internal class DummyConsoleOutput : IOutput /// /// The lines. /// - internal List Lines; + internal List Lines; public DummyConsoleOutput() { - Lines = new List(); + Lines = new List(); } - public void WriteLine(string message, OutputLevel level) + public void WriteLine(string? message, OutputLevel level) { Lines.Add(message); } - public void Write(string message, OutputLevel level) + public void Write(string? message, OutputLevel level) { throw new NotImplementedException(); } diff --git a/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs index da5dd95147..cb4c752f42 100644 --- a/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunSettingsArgumentProcessorTests.cs @@ -208,7 +208,7 @@ public void InitializeShouldAddDefaultSettingsIfNotPresent() RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(_settingsProvider.ActiveRunSettings.SettingsXml); Assert.AreEqual(runConfiguration.ResultsDirectory, Constants.DefaultResultsDirectory); - Assert.AreEqual(runConfiguration.TargetFramework.ToString(), Framework.DefaultFramework.ToString()); + Assert.AreEqual(runConfiguration.TargetFramework!.ToString(), Framework.DefaultFramework.ToString()); Assert.AreEqual(runConfiguration.TargetPlatform, Constants.DefaultPlatform); } diff --git a/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs b/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs index 9c08bef69b..e6aae3a36f 100644 --- a/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs +++ b/test/vstest.console.UnitTests/TestPlatformHelpers/TestRequestManagerTests.cs @@ -264,7 +264,7 @@ public void DiscoverTestsShouldPassSameProtocolConfigInRequestData() _testRequestManager.DiscoverTests(payload, mockDiscoveryRegistrar.Object, mockProtocolConfig); // Verify. - Assert.AreEqual(6, actualRequestData!.ProtocolConfig.Version); + Assert.AreEqual(6, actualRequestData!.ProtocolConfig!.Version); } @@ -681,7 +681,7 @@ public void DiscoverTestsShouldUpdateFrameworkAndPlatformIfNotSpecifiedInDesignM _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny())); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny())); - Assert.IsTrue(actualDiscoveryCriteria!.RunSettings.Contains(Constants.DotNetFramework46)); + Assert.IsTrue(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); Assert.IsTrue(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); } @@ -715,7 +715,7 @@ public void DiscoverTestsShouldNotUpdateFrameworkAndPlatformIfSpecifiedInDesignM _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny()), Times.Never); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny()), Times.Never); - Assert.IsTrue(actualDiscoveryCriteria!.RunSettings.Contains(Constants.DotNetFramework46)); + Assert.IsTrue(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); Assert.IsTrue(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); } @@ -746,7 +746,7 @@ public void DiscoverTestsShouldUpdateFrameworkAndPlatformInCommandLineScenariosI _mockAssemblyMetadataProvider.Verify(a => a.GetArchitecture(It.IsAny())); _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny())); - Assert.IsTrue(actualDiscoveryCriteria!.RunSettings.Contains(Constants.DotNetFramework46)); + Assert.IsTrue(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); Assert.IsTrue(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); } @@ -787,8 +787,8 @@ public void DiscoverTestsShouldNotInferAndUpdateFrameworkAndPlatformInCommandLin _mockAssemblyMetadataProvider.Verify(a => a.GetFrameworkName(It.IsAny()), Times.Once); // but we don't update the settings, to keep what user specified - Assert.IsFalse(actualDiscoveryCriteria!.RunSettings.Contains(Constants.DotNetFramework46)); - Assert.IsFalse(actualDiscoveryCriteria!.RunSettings.Contains(nameof(Architecture.ARM))); + Assert.IsFalse(actualDiscoveryCriteria!.RunSettings!.Contains(Constants.DotNetFramework46)); + Assert.IsFalse(actualDiscoveryCriteria.RunSettings.Contains(nameof(Architecture.ARM))); } [TestMethod] @@ -913,7 +913,7 @@ public void RunTestsShouldPassSameProtocolConfigInRequestData() _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, mockProtocolConfig); // Verify. - Assert.AreEqual(6, actualRequestData!.ProtocolConfig.Version); + Assert.AreEqual(6, actualRequestData!.ProtocolConfig!.Version); } [TestMethod] @@ -1326,11 +1326,11 @@ public void DiscoverTestsShouldUpdateDesignModeAndCollectSourceInformation(bool var designmode = $"{designModeValue}"; _mockTestPlatform.Verify( - tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings.Contains(designmode)), It.IsAny(), It.IsAny>(), It.IsAny())); + tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings!.Contains(designmode)), It.IsAny(), It.IsAny>(), It.IsAny())); var collectSourceInformation = $"{designModeValue}"; _mockTestPlatform.Verify( - tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings.Contains(collectSourceInformation)), It.IsAny(), It.IsAny>(), It.IsAny())); + tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings!.Contains(collectSourceInformation)), It.IsAny(), It.IsAny>(), It.IsAny())); } [TestMethod] @@ -1344,7 +1344,7 @@ public void DiscoverTestsShouldNotUpdateDesignModeIfUserHasSetDesignModeInRunSet var designmode = "False"; _mockTestPlatform.Verify( - tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings.Contains(designmode)), It.IsAny(), It.IsAny>(), It.IsAny())); + tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings!.Contains(designmode)), It.IsAny(), It.IsAny>(), It.IsAny())); } [DataTestMethod] @@ -1379,7 +1379,7 @@ public void DiscoverTestsShouldNotUpdateCollectSourceInformationIfUserHasSetItIn var collectSourceInformation = $"{val}"; _mockTestPlatform.Verify( - tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings.Contains(collectSourceInformation)), It.IsAny(), It.IsAny>(), It.IsAny())); + tp => tp.CreateDiscoveryRequest(It.IsAny(), It.Is(dc => dc.RunSettings!.Contains(collectSourceInformation)), It.IsAny(), It.IsAny>(), It.IsAny())); } [TestMethod] @@ -1735,7 +1735,7 @@ public void RunTestsShouldAddConsoleLoggerInRunSettingsInNonDesignMode() _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; Assert.AreEqual(1, loggerSettingsList.Count); Assert.AreEqual("Console", loggerSettingsList[0].FriendlyName); Assert.IsNotNull(loggerSettingsList[0].AssemblyQualifiedName); @@ -1773,7 +1773,7 @@ public void RunTestsShouldAddConsoleLoggerInRunSettingsIfDesignModeSetFalseInRun (IRequestData requestData, TestRunCriteria runCriteria, TestPlatformOptions options, Dictionary sourceToSourceDetailMap, IWarningLogger _) => actualTestRunCriteria = runCriteria).Returns(mockTestRunRequest.Object); _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; Assert.AreEqual(2, loggerSettingsList.Count); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); @@ -1816,7 +1816,7 @@ public void DiscoverTestsShouldAddConsoleLoggerInRunSettingsIfDesignModeSetFalse _testRequestManager.DiscoverTests(payload, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; Assert.AreEqual(2, loggerSettingsList.Count); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); @@ -1874,7 +1874,7 @@ public void DiscoverTestsShouldAddConsoleLoggerInRunSettingsInNonDesignMode() _testRequestManager.DiscoverTests(payload, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; Assert.AreEqual(1, loggerSettingsList.Count); Assert.AreEqual("Console", loggerSettingsList[0].FriendlyName); Assert.IsNotNull(loggerSettingsList[0].AssemblyQualifiedName); @@ -1906,7 +1906,7 @@ public void DiscoverTestsShouldNotAddConsoleLoggerInRunSettingsInDesignMode() _testRequestManager.DiscoverTests(payload, new Mock().Object, _protocolConfig); - Assert.IsFalse(actualDiscoveryCriteria!.RunSettings.Contains("LoggerRunSettings")); + Assert.IsFalse(actualDiscoveryCriteria!.RunSettings!.Contains("LoggerRunSettings")); } [TestMethod] @@ -1945,15 +1945,15 @@ public void RunTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPresentI (IRequestData requestData, TestRunCriteria runCriteria, TestPlatformOptions options, Dictionary sourceToSourceDetailMap, IWarningLogger _) => actualTestRunCriteria = runCriteria).Returns(mockTestRunRequest.Object); _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; Assert.AreEqual(2, loggerSettingsList.Count); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("console", loggerSettingsList[1].FriendlyName); - Assert.AreEqual(new Uri("logger://tempconsoleUri").ToString(), loggerSettingsList[1].Uri.ToString()); + Assert.AreEqual(new Uri("logger://tempconsoleUri").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempCodeBase", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration.InnerXml.Contains("Value1")); + Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -1997,15 +1997,15 @@ public void DiscoverTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPre _testRequestManager.DiscoverTests(payload, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; Assert.AreEqual(2, loggerSettingsList.Count); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("consoleTemp", loggerSettingsList[1].FriendlyName); - Assert.AreEqual(new Uri("logger://Microsoft/TestPlatform/ConsoleLogger/v1").ToString(), loggerSettingsList[1].Uri.ToString()); + Assert.AreEqual(new Uri("logger://Microsoft/TestPlatform/ConsoleLogger/v1").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration.InnerXml.Contains("Value1")); + Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -2046,15 +2046,15 @@ public void RunTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPresentI (IRequestData requestData, TestRunCriteria runCriteria, TestPlatformOptions options, Dictionary sourceToSourceDetailMap, IWarningLogger _) => actualTestRunCriteria = runCriteria).Returns(mockTestRunRequest.Object); _testRequestManager.RunTests(payload, new Mock().Object, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualTestRunCriteria!.TestRunSettings)!.LoggerSettingsList; Assert.AreEqual(2, loggerSettingsList.Count); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("console", loggerSettingsList[1].FriendlyName); - Assert.AreEqual(new Uri("logger://tempconsoleUri").ToString(), loggerSettingsList[1].Uri.ToString()); + Assert.AreEqual(new Uri("logger://tempconsoleUri").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempCodeBase", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration.InnerXml.Contains("Value1")); + Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -2098,15 +2098,15 @@ public void DiscoverTestsShouldOverrideOnlyAssemblyNameIfConsoleLoggerAlreadyPre _testRequestManager.DiscoverTests(payload, new Mock().Object, _protocolConfig); - var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings).LoggerSettingsList; + var loggerSettingsList = XmlRunSettingsUtilities.GetLoggerRunSettings(actualDiscoveryCriteria!.RunSettings)!.LoggerSettingsList; Assert.AreEqual(2, loggerSettingsList.Count); Assert.IsNotNull(loggerSettingsList[0].Configuration); Assert.AreEqual("blabla", loggerSettingsList[0].FriendlyName); Assert.AreEqual("consoleTemp", loggerSettingsList[1].FriendlyName); - Assert.AreEqual(new Uri("logger://Microsoft/TestPlatform/ConsoleLogger/v1").ToString(), loggerSettingsList[1].Uri.ToString()); + Assert.AreEqual(new Uri("logger://Microsoft/TestPlatform/ConsoleLogger/v1").ToString(), loggerSettingsList[1].Uri!.ToString()); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].AssemblyQualifiedName); Assert.AreNotEqual("tempAssemblyName", loggerSettingsList[1].CodeBase); - Assert.IsTrue(loggerSettingsList[1].Configuration.InnerXml.Contains("Value1")); + Assert.IsTrue(loggerSettingsList[1].Configuration!.InnerXml.Contains("Value1")); Assert.IsNotNull(loggerSettingsList[1].AssemblyQualifiedName); Assert.IsNotNull(loggerSettingsList[1].CodeBase); } @@ -2280,7 +2280,7 @@ public void StartTestSessionShouldUpdateSettings() .Callback( (IRequestData _, StartTestSessionCriteria criteria, ITestSessionEventsHandler _, Dictionary _, IWarningLogger _) => { - Assert.IsTrue(criteria.RunSettings.Contains(Constants.DotNetFramework46)); + Assert.IsTrue(criteria.RunSettings!.Contains(Constants.DotNetFramework46)); Assert.IsTrue(criteria.RunSettings.Contains(nameof(Architecture.ARM))); });