diff --git a/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs b/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs index d965c51b91..479ae048ec 100644 --- a/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs +++ b/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs @@ -11,6 +11,7 @@ using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper; using Microsoft.VisualStudio.TestPlatform.Client.TestRunAttachmentsProcessing; +using Microsoft.VisualStudio.TestPlatform.Common; using Microsoft.VisualStudio.TestPlatform.Common.Logging; using Microsoft.VisualStudio.TestPlatform.Common.Utilities; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; @@ -158,7 +159,7 @@ private void ProcessRequests(ITestRequestManager testRequestManager) EqtTrace.Info("DesignModeClient.ProcessRequests: Processing Message: {0}", message); - switch (message.MessageType) + switch (message?.MessageType) { case MessageType.VersionCheck: { @@ -179,6 +180,7 @@ private void ProcessRequests(ITestRequestManager testRequestManager) case MessageType.StartTestSession: { var testSessionPayload = _communicationManager.DeserializePayload(message); + TPDebug.Assert(testSessionPayload is not null, "testSessionPayload is null"); StartTestSession(testSessionPayload, testRequestManager); break; } @@ -186,6 +188,7 @@ private void ProcessRequests(ITestRequestManager testRequestManager) case MessageType.StopTestSession: { var testSessionPayload = _communicationManager.DeserializePayload(message); + TPDebug.Assert(testSessionPayload is not null, "testSessionPayload is null"); StopTestSession(testSessionPayload, testRequestManager); break; } @@ -193,6 +196,7 @@ private void ProcessRequests(ITestRequestManager testRequestManager) case MessageType.StartDiscovery: { var discoveryPayload = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(discoveryPayload is not null, "discoveryPayload is null"); StartDiscovery(discoveryPayload, testRequestManager); break; } @@ -203,6 +207,7 @@ private void ProcessRequests(ITestRequestManager testRequestManager) var testRunPayload = _communicationManager.DeserializePayload( message); + TPDebug.Assert(testRunPayload is not null, "testRunPayload is null"); StartTestRun(testRunPayload, testRequestManager, shouldLaunchTesthost: true); break; } @@ -213,6 +218,7 @@ private void ProcessRequests(ITestRequestManager testRequestManager) var testRunPayload = _communicationManager.DeserializePayload( message); + TPDebug.Assert(testRunPayload is not null, "testRunPayload is null"); StartTestRun(testRunPayload, testRequestManager, shouldLaunchTesthost: false); break; } @@ -221,6 +227,7 @@ private void ProcessRequests(ITestRequestManager testRequestManager) { var testRunAttachmentsProcessingPayload = _communicationManager.DeserializePayload(message); + TPDebug.Assert(testRunAttachmentsProcessingPayload is not null, "testRunAttachmentsProcessingPayload is null"); StartTestRunAttachmentsProcessing(testRunAttachmentsProcessingPayload, testRequestManager); break; } @@ -323,7 +330,9 @@ public int LaunchCustomHost(TestProcessStartInfo testProcessStartInfo, Cancellat onCustomTestHostLaunchAckReceived = null; + TPDebug.Assert(ackMessage is not null, "ackMessage is null"); var ackPayload = _dataSerializer.DeserializePayload(ackMessage); + TPDebug.Assert(ackPayload is not null, "ackPayload is null"); return ackPayload.HostProcessId > 0 ? ackPayload.HostProcessId : throw new TestPlatformException(ackPayload.ErrorMessage); } @@ -344,7 +353,7 @@ public bool AttachDebuggerToProcess(AttachDebuggerInfo attachDebuggerInfo, Cance { var waitHandle = new AutoResetEvent(false); Message? ackMessage = null; - onAttachDebuggerAckRecieved = (ackRawMessage) => + onAttachDebuggerAckRecieved = ackRawMessage => { ackMessage = ackRawMessage; waitHandle.Set(); @@ -355,9 +364,7 @@ public bool AttachDebuggerToProcess(AttachDebuggerInfo attachDebuggerInfo, Cance // a type of T as well to prevent some more mistakes. if (_protocolConfig.Version < 7) { -#pragma warning disable CS0618 // Type or member is obsolete _communicationManager.SendMessage(MessageType.EditorAttachDebugger, attachDebuggerInfo.ProcessId, _protocolConfig.Version); -#pragma warning restore CS0618 // Type or member is obsolete } else { @@ -374,7 +381,9 @@ public bool AttachDebuggerToProcess(AttachDebuggerInfo attachDebuggerInfo, Cance cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested(); onAttachDebuggerAckRecieved = null; + TPDebug.Assert(ackMessage is not null, "ackMessage is null"); var ackPayload = _dataSerializer.DeserializePayload(ackMessage); + TPDebug.Assert(ackPayload is not null, "ackPayload is null"); if (!ackPayload.Attached) { EqtTrace.Warning($"DesignModeClient.AttachDebuggerToProcess: Attaching to process failed: {ackPayload.ErrorMessage}"); diff --git a/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs b/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs index d2866e204c..ca9a470453 100644 --- a/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs +++ b/src/Microsoft.TestPlatform.Client/Discovery/DiscoveryRequest.cs @@ -364,7 +364,7 @@ public void HandleRawMessage(string rawMessage) if (string.Equals(message?.MessageType, MessageType.DiscoveryComplete)) { - var discoveryCompletePayload = _dataSerializer.DeserializePayload(message); + var discoveryCompletePayload = _dataSerializer.DeserializePayload(message!); rawMessage = UpdateRawMessageWithTelemetryInfo(discoveryCompletePayload, message) ?? rawMessage; HandleLoggerManagerDiscoveryComplete(discoveryCompletePayload); } @@ -376,7 +376,7 @@ public void HandleRawMessage(string rawMessage) /// Handles LoggerManager's DiscoveryComplete. /// /// Discovery complete payload. - private void HandleLoggerManagerDiscoveryComplete(DiscoveryCompletePayload discoveryCompletePayload) + private void HandleLoggerManagerDiscoveryComplete(DiscoveryCompletePayload? discoveryCompletePayload) { if (LoggerManager.LoggersInitialized && discoveryCompletePayload != null) { diff --git a/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs b/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs index 3177f9b0fd..2051479aaa 100644 --- a/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs +++ b/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs @@ -537,7 +537,7 @@ public void HandleRawMessage(string rawMessage) if (string.Equals(message?.MessageType, MessageType.ExecutionComplete)) { - var testRunCompletePayload = _dataSerializer.DeserializePayload(message); + var testRunCompletePayload = _dataSerializer.DeserializePayload(message!); rawMessage = UpdateRawMessageWithTelemetryInfo(testRunCompletePayload, message) ?? rawMessage; HandleLoggerManagerTestRunComplete(testRunCompletePayload); } @@ -549,7 +549,7 @@ public void HandleRawMessage(string rawMessage) /// Handles LoggerManager's TestRunComplete. /// /// TestRun complete payload. - private void HandleLoggerManagerTestRunComplete(TestRunCompletePayload testRunCompletePayload) + private void HandleLoggerManagerTestRunComplete(TestRunCompletePayload? testRunCompletePayload) { if (!LoggerManager.LoggersInitialized || testRunCompletePayload == null) { @@ -567,7 +567,7 @@ private void HandleLoggerManagerTestRunComplete(TestRunCompletePayload testRunCo // Send test run complete to logger manager. TestRunCompleteEventArgs testRunCompleteArgs = new( - testRunCompletePayload.TestRunCompleteArgs.TestRunStatistics, + testRunCompletePayload.TestRunCompleteArgs!.TestRunStatistics, testRunCompletePayload.TestRunCompleteArgs.IsCanceled, testRunCompletePayload.TestRunCompleteArgs.IsAborted, testRunCompletePayload.TestRunCompleteArgs.Error, diff --git a/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt index 872bef0d70..8efd952404 100644 --- a/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.Client/PublicAPI/PublicAPI.Shipped.txt @@ -63,7 +63,7 @@ Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.Can Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.CancelTestRun() -> void Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.CancelTestRunAttachmentsProcessing() -> void Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.DiscoverTests(Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.DiscoveryRequestPayload! discoveryPayload, Microsoft.VisualStudio.TestPlatform.Common.Interfaces.ITestDiscoveryEventsRegistrar! disoveryEventsRegistrar, Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.ProtocolConfig! protocolConfig) -> void -Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.InitializeExtensions(System.Collections.Generic.IEnumerable! pathToAdditionalExtensions, bool skipExtensionFilters) -> void +Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.InitializeExtensions(System.Collections.Generic.IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters) -> void Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.ProcessTestRunAttachments(Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.TestRunAttachmentsProcessingPayload! testRunAttachmentsProcessingPayload, Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.ITestRunAttachmentsProcessingEventsHandler! testRunAttachmentsProcessingEventsHandler, Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.ProtocolConfig! protocolConfig) -> void Microsoft.VisualStudio.TestPlatform.Client.RequestHelper.ITestRequestManager.ResetOptions() -> void Microsoft.VisualStudio.TestPlatform.Client.TestPlatformFactory diff --git a/src/Microsoft.TestPlatform.Client/RequestHelper/ITestRequestManager.cs b/src/Microsoft.TestPlatform.Client/RequestHelper/ITestRequestManager.cs index d44026f148..291d69954f 100644 --- a/src/Microsoft.TestPlatform.Client/RequestHelper/ITestRequestManager.cs +++ b/src/Microsoft.TestPlatform.Client/RequestHelper/ITestRequestManager.cs @@ -24,7 +24,7 @@ public interface ITestRequestManager : IDisposable /// Paths to additional extensions. /// Skip extension filtering by name if true. void InitializeExtensions( - IEnumerable pathToAdditionalExtensions, + IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters); /// diff --git a/src/Microsoft.TestPlatform.Client/TestPlatform.cs b/src/Microsoft.TestPlatform.Client/TestPlatform.cs index a07f6618db..522aa87914 100644 --- a/src/Microsoft.TestPlatform.Client/TestPlatform.cs +++ b/src/Microsoft.TestPlatform.Client/TestPlatform.cs @@ -176,7 +176,7 @@ public void Dispose() /// public void UpdateExtensions( - IEnumerable pathToAdditionalExtensions, + IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters) { _testEngine.GetExtensionManager().UseAdditionalExtensions(pathToAdditionalExtensions, skipExtensionFilters); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/CommunicationEndpointFactory.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/CommunicationEndpointFactory.cs index 24fc6754ac..2f9464849f 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/CommunicationEndpointFactory.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/CommunicationEndpointFactory.cs @@ -2,11 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; - using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs index ade5066407..a83614baf5 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs @@ -31,8 +31,6 @@ using CommunicationUtilitiesResources = Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Resources.Resources; using CoreUtilitiesConstants = Microsoft.VisualStudio.TestPlatform.CoreUtilities.Constants; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.DataCollection; /// @@ -43,21 +41,15 @@ internal class DataCollectionRequestHandler : IDataCollectionRequestHandler, IDi private static readonly object SyncObject = new(); private readonly ICommunicationManager _communicationManager; - private readonly IMessageSink _messageSink; - private readonly IDataCollectionManager _dataCollectionManager; - private readonly IDataCollectionTestCaseEventHandler _dataCollectionTestCaseEventHandler; - - private Task _testCaseEventMonitorTask; - private readonly IDataSerializer _dataSerializer; - private readonly IFileHelper _fileHelper; - private readonly IRequestData _requestData; + private Task? _testCaseEventMonitorTask; + /// /// Use to cancel data collection test case events monitoring if test run is canceled. /// @@ -131,7 +123,7 @@ protected DataCollectionRequestHandler( /// /// Gets the singleton instance of DataCollectionRequestHandler. /// - public static DataCollectionRequestHandler Instance { get; private set; } + public static DataCollectionRequestHandler? Instance { get; private set; } /// /// Creates singleton instance of DataCollectionRequestHandler. @@ -208,7 +200,7 @@ public void ProcessRequests() EqtTrace.Info("DataCollectionRequestHandler.ProcessRequests: Datacollector received message: {0}", message); - switch (message.MessageType) + switch (message?.MessageType) { case MessageType.BeforeTestRunStart: HandleBeforeTestRunStart(message); @@ -221,11 +213,12 @@ public void ProcessRequests() case MessageType.TestHostLaunched: var testHostLaunchedPayload = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(testHostLaunchedPayload is not null, "testHostLaunchedPayload is null"); _dataCollectionManager.TestHostLaunched(testHostLaunchedPayload.ProcessId); break; default: - EqtTrace.Error("DataCollectionRequestHandler.ProcessRequests : Invalid Message types: {0}", message.MessageType); + EqtTrace.Error("DataCollectionRequestHandler.ProcessRequests : Invalid Message types: {0}", message?.MessageType); break; } } @@ -270,7 +263,13 @@ private void AddExtensionAssemblies(BeforeTestRunStartPayload payload) { try { - var customTestAdaptersPaths = RunSettingsUtilities.GetTestAdaptersPaths(payload.SettingsXml); + TPDebug.Assert(payload is not null, "payload is null"); + + if (payload.Sources is null) + { + EqtTrace.Verbose("DataCollectionRequestHandler.AddExtensionAssemblies: No sources provided"); + return; + } // In case of dotnet vstest with code coverage, data collector needs to be picked up from publish folder. // Therefore, adding source dll folders to search datacollectors in these. @@ -280,6 +279,7 @@ private void AddExtensionAssemblies(BeforeTestRunStartPayload payload) datacollectorSearchPaths.Add(Path.GetDirectoryName(source)); } + var customTestAdaptersPaths = RunSettingsUtilities.GetTestAdaptersPaths(payload.SettingsXml); if (customTestAdaptersPaths != null) { datacollectorSearchPaths.UnionWith(customTestAdaptersPaths); @@ -319,12 +319,13 @@ private void HandleBeforeTestRunStart(Message message) { // Initialize datacollectors and get environment variables. var payload = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(payload is not null, "payload is null"); UpdateRequestData(payload.IsTelemetryOptedIn); AddExtensionAssemblies(payload); var envVariables = _dataCollectionManager.InitializeDataCollectors(payload.SettingsXml); - var properties = new Dictionary + var properties = new Dictionary { { CoreUtilitiesConstants.TestSourcesKeyName, payload.Sources } }; diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestSender.cs index 4e810c4adc..55adf2f211 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestSender.cs @@ -15,8 +15,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.DataCollection; /// @@ -100,10 +98,10 @@ public void SendTestHostLaunched(TestHostLaunchedPayload testHostLaunchedPayload } /// - public BeforeTestRunStartResult SendBeforeTestRunStartAndGetResult(string settingsXml, IEnumerable sources, bool isTelemetryOptedIn, ITestMessageEventHandler runEventsHandler) + public BeforeTestRunStartResult? SendBeforeTestRunStartAndGetResult(string settingsXml, IEnumerable sources, bool isTelemetryOptedIn, ITestMessageEventHandler? runEventsHandler) { var isDataCollectionStarted = false; - BeforeTestRunStartResult result = null; + BeforeTestRunStartResult? result = null; EqtTrace.Verbose("DataCollectionRequestSender.SendBeforeTestRunStartAndGetResult: Send BeforeTestRunStart message with settingsXml {0} and sources {1}: ", settingsXml, sources.ToString()); @@ -119,12 +117,14 @@ public BeforeTestRunStartResult SendBeforeTestRunStartAndGetResult(string settin while (!isDataCollectionStarted) { var message = _communicationManager.ReceiveMessage(); + TPDebug.Assert(message is not null, "message is null"); EqtTrace.Verbose("DataCollectionRequestSender.SendBeforeTestRunStartAndGetResult: Received message: {0}", message); if (message.MessageType == MessageType.DataCollectionMessage) { var dataCollectionMessageEventArgs = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(dataCollectionMessageEventArgs is not null, $"{nameof(dataCollectionMessageEventArgs)} is null"); LogDataCollectorMessage(dataCollectionMessageEventArgs, runEventsHandler); } else if (message.MessageType == MessageType.BeforeTestRunStartResult) @@ -138,10 +138,10 @@ public BeforeTestRunStartResult SendBeforeTestRunStartAndGetResult(string settin } /// - public AfterTestRunEndResult SendAfterTestRunEndAndGetResult(ITestMessageEventHandler runEventsHandler, bool isCancelled) + public AfterTestRunEndResult? SendAfterTestRunEndAndGetResult(ITestMessageEventHandler? runEventsHandler, bool isCancelled) { var isDataCollectionComplete = false; - AfterTestRunEndResult result = null; + AfterTestRunEndResult? result = null; EqtTrace.Verbose("DataCollectionRequestSender.SendAfterTestRunStartAndGetResult: Send AfterTestRunEnd message with isCancelled: {0}", isCancelled); @@ -152,12 +152,14 @@ public AfterTestRunEndResult SendAfterTestRunEndAndGetResult(ITestMessageEventHa while (!isDataCollectionComplete && !isCancelled) { var message = _communicationManager.ReceiveMessage(); + TPDebug.Assert(message is not null, "message is null"); EqtTrace.Verbose("DataCollectionRequestSender.SendAfterTestRunStartAndGetResult: Received message: {0}", message); if (message.MessageType == MessageType.DataCollectionMessage) { var dataCollectionMessageEventArgs = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(dataCollectionMessageEventArgs is not null, $"{nameof(dataCollectionMessageEventArgs)} is null"); LogDataCollectorMessage(dataCollectionMessageEventArgs, runEventsHandler); } else if (message.MessageType == MessageType.AfterTestRunEndResult) @@ -170,10 +172,10 @@ public AfterTestRunEndResult SendAfterTestRunEndAndGetResult(ITestMessageEventHa return result; } - private void LogDataCollectorMessage(DataCollectionMessageEventArgs dataCollectionMessageEventArgs, ITestMessageEventHandler requestHandler) + private static void LogDataCollectorMessage(DataCollectionMessageEventArgs dataCollectionMessageEventArgs, ITestMessageEventHandler? requestHandler) { string logMessage; - if (string.IsNullOrWhiteSpace(dataCollectionMessageEventArgs.FriendlyName)) + if (dataCollectionMessageEventArgs.FriendlyName.IsNullOrWhiteSpace()) { // Message from data collection framework. logMessage = string.Format(CultureInfo.CurrentCulture, CommonResources.DataCollectionMessageFormat, dataCollectionMessageEventArgs.Message); @@ -184,6 +186,6 @@ private void LogDataCollectorMessage(DataCollectionMessageEventArgs dataCollecti logMessage = string.Format(CultureInfo.CurrentCulture, CommonResources.DataCollectorMessageFormat, dataCollectionMessageEventArgs.FriendlyName, dataCollectionMessageEventArgs.Message); } - requestHandler.HandleLogMessage(dataCollectionMessageEventArgs.Level, logMessage); + requestHandler?.HandleLogMessage(dataCollectionMessageEventArgs.Level, logMessage); } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs index 469448b2dd..777251c439 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventHandler.cs @@ -13,8 +13,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.DataCollection; /// @@ -76,7 +74,7 @@ public void ProcessRequests() do { var message = _communicationManager.ReceiveMessage(); - switch (message.MessageType) + switch (message?.MessageType) { case MessageType.DataCollectionTestStart: EqtTrace.Info("DataCollectionTestCaseEventHandler: Test case starting."); @@ -139,7 +137,7 @@ public void ProcessRequests() break; default: - EqtTrace.Info("DataCollectionTestCaseEventHandler: Invalid Message type '{0}'", message.MessageType); + EqtTrace.Info("DataCollectionTestCaseEventHandler: Invalid Message type '{0}'", message?.MessageType); break; } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventSender.cs index d76f7aa63f..a2c576f7f7 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionTestCaseEventSender.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; public class DataCollectionTestCaseEventSender : IDataCollectionTestCaseEventSender @@ -18,7 +16,6 @@ public class DataCollectionTestCaseEventSender : IDataCollectionTestCaseEventSen private static readonly object SyncObject = new(); private readonly ICommunicationManager _communicationManager; - private readonly IDataSerializer _dataSerializer; /// @@ -44,7 +41,7 @@ protected DataCollectionTestCaseEventSender(ICommunicationManager communicationM /// Gets the singleton instance of DataCollectionTestCaseEventSender. /// // TODO : Re-factor to pass the instance as singleton. - public static DataCollectionTestCaseEventSender Instance { get; private set; } + public static DataCollectionTestCaseEventSender? Instance { get; private set; } /// /// Gets singleton instance of DataCollectionRequestHandler. @@ -98,7 +95,7 @@ public void SendTestCaseStart(TestCaseStartEventArgs e) } /// - public Collection SendTestCaseEnd(TestCaseEndEventArgs e) + public Collection? SendTestCaseEnd(TestCaseEndEventArgs e) { var attachmentSets = new Collection(); _communicationManager.SendMessage(MessageType.DataCollectionTestEnd, e); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs index 243b0d04fd..73e5cd35e4 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestDiscoveryEventHandler.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -32,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); @@ -43,7 +41,7 @@ public void HandleDiscoveredTests(IEnumerable discoveredTestCases) /// /// Discovery Complete Events Args. /// The last chunk. - public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable lastChunk) + public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable? lastChunk) { EqtTrace.Info(discoveryCompleteEventArgs.IsAborted ? "Discover Aborted." : "Discover Finished."); @@ -57,7 +55,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete /// Logging 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/TestInitializeEventsHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestInitializeEventsHandler.cs index f20d63a602..067e4f3e24 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestInitializeEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestInitializeEventsHandler.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.EventHandlers; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs index 26bc970dd1..bde9f7a619 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/EventHandlers/TestRunEventsHandler.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.EventHandlers; /// @@ -34,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); @@ -47,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); @@ -94,7 +92,7 @@ public void HandleRawMessage(string rawMessage) /// /// Process start info /// ProcessId of the launched process - public int LaunchProcessWithDebuggerAttached(TestProcessStartInfo testProcessStartInfo) + public int LaunchProcessWithDebuggerAttached(TestProcessStartInfo? testProcessStartInfo) { EqtTrace.Info("Sending LaunchProcessWithDebuggerAttached on additional test process: {0}", testProcessStartInfo?.FileName); return _requestHandler.LaunchProcessWithDebuggerAttached(testProcessStartInfo); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/CommunicationException.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/CommunicationException.cs index ac3594ff79..bf08a4f30f 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/CommunicationException.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/CommunicationException.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// @@ -24,7 +22,7 @@ public CommunicationException() /// message. /// /// Message describing the error. - public CommunicationException(string message) + public CommunicationException(string? message) : base(message) { } @@ -35,7 +33,7 @@ public CommunicationException(string message) /// /// Message describing the error. /// Inner exception. - public CommunicationException(string message, Exception inner) + public CommunicationException(string? message, Exception? inner) : base(message, inner) { } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ConnectedEventArgs.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ConnectedEventArgs.cs index c1971657e2..739ea5d982 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ConnectedEventArgs.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ConnectedEventArgs.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// @@ -39,7 +37,7 @@ public ConnectedEventArgs(Exception faultException) /// /// Gets the communication channel based on this connection. /// - public ICommunicationChannel Channel { get; private set; } + public ICommunicationChannel? Channel { get; private set; } /// /// Gets a value indicating whether channel is connected or not, true if it's connected. @@ -49,5 +47,5 @@ public ConnectedEventArgs(Exception faultException) /// /// Gets the exception if it's not connected. /// - public Exception Fault { get; private set; } + public Exception? Fault { get; private set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/DisconnectedEventArgs.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/DisconnectedEventArgs.cs index f3ee702417..f3e5f1aec1 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/DisconnectedEventArgs.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/DisconnectedEventArgs.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// @@ -15,5 +13,5 @@ public class DisconnectedEventArgs : EventArgs /// /// Gets or sets if there's an error on disconnection. /// - public Exception Error { get; set; } + public Exception? Error { get; set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ICommunicationChannel.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ICommunicationChannel.cs index c9f25c3556..4727c2875b 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ICommunicationChannel.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/ICommunicationChannel.cs @@ -4,8 +4,6 @@ using System; using System.Threading.Tasks; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; public interface ICommunicationChannel : IDisposable diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/MessageReceivedEventArgs.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/MessageReceivedEventArgs.cs index b479cee574..f23bd9ed71 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/MessageReceivedEventArgs.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/Communication/MessageReceivedEventArgs.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// @@ -15,5 +13,5 @@ public class MessageReceivedEventArgs : EventArgs /// /// Gets or sets the data contained in message frame. /// - public string Data { get; set; } + public string? Data { get; set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpoint.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpoint.cs index 4565659bae..00f2d6a1a4 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpoint.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpoint.cs @@ -3,8 +3,6 @@ using System; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; public interface ICommunicationEndPoint diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpointFactory.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpointFactory.cs index 872b045215..3abd70df5a 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpointFactory.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationEndpointFactory.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; public interface ICommunicationEndpointFactory diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationManager.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationManager.cs index 4c36cb241b..44a0a1e5da 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationManager.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ICommunicationManager.cs @@ -5,8 +5,6 @@ using System.Threading; using System.Threading.Tasks; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// @@ -72,13 +70,13 @@ public interface ICommunicationManager /// Reads message from the binary reader /// /// Returns message read from the binary reader - Message ReceiveMessage(); + Message? ReceiveMessage(); /// /// Reads message from the binary reader /// /// Raw message string - string ReceiveRawMessage(); + string? ReceiveRawMessage(); /// /// Reads message from the binary reader using read timeout @@ -89,7 +87,7 @@ public interface ICommunicationManager /// /// Returns message read from the binary reader /// - Task ReceiveMessageAsync(CancellationToken cancellationToken); + Task ReceiveMessageAsync(CancellationToken cancellationToken); /// /// Reads message from the binary reader using read timeout @@ -100,7 +98,7 @@ public interface ICommunicationManager /// /// Raw message string /// - Task ReceiveRawMessageAsync(CancellationToken cancellationToken); + Task ReceiveRawMessageAsync(CancellationToken cancellationToken); /// /// Writes message to the binary writer with payload @@ -129,5 +127,5 @@ public interface ICommunicationManager /// The type of object to deserialize to. /// Message object /// TestPlatform object - T DeserializePayload(Message message); + T? DeserializePayload(Message message); } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestHandler.cs index c38c8c3fda..6d26592429 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestHandler.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.CommunicationUtilities.DataCollection.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestSender.cs index 0459e5c8a1..960e1ae741 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionRequestSender.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.DataCollection.Interfaces; /// @@ -60,7 +58,7 @@ internal interface IDataCollectionRequestSender /// /// BeforeTestRunStartResult containing environment variables /// - BeforeTestRunStartResult SendBeforeTestRunStartAndGetResult(string settingXml, IEnumerable sources, bool isTelemetryOptedIn, ITestMessageEventHandler runEventsHandler); + BeforeTestRunStartResult? SendBeforeTestRunStartAndGetResult(string settingXml, IEnumerable sources, bool isTelemetryOptedIn, ITestMessageEventHandler? runEventsHandler); /// /// Sends the AfterTestRunEnd event and waits for result @@ -74,5 +72,5 @@ internal interface IDataCollectionRequestSender /// /// AfterTestRunEndResult containing dataCollector attachments and metrics /// - AfterTestRunEndResult SendAfterTestRunEndAndGetResult(ITestMessageEventHandler runEventsHandler, bool isCancelled); + AfterTestRunEndResult? SendAfterTestRunEndAndGetResult(ITestMessageEventHandler? runEventsHandler, bool isCancelled); } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventHandler.cs index ba136915e4..50be863e85 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventHandler.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.CommunicationUtilities.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventSender.cs index 10834221ad..6a0efce3ce 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataCollectionTestCaseEventSender.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// @@ -50,7 +48,7 @@ public interface IDataCollectionTestCaseEventSender /// /// The Collection of TestCase attachments. /// - Collection SendTestCaseEnd(TestCaseEndEventArgs e); + Collection? SendTestCaseEnd(TestCaseEndEventArgs e); /// /// Sends the SessionEnd event. This is used to as a trigger to close communication channel between datacollector process and testhost process. diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataSerializer.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataSerializer.cs index c3b0711fe8..ce8696170f 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataSerializer.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/IDataSerializer.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.CommunicationUtilities.Interfaces; /// @@ -23,14 +21,14 @@ public interface IDataSerializer /// The type of object to deserialize to. /// Message object /// TestPlatform object - T DeserializePayload(Message message); + T? DeserializePayload(Message message); /// /// Serializes and creates a raw message given a message type /// /// Message Type /// Raw Serialized message - string SerializeMessage(string messageType); + string SerializeMessage(string? messageType); /// /// Serializes and creates a raw message given a message type and the object payload @@ -38,7 +36,7 @@ public interface IDataSerializer /// Message Type /// Payload of the message /// Raw Serialized message - string SerializePayload(string messageType, object payload); + string SerializePayload(string? messageType, object? payload); /// /// Serializes and creates a raw message given a message type and the object payload @@ -47,7 +45,7 @@ public interface IDataSerializer /// Payload of the message /// version to be sent /// Raw Serialized message - string SerializePayload(string messageType, object payload, int version); + string SerializePayload(string? messageType, object? payload, int version); /// /// Creates cloned object for given object. @@ -55,5 +53,5 @@ public interface IDataSerializer /// The type of object to be cloned. /// Object to be cloned. /// Newly cloned object. - T Clone(T obj); + T? Clone(T? obj); } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs index 5285b96f46..58f43a5ab8 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestHandler.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine.TesthostProtocol; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// @@ -51,13 +49,13 @@ 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. @@ -73,14 +71,14 @@ 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 /// /// Discovery Complete Event Args /// The last Chunk. - void DiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable lastChunk); + void DiscoveryComplete(DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable? lastChunk); /// /// Launches a process with a given process info under debugger @@ -88,7 +86,7 @@ public interface ITestRequestHandler : IDisposable /// /// Process start info /// ProcessId of the launched process - int LaunchProcessWithDebuggerAttached(TestProcessStartInfo testProcessStartInfo); + int LaunchProcessWithDebuggerAttached(TestProcessStartInfo? testProcessStartInfo); /// /// Attach debugger to an already running process. diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestSender.cs index 3ab7609546..51f6d4f2c5 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITestRequestSender.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITransport.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITransport.cs index c01e682421..b79b24c479 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITransport.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Interfaces/ITransport.cs @@ -4,8 +4,6 @@ using System; using System.Net; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs index e70f4ac930..c337b16c6c 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; @@ -11,8 +12,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -20,20 +19,17 @@ namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// public class JsonDataSerializer : IDataSerializer { - private static JsonDataSerializer s_instance; + private static JsonDataSerializer? s_instance; private static readonly bool DisableFastJson = FeatureFlag.Instance.IsSet(FeatureFlag.DISABLE_FASTER_JSON_SERIALIZATION); - private static JsonSerializer s_payloadSerializer; // payload serializer for version <= 1 - private static JsonSerializer s_payloadSerializer2; // payload serializer for version >= 2 - private static JsonSerializerSettings s_fastJsonSettings; // serializer settings for faster json - private static JsonSerializerSettings s_jsonSettings; // serializer settings for serializer v1, which should use to deserialize message headers - private static JsonSerializer s_serializer; // generic serializer + private static readonly JsonSerializer s_payloadSerializer; // payload serializer for version <= 1 + private static readonly JsonSerializer s_payloadSerializer2; // payload serializer for version >= 2 + private static readonly JsonSerializerSettings s_fastJsonSettings; // serializer settings for faster json + private static readonly JsonSerializerSettings s_jsonSettings; // serializer settings for serializer v1, which should use to deserialize message headers + private static readonly JsonSerializer s_serializer; // generic serializer - /// - /// Prevents a default instance of the class from being created. - /// - private JsonDataSerializer() + static JsonDataSerializer() { var jsonSettings = new JsonSerializerSettings { @@ -78,6 +74,11 @@ private JsonDataSerializer() #endif } + /// + /// Prevents a default instance of the class from being created. + /// + private JsonDataSerializer() { } + /// /// Gets the JSON Serializer instance. /// @@ -100,7 +101,7 @@ public Message DeserializeMessage(string rawMessage) // PERF: Try grabbing the version and message type from the string directly, we are pretty certain how the message is serialized // when the format does not match all we do is that we check if 6th character in the message is 'V' - if (!FastHeaderParse(rawMessage, out int version, out string messageType)) + if (!FastHeaderParse(rawMessage, out int version, out string? messageType)) { // PERF: If the fast path fails, deserialize into header object that does not have any Payload. When the message type info // is at the start of the message, this is also pretty fast. Again, this won't touch the payload. @@ -125,7 +126,7 @@ public Message DeserializeMessage(string rawMessage) /// A object. /// Payload type. /// The deserialized payload. - public T DeserializePayload(Message message) + public T? DeserializePayload(Message message) { if (message.GetType() == typeof(Message)) { @@ -135,7 +136,7 @@ public T DeserializePayload(Message message) // Unit tests also provide a Message in places where using the deserializer would actually // produce a VersionedMessage or VersionedMessageWithRawMessage. var serializerV1 = GetPayloadSerializer(null); - return Deserialize(serializerV1, message.Payload); + return Deserialize(serializerV1, message.Payload!); } var versionedMessage = (VersionedMessage)message; @@ -145,7 +146,7 @@ public T DeserializePayload(Message message) { // When fast json is disabled, then the message is a VersionedMessage // with JToken payload. - return Deserialize(payloadSerializer, message.Payload); + return Deserialize(payloadSerializer, message.Payload!); } // When fast json is enabled then the message is also a subtype of VersionedMessage, but @@ -166,11 +167,11 @@ public T DeserializePayload(Message message) // PERF: When payloadSerializer1 was resolved we need to deserialize JToken, and then deserialize that. // This is still better than deserializing the JToken in DeserializeMessage because here we know that the payload // will actually be used. - return Deserialize(payloadSerializer, Deserialize(rawMessage).Payload); + return Deserialize(payloadSerializer, Deserialize(rawMessage!).Payload!); } } - private bool FastHeaderParse(string rawMessage, out int version, out string messageType) + private static bool FastHeaderParse(string rawMessage, out int version, out string? messageType) { // PERF: This can be also done slightly better using ReadOnlySpan but we don't have that available by default in .NET Framework // and the speed improvement does not warrant additional dependency. This is already taking just few ms for 10k messages. @@ -205,7 +206,7 @@ private bool FastHeaderParse(string rawMessage, out int version, out string mess var firstVersionNumberIndex = 11; // The message is versioned, get the version and update the position of first quote that contains message type. - if (!TryGetSubstringUntilDelimiter(rawMessage, firstVersionNumberIndex, ',', maxSearchLength: 4, out string versionString, out int versionCommaIndex)) + if (!TryGetSubstringUntilDelimiter(rawMessage, firstVersionNumberIndex, ',', maxSearchLength: 4, out string? versionString, out int versionCommaIndex)) { return false; } @@ -231,7 +232,7 @@ private bool FastHeaderParse(string rawMessage, out int version, out string mess int messageTypeStartIndex = messageTypeStartQuoteIndex + 1; // "TestExecution.LaunchAdapterProcessWithDebuggerAttachedCallback" is the longest message type we currently have with 62 chars - if (!TryGetSubstringUntilDelimiter(rawMessage, messageTypeStartIndex, '"', maxSearchLength: 100, out string messageTypeString, out _)) + if (!TryGetSubstringUntilDelimiter(rawMessage, messageTypeStartIndex, '"', maxSearchLength: 100, out string? messageTypeString, out _)) { return false; } @@ -249,7 +250,7 @@ private bool FastHeaderParse(string rawMessage, out int version, out string mess /// /// Try getting substring until a given delimiter, but don't search more characters than maxSearchLength. /// - private bool TryGetSubstringUntilDelimiter(string rawMessage, int start, char character, int maxSearchLength, out string substring, out int delimiterIndex) + private static bool TryGetSubstringUntilDelimiter(string rawMessage, int start, char character, int maxSearchLength, out string? substring, out int delimiterIndex) { var length = rawMessage.Length; var searchEnd = start + maxSearchLength; @@ -286,7 +287,7 @@ public T Deserialize(string json, int version = 1) /// /// Type of the message. /// Serialized message. - public string SerializeMessage(string messageType) + public string SerializeMessage(string? messageType) { return Serialize(s_serializer, new Message { MessageType = messageType }); } @@ -297,7 +298,7 @@ public string SerializeMessage(string messageType) /// Type of the message. /// Payload for the message. /// Serialized message. - public string SerializePayload(string messageType, object payload) + public string SerializePayload(string? messageType, object? payload) { return SerializePayload(messageType, payload, 1); } @@ -309,7 +310,7 @@ public string SerializePayload(string messageType, object payload) /// Payload for the message. /// Version for the message. /// Serialized message. - public string SerializePayload(string messageType, object payload, int version) + public string SerializePayload(string? messageType, object? payload, int version) { var payloadSerializer = GetPayloadSerializer(version); // Fast json is only equivalent to the serialization that is used for protocol version 2 and upwards (or more precisely for the paths that use s_payloadSerializer2) @@ -342,7 +343,8 @@ public string Serialize(T data, int version = 1) } /// - public T Clone(T obj) + [return: NotNullIfNotNull(nameof(obj))] + public T? Clone(T? obj) { if (obj == null) { @@ -350,7 +352,7 @@ public T Clone(T obj) } var stringObj = Serialize(obj, 2); - return Deserialize(stringObj, 2); + return Deserialize(stringObj, 2)!; } /// @@ -360,7 +362,7 @@ public T Clone(T obj) /// Serializer. /// Data to be serialized. /// Serialized data. - private string Serialize(JsonSerializer serializer, T data) + private static string Serialize(JsonSerializer serializer, T data) { using var stringWriter = new StringWriter(); using var jsonWriter = new JsonTextWriter(stringWriter); @@ -375,7 +377,7 @@ private string Serialize(JsonSerializer serializer, T data) /// Serializer. /// Data to be deserialized. /// Deserialized data. - private T Deserialize(JsonSerializer serializer, string data) + private static T Deserialize(JsonSerializer serializer, string data) { using var stringReader = new StringReader(data); using var jsonReader = new JsonTextReader(stringReader); @@ -389,12 +391,12 @@ private T Deserialize(JsonSerializer serializer, string data) /// Serializer. /// JToken to be deserialized. /// Deserialized data. - private T Deserialize(JsonSerializer serializer, JToken jToken) + private static T Deserialize(JsonSerializer serializer, JToken jToken) { return jToken.ToObject(serializer); } - private JsonSerializer GetPayloadSerializer(int? version) + private static JsonSerializer GetPayloadSerializer(int? version) { if (version == null) { @@ -422,7 +424,7 @@ private JsonSerializer GetPayloadSerializer(int? version) private class MessageHeader { public int Version { get; set; } - public string MessageType { get; set; } + public string? MessageType { get; set; } } /// @@ -434,7 +436,7 @@ private class MessageHeader /// private class VersionedMessageWithRawMessage : VersionedMessage { - public string RawMessage { get; set; } + public string? RawMessage { get; set; } public override string ToString() { @@ -448,7 +450,7 @@ public override string ToString() /// private class PayloadedMessage { - public T Payload { get; set; } + public T? Payload { get; set; } } /// @@ -464,11 +466,11 @@ private class VersionedMessageForSerialization /// /// Gets or sets the message type. /// - public string MessageType { get; set; } + public string? MessageType { get; set; } /// /// Gets or sets the payload. /// - public object Payload { get; set; } + public object? Payload { get; set; } } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs index 2ef5620d03..cb2caa195e 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs @@ -7,15 +7,10 @@ using System.Threading.Tasks; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; - using Microsoft.VisualStudio.TestPlatform.ObjectModel; - using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; - using Microsoft.VisualStudio.TestPlatform.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -42,7 +37,7 @@ public LengthPrefixCommunicationChannel(Stream stream) } /// - public event EventHandler MessageReceived; + public event EventHandler? MessageReceived; /// public Task Send(string data) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/BeforeTestRunStartPayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/BeforeTestRunStartPayload.cs index 1bb1d00d3b..6e3e9adc29 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/BeforeTestRunStartPayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/BeforeTestRunStartPayload.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -15,12 +13,12 @@ public class BeforeTestRunStartPayload /// /// Gets or sets run settings xml. /// - public string SettingsXml { get; set; } + public string? SettingsXml { get; set; } /// /// Gets or sets list of test sources. /// - public IEnumerable Sources { get; set; } + public IEnumerable? Sources { get; set; } /// /// Gets or sets a value indicating whether telemetry is enabled. diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs index d08b59dc2d..4ba52f8cef 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -22,7 +20,7 @@ public class DiscoveryCompletePayload /// /// Gets or sets the last chunk of discovered tests. /// - public IEnumerable LastDiscoveredTests { get; set; } + public IEnumerable? LastDiscoveredTests { get; set; } /// /// Gets or sets a value indicating whether discovery was aborted. @@ -32,7 +30,7 @@ public class DiscoveryCompletePayload /// /// Gets or sets the Metrics /// - public IDictionary Metrics { get; set; } + public IDictionary? Metrics { get; set; } /// /// Gets or sets list of sources which were fully discovered. diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/Message.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/Message.cs index a5d75e1549..e5037c5a9f 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/Message.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/Message.cs @@ -4,8 +4,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -16,7 +14,7 @@ public class Message /// /// Gets or sets the message type. /// - public string MessageType { get; set; } + public string? MessageType { get; set; } /// /// Gets or sets the payload. @@ -24,7 +22,7 @@ public class Message // TODO: Our public contract says that we should be able to communicate over JSON, but we should not be stopping ourselves from // negotiating a different protocol. Or using a different serialization library than NewtonsoftJson. Check why this is published as JToken // and not as a string. - public JToken Payload { get; set; } + public JToken? Payload { get; set; } /// /// To string implementation. @@ -34,6 +32,6 @@ public override string ToString() { // TODO: Review where this is used, we should avoid extensive serialization and deserialization, // and this might be happening in multiple places that are not the edge of our process. - return "(" + MessageType + ") -> " + (Payload == null ? "null" : Payload.ToString(Formatting.Indented)); + return $"({MessageType}) -> {(Payload == null ? "null" : Payload.ToString(Formatting.Indented))}"; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/MessageType.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/MessageType.cs index 0e78729547..e4907fde23 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/MessageType.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/MessageType.cs @@ -6,8 +6,6 @@ using static Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ProtocolVersioning; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestHostLaunchedPayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestHostLaunchedPayload.cs index 4c4598b2dd..d68f2786a4 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestHostLaunchedPayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestHostLaunchedPayload.cs @@ -3,8 +3,6 @@ using System.Runtime.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; public class TestHostLaunchedPayload diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestMessagePayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestMessagePayload.cs index d4d7f45550..f5d715df07 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestMessagePayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestMessagePayload.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -20,5 +18,5 @@ public class TestMessagePayload /// /// Gets or sets the message. /// - public string Message { get; set; } + public string? Message { get; set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingCompletePayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingCompletePayload.cs index f2b633455f..5ca9d1d3bf 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingCompletePayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingCompletePayload.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -18,10 +16,10 @@ public class TestRunAttachmentsProcessingCompletePayload /// /// Gets or sets the test run attachments processing complete args. /// - public TestRunAttachmentsProcessingCompleteEventArgs AttachmentsProcessingCompleteEventArgs { get; set; } + public TestRunAttachmentsProcessingCompleteEventArgs? AttachmentsProcessingCompleteEventArgs { get; set; } /// /// Gets or sets the attachments. /// - public IEnumerable Attachments { get; set; } + public IEnumerable? Attachments { get; set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingProgressPayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingProgressPayload.cs index 14e775f80d..2ec6d1af4f 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingProgressPayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunAttachmentsProcessingProgressPayload.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -15,5 +13,5 @@ public class TestRunAttachmentsProcessingProgressPayload /// /// Gets or sets the test run attachments processing complete args. /// - public TestRunAttachmentsProcessingProgressEventArgs AttachmentsProcessingProgressEventArgs { get; set; } + public TestRunAttachmentsProcessingProgressEventArgs? AttachmentsProcessingProgressEventArgs { get; set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunCompletePayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunCompletePayload.cs index fabd8c6fab..4953041d51 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunCompletePayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunCompletePayload.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -18,20 +16,20 @@ public class TestRunCompletePayload /// /// Gets or sets the test run complete args. /// - public TestRunCompleteEventArgs TestRunCompleteArgs { get; set; } + public TestRunCompleteEventArgs? TestRunCompleteArgs { get; set; } /// /// Gets or sets the last run tests. /// - public TestRunChangedEventArgs LastRunTests { get; set; } + public TestRunChangedEventArgs? LastRunTests { get; set; } /// /// Gets or sets the run attachments. /// - public ICollection RunAttachments { get; set; } + public ICollection? RunAttachments { get; set; } /// /// Gets or sets the executor uris that were used to run the tests. /// - public ICollection ExecutorUris { get; set; } + public ICollection? ExecutorUris { get; set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunStatsPayload.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunStatsPayload.cs index 26c2725438..159e8a1f6d 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunStatsPayload.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/TestRunStatsPayload.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -18,10 +16,10 @@ public class TestRunStatsPayload /// /// Gets or sets the test run changed event args. /// - public TestRunChangedEventArgs TestRunChangedArgs { get; set; } + public TestRunChangedEventArgs? TestRunChangedArgs { get; set; } /// /// Gets or sets the in progress test cases. /// - public IEnumerable InProgressTestCases { get; set; } + public IEnumerable? InProgressTestCases { get; set; } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/VersionedMessage.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/VersionedMessage.cs index b5e53e713d..a79a9eaceb 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/VersionedMessage.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Messages/VersionedMessage.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.CommunicationUtilities; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Microsoft.TestPlatform.CommunicationUtilities.csproj b/src/Microsoft.TestPlatform.CommunicationUtilities/Microsoft.TestPlatform.CommunicationUtilities.csproj index c5b5873f1a..20d3ed6aa4 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Microsoft.TestPlatform.CommunicationUtilities.csproj +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Microsoft.TestPlatform.CommunicationUtilities.csproj @@ -25,6 +25,11 @@ + + True + True + NullableHelpers.tt + True True @@ -38,6 +43,10 @@ + + NullableHelpers.cs + TextTemplatingFileGenerator + PublicResXFileCodeGenerator Resources.Designer.cs @@ -57,5 +66,8 @@ + + + diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/NullableHelpers.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/NullableHelpers.cs new file mode 100644 index 0000000000..3054557f08 --- /dev/null +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/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.VisualStudio.TestPlatform.CommunicationUtilities; + +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.CommunicationUtilities/NullableHelpers.tt b/src/Microsoft.TestPlatform.CommunicationUtilities/NullableHelpers.tt new file mode 100644 index 0000000000..7e3d8e7270 --- /dev/null +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/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.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs index 050788e2cc..8acd93afa3 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithSources.cs @@ -7,8 +7,6 @@ using Newtonsoft.Json; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -26,7 +24,7 @@ public class TestRunCriteriaWithSources /// The run settings. /// The test Execution Context. [JsonConstructor] - public TestRunCriteriaWithSources(Dictionary> adapterSourceMap, string package, string runSettings, TestExecutionContext testExecutionContext) + public TestRunCriteriaWithSources(Dictionary> adapterSourceMap, string package, string? runSettings, TestExecutionContext? testExecutionContext) { AdapterSourceMap = adapterSourceMap; Package = package; @@ -42,12 +40,12 @@ public TestRunCriteriaWithSources(Dictionary> adapte /// /// Gets the run settings. /// - public string RunSettings { get; private set; } + public string? RunSettings { get; private set; } /// /// Gets or sets the test execution context. /// - public TestExecutionContext TestExecutionContext { get; set; } + public TestExecutionContext? TestExecutionContext { get; set; } /// /// Gets the test Containers (e.g. .appx, .appxrecipie) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs index bba56c0417..2d5cb218ac 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/ObjectModel/TestRunCriteriaWithTests.cs @@ -8,8 +8,6 @@ using Newtonsoft.Json; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; /// @@ -28,7 +26,7 @@ public class TestRunCriteriaWithTests /// The test run settings. /// The test Execution Context. [JsonConstructor] - public TestRunCriteriaWithTests(IEnumerable tests, string package, string runSettings, TestExecutionContext testExecutionContext) + public TestRunCriteriaWithTests(IEnumerable tests, string package, string? runSettings, TestExecutionContext? testExecutionContext) { Tests = tests; Package = package; @@ -44,12 +42,12 @@ public TestRunCriteriaWithTests(IEnumerable tests, string package, str /// /// Gets the test run settings. /// - public string RunSettings { get; private set; } + public string? RunSettings { get; private set; } /// /// Gets or sets the test execution context. /// - public TestExecutionContext TestExecutionContext { get; set; } + public TestExecutionContext? TestExecutionContext { get; set; } /// /// Gets the test Containers (e.g. .appx, .appxrecipie) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/DefaultTestPlatformContractResolver.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/DefaultTestPlatformContractResolver.cs index 325dbcc203..354ad4d793 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/DefaultTestPlatformContractResolver.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/DefaultTestPlatformContractResolver.cs @@ -9,8 +9,6 @@ using Newtonsoft.Json.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Serialization; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs index 590d1d42bf..4c2ce9d6b4 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs @@ -8,8 +8,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Serialization; /// @@ -41,7 +39,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist // Let the null values be passed in as null data var token = property["Value"]; - string propertyData = null; + string? propertyData = null; if (token.Type != JTokenType.Null) { // If the property is already a string. No need to convert again. @@ -89,7 +87,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // P2 to P1 - var testCase = value as TestCase; + var testCase = (TestCase)value; writer.WriteStartObject(); writer.WritePropertyName("Properties"); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs index 93bc433c3c..ea82810608 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs @@ -10,8 +10,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Serialization; /// @@ -40,40 +38,44 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist throw new ArgumentException("the objectType was not a KeyValuePair list", nameof(objectType)); } - var propertyList = new List>(); + var propertyList = new List>(); + + if (reader.TokenType != JsonToken.StartArray) + { + return propertyList; + } - if (reader.TokenType == JsonToken.StartArray) + var properties = JArray.Load(reader); + if (properties == null || !properties.HasValues) { - var properties = JArray.Load(reader); - if (properties != null && properties.HasValues) + return propertyList; + } + + // Every class that inherits from TestObject uses a properties store for + // key value pairs. + foreach (var property in properties) + { + var testProperty = property["Key"].ToObject(serializer); + + // Let the null values be passed in as null data + var token = property["Value"]; + object? propertyData = null; + if (token.Type != JTokenType.Null) { - // Every class that inherits from TestObject uses a properties store for - // key value pairs. - foreach (var property in properties) + // If the property is already a string. No need to convert again. + if (token.Type == JTokenType.String) { - var testProperty = property["Key"].ToObject(serializer); - - // Let the null values be passed in as null data - var token = property["Value"]; - object propertyData = null; - if (token.Type != JTokenType.Null) - { - // If the property is already a string. No need to convert again. - if (token.Type == JTokenType.String) - { - propertyData = token.ToObject(typeof(string), serializer); - } - else - { - // On deserialization, the value for each TestProperty is always a string. It is up - // to the consumer to deserialize it further as appropriate. - propertyData = token.ToString(Formatting.None).Trim('"'); - } - } - - propertyList.Add(new KeyValuePair(testProperty, propertyData)); + propertyData = token.ToObject(typeof(string), serializer); + } + else + { + // On deserialization, the value for each TestProperty is always a string. It is up + // to the consumer to deserialize it further as appropriate. + propertyData = token.ToString(Formatting.None).Trim('"'); } } + + propertyList.Add(new KeyValuePair(testProperty, propertyData)); } return propertyList; @@ -111,7 +113,7 @@ public TestObjectConverter7() /// public override bool CanWrite => false; - public ConstructorInfo TestPropertyCtor { get; } + public ConstructorInfo? TestPropertyCtor { get; } /// public override bool CanConvert(Type objectType) @@ -128,49 +130,50 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist throw new ArgumentException("the objectType was not a KeyValuePair list", nameof(objectType)); } - if (reader.TokenType == JsonToken.StartArray) + if (reader.TokenType != JsonToken.StartArray) { - var deserializedProperties = serializer.Deserialize>>(reader); - // Initialize the list capacity to be the number of properties we might add. - var propertyList = new List>(deserializedProperties.Count); + return new List>(); + } - // Every class that inherits from TestObject uses a properties store for - // key value pairs. - foreach (var property in deserializedProperties) + var deserializedProperties = serializer.Deserialize>>(reader); + // Initialize the list capacity to be the number of properties we might add. + var propertyList = new List>(deserializedProperties.Count); + + // Every class that inherits from TestObject uses a properties store for + // key value pairs. + foreach (var property in deserializedProperties) + { + // 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.Attributes = (TestPropertyAttributes)property.Key.Attributes; + testProperty.ValueType = property.Key.ValueType; + + + object? propertyData = null; + JToken token = property.Value; + if (token.Type != JTokenType.Null) { - 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.Attributes = (TestPropertyAttributes)property.Key.Attributes; - testProperty.ValueType = property.Key.ValueType; - - - object propertyData = null; - JToken token = property.Value; - if (token.Type != JTokenType.Null) + // If the property is already a string. No need to convert again. + if (token.Type == JTokenType.String) { - // If the property is already a string. No need to convert again. - if (token.Type == JTokenType.String) - { - propertyData = token.ToObject(typeof(string), serializer); - } - else - { - // On deserialization, the value for each TestProperty is always a string. It is up - // to the consumer to deserialize it further as appropriate. - propertyData = token.ToString(Formatting.None).Trim('"'); - } + propertyData = token.ToObject(typeof(string), serializer); + } + else + { + // On deserialization, the value for each TestProperty is always a string. It is up + // to the consumer to deserialize it further as appropriate. + propertyData = token.ToString(Formatting.None).Trim('"'); } - - propertyList.Add(new KeyValuePair(testProperty, propertyData)); } - return propertyList; + propertyList.Add(new KeyValuePair(testProperty, propertyData)); } - return new List>(); + return propertyList; } /// @@ -181,11 +184,11 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s private class TestPropertyTemplate { - public string Id { get; set; } - public string Label { get; set; } - public string Category { get; set; } - public string Description { get; set; } + public string? Id { get; set; } + public string? Label { get; set; } + public string? Category { get; set; } + public string? Description { get; set; } public int Attributes { get; set; } - public string ValueType { get; set; } + public string? ValueType { get; set; } } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestPlatformContractResolver1.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestPlatformContractResolver1.cs index 05f4a051ef..21d08a53fb 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestPlatformContractResolver1.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestPlatformContractResolver1.cs @@ -7,8 +7,6 @@ using Newtonsoft.Json.Serialization; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Serialization; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs index 5e1c869551..0bfb2c241c 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs @@ -8,8 +8,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Serialization; /// @@ -58,57 +56,59 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist } JToken properties = data["Properties"]; - if (properties != null && properties.HasValues) + if (properties == null || !properties.HasValues) { - // Every class that inherits from TestObject uses a properties store for - // key value pairs. - foreach (var property in properties.Values()) - { - var testProperty = property["Key"].ToObject(serializer); + return testResult; + } + + // Every class that inherits from TestObject uses a properties store for + // key value pairs. + foreach (var property in properties.Values()) + { + var testProperty = property["Key"].ToObject(serializer); - // Let the null values be passed in as null data - var token = property["Value"]; - string propertyData = null; - if (token.Type != JTokenType.Null) + // Let the null values be passed in as null data + var token = property["Value"]; + string? propertyData = null; + if (token.Type != JTokenType.Null) + { + // If the property is already a string. No need to convert again. + if (token.Type == JTokenType.String) { - // If the property is already a string. No need to convert again. - if (token.Type == JTokenType.String) - { - propertyData = token.ToObject(serializer); - } - else - { - // On deserialization, the value for each TestProperty is always a string. It is up - // to the consumer to deserialize it further as appropriate. - propertyData = token.ToString(Formatting.None).Trim('"'); - } + propertyData = token.ToObject(serializer); } - - switch (testProperty.Id) + else { - case "TestResult.DisplayName": - testResult.DisplayName = propertyData; break; - case "TestResult.ComputerName": - testResult.ComputerName = propertyData ?? string.Empty; break; - case "TestResult.Outcome": - testResult.Outcome = (TestOutcome)Enum.Parse(typeof(TestOutcome), propertyData); break; - case "TestResult.Duration": - testResult.Duration = TimeSpan.Parse(propertyData); break; - case "TestResult.StartTime": - testResult.StartTime = DateTimeOffset.Parse(propertyData); break; - case "TestResult.EndTime": - testResult.EndTime = DateTimeOffset.Parse(propertyData); break; - case "TestResult.ErrorMessage": - testResult.ErrorMessage = propertyData; break; - case "TestResult.ErrorStackTrace": - testResult.ErrorStackTrace = propertyData; break; - default: - // No need to register member properties as they get registered as part of TestResultProperties class. - testProperty = TestProperty.Register(testProperty.Id, testProperty.Label, testProperty.GetValueType(), testProperty.Attributes, typeof(TestObject)); - testResult.SetPropertyValue(testProperty, propertyData); - break; + // On deserialization, the value for each TestProperty is always a string. It is up + // to the consumer to deserialize it further as appropriate. + propertyData = token.ToString(Formatting.None).Trim('"'); } } + + switch (testProperty.Id) + { + case "TestResult.DisplayName": + testResult.DisplayName = propertyData; break; + case "TestResult.ComputerName": + testResult.ComputerName = propertyData ?? string.Empty; break; + case "TestResult.Outcome": + testResult.Outcome = (TestOutcome)Enum.Parse(typeof(TestOutcome), propertyData); break; + case "TestResult.Duration": + testResult.Duration = TimeSpan.Parse(propertyData); break; + case "TestResult.StartTime": + testResult.StartTime = DateTimeOffset.Parse(propertyData); break; + case "TestResult.EndTime": + testResult.EndTime = DateTimeOffset.Parse(propertyData); break; + case "TestResult.ErrorMessage": + testResult.ErrorMessage = propertyData; break; + case "TestResult.ErrorStackTrace": + testResult.ErrorStackTrace = propertyData; break; + default: + // No need to register member properties as they get registered as part of TestResultProperties class. + testProperty = TestProperty.Register(testProperty.Id, testProperty.Label, testProperty.GetValueType(), testProperty.Attributes, typeof(TestObject)); + testResult.SetPropertyValue(testProperty, propertyData); + break; + } } return testResult; @@ -118,7 +118,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // P2 to P1 - var testResult = value as TestResult; + var testResult = (TestResult)value; writer.WriteStartObject(); writer.WritePropertyName("TestCase"); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestRunStatisticsConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestRunStatisticsConverter.cs index 166dcc8c5e..05a03fdf57 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestRunStatisticsConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestRunStatisticsConverter.cs @@ -7,8 +7,6 @@ using Newtonsoft.Json; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Serialization; /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketClient.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketClient.cs index f670ba9330..d8a51561ed 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketClient.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketClient.cs @@ -8,13 +8,9 @@ using System.Threading.Tasks; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; - using Microsoft.VisualStudio.TestPlatform.ObjectModel; - using Microsoft.VisualStudio.TestPlatform.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -25,9 +21,10 @@ public class SocketClient : ICommunicationEndPoint private readonly CancellationTokenSource _cancellation; private readonly TcpClient _tcpClient; private readonly Func _channelFactory; - private ICommunicationChannel _channel; + + private ICommunicationChannel? _channel; private bool _stopped; - private string _endPoint; + private string? _endPoint; public SocketClient() : this(stream => new LengthPrefixCommunicationChannel(stream)) @@ -45,10 +42,10 @@ protected SocketClient(Func channelFactory) } /// - public event EventHandler Connected; + public event EventHandler? Connected; /// - public event EventHandler Disconnected; + public event EventHandler? Disconnected; /// public string Start(string endPoint) @@ -103,7 +100,7 @@ private void OnServerConnected(Task connectAsyncTask) } } - private void StopOnError(Exception error) + private void StopOnError(Exception? error) { EqtTrace.Info("SocketClient.PrivateStop: Stop communication from server endpoint: {0}, error:{1}", _endPoint, error); // This is here to prevent stack overflow. @@ -120,7 +117,7 @@ private void StopOnError(Exception error) // tcpClient.Close() not available for netstandard1.5. _tcpClient?.Dispose(); #endif - _channel.Dispose(); + _channel?.Dispose(); _cancellation.Dispose(); Disconnected?.SafeInvoke(this, new DisconnectedEventArgs(), "SocketClient: ServerDisconnected"); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketCommunicationManager.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketCommunicationManager.cs index e6b15b4b9e..d7dc481b39 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketCommunicationManager.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketCommunicationManager.cs @@ -14,8 +14,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -31,22 +29,22 @@ public class SocketCommunicationManager : ICommunicationManager /// /// TCP Listener to host TCP channel and listen /// - private TcpListener _tcpListener; + private TcpListener? _tcpListener; /// /// TCP Client that can connect to a TCP listener /// - private TcpClient _tcpClient; + private TcpClient? _tcpClient; /// /// Binary Writer to write to channel stream /// - private BinaryWriter _binaryWriter; + private BinaryWriter? _binaryWriter; /// /// Binary reader to read from channel stream /// - private BinaryReader _binaryReader; + private BinaryReader? _binaryReader; /// /// Serializer for the data objects @@ -74,7 +72,7 @@ public class SocketCommunicationManager : ICommunicationManager /// private readonly object _receiveSyncObject = new(); - private Socket _socket; + private Socket? _socket; /// /// Initializes a new instance of the class. @@ -111,24 +109,26 @@ public IPEndPoint HostServer(IPEndPoint endpoint) /// A representing the asynchronous operation. public async Task AcceptClientAsync() { - if (_tcpListener != null) + if (_tcpListener == null) { - _clientConnectedEvent.Reset(); + return; + } - var client = await _tcpListener.AcceptTcpClientAsync(); - _socket = client.Client; - _socket.NoDelay = true; + _clientConnectedEvent.Reset(); - // Using Buffered stream only in case of write, and Network stream in case of read. - var bufferedStream = new PlatformStream().CreateBufferedStream(client.GetStream(), SocketConstants.BufferSize); - var networkStream = client.GetStream(); - _binaryReader = new BinaryReader(networkStream); - _binaryWriter = new BinaryWriter(bufferedStream); + var client = await _tcpListener.AcceptTcpClientAsync(); + _socket = client.Client; + _socket.NoDelay = true; - _clientConnectedEvent.Set(); - EqtTrace.Info("Using the buffer size of {0} bytes", SocketConstants.BufferSize); - EqtTrace.Info("Accepted Client request and set the flag"); - } + // Using Buffered stream only in case of write, and Network stream in case of read. + var bufferedStream = new PlatformStream().CreateBufferedStream(client.GetStream(), SocketConstants.BufferSize); + var networkStream = client.GetStream(); + _binaryReader = new BinaryReader(networkStream); + _binaryWriter = new BinaryWriter(bufferedStream); + + _clientConnectedEvent.Set(); + EqtTrace.Info("Using the buffer size of {0} bytes", SocketConstants.BufferSize); + EqtTrace.Info("Accepted Client request and set the flag"); } /// @@ -287,15 +287,12 @@ public void SendRawMessage(string rawMessage) /// Reads message from the binary reader /// /// Returns message read from the binary reader - public Message ReceiveMessage() + public Message? ReceiveMessage() { var rawMessage = ReceiveRawMessage(); - if (!string.IsNullOrEmpty(rawMessage)) - { - return _dataSerializer.DeserializeMessage(rawMessage); - } - - return null; + return !rawMessage.IsNullOrEmpty() + ? _dataSerializer.DeserializeMessage(rawMessage) + : null; } /// @@ -307,22 +304,19 @@ public Message ReceiveMessage() /// /// Returns message read from the binary reader /// - public async Task ReceiveMessageAsync(CancellationToken cancellationToken) + public async Task ReceiveMessageAsync(CancellationToken cancellationToken) { var rawMessage = await ReceiveRawMessageAsync(cancellationToken); - if (!string.IsNullOrEmpty(rawMessage)) - { - return _dataSerializer.DeserializeMessage(rawMessage); - } - - return null; + return !rawMessage.IsNullOrEmpty() + ? _dataSerializer.DeserializeMessage(rawMessage) + : null; } /// /// Reads message from the binary reader /// /// Raw message string - public string ReceiveRawMessage() + public string? ReceiveRawMessage() { lock (_receiveSyncObject) { @@ -340,7 +334,7 @@ public string ReceiveRawMessage() /// /// Raw message string /// - public async Task ReceiveRawMessageAsync(CancellationToken cancellationToken) + public async Task ReceiveRawMessageAsync(CancellationToken cancellationToken) { var str = await Task.Run(() => TryReceiveRawMessage(cancellationToken)); return str; @@ -352,14 +346,14 @@ public async Task ReceiveRawMessageAsync(CancellationToken cancellationT /// The type of object to deserialize to. /// Message object /// TestPlatform object - public T DeserializePayload(Message message) + public T? DeserializePayload(Message message) { return _dataSerializer.DeserializePayload(message); } - private string TryReceiveRawMessage(CancellationToken cancellationToken) + private string? TryReceiveRawMessage(CancellationToken cancellationToken) { - string str = null; + string? str = null; bool success = false; // Set read timeout to avoid blocking receive raw message @@ -367,6 +361,7 @@ private string TryReceiveRawMessage(CancellationToken cancellationToken) { try { + TPDebug.Assert(_socket is not null, "_socket is null"); if (_socket.Poll(STREAMREADTIMEOUT, SelectMode.SelectRead)) { str = ReceiveRawMessage(); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketConstants.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketConstants.cs index 7fb383ee6a..0832b30eb0 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketConstants.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketConstants.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.CommunicationUtilities; public class SocketConstants diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketServer.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketServer.cs index a4d5ec0c5b..6434c016bb 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketServer.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketServer.cs @@ -8,13 +8,9 @@ using System.Threading.Tasks; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; - using Microsoft.VisualStudio.TestPlatform.ObjectModel; - using Microsoft.VisualStudio.TestPlatform.Utilities; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -23,18 +19,13 @@ namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; public class SocketServer : ICommunicationEndPoint { private readonly CancellationTokenSource _cancellation; - private readonly Func _channelFactory; - private ICommunicationChannel _channel; - - private TcpListener _tcpListener; - - private TcpClient _tcpClient; - + private ICommunicationChannel? _channel; + private TcpListener? _tcpListener; + private TcpClient? _tcpClient; private bool _stopped; - - private string _endPoint; + private string? _endPoint; /// /// Initializes a new instance of the class. @@ -58,10 +49,10 @@ protected SocketServer(Func channelFactory) } /// - public event EventHandler Connected; + public event EventHandler? Connected; /// - public event EventHandler Disconnected; + public event EventHandler? Disconnected; public string Start(string endPoint) { @@ -102,16 +93,18 @@ private void OnClientConnected(TcpClient client) _tcpClient = client; _tcpClient.Client.NoDelay = true; - if (Connected != null) + if (Connected == null) { - _channel = _channelFactory(_tcpClient.GetStream()); - Connected.SafeInvoke(this, new ConnectedEventArgs(_channel), "SocketServer: ClientConnected"); + return; + } - EqtTrace.Verbose("SocketServer.OnClientConnected: Client connected for endPoint: {0}, starting MessageLoopAsync:", _endPoint); + _channel = _channelFactory(_tcpClient.GetStream()); + Connected.SafeInvoke(this, new ConnectedEventArgs(_channel), "SocketServer: ClientConnected"); - // Start the message loop - Task.Run(() => _tcpClient.MessageLoopAsync(_channel, error => StopOnError(error), _cancellation.Token)).ConfigureAwait(false); - } + EqtTrace.Verbose("SocketServer.OnClientConnected: Client connected for endPoint: {0}, starting MessageLoopAsync:", _endPoint); + + // Start the message loop + Task.Run(() => _tcpClient.MessageLoopAsync(_channel, error => StopOnError(error), _cancellation.Token)).ConfigureAwait(false); } /// @@ -119,31 +112,36 @@ private void OnClientConnected(TcpClient client) /// that we aborted. /// /// - private void StopOnError(Exception error) + private void StopOnError(Exception? error) { EqtTrace.Info("SocketServer.PrivateStop: Stopping server endPoint: {0} error: {1}", _endPoint, error); - if (!_stopped) + if (_stopped) { - // Do not allow stop to be called multiple times. - _stopped = true; + return; + } + + TPDebug.Assert(_tcpListener is not null, $"{nameof(_tcpListener)} is null"); + TPDebug.Assert(_channel is not null, $"{nameof(_channel)} is null"); - // Stop accepting any other connections - _tcpListener.Stop(); + // Do not allow stop to be called multiple times. + _stopped = true; - // Close the client and dispose the underlying stream + // Stop accepting any other connections + _tcpListener.Stop(); + + // Close the client and dispose the underlying stream #if NETFRAMEWORK - // tcpClient.Close() calls tcpClient.Dispose(). - _tcpClient?.Close(); + // tcpClient.Close() calls tcpClient.Dispose(). + _tcpClient?.Close(); #else - // tcpClient.Close() not available for netstandard1.5. - _tcpClient?.Dispose(); + // tcpClient.Close() not available for netstandard1.5. + _tcpClient?.Dispose(); #endif - _channel.Dispose(); - _cancellation.Dispose(); + _channel.Dispose(); + _cancellation.Dispose(); - EqtTrace.Info("SocketServer.Stop: Raise disconnected event endPoint: {0} error: {1}", _endPoint, error); - Disconnected?.SafeInvoke(this, new DisconnectedEventArgs { Error = error }, "SocketServer: ClientDisconnected"); - } + EqtTrace.Info("SocketServer.Stop: Raise disconnected event endPoint: {0} error: {1}", _endPoint, error); + Disconnected?.SafeInvoke(this, new DisconnectedEventArgs { Error = error }, "SocketServer: ClientDisconnected"); } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketTransport.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketTransport.cs index 0bd9a4e047..150fc0f732 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/SocketTransport.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/SocketTransport.cs @@ -5,25 +5,21 @@ using System.Net; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; - using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// public sealed class SocketTransport : ITransport { + private readonly TestHostConnectionInfo _connectionInfo; + private readonly ICommunicationManager _communicationManager; + /// /// Specifies whether the resolver is disposed or not /// private bool _disposed; - private readonly TestHostConnectionInfo _connectionInfo; - - private readonly ICommunicationManager _communicationManager; - public SocketTransport(ICommunicationManager communicationManager, TestHostConnectionInfo connectionInfo) { _communicationManager = communicationManager; @@ -34,6 +30,7 @@ public SocketTransport(ICommunicationManager communicationManager, TestHostConne public IPEndPoint Initialize() { var endpoint = GetIpEndPoint(_connectionInfo.Endpoint); + TPDebug.Assert(endpoint is not null, "endpoint is null"); switch (_connectionInfo.Role) { case ConnectionRole.Host: @@ -47,7 +44,7 @@ public IPEndPoint Initialize() case ConnectionRole.Client: { - _communicationManager.SetupClientAsync(GetIpEndPoint(_connectionInfo.Endpoint)); + _communicationManager.SetupClientAsync(endpoint); return endpoint; } @@ -92,7 +89,7 @@ private void Dispose(bool disposing) /// /// Input endpoint address /// IPEndpoint from give string - private IPEndPoint GetIpEndPoint(string endpointAddress) + private static IPEndPoint? GetIpEndPoint(string endpointAddress) { return Uri.TryCreate(string.Concat("tcp://", endpointAddress), UriKind.Absolute, out Uri uri) ? new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port) diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/TcpClientExtensions.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/TcpClientExtensions.cs index fd6ad3c0bd..36e8dccaa0 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/TcpClientExtensions.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/TcpClientExtensions.cs @@ -9,11 +9,8 @@ using System.Threading.Tasks; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; - using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; internal static class TcpClientExtensions @@ -24,10 +21,10 @@ internal static class TcpClientExtensions internal static Task MessageLoopAsync( this TcpClient client, ICommunicationChannel channel, - Action errorHandler, + Action errorHandler, CancellationToken cancellationToken) { - Exception error = null; + Exception? error = null; var remoteEndPoint = string.Empty; var localEndPoint = string.Empty; diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs index ead4d77aaa..8ecade2906 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs @@ -19,8 +19,6 @@ using CommonResources = Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Resources.Resources; using ObjectModelConstants = Microsoft.VisualStudio.TestPlatform.ObjectModel.Constants; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// @@ -32,38 +30,24 @@ public class TestRequestSender : ITestRequestSender private const int ClientProcessExitWaitTimeout = 10 * 1000; private readonly IDataSerializer _dataSerializer; - private readonly ManualResetEventSlim _connected; - private readonly ManualResetEventSlim _clientExited; - private readonly int _clientExitedWaitTime; - private readonly ICommunicationEndPoint _communicationEndpoint; + private readonly int _highestSupportedVersion = ProtocolVersioning.HighestSupportedVersion; + private readonly TestHostConnectionInfo _connectionInfo; + private readonly ITestRuntimeProvider? _runtimeProvider; - private ICommunicationChannel _channel; - - private EventHandler _onMessageReceived; - - private Action _onDisconnected; - + private ICommunicationChannel? _channel; + private EventHandler? _onMessageReceived; + private Action? _onDisconnected; // Set to 1 if Discovery/Execution is complete, i.e. complete handlers have been invoked private int _operationCompleted; - - private ITestMessageEventHandler _messageEventHandler; - - private string _clientExitErrorMessage; - + private ITestMessageEventHandler? _messageEventHandler; + private string? _clientExitErrorMessage; // Set default to 1, if protocol version check does not happen // that implies host is using version 1. private int _protocolVersion = 1; - - private readonly int _highestSupportedVersion = ProtocolVersioning.HighestSupportedVersion; - - private readonly TestHostConnectionInfo _connectionInfo; - - private readonly ITestRuntimeProvider _runtimeProvider; - private bool _isDiscoveryAborted; /// @@ -83,8 +67,8 @@ public TestRequestSender(ProtocolConfig protocolConfig, ITestRuntimeProvider run } internal TestRequestSender( - ITestRuntimeProvider runtimeProvider, - ICommunicationEndPoint communicationEndPoint, + ITestRuntimeProvider? runtimeProvider, + ICommunicationEndPoint? communicationEndPoint, TestHostConnectionInfo testhostConnectionInfo, IDataSerializer serializer, ProtocolConfig protocolConfig, @@ -197,6 +181,8 @@ public bool WaitForRequestHandlerConnection(int connectionTimeout, CancellationT /// public void CheckVersionWithTestHost() { + TPDebug.Assert(_channel is not null, "_channel is null"); + // Negotiation follows these steps: // Runner sends highest supported version to Test host // Test host compares the version with the highest version it can support. @@ -205,7 +191,7 @@ public void CheckVersionWithTestHost() var protocolNegotiated = new ManualResetEvent(false); _onMessageReceived = (sender, args) => { - var message = _dataSerializer.DeserializeMessage(args.Data); + var message = _dataSerializer.DeserializeMessage(args.Data!); EqtTrace.Verbose("TestRequestSender.CheckVersionWithTestHost: onMessageReceived received message: {0}", message); @@ -266,6 +252,7 @@ public void CheckVersionWithTestHost() /// public void InitializeDiscovery(IEnumerable pathToAdditionalExtensions) { + TPDebug.Assert(_channel is not null, "_channel is null"); var message = _dataSerializer.SerializePayload( MessageType.DiscoveryInitialize, pathToAdditionalExtensions, @@ -279,10 +266,11 @@ public void InitializeDiscovery(IEnumerable pathToAdditionalExtensions) /// public void DiscoverTests(DiscoveryCriteria discoveryCriteria, ITestDiscoveryEventsHandler2 discoveryEventsHandler) { + TPDebug.Assert(_channel is not null, "_channel is null"); _messageEventHandler = discoveryEventsHandler; // When testhost disconnects, it normally means there was an error in the testhost and it exited unexpectedly. // But when it was us who aborted the run and killed the testhost, we don't want to wait for it to report error, because there won't be any. - _onDisconnected = (disconnectedEventArgs) => OnDiscoveryAbort(discoveryEventsHandler, disconnectedEventArgs.Error, getClientError: !_isDiscoveryAborted); + _onDisconnected = disconnectedEventArgs => OnDiscoveryAbort(discoveryEventsHandler, disconnectedEventArgs.Error, getClientError: !_isDiscoveryAborted); _onMessageReceived = (sender, args) => OnDiscoveryMessageReceived(discoveryEventsHandler, args); _channel.MessageReceived += _onMessageReceived; @@ -316,6 +304,7 @@ public void SendDiscoveryAbort() /// public void InitializeExecution(IEnumerable pathToAdditionalExtensions) { + TPDebug.Assert(_channel is not null, "_channel is null"); var message = _dataSerializer.SerializePayload( MessageType.ExecutionInitialize, pathToAdditionalExtensions, @@ -329,6 +318,7 @@ public void InitializeExecution(IEnumerable pathToAdditionalExtensions) /// public void StartTestRun(TestRunCriteriaWithSources runCriteria, IInternalTestRunEventsHandler eventHandler) { + TPDebug.Assert(_channel is not null, "_channel is null"); _messageEventHandler = eventHandler; _onDisconnected = (disconnectedEventArgs) => OnTestRunAbort(eventHandler, disconnectedEventArgs.Error, true); @@ -371,6 +361,7 @@ public void StartTestRun(TestRunCriteriaWithSources runCriteria, IInternalTestRu /// public void StartTestRun(TestRunCriteriaWithTests runCriteria, IInternalTestRunEventsHandler eventHandler) { + TPDebug.Assert(_channel is not null, "_channel is null"); _messageEventHandler = eventHandler; _onDisconnected = (disconnectedEventArgs) => OnTestRunAbort(eventHandler, disconnectedEventArgs.Error, true); @@ -490,6 +481,8 @@ private void OnExecutionMessageReceived(MessageReceivedEventArgs messageReceived { var rawMessage = messageReceived.Data; EqtTrace.Verbose("TestRequestSender.OnExecutionMessageReceived: Received message: {0}", rawMessage); + TPDebug.Assert(rawMessage is not null, "rawMessage is null"); + TPDebug.Assert(_channel is not null, "_channel is null"); // Send raw message first to unblock handlers waiting to send message to IDEs testRunEventsHandler.HandleRawMessage(rawMessage); @@ -505,6 +498,7 @@ private void OnExecutionMessageReceived(MessageReceivedEventArgs messageReceived break; case MessageType.ExecutionComplete: var testRunCompletePayload = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(testRunCompletePayload is not null, "testRunCompletePayload is null"); testRunEventsHandler.HandleTestRunComplete( testRunCompletePayload.TestRunCompleteArgs, @@ -516,6 +510,7 @@ private void OnExecutionMessageReceived(MessageReceivedEventArgs messageReceived break; case MessageType.TestMessage: var testMessagePayload = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(testMessagePayload is not null, "testMessagePayload is null"); testRunEventsHandler.HandleLogMessage(testMessagePayload.MessageLevel, testMessagePayload.Message); break; case MessageType.LaunchAdapterProcessWithDebuggerAttached: @@ -534,6 +529,7 @@ private void OnExecutionMessageReceived(MessageReceivedEventArgs messageReceived case MessageType.AttachDebugger: var testProcessAttachDebuggerPayload = _dataSerializer.DeserializePayload(message); + TPDebug.Assert(testProcessAttachDebuggerPayload is not null, "testProcessAttachDebuggerPayload is null"); AttachDebuggerInfo attachDebugerInfo = MessageConverter.ConvertToAttachDebuggerInfo(testProcessAttachDebuggerPayload, message, _protocolVersion); bool result = testRunEventsHandler.AttachDebuggerToProcess(attachDebugerInfo); @@ -562,6 +558,7 @@ private void OnDiscoveryMessageReceived(ITestDiscoveryEventsHandler2 discoveryEv try { var rawMessage = args.Data; + TPDebug.Assert(rawMessage is not null, "rawMessage is null"); // Currently each of the operations are not separate tasks since they should not each take much time. This is just a notification. EqtTrace.Verbose("TestRequestSender.OnDiscoveryMessageReceived: Received message: {0}", rawMessage); @@ -570,7 +567,7 @@ private void OnDiscoveryMessageReceived(ITestDiscoveryEventsHandler2 discoveryEv discoveryEventsHandler.HandleRawMessage(rawMessage); var data = _dataSerializer.DeserializeMessage(rawMessage); - switch (data.MessageType) + switch (data!.MessageType) { case MessageType.TestCasesFound: var testCases = _dataSerializer.DeserializePayload>(data); @@ -578,6 +575,7 @@ private void OnDiscoveryMessageReceived(ITestDiscoveryEventsHandler2 discoveryEv break; case MessageType.DiscoveryComplete: var payload = _dataSerializer.DeserializePayload(data); + TPDebug.Assert(payload is not null, "payload is null"); var discoveryCompleteEventArgs = new DiscoveryCompleteEventArgs { TotalCount = payload.TotalTests, @@ -597,6 +595,7 @@ private void OnDiscoveryMessageReceived(ITestDiscoveryEventsHandler2 discoveryEv case MessageType.TestMessage: var testMessagePayload = _dataSerializer.DeserializePayload( data); + TPDebug.Assert(testMessagePayload is not null, "testMessagePayload is null"); discoveryEventsHandler.HandleLogMessage( testMessagePayload.MessageLevel, testMessagePayload.Message); @@ -609,7 +608,7 @@ private void OnDiscoveryMessageReceived(ITestDiscoveryEventsHandler2 discoveryEv } } - private void OnTestRunAbort(IInternalTestRunEventsHandler testRunEventsHandler, Exception exception, bool getClientError) + private void OnTestRunAbort(IInternalTestRunEventsHandler testRunEventsHandler, Exception? exception, bool getClientError) { if (IsOperationComplete()) { @@ -634,7 +633,7 @@ private void OnTestRunAbort(IInternalTestRunEventsHandler testRunEventsHandler, testRunEventsHandler.HandleTestRunComplete(completeArgs, null, null, null); } - private void OnDiscoveryAbort(ITestDiscoveryEventsHandler2 eventHandler, Exception exception, bool getClientError) + private void OnDiscoveryAbort(ITestDiscoveryEventsHandler2 eventHandler, Exception? exception, bool getClientError) { if (IsOperationComplete()) { @@ -671,9 +670,9 @@ private void OnDiscoveryAbort(ITestDiscoveryEventsHandler2 eventHandler, Excepti eventHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, null); } - private string GetAbortErrorMessage(Exception exception, bool getClientError) + private string? GetAbortErrorMessage(Exception? exception, bool getClientError) { - EqtTrace.Verbose("TestRequestSender: GetAbortErrorMessage: Exception: " + exception); + EqtTrace.Verbose("TestRequestSender.GetAbortErrorMessage: Exception: " + exception); // It is also possible for an operation to abort even if client has not // disconnected, because we initiate client abort when there is error in processing incoming messages. @@ -685,7 +684,7 @@ private string GetAbortErrorMessage(Exception exception, bool getClientError) return exception?.Message; } - EqtTrace.Verbose("TestRequestSender: GetAbortErrorMessage: Client has disconnected. Wait for standard error."); + EqtTrace.Verbose("TestRequestSender.GetAbortErrorMessage: Client has disconnected. Wait for standard error."); // Wait for test host to exit for a moment // TODO: this timeout is 10 seconds, make it also configurable like the other famous timeout that is 100ms @@ -693,7 +692,7 @@ private string GetAbortErrorMessage(Exception exception, bool getClientError) { // Set a default message of test host process exited and additionally specify the error if we were able to get it // from error output of the process - EqtTrace.Info("TestRequestSender: GetAbortErrorMessage: Received test host error message."); + EqtTrace.Info("TestRequestSender.GetAbortErrorMessage: Received test host error message."); var reason = CommonResources.TestHostProcessCrashed; if (!string.IsNullOrWhiteSpace(_clientExitErrorMessage)) { @@ -704,7 +703,7 @@ private string GetAbortErrorMessage(Exception exception, bool getClientError) } else { - EqtTrace.Info("TestRequestSender: GetAbortErrorMessage: Timed out waiting for test host error message."); + EqtTrace.Info("TestRequestSender.GetAbortErrorMessage: Timed out waiting for test host error message."); return CommonResources.UnableToCommunicateToTestHost; } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs index 5f071e7621..fda1d79677 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/PathConverter.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; @@ -43,10 +44,11 @@ public PathConverter(string originalPath, string deploymentPath, IFileHelper fil _deploymentPath = normalizedDeploymentPath; } + [return: NotNullIfNotNull(nameof(path))] public string? UpdatePath(string? path, PathConversionDirection updateDirection) { if (path == null) - return path; + return null; string find; string replaceWith; @@ -63,7 +65,7 @@ public PathConverter(string originalPath, string deploymentPath, IFileHelper fil replaceWith = _originalPath; } - var result = path?.Replace(find, replaceWith); + var result = path.Replace(find, replaceWith); return result; } @@ -157,8 +159,9 @@ public DiscoveryCriteria UpdateDiscoveryCriteria(DiscoveryCriteria discoveryCrit public TestRunCriteriaWithSources UpdateTestRunCriteriaWithSources(TestRunCriteriaWithSources testRunCriteriaWithSources, PathConversionDirection updateDirection) { ValidateArg.NotNull(testRunCriteriaWithSources, nameof(testRunCriteriaWithSources)); - testRunCriteriaWithSources.AdapterSourceMap.ToList().ForEach(adapter => testRunCriteriaWithSources.AdapterSourceMap[adapter.Key] = UpdatePaths(adapter.Value, updateDirection)); - var package = UpdatePath(testRunCriteriaWithSources.Package, updateDirection); + testRunCriteriaWithSources.AdapterSourceMap.ToList().ForEach(adapter => + testRunCriteriaWithSources.AdapterSourceMap[adapter.Key] = UpdatePaths(adapter.Value, updateDirection)!); + var package = UpdatePath(testRunCriteriaWithSources.Package, updateDirection)!; return new TestRunCriteriaWithSources(testRunCriteriaWithSources.AdapterSourceMap, package, testRunCriteriaWithSources.RunSettings, testRunCriteriaWithSources.TestExecutionContext); } @@ -166,7 +169,7 @@ public TestRunCriteriaWithTests UpdateTestRunCriteriaWithTests(TestRunCriteriaWi { ValidateArg.NotNull(testRunCriteriaWithTests, nameof(testRunCriteriaWithTests)); var tests = UpdateTestCases(testRunCriteriaWithTests.Tests, updateDirection); - var package = UpdatePath(testRunCriteriaWithTests.Package, updateDirection); + var package = UpdatePath(testRunCriteriaWithTests.Package, updateDirection)!; return new TestRunCriteriaWithTests(tests, package, testRunCriteriaWithTests.RunSettings, testRunCriteriaWithTests.TestExecutionContext); } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/ArtifactProcessingManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/ArtifactProcessingManager.cs index 3f8d785628..d53a561be3 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/ArtifactProcessingManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/ArtifactProcessingManager.cs @@ -189,7 +189,7 @@ private async Task DataCollectorsAttachmentsPostProcessing(TestArtifacts[] testA using var streamReader = new StreamReader(artifactStream); string executionCompleteMessage = await streamReader.ReadToEndAsync(); EqtTrace.Verbose($"ArtifactProcessingManager.MergeDataCollectorAttachments: ExecutionComplete message \n{executionCompleteMessage}"); - TestRunCompleteEventArgs eventArgs = _dataSerialized.DeserializePayload(_dataSerialized.DeserializeMessage(executionCompleteMessage)); + TestRunCompleteEventArgs? eventArgs = _dataSerialized.DeserializePayload(_dataSerialized.DeserializeMessage(executionCompleteMessage)); foreach (var invokedDataCollector in eventArgs?.InvokedDataCollectors ?? Enumerable.Empty()) { invokedDataCollectors.Add(invokedDataCollector); diff --git a/src/datacollector/MessageSink.cs b/src/datacollector/MessageSink.cs index 2f0a5c2aab..579736ea50 100644 --- a/src/datacollector/MessageSink.cs +++ b/src/datacollector/MessageSink.cs @@ -16,6 +16,6 @@ internal class MessageSink : IMessageSink /// Data collection message event args. public void SendMessage(DataCollectionMessageEventArgs args) { - DataCollectionRequestHandler.Instance.SendDataCollectionMessage(args); + DataCollectionRequestHandler.Instance?.SendDataCollectionMessage(args); } } diff --git a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs index bc40c0d72f..4280794565 100644 --- a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs +++ b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs @@ -133,7 +133,7 @@ public static ITestRequestManager Instance /// public void InitializeExtensions( - IEnumerable pathToAdditionalExtensions, + IEnumerable? pathToAdditionalExtensions, bool skipExtensionFilters) { // It is possible for an Editor/IDE to keep running the runner in design mode for long diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs index fc376debf3..ee29abb159 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs @@ -29,9 +29,7 @@ public class SocketCommunicationManagerTests : IDisposable private const string DummyPayload = "Dummy Payload"; private readonly SocketCommunicationManager _communicationManager; - private readonly TcpClient _tcpClient; - private readonly TcpListener _tcpListener; public SocketCommunicationManagerTests() @@ -228,11 +226,11 @@ public async Task ReceiveMessageShouldReadMessageTypeButNotDeserializeThePayload var message = _communicationManager.ReceiveMessage(); - Assert.AreEqual(MessageType.StartDiscovery, message.MessageType); + Assert.AreEqual(MessageType.StartDiscovery, message?.MessageType); // Payload property is present on the Message, but we don't populate it in the newer versions, - // instead we populate internal field with the rawMessage, and wait until Serializer.DeserializePayload(message) + // instead we populate internal field with the rawMessage, and wait until Serializer.DeserializePayload(message) // is called by the message consumer. This avoids deserializing the payload when we just want to route the message. - Assert.IsNull(message.Payload); + Assert.IsNull(message!.Payload); } [TestMethod] @@ -242,11 +240,11 @@ public async Task ReceiveMessageAsyncShouldReceiveDeserializedMessage() WriteToStream(client.GetStream(), TestDiscoveryStartMessageWithVersionAndPayload); var message = await _communicationManager.ReceiveMessageAsync(CancellationToken.None); - var versionedMessage = (VersionedMessage)message; + var versionedMessage = (VersionedMessage)message!; Assert.AreEqual(MessageType.StartDiscovery, versionedMessage.MessageType); Assert.AreEqual(2, versionedMessage.Version); // Payload property is present on the Message, but we don't populate it in the newer versions, - // instead we populate internal field with the rawMessage, and wait until Serializer.DeserializePayload(message) + // instead we populate internal field with the rawMessage, and wait until Serializer.DeserializePayload(message) // is called by the message consumer. This avoids deserializing the payload when we just want to route the message. Assert.IsNull(versionedMessage.Payload); } @@ -295,7 +293,7 @@ public void SocketPollShouldNotHangServerClientCommunication() var dataReceived = 0; while (dataReceived < 2048 * 5) { - dataReceived += server.ReceiveRawMessageAsync(CancellationToken.None).Result.Length; + dataReceived += server.ReceiveRawMessageAsync(CancellationToken.None).Result!.Length; Task.Delay(1000).Wait(); } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs index 0c3d784317..854314992f 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs @@ -76,13 +76,13 @@ public void Cleanup() [TestMethod] public void CreateInstanceShouldThrowExceptionIfInstanceCommunicationManagerIsNull() { - Assert.ThrowsException(() => DataCollectionRequestHandler.Create(null, _mockMessageSink.Object)); + Assert.ThrowsException(() => DataCollectionRequestHandler.Create(null!, _mockMessageSink.Object)); } [TestMethod] public void CreateInstanceShouldThrowExceptinIfInstanceMessageSinkIsNull() { - Assert.ThrowsException(() => DataCollectionRequestHandler.Create(_mockCommunicationManager.Object, null)); + Assert.ThrowsException(() => DataCollectionRequestHandler.Create(_mockCommunicationManager.Object, null!)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs index 6c57ca2e5e..a46afb2b75 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventHandlerTests.cs @@ -93,7 +93,7 @@ public void CloseShouldThrowExceptionIfThrownByCommunicationManager() [TestMethod] public void CloseShouldNotThrowExceptionIfCommunicationManagerIsNull() { - var requestHandler = new DataCollectionTestCaseEventHandler(_messageSink.Object, null, new Mock().Object, _dataSerializer.Object); + var requestHandler = new DataCollectionTestCaseEventHandler(_messageSink.Object, null!, new Mock().Object, _dataSerializer.Object); requestHandler.Close(); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventSenderTests.cs index 2e5b1e569e..7d1808ecc9 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionTestCaseEventSenderTests.cs @@ -107,7 +107,7 @@ public void SendTestCaseEndShouldReturnAttachments() var attachmentSet = new AttachmentSet(new Uri("my://attachment"), "displayname"); _mockCommunicationManager.Setup(x => x.ReceiveMessage()).Returns(new Message() { MessageType = MessageType.DataCollectionTestEndResult, Payload = JToken.FromObject(new Collection() { attachmentSet }) }); - var attachments = _dataCollectionTestCaseEventSender.SendTestCaseEnd(testCaseEndEventArgs); + var attachments = _dataCollectionTestCaseEventSender.SendTestCaseEnd(testCaseEndEventArgs)!; Assert.AreEqual(attachments[0].Uri, attachmentSet.Uri); Assert.AreEqual(attachments[0].DisplayName, attachmentSet.DisplayName); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs index 0d377f3620..9743127b79 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/JsonDataSerializerTests.cs @@ -108,7 +108,7 @@ public void CloneShouldCloneTestCaseObject() { var testCase = GetSampleTestCase(out var expectedTrait); - var clonedTestCase = _jsonDataSerializer.Clone(testCase); + var clonedTestCase = _jsonDataSerializer.Clone(testCase)!; VerifyTestCaseClone(clonedTestCase, testCase, expectedTrait); } @@ -123,7 +123,7 @@ public void CloneShouldCloneTestResultsObject() var startTime = DateTimeOffset.UtcNow; testResult.StartTime = startTime; - var clonedTestResult = _jsonDataSerializer.Clone(testResult); + var clonedTestResult = _jsonDataSerializer.Clone(testResult)!; Assert.IsFalse(ReferenceEquals(testResult, clonedTestResult)); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs index 8d27362851..983a274571 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs @@ -234,7 +234,7 @@ public void OnClientProcessExitShouldNotSendRawMessageIfOperationNotStarted() _testRequestSender.OnClientProcessExit("Dummy Stderr"); RaiseClientDisconnectedEvent(); - _mockDataSerializer.Verify(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message.Contains("Dummy Stderr"))), Times.Never); + _mockDataSerializer.Verify(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message!.Contains("Dummy Stderr"))), Times.Never); _mockExecutionEventsHandler.Verify(eh => eh.HandleRawMessage(It.IsAny()), Times.Never); } @@ -444,7 +444,7 @@ public void DiscoverTestShouldNotifyLogMessageIfClientDisconnected() // Expect default error message since we've not set any client exit message var expectedErrorMessage = "Reason: Unable to communicate"; SetupFakeCommunicationChannel(); - _mockDataSerializer.Setup(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message.Contains(expectedErrorMessage)))) + _mockDataSerializer.Setup(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message!.Contains(expectedErrorMessage)))) .Returns("Serialized error"); _testRequestSender.DiscoverTests(new DiscoveryCriteria(), _mockDiscoveryEventsHandler.Object); @@ -458,7 +458,7 @@ public void DiscoverTestShouldNotifyLogMessageIfClientDisconnected() public void DiscoverTestShouldNotifyLogMessageIfClientDisconnectedWithClientExit() { SetupFakeCommunicationChannel(); - _mockDataSerializer.Setup(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message.Contains("Dummy Stderr")))) + _mockDataSerializer.Setup(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message!.Contains("Dummy Stderr")))) .Returns("Serialized Stderr"); _testRequestSender.DiscoverTests(new DiscoveryCriteria(), _mockDiscoveryEventsHandler.Object); _testRequestSender.OnClientProcessExit("Dummy Stderr"); @@ -838,7 +838,7 @@ private void SetupExceptionMessageSerialize() { // Serialize the exception message _mockDataSerializer - .Setup(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message.Contains("Dummy Message")))) + .Setup(ds => ds.SerializePayload(MessageType.TestMessage, It.Is(p => p.Message!.Contains("Dummy Message")))) .Returns("SerializedMessage"); } @@ -846,7 +846,7 @@ private void SetupOperationAbortedPayload() { // Serialize the execution aborted _mockDataSerializer - .Setup(ds => ds.SerializePayload(MessageType.ExecutionComplete, It.Is(p => p.TestRunCompleteArgs.IsAborted))) + .Setup(ds => ds.SerializePayload(MessageType.ExecutionComplete, It.Is(p => p.TestRunCompleteArgs!.IsAborted))) .Returns("SerializedAbortedPayload"); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs index deb9e7ea48..a87d783b83 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyBaseManagerTests.cs @@ -48,7 +48,7 @@ public ProxyBaseManagerTests() _discoveryDataAggregator = new(); _mockRequestData.Setup(rd => rd.MetricsCollection).Returns(new Mock().Object); - _mockDataSerializer.Setup(mds => mds.DeserializeMessage(null)).Returns(new Message()); + _mockDataSerializer.Setup(mds => mds.DeserializeMessage(null!)).Returns(new Message()); _mockDataSerializer.Setup(mds => mds.DeserializeMessage(string.Empty)).Returns(new Message()); _mockTestHostManager.SetupGet(th => th.Shared).Returns(true); _mockTestHostManager.Setup( @@ -90,7 +90,7 @@ public void SetupChannelMessage(string messageType, string returnMessa _mockDataSerializer.Setup(ds => ds.SerializePayload(It.Is(s => s.Equals(messageType)), It.IsAny())).Returns(messageType); _mockDataSerializer.Setup(ds => ds.SerializePayload(It.Is(s => s.Equals(messageType)), It.IsAny(), It.IsAny())).Returns(messageType); _mockDataSerializer.Setup(ds => ds.DeserializeMessage(It.Is(s => s.Equals(messageType)))).Returns(new Message { MessageType = returnMessageType }); - _mockDataSerializer.Setup(ds => ds.DeserializePayload(It.Is(m => m.MessageType.Equals(messageType)))).Returns(returnPayload); + _mockDataSerializer.Setup(ds => ds.DeserializePayload(It.Is(m => string.Equals(m.MessageType, messageType)))).Returns(returnPayload); } public void RaiseMessageReceived(string data) diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs index 448dd8b846..9d763ed183 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs @@ -442,7 +442,7 @@ public void StartTestRunShouldInitiateTestRunForSourcesThroughTheServer() Assert.IsNotNull(testRunCriteriaPassed); CollectionAssert.AreEqual(_mockTestRunCriteria.Object.AdapterSourceMap.Keys, testRunCriteriaPassed.AdapterSourceMap.Keys); CollectionAssert.AreEqual(_mockTestRunCriteria.Object.AdapterSourceMap.Values, testRunCriteriaPassed.AdapterSourceMap.Values); - Assert.AreEqual(_mockTestRunCriteria.Object.FrequencyOfRunStatsChangeEvent, testRunCriteriaPassed.TestExecutionContext.FrequencyOfRunStatsChangeEvent); + Assert.AreEqual(_mockTestRunCriteria.Object.FrequencyOfRunStatsChangeEvent, testRunCriteriaPassed.TestExecutionContext!.FrequencyOfRunStatsChangeEvent); Assert.AreEqual(_mockTestRunCriteria.Object.RunStatsChangeEventTimeout, testRunCriteriaPassed.TestExecutionContext.RunStatsChangeEventTimeout); Assert.AreEqual(_mockTestRunCriteria.Object.TestRunSettings, testRunCriteriaPassed.RunSettings); } @@ -466,7 +466,7 @@ public void StartTestRunShouldInitiateTestRunForTestsThroughTheServer() CollectionAssert.AreEqual(runCriteria.Object.Tests.ToList(), testRunCriteriaPassed.Tests.ToList()); Assert.AreEqual( runCriteria.Object.FrequencyOfRunStatsChangeEvent, - testRunCriteriaPassed.TestExecutionContext.FrequencyOfRunStatsChangeEvent); + testRunCriteriaPassed.TestExecutionContext!.FrequencyOfRunStatsChangeEvent); Assert.AreEqual( runCriteria.Object.RunStatsChangeEventTimeout, testRunCriteriaPassed.TestExecutionContext.RunStatsChangeEventTimeout); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs index 6d08727562..26ee69e0aa 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs @@ -121,8 +121,10 @@ public void HandleRawMessageShouldInvokeAfterTestRunEndAndReturnInvokedDataColle .Returns(new DataCollectionResult(null, invokedDataCollectors)); _mockDataSerializer.Setup(r => r.SerializePayload(It.IsAny(), It.IsAny())).Callback((string message, object o) => { - Assert.AreEqual(1, ((TestRunCompletePayload)o).TestRunCompleteArgs.InvokedDataCollectors.Count); - Assert.AreEqual(invokedDataCollectors[0], ((TestRunCompletePayload)o).TestRunCompleteArgs.InvokedDataCollectors[0]); + var testRunCompleteArgs = o as TestRunCompletePayload; + Assert.IsNotNull(testRunCompleteArgs); + Assert.AreEqual(1, testRunCompleteArgs.TestRunCompleteArgs!.InvokedDataCollectors.Count); + Assert.AreEqual(invokedDataCollectors[0], testRunCompleteArgs.TestRunCompleteArgs.InvokedDataCollectors[0]); }); _testRunEventHandler = new DataCollectionTestRunEventsHandler(_baseTestRunEventsHandler.Object, _proxyDataCollectionManager.Object, _mockDataSerializer.Object, CancellationToken.None); diff --git a/test/Microsoft.TestPlatform.PerformanceTests/SocketTests.cs b/test/Microsoft.TestPlatform.PerformanceTests/SocketTests.cs index 717ff68b02..470501e3de 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/SocketTests.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/SocketTests.cs @@ -39,10 +39,10 @@ public void SocketThroughput2() server.Connected += (sender, args) => { serverChannel = args.Channel; - serverChannel.MessageReceived += (channel, messageReceived) => + serverChannel!.MessageReceived += (channel, messageReceived) => { // Keep count of bytes - dataReceived += messageReceived.Data.Length; + dataReceived += messageReceived.Data!.Length; if (dataReceived >= 65536 * 20000) { @@ -96,7 +96,7 @@ public void SocketThroughput1() var dataReceived = 0; while (dataReceived < 65536 * 20000) { - dataReceived += server.ReceiveRawMessage().Length; + dataReceived += server.ReceiveRawMessage()!.Length; } watch.Stop(); diff --git a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs index 4d50bf1225..cc1d9ecb15 100644 --- a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs +++ b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs @@ -180,7 +180,7 @@ public async Task InitializeCommunicationAsyncShouldFailConnectionIfSessionConne var discoveryMessage = new Message() { MessageType = MessageType.StartDiscovery }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryMessage)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryMessage)); var portOutput = await _requestSender.InitializeCommunicationAsync(_waitTimeout); Assert.AreEqual(-1, portOutput, "Connection must fail if version check failed."); @@ -229,7 +229,7 @@ public async Task InitializeCommunicationAsyncShouldFailConnectionIfSendMessageF var sessionConnected = new Message() { MessageType = MessageType.SessionConnected }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(sessionConnected)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(sessionConnected)); _mockCommunicationManager.Setup(cm => cm.SendMessage(MessageType.VersionCheck, _protocolVersion)).Throws(new Exception("Fail")); var portOutput = await _requestSender.InitializeCommunicationAsync(_waitTimeout); @@ -298,9 +298,9 @@ public async Task InitializeCommunicationAsyncShouldFailConnectionIfProtocolIsNo }; Action changedMessage = - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(protocolError)); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(protocolError)); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(sessionConnected)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(sessionConnected)); _mockCommunicationManager.Setup(cm => cm.SendMessage(MessageType.VersionCheck)).Callback(changedMessage); var portOutput = await _requestSender.InitializeCommunicationAsync(_waitTimeout); @@ -330,7 +330,7 @@ public void DiscoverTestsShouldCompleteWithZeroTests() MessageType = MessageType.DiscoveryComplete, Payload = JToken.FromObject(payload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); _requestSender.DiscoverTests(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -352,7 +352,7 @@ public async Task DiscoverTestsAsyncShouldCompleteWithZeroTests() MessageType = MessageType.DiscoveryComplete, Payload = JToken.FromObject(payload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); await _requestSender.DiscoverTestsAsync(new List() { "1.dll" }, null, null, null, mockHandler.Object); @@ -383,9 +383,9 @@ public void DiscoverTestsShouldCompleteWithSingleTest() Payload = JToken.FromObject(payload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); _requestSender.DiscoverTests(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -416,9 +416,9 @@ public async Task DiscoverTestsAsyncShouldCompleteWithSingleTest() Payload = JToken.FromObject(payload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); await _requestSender.DiscoverTestsAsync(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -452,9 +452,9 @@ public void DiscoverTestsShouldCompleteWithSingleFullyDiscoveredSource() DiscoveryCompleteEventArgs? receivedDiscoveryCompleteEventArgs = null; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())) - .Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); + .Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); mockHandler.Setup(mh => mh.HandleDiscoveryComplete(It.IsAny(), It.IsAny>())) .Callback((DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable tests) => receivedDiscoveryCompleteEventArgs = discoveryCompleteEventArgs); @@ -492,9 +492,9 @@ public void DiscoverTestsShouldCompleteWithCorrectAbortedValuesIfAbortingWasRequ DiscoveryCompleteEventArgs? receivedDiscoveryCompleteEventArgs = null; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())) - .Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); + .Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); mockHandler.Setup(mh => mh.HandleDiscoveryComplete(It.IsAny(), It.IsAny>())) .Callback((DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable tests) => receivedDiscoveryCompleteEventArgs = discoveryCompleteEventArgs); @@ -528,13 +528,13 @@ public void DiscoverTestsShouldReportBackTestsWithTraitsInTestsFoundMessage() var payload = new DiscoveryCompletePayload() { TotalTests = 1, LastDiscoveredTests = null, IsAborted = false }; var discoveryComplete = CreateMessage(MessageType.DiscoveryComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())) .Callback( (IEnumerable tests) => { receivedTestCases = tests?.ToList(); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult((discoveryComplete))); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); }); _requestSender.DiscoverTests(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -566,13 +566,13 @@ public async Task DiscoverTestsAsyncShouldReportBackTestsWithTraitsInTestsFoundM var payload = new DiscoveryCompletePayload() { TotalTests = 1, LastDiscoveredTests = null, IsAborted = false }; var discoveryComplete = CreateMessage(MessageType.DiscoveryComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())) .Callback( (IEnumerable? tests) => { receivedTestCases = tests?.ToList(); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult((discoveryComplete))); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); }); await _requestSender.DiscoverTestsAsync(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -603,7 +603,7 @@ public void DiscoverTestsShouldReportBackTestsWithTraitsInDiscoveryCompleteMessa var payload = new DiscoveryCompletePayload() { TotalTests = 1, LastDiscoveredTests = testCaseList, IsAborted = false }; var discoveryComplete = CreateMessage(MessageType.DiscoveryComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); mockHandler.Setup(mh => mh.HandleDiscoveryComplete(It.IsAny(), It.IsAny>())) .Callback( (DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable tests) => receivedTestCases = tests?.ToList()); @@ -636,7 +636,7 @@ public async Task DiscoverTestsAsyncShouldReportBackTestsWithTraitsInDiscoveryCo var payload = new DiscoveryCompletePayload() { TotalTests = 1, LastDiscoveredTests = testCaseList, IsAborted = false }; var discoveryComplete = CreateMessage(MessageType.DiscoveryComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete)); mockHandler.Setup(mh => mh.HandleDiscoveryComplete(It.IsAny(), It.IsAny>())) .Callback( (DiscoveryCompleteEventArgs discoveryCompleteEventArgs, IEnumerable tests) => receivedTestCases = tests?.ToList()); @@ -670,11 +670,11 @@ public void DiscoverTestsShouldCompleteWithTestMessage() var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message))); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); _requestSender.DiscoverTests(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -700,11 +700,11 @@ public async Task DiscoverTestsAsyncShouldCompleteWithTestMessage() var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsFound)); mockHandler.Setup(mh => mh.HandleDiscoveredTests(It.IsAny>())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message))); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(discoveryComplete))); await _requestSender.DiscoverTestsAsync(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -818,7 +818,7 @@ public void StartTestRunShouldCompleteWithZeroTests() }; var runComplete = CreateMessage(MessageType.ExecutionComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); _requestSender.StartTestRun(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -847,7 +847,7 @@ public async Task StartTestRunAsyncShouldCompleteWithZeroTests() }; var runComplete = CreateMessage(MessageType.ExecutionComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); await _requestSender.StartTestRunAsync(new List() { "1.dll" }, null, null, null, mockHandler.Object); @@ -889,17 +889,17 @@ public void StartTestRunShouldCompleteWithSingleTestAndMessage() var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); _requestSender.StartTestRun(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -941,17 +941,17 @@ public async Task StartTestRunAsyncShouldCompleteWithSingleTestAndMessage() var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); await _requestSender.StartTestRunAsync(new List() { "1.dll" }, null, null, null, mockHandler.Object); @@ -1046,17 +1046,17 @@ public void StartTestRunWithCustomHostShouldComplete() (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); var mockLauncher = new Mock(); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())).Callback - (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); + (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); _requestSender.StartTestRunWithCustomHost(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object, mockLauncher.Object); @@ -1107,17 +1107,17 @@ public async Task StartTestRunAsyncWithCustomHostShouldComplete() (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); var mockLauncher = new Mock(); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())).Callback - (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); + (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); await _requestSender.StartTestRunWithCustomHostAsync(new List() { "1.dll" }, null, null, null, mockHandler.Object, mockLauncher.Object); @@ -1166,10 +1166,10 @@ public void StartTestRunWithCustomHostShouldNotAbortAndSendErrorToVstestConsoleI var mockLauncher = new Mock(); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())).Throws(new Exception("BadError")); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny(), _protocolVersion)). - Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); _requestSender.StartTestRunWithCustomHost(new List() { "1.dll" }, null, new TestPlatformOptions(), null, mockHandler.Object, mockLauncher.Object); @@ -1215,10 +1215,10 @@ public async Task StartTestRunAsyncWithCustomHostShouldNotAbortAndSendErrorToVst var mockLauncher = new Mock(); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())).Throws(new Exception("BadError")); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny(), _protocolVersion)). - Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + Callback(() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); await _requestSender.StartTestRunWithCustomHostAsync(new List() { "1.dll" }, null, null, null, mockHandler.Object, mockLauncher.Object); @@ -1288,7 +1288,7 @@ public void StartTestRunWithSelectedTestsShouldCompleteWithZeroTests() TestRunCompleteArgs = dummyCompleteArgs }; var runComplete = CreateMessage(MessageType.ExecutionComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); _requestSender.StartTestRun(new List(), null, new TestPlatformOptions(), null, mockHandler.Object); @@ -1315,7 +1315,7 @@ public async Task StartTestRunAsyncWithSelectedTestsShouldCompleteWithZeroTests( TestRunCompleteArgs = dummyCompleteArgs }; var runComplete = CreateMessage(MessageType.ExecutionComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); await _requestSender.StartTestRunAsync(new List(), null, new TestPlatformOptions(), null, mockHandler.Object); @@ -1356,17 +1356,17 @@ public void StartTestRunWithSelectedTestsShouldCompleteWithSingleTestAndMessage( var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); _requestSender.StartTestRun(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -1407,17 +1407,17 @@ public async Task StartTestRunAsyncWithSelectedTestsShouldCompleteWithSingleTest var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload)); mockHandler.Setup(mh => mh.HandleTestRunStatsChange(It.IsAny())).Callback( (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); await _requestSender.StartTestRunAsync(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -1455,7 +1455,7 @@ public void StartTestRunWithSelectedTestsHavingTraitsShouldReturnTestRunComplete }; var runComplete = CreateMessage(MessageType.ExecutionComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); mockHandler.Setup(mh => mh.HandleTestRunComplete( It.IsAny(), @@ -1508,7 +1508,7 @@ public async Task StartTestRunAsyncWithSelectedTestsHavingTraitsShouldReturnTest }; var runComplete = CreateMessage(MessageType.ExecutionComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); mockHandler.Setup(mh => mh.HandleTestRunComplete( It.IsAny(), @@ -1567,7 +1567,7 @@ public void StartTestRunWithSelectedTestsHavingTraitsShouldReturnTestRunStatsWit }; var runComplete = CreateMessage(MessageType.ExecutionComplete, testRunCompletepayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsRunStatsPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsRunStatsPayload)); mockHandler.Setup(mh => mh.HandleTestRunStatsChange( It.IsAny())) @@ -1575,7 +1575,7 @@ public void StartTestRunWithSelectedTestsHavingTraitsShouldReturnTestRunStatsWit (TestRunChangedEventArgs stats) => { receivedChangeEventArgs = stats; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); }); _requestSender.StartTestRun(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -1624,7 +1624,7 @@ public async Task StartTestRunAsyncWithSelectedTestsHavingTraitsShouldReturnTest }; var runComplete = CreateMessage(MessageType.ExecutionComplete, testRunCompletepayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsRunStatsPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsRunStatsPayload)); mockHandler.Setup(mh => mh.HandleTestRunStatsChange( It.IsAny())) @@ -1632,7 +1632,7 @@ public async Task StartTestRunAsyncWithSelectedTestsHavingTraitsShouldReturnTest (TestRunChangedEventArgs stats) => { receivedChangeEventArgs = stats; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); }); await _requestSender.StartTestRunAsync(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object); @@ -1685,17 +1685,17 @@ public void StartTestRunWithCustomHostWithSelectedTestsComplete() (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); var mockLauncher = new Mock(); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())).Callback - (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); + (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); _requestSender.StartTestRunWithCustomHost(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object, mockLauncher.Object); @@ -1744,17 +1744,17 @@ public async Task StartTestRunWithCustomHostAsyncWithSelectedTestsShouldComplete (testRunChangedArgs) => { Assert.IsTrue(testRunChangedArgs.NewTestResults != null && testsChangedArgs.NewTestResults.Any(), "TestResults must be passed properly"); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); + () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete))); var mockLauncher = new Mock(); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())).Callback - (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); + (() => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(testsPayload))); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runprocessInfoPayload)); await _requestSender.StartTestRunWithCustomHostAsync(testCaseList, null, new TestPlatformOptions(), null, mockHandler.Object, mockLauncher.Object); @@ -1785,17 +1785,17 @@ public void StartTestRunWithCustomHostInParallelShouldCallCustomHostMultipleTime }; var runComplete = CreateMessage(MessageType.ExecutionComplete, completepayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message1)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message1)); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())) .Callback((startInfo) => { if (startInfo.FileName.Equals(p1.FileName)) { - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message2)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message2)); } else if (startInfo.FileName.Equals(p2.FileName)) { - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); } }); _requestSender.InitializeCommunication(); @@ -1824,17 +1824,17 @@ public async Task StartTestRunWithCustomHostAsyncInParallelShouldCallCustomHostM }; var runComplete = CreateMessage(MessageType.ExecutionComplete, completepayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message1)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message1)); mockLauncher.Setup(ml => ml.LaunchTestHost(It.IsAny())) .Callback((startInfo) => { if (startInfo.FileName.Equals(p1.FileName)) { - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message2)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message2)); } else if (startInfo.FileName.Equals(p2.FileName)) { - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); } }); @@ -1960,7 +1960,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithZeroAttachment MessageType = MessageType.TestRunAttachmentsProcessingComplete, Payload = JToken.FromObject(payload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); @@ -1999,7 +1999,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachment( Payload = JToken.FromObject(payload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); @@ -2042,14 +2042,14 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachmentA var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); _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()); }); mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete))); + () => _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") }, @@ -2094,7 +2094,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachmentA MessageType = MessageType.TestRunAttachmentsProcessingProgress, Payload = JToken.FromObject(progressPayload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingProgress)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingProgress)); _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); @@ -2102,7 +2102,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldCompleteWithOneAttachmentA }); mockHandler.Setup(mh => mh.HandleTestRunAttachmentsProcessingProgress(It.IsAny())).Callback( - () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete))); + () => _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") }, @@ -2141,7 +2141,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldSendCancelMessageIfCancell var mpayload = new TestMessagePayload() { MessageLevel = TestMessageLevel.Informational, Message = "Hello" }; var message = CreateMessage(MessageType.TestMessage, mpayload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(message)); _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); @@ -2150,7 +2150,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldSendCancelMessageIfCancell mockHandler.Setup(mh => mh.HandleLogMessage(It.IsAny(), It.IsAny())).Callback(() => { cts.Cancel(); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); }); await _requestSender.ProcessTestRunAttachmentsAsync( @@ -2187,7 +2187,7 @@ public async Task ProcessTestRunAttachmentsAsyncShouldSendCancelMessageIfCancell Payload = JToken.FromObject(payload) }; - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(attachmentsProcessingComplete)); _mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny(), It.IsAny())).Callback((string _, object o) => { Assert.AreEqual(Constants.EmptyRunSettings, ((TestRunAttachmentsProcessingPayload)o).RunSettings); @@ -2320,7 +2320,7 @@ public void StartTestSessionShouldSucceed() It.IsAny(), _protocolVersion)).Callback(() => { }); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(message)); + .Returns(Task.FromResult(message)); Assert.AreEqual( testSessionInfo, @@ -2374,7 +2374,7 @@ public async Task StartTestSessionAsyncShouldSucceed() It.IsAny(), _protocolVersion)).Callback(() => { }); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(message)); + .Returns(Task.FromResult(message)); Assert.AreEqual( testSessionInfo, @@ -2432,7 +2432,7 @@ public void StartTestSessionWithTesthostLauncherShouldSucceed() ackPayload); Action reconfigureAction = () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(ackMessage)); + .Returns(Task.FromResult(ackMessage)); _mockCommunicationManager.Setup(cm => cm.SendMessage( MessageType.StartTestSession, @@ -2444,7 +2444,7 @@ public void StartTestSessionWithTesthostLauncherShouldSucceed() _protocolVersion)) .Callback((string messageType, object payload, int version) => Assert.AreEqual(((CustomHostLaunchAckPayload)payload).HostProcessId, TesthostPid)); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(launchMessage)) + .Returns(Task.FromResult(launchMessage)) .Callback(reconfigureAction); // Act @@ -2507,7 +2507,7 @@ public async Task StartTestSessionAsyncWithTesthostLauncherShouldSucceed() ackPayload); Action reconfigureAction = () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(ackMessage)); + .Returns(Task.FromResult(ackMessage)); _mockCommunicationManager.Setup(cm => cm.SendMessage( MessageType.StartTestSession, @@ -2519,7 +2519,7 @@ public async Task StartTestSessionAsyncWithTesthostLauncherShouldSucceed() _protocolVersion)) .Callback((string messageType, object payload, int version) => Assert.AreEqual(((CustomHostLaunchAckPayload)payload).HostProcessId, TesthostPid)); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(launchMessage)) + .Returns(Task.FromResult(launchMessage)) .Callback(reconfigureAction); // Act @@ -2581,7 +2581,7 @@ public void StartTestSessionWithTesthostLauncherAttachingToProcessShouldSucceed( ackPayload); Action reconfigureAction = () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(ackMessage)); + .Returns(Task.FromResult(ackMessage)); _mockCommunicationManager.Setup(cm => cm.SendMessage( MessageType.StartTestSession, @@ -2593,7 +2593,7 @@ public void StartTestSessionWithTesthostLauncherAttachingToProcessShouldSucceed( _protocolVersion)) .Callback((string messageType, object payload, int version) => Assert.IsTrue(((EditorAttachDebuggerAckPayload)payload).Attached)); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(launchMessage)) + .Returns(Task.FromResult(launchMessage)) .Callback(reconfigureAction); // Act @@ -2655,7 +2655,7 @@ public async Task StartTestSessionAsyncWithTesthostLauncherAttachingToProcessSho ackPayload); Action reconfigureAction = () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(ackMessage)); + .Returns(Task.FromResult(ackMessage)); _mockCommunicationManager.Setup(cm => cm.SendMessage( MessageType.StartTestSession, @@ -2667,7 +2667,7 @@ public async Task StartTestSessionAsyncWithTesthostLauncherAttachingToProcessSho _protocolVersion)) .Callback((string messageType, object payload, int version) => Assert.IsTrue(((EditorAttachDebuggerAckPayload)payload).Attached)); _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())) - .Returns(Task.FromResult(launchMessage)) + .Returns(Task.FromResult(launchMessage)) .Callback(reconfigureAction); // Act @@ -2749,7 +2749,7 @@ private void SetupMockCommunicationForRunRequest() var runComplete = CreateMessage(MessageType.ExecutionComplete, payload); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(runComplete)); } private async Task InitializeCommunicationAsync() @@ -2766,9 +2766,9 @@ private async Task InitializeCommunicationAsync(int protocolVersion) var sessionConnected = new Message() { MessageType = MessageType.SessionConnected }; var versionCheck = new Message() { MessageType = MessageType.VersionCheck, Payload = protocolVersion }; - Action changedMessage = () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(versionCheck)); + Action changedMessage = () => _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(versionCheck)); - _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(sessionConnected)); + _mockCommunicationManager.Setup(cm => cm.ReceiveMessageAsync(It.IsAny())).Returns(Task.FromResult(sessionConnected)); _mockCommunicationManager.Setup(cm => cm.SendMessage(MessageType.VersionCheck, It.IsAny())).Callback(changedMessage); var portOutput = await _requestSender.InitializeCommunicationAsync(_waitTimeout);