From 6fffbd8ac972704ba3123e89d26dbda19572424c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 18 Jan 2022 16:30:41 +0100 Subject: [PATCH] Simplify using statements and collection initializers --- src/DataCollectors/DumpMinitool/Program.cs | 88 +++--- .../EventLogXmlWriter.cs | 80 +++-- .../Tasks/VSTestForwardingApp.cs | 14 +- .../TestPlatformDataCollectionEvents.cs | 15 +- .../RunSettings.cs | 24 +- .../Utilities/AssemblyProperties.cs | 24 +- .../RunSettingsProviderExtensions.cs | 35 +-- .../DataCollectionRequestHandler.cs | 6 +- .../JsonDataSerializer.cs | 18 +- .../Helpers/DotnetHostHelper.cs | 134 ++++---- .../Utilities/JobQueue.cs | 12 +- .../InProcDataCollectionExtensionManager.cs | 6 +- .../ProxyDataCollectionManager.cs | 37 ++- .../Execution/RunTestsWithSources.cs | 6 +- .../Execution/RunTestsWithTests.cs | 12 +- .../WindowsHangDumper.cs | 76 +++-- .../TrxLogger.cs | 18 +- .../Client/DiscoveryCriteria.cs | 6 +- .../Client/TestRunCriteria.cs | 12 +- .../Navigation/DiaSession.cs | 12 +- .../Navigation/PortableSymbolReader.cs | 74 +++-- .../TestProperty/CustomKeyValueConverter.cs | 12 +- .../CustomStringArrayConverter.cs | 10 +- .../Utilities/AssemblyLoadWorker.cs | 110 ++++--- .../Utilities/Sha1Helper.cs | 8 +- .../Utilities/XmlRunSettingsUtilities.cs | 132 ++++---- .../common/Tracing/PlatformEqtTrace.cs | 27 +- .../Hosting/DotnetTestHostManager.cs | 20 +- .../InferRunSettingsHelper.cs | 194 ++++++------ src/SettingsMigrator/Migrator.cs | 52 ++-- .../CommandLine/AssemblyMetadataProvider.cs | 118 ++++--- .../RunSettingsArgumentProcessor.cs | 12 +- .../TestPlatformHelpers/TestRequestManager.cs | 134 ++++---- .../EventLogContainerTests.cs | 12 +- .../EventLogDataCollectorTests.cs | 38 ++- .../EventLogSessionContextTests.cs | 6 +- .../CodeCoverageAcceptanceTestBase.cs | 42 ++- .../DataCollectionTests.cs | 15 +- .../DotnetArchitectureSwitchTests.Windows.cs | 82 +++-- .../DotnetArchitectureSwitchTests.cs | 40 ++- .../EventLogCollectorTests.cs | 10 +- .../LoggerTests.cs | 12 +- .../TestIdProvider/SHA1ImplTests.cs | 6 +- .../Discovery/DiscoveryRequestTests.cs | 6 +- .../Execution/TestRunRequestTests.cs | 6 +- .../Utilities/TestExtensionsTests.cs | 138 +++++---- .../SocketCommunicationManagerTests.cs | 14 +- .../SocketTestsBase.cs | 12 +- .../LengthPrefixCommunicationChannelTests.cs | 12 +- .../Helpers/FileHelperTests.cs | 10 +- .../Tracing/EqtTraceTests.cs | 10 +- .../Utilities/JobQueueTests.cs | 292 +++++++++--------- ...lectorAttachmentsProcessorsFactoryTests.cs | 30 +- .../ParallelDiscoveryDataAggregatorTests.cs | 44 ++- .../ParallelProxyExecutionManagerTests.cs | 14 +- .../ParallelRunDataAggregatorTests.cs | 90 ++++-- ...DataCollectionTestRunEventsHandlerTests.cs | 6 +- ...ProcDataCollectionExtensionManagerTests.cs | 6 +- ...roxyOutOfProcDataCollectionManagerTests.cs | 6 +- .../Discovery/DiscovererEnumeratorTests.cs | 86 ++++-- .../Discovery/DiscoveryManagerTests.cs | 6 +- .../EventHandlers/TestRequestHandlerTests.cs | 6 +- .../Execution/BaseRunTestsTests.cs | 12 +- .../Execution/ExecutionManagerTests.cs | 6 +- .../Execution/RunTestsWithSourcesTests.cs | 56 ++-- .../Utilities/TestSourcesUtilityTests.cs | 16 +- .../HtmlLoggerTests.cs | 46 +-- .../TrxLoggerTests.cs | 74 +++-- .../Events/SessionEventsTests.cs | 8 +- .../DotnetHostArchitectureVerifierTests.cs | 44 ++- .../IntegrationTestBase.cs | 116 ++++--- .../IntegrationTestEnvironment.cs | 26 +- .../PerfInstrumentation/PerfAnalyzer.cs | 63 ++-- .../MigratorTests.cs | 78 +++-- .../CommunicationLayerIntegrationTests.cs | 48 ++- .../TestRunResultAggregatorTests.cs | 18 +- .../Internal/ConsoleLoggerTests.cs | 132 +++++--- ...llyQualifiedTestsArgumentProcessorTests.cs | 8 +- .../ListTestsArgumentProcessorTests.cs | 8 +- .../RunSpecificTestsArgumentProcessorTests.cs | 84 +++-- .../RunTestsArgumentProcessorTests.cs | 8 +- 81 files changed, 1791 insertions(+), 1655 deletions(-) diff --git a/src/DataCollectors/DumpMinitool/Program.cs b/src/DataCollectors/DumpMinitool/Program.cs index 815cf6bfa9..6ef7feb025 100644 --- a/src/DataCollectors/DumpMinitool/Program.cs +++ b/src/DataCollectors/DumpMinitool/Program.cs @@ -29,63 +29,61 @@ static int Main(string[] args) var process = Process.GetProcessById(processId); - using (var stream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) + using var stream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None); + NativeMethods.MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = default; + + NativeMethods.MINIDUMP_TYPE dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpNormal; + switch (type) { - NativeMethods.MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = default; + case DumpTypeOption.Full: + dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemory | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; + break; + case DumpTypeOption.WithHeap: + dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithPrivateReadWriteMemory | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; + break; + case DumpTypeOption.Mini: + dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo; + break; + } - NativeMethods.MINIDUMP_TYPE dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpNormal; - switch (type) + // Retry the write dump on ERROR_PARTIAL_COPY + for (int i = 0; i < 5; i++) + { + // Dump the process! + if (NativeMethods.MiniDumpWriteDump(process.Handle, (uint)process.Id, stream.SafeFileHandle, dumpType, ref exceptionInfo, IntPtr.Zero, IntPtr.Zero)) { - case DumpTypeOption.Full: - dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemory | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; - break; - case DumpTypeOption.WithHeap: - dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithPrivateReadWriteMemory | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; - break; - case DumpTypeOption.Mini: - dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo; - break; + Console.WriteLine("Dumped process."); + return 0; } - - // Retry the write dump on ERROR_PARTIAL_COPY - for (int i = 0; i < 5; i++) + else { - // Dump the process! - if (NativeMethods.MiniDumpWriteDump(process.Handle, (uint)process.Id, stream.SafeFileHandle, dumpType, ref exceptionInfo, IntPtr.Zero, IntPtr.Zero)) + int err = Marshal.GetHRForLastWin32Error(); + if (err != NativeMethods.ERROR_PARTIAL_COPY) { - Console.WriteLine("Dumped process."); - return 0; + Console.WriteLine($"Error dumping process {err}"); + Marshal.ThrowExceptionForHR(err); } else { - int err = Marshal.GetHRForLastWin32Error(); - if (err != NativeMethods.ERROR_PARTIAL_COPY) - { - Console.WriteLine($"Error dumping process {err}"); - Marshal.ThrowExceptionForHR(err); - } - else - { - Console.WriteLine($"Error dumping process, was ERROR_PARTIAL_COPY, retrying."); - } + Console.WriteLine($"Error dumping process, was ERROR_PARTIAL_COPY, retrying."); } } - - Console.WriteLine($"Error dumping process after 5 retries."); - return 1; } + + Console.WriteLine($"Error dumping process after 5 retries."); + return 1; } private static class NativeMethods diff --git a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogXmlWriter.cs b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogXmlWriter.cs index 1446d31295..07312aa9c6 100644 --- a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogXmlWriter.cs +++ b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogXmlWriter.cs @@ -34,55 +34,51 @@ internal static class EventLogXmlWriter /// public static void WriteEventLogEntriesToXmlFile(string xmlFilePath, List eventLogEntries, IFileHelper fileHelper) { - using (DataTable dataTable = new DataTable()) - { - dataTable.Locale = CultureInfo.InvariantCulture; + using DataTable dataTable = new DataTable(); + dataTable.Locale = CultureInfo.InvariantCulture; - // The MaxLength of the Type and Source columns must be set to allow indices to be created on them - DataColumn typeColumn = new DataColumn("Type", typeof(string)); - typeColumn.MaxLength = EventLogConstants.TypeColumnMaxLength; - dataTable.Columns.Add(typeColumn); + // The MaxLength of the Type and Source columns must be set to allow indices to be created on them + DataColumn typeColumn = new DataColumn("Type", typeof(string)); + typeColumn.MaxLength = EventLogConstants.TypeColumnMaxLength; + dataTable.Columns.Add(typeColumn); - dataTable.Columns.Add(new DataColumn("DateTime", typeof(DateTime))); + dataTable.Columns.Add(new DataColumn("DateTime", typeof(DateTime))); - DataColumn sourceColumn = new DataColumn("Source", typeof(string)); - sourceColumn.MaxLength = EventLogConstants.SourceColumnMaxLength; - dataTable.Columns.Add(sourceColumn); + DataColumn sourceColumn = new DataColumn("Source", typeof(string)); + sourceColumn.MaxLength = EventLogConstants.SourceColumnMaxLength; + dataTable.Columns.Add(sourceColumn); - dataTable.Columns.Add(new DataColumn("Category", typeof(string))); - dataTable.Columns.Add(new DataColumn("EventID", typeof(long))); - dataTable.Columns.Add(new DataColumn("Description", typeof(string))); - dataTable.Columns.Add(new DataColumn("User", typeof(string))); - dataTable.Columns.Add(new DataColumn("Computer", typeof(string))); - dataTable.ExtendedProperties.Add("TimestampColumnName", "DateTime"); - dataTable.ExtendedProperties.Add("IndexColumnNames", "Source,Type"); + dataTable.Columns.Add(new DataColumn("Category", typeof(string))); + dataTable.Columns.Add(new DataColumn("EventID", typeof(long))); + dataTable.Columns.Add(new DataColumn("Description", typeof(string))); + dataTable.Columns.Add(new DataColumn("User", typeof(string))); + dataTable.Columns.Add(new DataColumn("Computer", typeof(string))); + dataTable.ExtendedProperties.Add("TimestampColumnName", "DateTime"); + dataTable.ExtendedProperties.Add("IndexColumnNames", "Source,Type"); - foreach (EventLogEntry entry in eventLogEntries) - { - DataRow row = dataTable.NewRow(); - row["Type"] = entry.EntryType.ToString(); - row["DateTime"] = entry.TimeGenerated; - row["Source"] = entry.Source; - row["Category"] = entry.Category; - row["EventID"] = entry.InstanceId; - row["Description"] = entry.Message; - row["User"] = entry.UserName; - row["Computer"] = entry.MachineName; - dataTable.Rows.Add(row); - } + foreach (EventLogEntry entry in eventLogEntries) + { + DataRow row = dataTable.NewRow(); + row["Type"] = entry.EntryType.ToString(); + row["DateTime"] = entry.TimeGenerated; + row["Source"] = entry.Source; + row["Category"] = entry.Category; + row["EventID"] = entry.InstanceId; + row["Description"] = entry.Message; + row["User"] = entry.UserName; + row["Computer"] = entry.MachineName; + dataTable.Rows.Add(row); + } - DataSet dataSet = new DataSet(); - dataSet.Locale = CultureInfo.InvariantCulture; - dataSet.Tables.Add(dataTable); + DataSet dataSet = new DataSet(); + dataSet.Locale = CultureInfo.InvariantCulture; + dataSet.Tables.Add(dataTable); - // Use UTF-16 encoding - StringBuilder stringBuilder = new StringBuilder(); - using (StringWriter stringWriter = new StringWriter(stringBuilder)) - { - dataSet.WriteXml(stringWriter, XmlWriteMode.WriteSchema); - fileHelper.WriteAllTextToFile(xmlFilePath, stringBuilder.ToString()); - } - } + // Use UTF-16 encoding + StringBuilder stringBuilder = new StringBuilder(); + using StringWriter stringWriter = new StringWriter(stringBuilder); + dataSet.WriteXml(stringWriter, XmlWriteMode.WriteSchema); + fileHelper.WriteAllTextToFile(xmlFilePath, stringBuilder.ToString()); } } #endregion diff --git a/src/Microsoft.TestPlatform.Build/Tasks/VSTestForwardingApp.cs b/src/Microsoft.TestPlatform.Build/Tasks/VSTestForwardingApp.cs index 0131b222d5..06d174787c 100644 --- a/src/Microsoft.TestPlatform.Build/Tasks/VSTestForwardingApp.cs +++ b/src/Microsoft.TestPlatform.Build/Tasks/VSTestForwardingApp.cs @@ -38,15 +38,13 @@ public int Execute() Tracing.Trace("VSTest: Starting vstest.console..."); Tracing.Trace("VSTest: Arguments: " + processInfo.FileName + " " + processInfo.Arguments); - using (var activeProcess = new Process { StartInfo = processInfo }) - { - activeProcess.Start(); - this.activeProcessId = activeProcess.Id; + using var activeProcess = new Process { StartInfo = processInfo }; + activeProcess.Start(); + this.activeProcessId = activeProcess.Id; - activeProcess.WaitForExit(); - Tracing.Trace("VSTest: Exit code: " + activeProcess.ExitCode); - return activeProcess.ExitCode; - } + activeProcess.WaitForExit(); + Tracing.Trace("VSTest: Exit code: " + activeProcess.ExitCode); + return activeProcess.ExitCode; } public void Cancel() diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs index 35585a6663..2dcf7a34e6 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/TestPlatformDataCollectionEvents.cs @@ -26,13 +26,14 @@ internal sealed class TestPlatformDataCollectionEvents : DataCollectionEvents /// internal TestPlatformDataCollectionEvents() { - this.eventArgsToEventInvokerMap = new Dictionary(4); - - this.eventArgsToEventInvokerMap[typeof(TestHostLaunchedEventArgs)] = this.OnTestHostLaunched; - this.eventArgsToEventInvokerMap[typeof(SessionStartEventArgs)] = this.OnSessionStart; - this.eventArgsToEventInvokerMap[typeof(SessionEndEventArgs)] = this.OnSessionEnd; - this.eventArgsToEventInvokerMap[typeof(TestCaseStartEventArgs)] = this.OnTestCaseStart; - this.eventArgsToEventInvokerMap[typeof(TestCaseEndEventArgs)] = this.OnTestCaseEnd; + this.eventArgsToEventInvokerMap = new Dictionary(4) + { + [typeof(TestHostLaunchedEventArgs)] = this.OnTestHostLaunched, + [typeof(SessionStartEventArgs)] = this.OnSessionStart, + [typeof(SessionEndEventArgs)] = this.OnSessionEnd, + [typeof(TestCaseStartEventArgs)] = this.OnTestCaseStart, + [typeof(TestCaseEndEventArgs)] = this.OnTestCaseEnd + }; } /// diff --git a/src/Microsoft.TestPlatform.Common/RunSettings.cs b/src/Microsoft.TestPlatform.Common/RunSettings.cs index 722c642d15..f09170803c 100644 --- a/src/Microsoft.TestPlatform.Common/RunSettings.cs +++ b/src/Microsoft.TestPlatform.Common/RunSettings.cs @@ -98,11 +98,9 @@ public void LoadSettingsXml(string settings) throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, settings); } - using (var stringReader = new StringReader(settings)) - { - var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); - this.ValidateAndSaveSettings(reader); - } + using var stringReader = new StringReader(settings); + var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); + this.ValidateAndSaveSettings(reader); } /// @@ -113,11 +111,9 @@ public void LoadSettingsXml(string settings) Justification = "XmlReaderSettings.XmlResolver is not available in core. Suppress until fxcop issue is fixed.")] public void InitializeSettingsProviders(string settings) { - using (var stringReader = new StringReader(settings)) - { - var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); - this.ReadRunSettings(reader); - } + using var stringReader = new StringReader(settings); + var reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); + this.ReadRunSettings(reader); } #endregion @@ -137,11 +133,9 @@ private void ValidateAndSaveSettings(XmlReader reader) { var dom = new XmlDocument(); dom.Load(reader); - using (var writer = new StringWriter(CultureInfo.InvariantCulture)) - { - dom.Save(writer); - this.SettingsXml = writer.ToString(); - } + using var writer = new StringWriter(CultureInfo.InvariantCulture); + dom.Save(writer); + this.SettingsXml = writer.ToString(); } catch (Exception e) { diff --git a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs index 504776695b..4c84066fc0 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyProperties.cs @@ -41,21 +41,19 @@ public AssemblyType GetAssemblyType(string filePath) try { - using (var fileStream = this.fileHelper.GetStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - using (var peReader = new PEReader(fileStream)) - { - // Resources for PEReader: - // 1. https://msdn.microsoft.com/library/windows/desktop/ms680547(v=vs.85).aspx?id=19509 - // 2. https://github.com/dotnet/corefx/tree/master/src/System.Reflection.Metadata + using var fileStream = this.fileHelper.GetStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var peReader = new PEReader(fileStream); + // Resources for PEReader: + // 1. https://msdn.microsoft.com/library/windows/desktop/ms680547(v=vs.85).aspx?id=19509 + // 2. https://github.com/dotnet/corefx/tree/master/src/System.Reflection.Metadata - var peHeaders = peReader.PEHeaders; - var corHeader = peHeaders.CorHeader; - var corHeaderStartOffset = peHeaders.CorHeaderStartOffset; + var peHeaders = peReader.PEHeaders; + var corHeader = peHeaders.CorHeader; + var corHeaderStartOffset = peHeaders.CorHeaderStartOffset; - assemblyType = (corHeader != null && corHeaderStartOffset >= 0) ? - AssemblyType.Managed : - AssemblyType.Native; - } + assemblyType = (corHeader != null && corHeaderStartOffset >= 0) ? + AssemblyType.Managed : + AssemblyType.Native; } catch (Exception ex) { diff --git a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs index 9caf3d38d1..623cc31739 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs @@ -189,15 +189,13 @@ private static string AddDefaultRunSettings(string runSettings) var framework = Framework.DefaultFramework; var defaultResultsDirectory = Path.Combine(Directory.GetCurrentDirectory(), Constants.ResultsDirectoryName); - using (var stream = new StringReader(runSettings)) - using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings)) - { - var document = new XmlDocument(); - document.Load(reader); + using var stream = new StringReader(runSettings); + using var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings); + var document = new XmlDocument(); + document.Load(reader); - InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(document, architecture, framework, defaultResultsDirectory); - return document.OuterXml; - } + InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(document, architecture, framework, defaultResultsDirectory); + return document.OuterXml; } private static XmlNode CreateNode(XmlDocument doc, string xPath) @@ -227,31 +225,24 @@ private static XmlDocument GetRunSettingXmlDocument(this IRunSettingsProvider ru var settingsXml = runSettingsProvider.ActiveRunSettings.SettingsXml; #if NETFRAMEWORK - using (var reader = XmlReader.Create(new StringReader(settingsXml), new XmlReaderSettings() { XmlResolver = null, CloseInput = true, DtdProcessing = DtdProcessing.Prohibit })) - { + using var reader = XmlReader.Create(new StringReader(settingsXml), new XmlReaderSettings() { XmlResolver = null, CloseInput = true, DtdProcessing = DtdProcessing.Prohibit }); #else - using ( - var reader = XmlReader.Create(new StringReader(settingsXml), - new XmlReaderSettings() { CloseInput = true, DtdProcessing = DtdProcessing.Prohibit })) - { + using var reader = XmlReader.Create(new StringReader(settingsXml), + new XmlReaderSettings() { CloseInput = true, DtdProcessing = DtdProcessing.Prohibit }); #endif - doc.Load(reader); - } + doc.Load(reader); } else { #if NETFRAMEWORK doc = (XmlDocument) XmlRunSettingsUtilities.CreateDefaultRunSettings(); #else - using ( - var reader = + using var reader = XmlReader.Create( new StringReader( XmlRunSettingsUtilities.CreateDefaultRunSettings().CreateNavigator().OuterXml), - new XmlReaderSettings() { CloseInput = true, DtdProcessing = DtdProcessing.Prohibit })) - { - doc.Load(reader); - } + new XmlReaderSettings() { CloseInput = true, DtdProcessing = DtdProcessing.Prohibit }); + doc.Load(reader); #endif } return doc; diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs index 8ed776bba3..ef5b4d4c71 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs @@ -317,8 +317,10 @@ private void HandleBeforeTestRunStart(Message message) var envVariables = this.dataCollectionManager.InitializeDataCollectors(payload.SettingsXml); - var properties = new Dictionary(); - properties.Add(CoreUtilitiesConstants.TestSourcesKeyName, payload.Sources); + var properties = new Dictionary + { + { CoreUtilitiesConstants.TestSourcesKeyName, payload.Sources } + }; var eventArgs = new SessionStartEventArgs(properties); var areTestCaseLevelEventsRequired = this.dataCollectionManager.SessionStarted(eventArgs); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs index 72c44d1e6c..84b4538f4d 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/JsonDataSerializer.cs @@ -173,12 +173,10 @@ public T Clone(T obj) /// Serialized data. private string Serialize(JsonSerializer serializer, T data) { - using (var stringWriter = new StringWriter()) - using (var jsonWriter = new JsonTextWriter(stringWriter)) - { - serializer.Serialize(jsonWriter, data); - return stringWriter.ToString(); - } + using var stringWriter = new StringWriter(); + using var jsonWriter = new JsonTextWriter(stringWriter); + serializer.Serialize(jsonWriter, data); + return stringWriter.ToString(); } /// @@ -190,11 +188,9 @@ private string Serialize(JsonSerializer serializer, T data) /// Deserialized data. private T Deserialize(JsonSerializer serializer, string data) { - using (var stringReader = new StringReader(data)) - using (var jsonReader = new JsonTextReader(stringReader)) - { - return serializer.Deserialize(jsonReader); - } + using var stringReader = new StringReader(data); + using var jsonReader = new JsonTextReader(stringReader); + return serializer.Deserialize(jsonReader); } /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs index 613c9a7cb6..dc2011c33b 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs @@ -304,31 +304,27 @@ private string GetMuxerFromGlobalRegistrationWin(PlatformArchitecture targetArch { if (hklm != null) { - using (IRegistryKey dotnetInstalledVersion = hklm.OpenSubKey(@"SOFTWARE\dotnet\Setup\InstalledVersions")) + using IRegistryKey dotnetInstalledVersion = hklm.OpenSubKey(@"SOFTWARE\dotnet\Setup\InstalledVersions"); + if (dotnetInstalledVersion != null) { - if (dotnetInstalledVersion != null) + using IRegistryKey nativeArch = dotnetInstalledVersion.OpenSubKey(targetArchitecture.ToString().ToLowerInvariant()); + string installLocation = nativeArch?.GetValue("InstallLocation")?.ToString(); + + if (installLocation != null) { - using (IRegistryKey nativeArch = dotnetInstalledVersion.OpenSubKey(targetArchitecture.ToString().ToLowerInvariant())) - { - string installLocation = nativeArch?.GetValue("InstallLocation")?.ToString(); - - if (installLocation != null) - { - string path = Path.Combine(installLocation.Trim(), this.muxerName); - EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Muxer resolved using win registry key 'SOFTWARE\dotnet\Setup\InstalledVersions\{targetArchitecture.ToString().ToLowerInvariant()}\InstallLocation' in '{path}'"); - return path; - } - else - { - EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing registry InstallLocation"); - } - } + string path = Path.Combine(installLocation.Trim(), this.muxerName); + EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Muxer resolved using win registry key 'SOFTWARE\dotnet\Setup\InstalledVersions\{targetArchitecture.ToString().ToLowerInvariant()}\InstallLocation' in '{path}'"); + return path; } else { - EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing RegistryHive.LocalMachine for RegistryView.Registry32"); + EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing registry InstallLocation"); } } + else + { + EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing RegistryHive.LocalMachine for RegistryView.Registry32"); + } } else { @@ -356,15 +352,13 @@ private string GetMuxerFromGlobalRegistrationOnUnix(PlatformArchitecture targetA { try { - using (Stream stream = this.fileHelper.GetStream(installLocation, FileMode.Open, FileAccess.Read)) - using (StreamReader streamReader = new StreamReader(stream)) - { - string content = streamReader.ReadToEnd().Trim(); - EqtTrace.Verbose($"DotnetHostHelper: '{installLocation}' content '{content}'"); - string path = Path.Combine(content, this.muxerName); - EqtTrace.Verbose($"DotnetHostHelper: Muxer resolved using '{installLocation}' in '{path}'"); - return path; - } + using Stream stream = this.fileHelper.GetStream(installLocation, FileMode.Open, FileAccess.Read); + using StreamReader streamReader = new StreamReader(stream); + string content = streamReader.ReadToEnd().Trim(); + EqtTrace.Verbose($"DotnetHostHelper: '{installLocation}' content '{content}'"); + string path = Path.Combine(content, this.muxerName); + EqtTrace.Verbose($"DotnetHostHelper: Muxer resolved using '{installLocation}' in '{path}'"); + return path; } catch (Exception ex) { @@ -379,24 +373,22 @@ private string GetMuxerFromGlobalRegistrationOnUnix(PlatformArchitecture targetA { try { - using (Stream stream = this.fileHelper.GetStream(path, FileMode.Open, FileAccess.Read)) - using (PEReader peReader = new PEReader(stream)) + using Stream stream = this.fileHelper.GetStream(path, FileMode.Open, FileAccess.Read); + using PEReader peReader = new PEReader(stream); + switch (peReader.PEHeaders.CoffHeader.Machine) { - switch (peReader.PEHeaders.CoffHeader.Machine) - { - case Machine.Amd64: - return PlatformArchitecture.X64; - case Machine.IA64: - return PlatformArchitecture.X64; - case Machine.Arm64: - return PlatformArchitecture.ARM64; - case Machine.Arm: - return PlatformArchitecture.ARM; - case Machine.I386: - return PlatformArchitecture.X86; - default: - break; - } + case Machine.Amd64: + return PlatformArchitecture.X64; + case Machine.IA64: + return PlatformArchitecture.X64; + case Machine.Arm64: + return PlatformArchitecture.ARM64; + case Machine.Arm: + return PlatformArchitecture.ARM; + case Machine.I386: + return PlatformArchitecture.X86; + default: + break; } } catch (Exception ex) @@ -414,36 +406,34 @@ private string GetMuxerFromGlobalRegistrationOnUnix(PlatformArchitecture targetA try { PlatformArchitecture? architecture; - using (var headerReader = this.fileHelper.GetStream(path, FileMode.Open, FileAccess.Read)) + using var headerReader = this.fileHelper.GetStream(path, FileMode.Open, FileAccess.Read); + var magicBytes = new byte[4]; + var cpuInfoBytes = new byte[4]; + headerReader.Read(magicBytes, 0, magicBytes.Length); + headerReader.Read(cpuInfoBytes, 0, cpuInfoBytes.Length); + + var magic = BitConverter.ToUInt32(magicBytes, 0); + var cpuInfo = BitConverter.ToUInt32(cpuInfoBytes, 0); + switch ((MacOsCpuType)cpuInfo) { - var magicBytes = new byte[4]; - var cpuInfoBytes = new byte[4]; - headerReader.Read(magicBytes, 0, magicBytes.Length); - headerReader.Read(cpuInfoBytes, 0, cpuInfoBytes.Length); - - var magic = BitConverter.ToUInt32(magicBytes, 0); - var cpuInfo = BitConverter.ToUInt32(cpuInfoBytes, 0); - switch ((MacOsCpuType)cpuInfo) - { - case MacOsCpuType.Arm64Magic: - case MacOsCpuType.Arm64Cigam: - architecture = PlatformArchitecture.ARM64; - break; - case MacOsCpuType.X64Magic: - case MacOsCpuType.X64Cigam: - architecture = PlatformArchitecture.X64; - break; - case MacOsCpuType.X86Magic: - case MacOsCpuType.X86Cigam: - architecture = PlatformArchitecture.X86; - break; - default: - architecture = null; - break; - } - - return architecture; + case MacOsCpuType.Arm64Magic: + case MacOsCpuType.Arm64Cigam: + architecture = PlatformArchitecture.ARM64; + break; + case MacOsCpuType.X64Magic: + case MacOsCpuType.X64Cigam: + architecture = PlatformArchitecture.X64; + break; + case MacOsCpuType.X86Magic: + case MacOsCpuType.X86Cigam: + architecture = PlatformArchitecture.X86; + break; + default: + architecture = null; + break; } + + return architecture; } catch (Exception ex) { diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs index 09b3f3dbb3..dc1b132f2e 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs @@ -188,15 +188,13 @@ public void Flush() this.CheckDisposed(); // Create the wait job. - using (var waitEvent = new ManualResetEvent(false)) - { - var waitJob = Job.CreateWaitJob(waitEvent); + using var waitEvent = new ManualResetEvent(false); + var waitJob = Job.CreateWaitJob(waitEvent); - // Queue the wait job and wait for it to be processed. - this.InternalQueueJob(waitJob); + // Queue the wait job and wait for it to be processed. + this.InternalQueueJob(waitJob); - waitEvent.WaitOne(); - } + waitEvent.WaitOne(); } /// diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs index 7e82007df3..f0e592eb5a 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollectionExtensionManager.cs @@ -260,8 +260,10 @@ private string GetCodebase(string codeBase) private IDictionary GetSessionStartProperties(SessionStartEventArgs sessionStartEventArgs) { - var properties = new Dictionary(); - properties.Add(Constants.TestSourcesPropertyName, sessionStartEventArgs.GetPropertyValue>(Constants.TestSourcesPropertyName)); + var properties = new Dictionary + { + { Constants.TestSourcesPropertyName, sessionStartEventArgs.GetPropertyValue>(Constants.TestSourcesPropertyName) } + }; return properties; } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs index 8757b1bc4a..e26e7d711d 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs @@ -317,13 +317,14 @@ private void HandleExceptionMessage(ITestMessageEventHandler runEventsHandler, E private IList GetCommandLineArguments(int portNumber) { - var commandlineArguments = new List(); - - commandlineArguments.Add(PortOption); - commandlineArguments.Add(portNumber.ToString()); + var commandlineArguments = new List + { + PortOption, + portNumber.ToString(), - commandlineArguments.Add(ParentProcessIdOption); - commandlineArguments.Add(this.processHelper.GetCurrentProcessId().ToString()); + ParentProcessIdOption, + this.processHelper.GetCurrentProcessId().ToString() + }; if (!string.IsNullOrEmpty(EqtTrace.LogFile)) { @@ -361,23 +362,21 @@ private static string UpdateExtensionsFolderInRunSettings(string settingsXml) var extensionsFolder = Path.Combine(Path.GetDirectoryName(typeof(ITestPlatform).GetTypeInfo().Assembly.GetAssemblyLocation()), "Extensions"); - using (var stream = new StringReader(settingsXml)) - using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings)) - { - var document = new XmlDocument(); - document.Load(reader); + using var stream = new StringReader(settingsXml); + using var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings); + var document = new XmlDocument(); + document.Load(reader); - var tapNode = RunSettingsProviderExtensions.GetXmlNode(document, "RunConfiguration.TestAdaptersPaths"); + var tapNode = RunSettingsProviderExtensions.GetXmlNode(document, "RunConfiguration.TestAdaptersPaths"); - if (tapNode != null && !string.IsNullOrWhiteSpace(tapNode.InnerText)) - { - extensionsFolder = string.Concat(tapNode.InnerText, ';', extensionsFolder); - } + if (tapNode != null && !string.IsNullOrWhiteSpace(tapNode.InnerText)) + { + extensionsFolder = string.Concat(tapNode.InnerText, ';', extensionsFolder); + } - RunSettingsProviderExtensions.UpdateRunSettingsXmlDocument(document, "RunConfiguration.TestAdaptersPaths", extensionsFolder); + RunSettingsProviderExtensions.UpdateRunSettingsXmlDocument(document, "RunConfiguration.TestAdaptersPaths", extensionsFolder); - return document.OuterXml; - } + return document.OuterXml; } /// diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs index d9372453fd..070dbcdb7c 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs @@ -248,8 +248,10 @@ protected override void SendSessionStart() return; } - var properties = new Dictionary(); - properties.Add("TestSources", TestSourcesUtility.GetSources(this.adapterSourceMap)); + var properties = new Dictionary + { + { "TestSources", TestSourcesUtility.GetSources(this.adapterSourceMap) } + }; this.testCaseEventsHandler.SendSessionStart(properties); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs index b072cac0a0..f922acf81b 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs @@ -110,8 +110,10 @@ protected override void SendSessionStart() return; } - var properties = new Dictionary(); - properties.Add("TestSources", TestSourcesUtility.GetSources(this.testCases)); + var properties = new Dictionary + { + { "TestSources", TestSourcesUtility.GetSources(this.testCases) } + }; this.testCaseEventsHandler.SendSessionStart(properties); } @@ -137,8 +139,10 @@ private Dictionary, List> GetExecutorVsTestCaseList } else { - testList = new List(); - testList.Add(test); + testList = new List + { + test + }; result.Add(executorUriExtensionTuple, testList); } } diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs index d06b1e6ed9..10979d5e82 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs @@ -181,51 +181,49 @@ internal static void CollectDump(Process process, string outputFile, DumpTypeOpt private static void CollectDumpUsingMiniDumpWriteDump(Process process, string outputFile, DumpTypeOption type) { // Open the file for writing - using (var stream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) + using var stream = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None); + NativeMethods.MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = default; + + NativeMethods.MINIDUMP_TYPE dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpNormal; + switch (type) { - NativeMethods.MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = default; + case DumpTypeOption.Full: + dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemory | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; + break; + case DumpTypeOption.WithHeap: + dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithPrivateReadWriteMemory | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | + NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; + break; + case DumpTypeOption.Mini: + dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo; + break; + } - NativeMethods.MINIDUMP_TYPE dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpNormal; - switch (type) + // Retry the write dump on ERROR_PARTIAL_COPY + for (int i = 0; i < 5; i++) + { + // Dump the process! + if (NativeMethods.MiniDumpWriteDump(process.Handle, (uint)process.Id, stream.SafeFileHandle, dumpType, ref exceptionInfo, IntPtr.Zero, IntPtr.Zero)) { - case DumpTypeOption.Full: - dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemory | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; - break; - case DumpTypeOption.WithHeap: - dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithPrivateReadWriteMemory | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithDataSegs | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithHandleData | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithUnloadedModules | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo | - NativeMethods.MINIDUMP_TYPE.MiniDumpWithTokenInformation; - break; - case DumpTypeOption.Mini: - dumpType = NativeMethods.MINIDUMP_TYPE.MiniDumpWithThreadInfo; - break; + break; } - - // Retry the write dump on ERROR_PARTIAL_COPY - for (int i = 0; i < 5; i++) + else { - // Dump the process! - if (NativeMethods.MiniDumpWriteDump(process.Handle, (uint)process.Id, stream.SafeFileHandle, dumpType, ref exceptionInfo, IntPtr.Zero, IntPtr.Zero)) - { - break; - } - else + int err = Marshal.GetHRForLastWin32Error(); + if (err != NativeMethods.ERROR_PARTIAL_COPY) { - int err = Marshal.GetHRForLastWin32Error(); - if (err != NativeMethods.ERROR_PARTIAL_COPY) - { - Marshal.ThrowExceptionForHR(err); - } + Marshal.ThrowExceptionForHR(err); } } } diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs index 2d726a4a6f..a57b1576ec 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs @@ -353,9 +353,11 @@ internal void TestRunCompleteHandler(object sender, TestRunCompleteEventArgs e) helper.SaveIEnumerable(this.entries.Values, rootElement, "TestEntries", ".", "TestEntry", parameters); // Save default categories - List categories = new List(); - categories.Add(TestListCategory.UncategorizedResults); - categories.Add(TestListCategory.AllResults); + List categories = new List + { + TestListCategory.UncategorizedResults, + TestListCategory.AllResults + }; helper.SaveList(categories, rootElement, "TestLists", ".", "TestList", parameters); // Save summary @@ -413,11 +415,9 @@ internal virtual void PopulateTrxFile(string trxFileName, XmlElement rootElement { using (var fs = File.Open(trxFileName, FileMode.Truncate)) { - using (XmlWriter writer = XmlWriter.Create(fs, new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize, Indent = true })) - { - rootElement.OwnerDocument.Save(writer); - writer.Flush(); - } + using XmlWriter writer = XmlWriter.Create(fs, new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize, Indent = true }); + rootElement.OwnerDocument.Save(writer); + writer.Flush(); } string resultsFileMessage = string.Format(CultureInfo.CurrentCulture, TrxLoggerResources.TrxLoggerResultsFile, trxFileName); @@ -486,7 +486,7 @@ private void ReserveTrxFilePath() { try { - using (var fs = File.Open(filePath, FileMode.CreateNew)) { } + using var fs = File.Open(filePath, FileMode.CreateNew); } catch (IOException) { diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs index b9b53c21c3..7b66af5ae1 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/DiscoveryCriteria.cs @@ -112,8 +112,10 @@ public DiscoveryCriteria( throw new ArgumentOutOfRangeException(nameof(discoveredTestEventTimeout), Resources.NotificationTimeoutIsZero); } - this.AdapterSourceMap = new Dictionary>(); - this.AdapterSourceMap.Add(Constants.UnspecifiedAdapterPath, sources); + this.AdapterSourceMap = new Dictionary> + { + { Constants.UnspecifiedAdapterPath, sources } + }; this.FrequencyOfDiscoveredTestsEvent = frequencyOfDiscoveredTestsEvent; this.DiscoveredTestEventTimeout = discoveredTestEventTimeout; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs index 1e23577f93..ad188c53ac 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Client/TestRunCriteria.cs @@ -230,8 +230,10 @@ public TestRunCriteria( var testSources = sources as IList ?? sources.ToList(); ValidateArg.NotNullOrEmpty(testSources, nameof(sources)); - this.AdapterSourceMap = new Dictionary>(); - this.AdapterSourceMap.Add(Constants.UnspecifiedAdapterPath, testSources); + this.AdapterSourceMap = new Dictionary> + { + { Constants.UnspecifiedAdapterPath, testSources } + }; this.TestCaseFilter = testCaseFilter; this.FilterOptions = filterOptions; @@ -255,8 +257,10 @@ public TestRunCriteria( var testSources = sources as IList ?? sources.ToArray(); ValidateArg.NotNullOrEmpty(testSources, nameof(sources)); - this.AdapterSourceMap = new Dictionary>(); - this.AdapterSourceMap.Add(Constants.UnspecifiedAdapterPath, testSources); + this.AdapterSourceMap = new Dictionary> + { + { Constants.UnspecifiedAdapterPath, testSources } + }; this.TestCaseFilter = testRunCriteria.testCaseFilter; this.FilterOptions = testRunCriteria.filterOptions; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs index 469063eaf2..0c0d1851e1 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs @@ -99,15 +99,13 @@ private static ISymbolReader GetSymbolReader(string binaryPath) // For remote scenario, also look for pdb in current directory, (esp for UWP) // The alternate search path should be an input from Adapters, but since it is not so currently adding a HACK pdbFilePath = !File.Exists(pdbFilePath) ? Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(pdbFilePath)) : pdbFilePath; - using (var stream = new FileHelper().GetStream(pdbFilePath, FileMode.Open, FileAccess.Read)) + using var stream = new FileHelper().GetStream(pdbFilePath, FileMode.Open, FileAccess.Read); + if (PortablePdbReader.IsPortable(stream)) { - if (PortablePdbReader.IsPortable(stream)) - { - return new PortableSymbolReader(); - } - - return new FullSymbolReader(); + return new PortableSymbolReader(); } + + return new FullSymbolReader(); } } } \ No newline at end of file diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs index ba03fecb79..b827cf04a3 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs @@ -89,55 +89,53 @@ private void PopulateCacheForTypeAndMethodSymbols(string binaryPath) try { var pdbFilePath = Path.ChangeExtension(binaryPath, ".pdb"); - using (var pdbReader = new PortablePdbReader(new FileHelper().GetStream(pdbFilePath, FileMode.Open, FileAccess.Read))) + using var pdbReader = new PortablePdbReader(new FileHelper().GetStream(pdbFilePath, FileMode.Open, FileAccess.Read)); + // At this point, the assembly should be already loaded into the load context. We query for a reference to + // find the types and cache the symbol information. Let the loader follow default lookup order instead of + // forcing load from a specific path. + Assembly asm; + try + { + asm = Assembly.Load(new PlatformAssemblyLoadContext().GetAssemblyNameFromPath(binaryPath)); + } + catch (FileNotFoundException) { - // At this point, the assembly should be already loaded into the load context. We query for a reference to - // find the types and cache the symbol information. Let the loader follow default lookup order instead of - // forcing load from a specific path. - Assembly asm; - try - { - asm = Assembly.Load(new PlatformAssemblyLoadContext().GetAssemblyNameFromPath(binaryPath)); - } - catch (FileNotFoundException) - { #if !NETSTANDARD1_3 && !WINDOWS_UWP && !NETCOREAPP1_0 - // fallback when the assembly is not loaded - asm = Assembly.LoadFile(binaryPath); + // fallback when the assembly is not loaded + asm = Assembly.LoadFile(binaryPath); #else - // fallback is not supported - throw; + // fallback is not supported + throw; #endif - } + } - foreach (var type in asm.GetTypes()) - { - // Get declared method infos - var methodInfoList = type.GetTypeInfo().DeclaredMethods; - var methodsNavigationData = new Dictionary(); + foreach (var type in asm.GetTypes()) + { + // Get declared method infos + var methodInfoList = type.GetTypeInfo().DeclaredMethods; + var methodsNavigationData = new Dictionary(); - foreach (var methodInfo in methodInfoList) + foreach (var methodInfo in methodInfoList) + { + var diaNavigationData = pdbReader.GetDiaNavigationData(methodInfo); + if (diaNavigationData != null) { - var diaNavigationData = pdbReader.GetDiaNavigationData(methodInfo); - if (diaNavigationData != null) - { - methodsNavigationData[methodInfo.Name] = diaNavigationData; - } - else - { - EqtTrace.Error( - string.Format( - "Unable to find source information for method: {0} type: {1}", - methodInfo.Name, - type.FullName)); - } + methodsNavigationData[methodInfo.Name] = diaNavigationData; } - - if (methodsNavigationData.Count != 0) + else { - this.methodsNavigationDataForType[type.FullName] = methodsNavigationData; + EqtTrace.Error( + string.Format( + "Unable to find source information for method: {0} type: {1}", + methodInfo.Name, + type.FullName)); } } + + if (methodsNavigationData.Count != 0) + { + this.methodsNavigationDataForType[type.FullName] = methodsNavigationData; + } } } catch (Exception ex) diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs index 6183496e9e..3130dbf4b2 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs @@ -41,14 +41,12 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c var data = value as string; if (data != null) { - using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(data))) - { - // Converting Json data to array of KeyValuePairs with duplicate keys. - var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(TraitObject[])); - var listOfTraitObjects = serializer.ReadObject(stream) as TraitObject[]; + using var stream = new MemoryStream(Encoding.Unicode.GetBytes(data)); + // Converting Json data to array of KeyValuePairs with duplicate keys. + var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(TraitObject[])); + var listOfTraitObjects = serializer.ReadObject(stream) as TraitObject[]; - return listOfTraitObjects.Select(i => new KeyValuePair(i.Key, i.Value)).ToArray(); - } + return listOfTraitObjects.Select(i => new KeyValuePair(i.Key, i.Value)).ToArray(); } return null; diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs index 254562555a..3ac948582e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomStringArrayConverter.cs @@ -36,13 +36,11 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c var data = value as string; if (data != null) { - using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(data))) - { - var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string[])); - var strings = serializer.ReadObject(stream) as string[]; + using var stream = new MemoryStream(Encoding.Unicode.GetBytes(data)); + var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string[])); + var strings = serializer.ReadObject(stream) as string[]; - return strings; - } + return strings; } return null; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs index 6ce8754042..92214b6c38 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs @@ -294,77 +294,75 @@ private static string GetArchitectureForSource(string imagePath) try { //get the input stream - using (Stream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) - { - bool validImage = true; + using Stream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read); + bool validImage = true; + + BinaryReader reader = new BinaryReader(fs); + //PE Header starts @ 0x3C (60). Its a 4 byte header. + fs.Position = 0x3C; + peHeader = reader.ReadUInt32(); - BinaryReader reader = new BinaryReader(fs); - //PE Header starts @ 0x3C (60). Its a 4 byte header. - fs.Position = 0x3C; - peHeader = reader.ReadUInt32(); + // Check if the offset is invalid + if (peHeader > fs.Length - 5) + { + validImage = false; + } + if (validImage) + { + //Moving to PE Header start location... + fs.Position = peHeader; - // Check if the offset is invalid - if (peHeader > fs.Length - 5) + UInt32 signature = reader.ReadUInt32(); //peHeaderSignature + // 0x00004550 is the letters "PE" followed by two terminating zeros. + if (signature != 0x00004550) { validImage = false; } + if (validImage) { - //Moving to PE Header start location... - fs.Position = peHeader; - - UInt32 signature = reader.ReadUInt32(); //peHeaderSignature - // 0x00004550 is the letters "PE" followed by two terminating zeros. - if (signature != 0x00004550) + //Read the image file header. + machine = reader.ReadUInt16(); + reader.ReadUInt16(); //NumberOfSections + reader.ReadUInt32(); //TimeDateStamp + reader.ReadUInt32(); //PointerToSymbolTable + reader.ReadUInt32(); //NumberOfSymbols + reader.ReadUInt16(); //SizeOfOptionalHeader + reader.ReadUInt16(); //Characteristics + + // magic number.32bit or 64bit assembly. + UInt16 magic = reader.ReadUInt16(); + if (magic != 0x010B && magic != 0x020B) { validImage = false; } + } - if (validImage) + if (validImage) + { + switch (machine) { - //Read the image file header. - machine = reader.ReadUInt16(); - reader.ReadUInt16(); //NumberOfSections - reader.ReadUInt32(); //TimeDateStamp - reader.ReadUInt32(); //PointerToSymbolTable - reader.ReadUInt32(); //NumberOfSymbols - reader.ReadUInt16(); //SizeOfOptionalHeader - reader.ReadUInt16(); //Characteristics - - // magic number.32bit or 64bit assembly. - UInt16 magic = reader.ReadUInt16(); - if (magic != 0x010B && magic != 0x020B) - { - validImage = false; - } - } + case IMAGE_FILE_MACHINE_I386: + archType = "X86"; + break; - if (validImage) - { - switch (machine) - { - case IMAGE_FILE_MACHINE_I386: - archType = "X86"; - break; - - case IMAGE_FILE_MACHINE_AMD64: - case IMAGE_FILE_MACHINE_IA64: - archType = "X64"; - break; - - case IMAGE_FILE_MACHINE_ARM: - case IMAGE_FILE_MACHINE_THUMB: - case IMAGE_FILE_MACHINE_ARMNT: - archType = "ARM"; - break; - } + case IMAGE_FILE_MACHINE_AMD64: + case IMAGE_FILE_MACHINE_IA64: + archType = "X64"; + break; + + case IMAGE_FILE_MACHINE_ARM: + case IMAGE_FILE_MACHINE_THUMB: + case IMAGE_FILE_MACHINE_ARMNT: + archType = "ARM"; + break; } - else + } + else + { + if (EqtTrace.IsVerboseEnabled) { - if (EqtTrace.IsVerboseEnabled) - { - EqtTrace.Verbose("Source path {0} is not a valid image path. Returning default proc arch type {1}.", imagePath, "AnyCPU"); - } + EqtTrace.Verbose("Source path {0} is not a valid image path. Returning default proc arch type {1}.", imagePath, "AnyCPU"); } } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs index 9acf17ebae..f56ed10b06 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/Sha1Helper.cs @@ -25,12 +25,10 @@ public static byte[] ComputeSha1(byte[] message) return hasher.ComputeHash(message); #else - using (HashAlgorithm provider = SHA1.Create()) - { - byte[] hash = provider.ComputeHash(message); + using HashAlgorithm provider = SHA1.Create(); + byte[] hash = provider.ComputeHash(message); - return hash; - } + return hash; #endif } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs index c0e21ac443..634557eb8e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlRunSettingsUtilities.cs @@ -104,20 +104,18 @@ public static IList GetDataCollectorsFriendlyName(string runsettingsXml) var friendlyNameList = new List(); if (!string.IsNullOrWhiteSpace(runsettingsXml)) { - using (var stream = new StringReader(runsettingsXml)) - using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings)) - { - var document = new XmlDocument(); - document.Load(reader); + using var stream = new StringReader(runsettingsXml); + using var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings); + var document = new XmlDocument(); + document.Load(reader); - var runSettingsNavigator = document.CreateNavigator(); - var nodes = runSettingsNavigator.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); + var runSettingsNavigator = document.CreateNavigator(); + var nodes = runSettingsNavigator.Select("/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); - foreach (XPathNavigator dataCollectorNavigator in nodes) - { - var friendlyName = dataCollectorNavigator.GetAttribute("friendlyName", string.Empty); - friendlyNameList.Add(friendlyName); - } + foreach (XPathNavigator dataCollectorNavigator in nodes) + { + var friendlyName = dataCollectorNavigator.GetAttribute("friendlyName", string.Empty); + friendlyNameList.Add(friendlyName); } } @@ -273,29 +271,27 @@ public static DataCollectionRunSettings GetDataCollectionRunSettings(string runS try { - using (var stringReader = new StringReader(runSettingsXml)) - { - var reader = XmlReader.Create(stringReader, ReaderSettings); + using var stringReader = new StringReader(runSettingsXml); + var reader = XmlReader.Create(stringReader, ReaderSettings); - // read to the fist child - XmlReaderUtilities.ReadToRootNode(reader); - reader.ReadToNextElement(); - - // Read till we reach DC element or reach EOF - while (!string.Equals(reader.Name, Constants.DataCollectionRunSettingsName) && !reader.EOF) - { - reader.SkipToNextElement(); - } + // read to the fist child + XmlReaderUtilities.ReadToRootNode(reader); + reader.ReadToNextElement(); - // If reached EOF => DC element not there - if (reader.EOF) - { - return null; - } + // Read till we reach DC element or reach EOF + while (!string.Equals(reader.Name, Constants.DataCollectionRunSettingsName) && !reader.EOF) + { + reader.SkipToNextElement(); + } - // Reached here => DC element present. - return DataCollectionRunSettings.FromXml(reader); + // If reached EOF => DC element not there + if (reader.EOF) + { + return null; } + + // Reached here => DC element present. + return DataCollectionRunSettings.FromXml(reader); } catch (XmlException ex) { @@ -321,29 +317,27 @@ public static DataCollectionRunSettings GetInProcDataCollectionRunSettings(strin } runSettingsXml = runSettingsXml.Trim(); - using (StringReader stringReader1 = new StringReader(runSettingsXml)) - { - XmlReader reader = XmlReader.Create(stringReader1, ReaderSettings); + using StringReader stringReader1 = new StringReader(runSettingsXml); + XmlReader reader = XmlReader.Create(stringReader1, ReaderSettings); - // read to the fist child - XmlReaderUtilities.ReadToRootNode(reader); - reader.ReadToNextElement(); - - // Read till we reach In Proc IDC element or reach EOF - while (!string.Equals(reader.Name, Constants.InProcDataCollectionRunSettingsName) && !reader.EOF) - { - reader.SkipToNextElement(); - } + // read to the fist child + XmlReaderUtilities.ReadToRootNode(reader); + reader.ReadToNextElement(); - // If reached EOF => IDC element not there - if (reader.EOF) - { - return null; - } + // Read till we reach In Proc IDC element or reach EOF + while (!string.Equals(reader.Name, Constants.InProcDataCollectionRunSettingsName) && !reader.EOF) + { + reader.SkipToNextElement(); + } - // Reached here => In Proc IDC element present. - return DataCollectionRunSettings.FromXml(reader, Constants.InProcDataCollectionRunSettingsName, Constants.InProcDataCollectorsSettingName, Constants.InProcDataCollectorSettingName); + // If reached EOF => IDC element not there + if (reader.EOF) + { + return null; } + + // Reached here => In Proc IDC element present. + return DataCollectionRunSettings.FromXml(reader, Constants.InProcDataCollectionRunSettingsName, Constants.InProcDataCollectorsSettingName, Constants.InProcDataCollectorSettingName); } #endif @@ -404,27 +398,25 @@ private static T GetNodeValue(string settingsXml, string nodeName, Func(); } - else if (runSettingsNavigator.HasChildren) - { - if (listOfInValidRunConfigurationSettings is null) - { - listOfInValidRunConfigurationSettings = new HashSet(); - } - - // Find all invalid RunConfiguration Settings - runSettingsNavigator.MoveToFirstChild(); - if (listOfValidRunConfigurationSettings != null) - { - do - { - if (!listOfValidRunConfigurationSettings.Contains(runSettingsNavigator.LocalName)) - { - listOfInValidRunConfigurationSettings.Add(runSettingsNavigator.LocalName); - } - } while (runSettingsNavigator.MoveToNext()); - } - // Delete all invalid RunConfiguration Settings - if (listOfInValidRunConfigurationSettings.Count > 0) + // Find all invalid RunConfiguration Settings + runSettingsNavigator.MoveToFirstChild(); + if (listOfValidRunConfigurationSettings != null) + { + do { - if (EqtTrace.IsWarningEnabled) + if (!listOfValidRunConfigurationSettings.Contains(runSettingsNavigator.LocalName)) { - string settingsName = string.Join(", ", listOfInValidRunConfigurationSettings); - EqtTrace.Warning(string.Format("InferRunSettingsHelper.MakeRunsettingsCompatible: Removing the following settings: {0} from RunSettings file. To use those settings please move to latest version of Microsoft.NET.Test.Sdk", settingsName)); + listOfInValidRunConfigurationSettings.Add(runSettingsNavigator.LocalName); } + } while (runSettingsNavigator.MoveToNext()); + } - // move navigator to RunConfiguration node - runSettingsNavigator.MoveToParent(); + // Delete all invalid RunConfiguration Settings + if (listOfInValidRunConfigurationSettings.Count > 0) + { + if (EqtTrace.IsWarningEnabled) + { + string settingsName = string.Join(", ", listOfInValidRunConfigurationSettings); + EqtTrace.Warning(string.Format("InferRunSettingsHelper.MakeRunsettingsCompatible: Removing the following settings: {0} from RunSettings file. To use those settings please move to latest version of Microsoft.NET.Test.Sdk", settingsName)); + } - foreach (var s in listOfInValidRunConfigurationSettings) - { - var nodePath = RunConfigurationNodePath + "/" + s; - XmlUtilities.RemoveChildNode(runSettingsNavigator, nodePath, s); - } + // move navigator to RunConfiguration node + runSettingsNavigator.MoveToParent(); - runSettingsNavigator.MoveToRoot(); - updatedRunSettingsXml = runSettingsNavigator.OuterXml; + foreach (var s in listOfInValidRunConfigurationSettings) + { + var nodePath = RunConfigurationNodePath + "/" + s; + XmlUtilities.RemoveChildNode(runSettingsNavigator, nodePath, s); } + + runSettingsNavigator.MoveToRoot(); + updatedRunSettingsXml = runSettingsNavigator.OuterXml; } } } @@ -312,54 +310,52 @@ public static bool TryGetLegacySettingElements(string runsettingsXml, out Dictio legacySettingsTelemetry = new Dictionary(); try { - using (var stream = new StringReader(runsettingsXml)) - using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings)) - { - var document = new XmlDocument(); - document.Load(reader); - var runSettingsNavigator = document.CreateNavigator(); + using var stream = new StringReader(runsettingsXml); + using var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings); + var document = new XmlDocument(); + document.Load(reader); + var runSettingsNavigator = document.CreateNavigator(); - var node = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings"); - if (node == null) - { - return false; - } + var node = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings"); + if (node == null) + { + return false; + } - var childNodes = node.SelectChildren(XPathNodeType.Element); + var childNodes = node.SelectChildren(XPathNodeType.Element); - var legacySettingElements = new List(); - while (childNodes.MoveNext()) - { - legacySettingElements.Add(childNodes.Current.Name); - } + var legacySettingElements = new List(); + while (childNodes.MoveNext()) + { + legacySettingElements.Add(childNodes.Current.Name); + } - foreach (var executionNodePath in ExecutionNodesPaths) + foreach (var executionNodePath in ExecutionNodesPaths) + { + var executionNode = runSettingsNavigator.SelectSingleNode(executionNodePath); + if (executionNode != null) { - var executionNode = runSettingsNavigator.SelectSingleNode(executionNodePath); - if (executionNode != null) - { - legacySettingElements.Add(executionNode.Name); - } + legacySettingElements.Add(executionNode.Name); } + } - if (legacySettingElements.Count > 0) - { - legacySettingsTelemetry.Add(LegacyElementsString, string.Join(", ", legacySettingElements)); - } + if (legacySettingElements.Count > 0) + { + legacySettingsTelemetry.Add(LegacyElementsString, string.Join(", ", legacySettingElements)); + } - var deploymentNode = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings/Deployment"); - var deploymentAttributes = GetNodeAttributes(deploymentNode); - if (deploymentAttributes != null) - { - legacySettingsTelemetry.Add(DeploymentAttributesString, string.Join(", ", deploymentAttributes)); - } + var deploymentNode = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings/Deployment"); + var deploymentAttributes = GetNodeAttributes(deploymentNode); + if (deploymentAttributes != null) + { + legacySettingsTelemetry.Add(DeploymentAttributesString, string.Join(", ", deploymentAttributes)); + } - var executiontNode = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings/Execution"); - var executiontAttributes = GetNodeAttributes(executiontNode); - if (executiontAttributes != null) - { - legacySettingsTelemetry.Add(ExecutionAttributesString, string.Join(", ", executiontAttributes)); - } + var executiontNode = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings/Execution"); + var executiontAttributes = GetNodeAttributes(executiontNode); + if (executiontAttributes != null) + { + legacySettingsTelemetry.Add(ExecutionAttributesString, string.Join(", ", executiontAttributes)); } } catch (Exception ex) @@ -398,28 +394,26 @@ public static Dictionary GetEnvironmentVariables(string runSetti Dictionary environmentVariables = null; try { - using (var stream = new StringReader(runSettings)) - using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings)) - { - var document = new XmlDocument(); - document.Load(reader); - var runSettingsNavigator = document.CreateNavigator(); + using var stream = new StringReader(runSettings); + using var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings); + var document = new XmlDocument(); + document.Load(reader); + var runSettingsNavigator = document.CreateNavigator(); - var node = runSettingsNavigator.SelectSingleNode(EnvironmentVariablesNodePath); - if (node == null) - { - return null; - } + var node = runSettingsNavigator.SelectSingleNode(EnvironmentVariablesNodePath); + if (node == null) + { + return null; + } - environmentVariables = new Dictionary(); - var childNodes = node.SelectChildren(XPathNodeType.Element); + environmentVariables = new Dictionary(); + var childNodes = node.SelectChildren(XPathNodeType.Element); - while (childNodes.MoveNext()) + while (childNodes.MoveNext()) + { + if (!environmentVariables.ContainsKey(childNodes.Current.Name)) { - if (!environmentVariables.ContainsKey(childNodes.Current.Name)) - { - environmentVariables.Add(childNodes.Current.Name, childNodes.Current?.Value); - } + environmentVariables.Add(childNodes.Current.Name, childNodes.Current?.Value); } } } diff --git a/src/SettingsMigrator/Migrator.cs b/src/SettingsMigrator/Migrator.cs index d558d52d17..2b2fe528b8 100644 --- a/src/SettingsMigrator/Migrator.cs +++ b/src/SettingsMigrator/Migrator.cs @@ -89,41 +89,39 @@ public void Migrate(string oldFilePath, string newFilePath) private void MigrateRunSettings(string oldRunSettingsPath, string newRunSettingsPath) { string testSettingsPath = null; - using (XmlTextReader reader = new XmlTextReader(oldRunSettingsPath)) - { - reader.Namespaces = false; + using XmlTextReader reader = new XmlTextReader(oldRunSettingsPath); + reader.Namespaces = false; - var runSettingsXmlDoc = new XmlDocument(); - runSettingsXmlDoc.Load(reader); - var root = runSettingsXmlDoc.DocumentElement; + var runSettingsXmlDoc = new XmlDocument(); + runSettingsXmlDoc.Load(reader); + var root = runSettingsXmlDoc.DocumentElement; - var testSettingsNode = root.SelectSingleNode(@"/RunSettings/MSTest/SettingsFile"); + var testSettingsNode = root.SelectSingleNode(@"/RunSettings/MSTest/SettingsFile"); - if (testSettingsNode != null) - { - testSettingsPath = testSettingsNode.InnerText; - } + if (testSettingsNode != null) + { + testSettingsPath = testSettingsNode.InnerText; + } - if (!string.IsNullOrWhiteSpace(testSettingsPath)) + if (!string.IsNullOrWhiteSpace(testSettingsPath)) + { + // Expand path relative to runSettings location. + if (!Path.IsPathRooted(testSettingsPath)) { - // Expand path relative to runSettings location. - if (!Path.IsPathRooted(testSettingsPath)) - { - testSettingsPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(oldRunSettingsPath), testSettingsPath)); - } + testSettingsPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(oldRunSettingsPath), testSettingsPath)); + } - // Remove the embedded testSettings node if it exists. - this.RemoveEmbeddedTestSettings(runSettingsXmlDoc); + // Remove the embedded testSettings node if it exists. + this.RemoveEmbeddedTestSettings(runSettingsXmlDoc); - this.MigrateTestSettingsNodesToRunSettings(testSettingsPath, runSettingsXmlDoc); + this.MigrateTestSettingsNodesToRunSettings(testSettingsPath, runSettingsXmlDoc); - runSettingsXmlDoc.Save(newRunSettingsPath); - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.RunSettingsCreated, newRunSettingsPath)); - } - else - { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.NoEmbeddedSettings)); - } + runSettingsXmlDoc.Save(newRunSettingsPath); + Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.RunSettingsCreated, newRunSettingsPath)); + } + else + { + Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.NoEmbeddedSettings)); } } diff --git a/src/vstest.console/CommandLine/AssemblyMetadataProvider.cs b/src/vstest.console/CommandLine/AssemblyMetadataProvider.cs index 2424097983..b938be3a72 100644 --- a/src/vstest.console/CommandLine/AssemblyMetadataProvider.cs +++ b/src/vstest.console/CommandLine/AssemblyMetadataProvider.cs @@ -35,10 +35,8 @@ public FrameworkName GetFrameWork(string filePath) FrameworkName frameworkName = new FrameworkName(Framework.DefaultFramework.Name); try { - using (var assemblyStream = this.fileHelper.GetStream(filePath, FileMode.Open, FileAccess.Read)) - { - frameworkName = AssemblyMetadataProvider.GetFrameworkNameFromAssemblyMetadata(assemblyStream); - } + using var assemblyStream = this.fileHelper.GetStream(filePath, FileMode.Open, FileAccess.Read); + frameworkName = AssemblyMetadataProvider.GetFrameworkNameFromAssemblyMetadata(assemblyStream); } catch (Exception ex) { @@ -208,79 +206,77 @@ public Architecture GetArchitectureForSource(string imagePath) try { //get the input stream - using (Stream fs = this.fileHelper.GetStream(imagePath, FileMode.Open, FileAccess.Read)) - using (var reader = new BinaryReader(fs)) + using Stream fs = this.fileHelper.GetStream(imagePath, FileMode.Open, FileAccess.Read); + using var reader = new BinaryReader(fs); + var validImage = true; + + //PE Header starts @ 0x3C (60). Its a 4 byte header. + fs.Position = 0x3C; + peHeader = reader.ReadUInt32(); + + // Check if the offset is invalid + if (peHeader > fs.Length - 5) { - var validImage = true; + validImage = false; + } - //PE Header starts @ 0x3C (60). Its a 4 byte header. - fs.Position = 0x3C; - peHeader = reader.ReadUInt32(); + if (validImage) + { + //Moving to PE Header start location... + fs.Position = peHeader; - // Check if the offset is invalid - if (peHeader > fs.Length - 5) + var signature = reader.ReadUInt32(); //peHeaderSignature + // 0x00004550 is the letters "PE" followed by two terminating zeros. + if (signature != 0x00004550) { validImage = false; } if (validImage) { - //Moving to PE Header start location... - fs.Position = peHeader; - - var signature = reader.ReadUInt32(); //peHeaderSignature - // 0x00004550 is the letters "PE" followed by two terminating zeros. - if (signature != 0x00004550) + //Read the image file header. + machine = reader.ReadUInt16(); + reader.ReadUInt16(); //NumberOfSections + reader.ReadUInt32(); //TimeDateStamp + reader.ReadUInt32(); //PointerToSymbolTable + reader.ReadUInt32(); //NumberOfSymbols + reader.ReadUInt16(); //SizeOfOptionalHeader + reader.ReadUInt16(); //Characteristics + + // magic number.32bit or 64bit assembly. + var magic = reader.ReadUInt16(); + if (magic != 0x010B && magic != 0x020B) { validImage = false; } + } - if (validImage) - { - //Read the image file header. - machine = reader.ReadUInt16(); - reader.ReadUInt16(); //NumberOfSections - reader.ReadUInt32(); //TimeDateStamp - reader.ReadUInt32(); //PointerToSymbolTable - reader.ReadUInt32(); //NumberOfSymbols - reader.ReadUInt16(); //SizeOfOptionalHeader - reader.ReadUInt16(); //Characteristics - - // magic number.32bit or 64bit assembly. - var magic = reader.ReadUInt16(); - if (magic != 0x010B && magic != 0x020B) - { - validImage = false; - } - } - - if (validImage) - { - switch (machine) - { - case IMAGE_FILE_MACHINE_I386: - archType = Architecture.X86; - break; - - case IMAGE_FILE_MACHINE_AMD64: - case IMAGE_FILE_MACHINE_IA64: - archType = Architecture.X64; - break; - - case IMAGE_FILE_MACHINE_ARM: - case IMAGE_FILE_MACHINE_THUMB: - case IMAGE_FILE_MACHINE_ARMNT: - archType = Architecture.ARM; - break; - } - } - else + if (validImage) + { + switch (machine) { - EqtTrace.Info( - "GetArchitectureForSource: Source path {0} is not a valid image path. Returning default proc arch type: {1}.", - imagePath, archType); + case IMAGE_FILE_MACHINE_I386: + archType = Architecture.X86; + break; + + case IMAGE_FILE_MACHINE_AMD64: + case IMAGE_FILE_MACHINE_IA64: + archType = Architecture.X64; + break; + + case IMAGE_FILE_MACHINE_ARM: + case IMAGE_FILE_MACHINE_THUMB: + case IMAGE_FILE_MACHINE_ARMNT: + archType = Architecture.ARM; + break; } } + else + { + EqtTrace.Info( + "GetArchitectureForSource: Source path {0} is not a valid image path. Returning default proc arch type: {1}.", + imagePath, archType); + } } } catch (Exception ex) diff --git a/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs b/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs index b06ef8abf8..75df543d9d 100644 --- a/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunSettingsArgumentProcessor.cs @@ -190,13 +190,11 @@ private XmlDocument GetRunSettingsDocument(string runSettingsFile) if (!MSTestSettingsUtilities.IsLegacyTestSettingsFile(runSettingsFile)) { - using (XmlReader reader = this.GetReaderForFile(runSettingsFile)) - { - var settingsDocument = new XmlDocument(); - settingsDocument.Load(reader); - ClientUtilities.FixRelativePathsInRunSettings(settingsDocument, runSettingsFile); - runSettingsDocument = settingsDocument; - } + using XmlReader reader = this.GetReaderForFile(runSettingsFile); + var settingsDocument = new XmlDocument(); + settingsDocument.Load(reader); + ClientUtilities.FixRelativePathsInRunSettings(settingsDocument, runSettingsFile); + runSettingsDocument = settingsDocument; } else { diff --git a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs index 61f75604b1..95d5826d63 100644 --- a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs +++ b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs @@ -582,80 +582,78 @@ private bool UpdateRunSettingsIfRequired( if (!string.IsNullOrEmpty(runsettingsXml)) { // TargetFramework is full CLR. Set DesignMode based on current context. - using (var stream = new StringReader(runsettingsXml)) - using (var reader = XmlReader.Create( + using var stream = new StringReader(runsettingsXml); + using var reader = XmlReader.Create( stream, - XmlRunSettingsUtilities.ReaderSettings)) - { - var document = new XmlDocument(); - document.Load(reader); - var navigator = document.CreateNavigator(); - var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); - var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runsettingsXml) - ?? new LoggerRunSettings(); - - settingsUpdated |= this.UpdateFramework( - document, - navigator, - sources, - sourceFrameworks, - registrar, - out Framework chosenFramework); - - // Choose default architecture based on the framework. - // For .NET core, the default platform architecture should be based on the process. - Architecture defaultArchitecture = Architecture.X86; - if (chosenFramework.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 - || chosenFramework.Name.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) >= 0 + XmlRunSettingsUtilities.ReaderSettings); + var document = new XmlDocument(); + document.Load(reader); + var navigator = document.CreateNavigator(); + var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runsettingsXml); + var loggerRunSettings = XmlRunSettingsUtilities.GetLoggerRunSettings(runsettingsXml) + ?? new LoggerRunSettings(); + + settingsUpdated |= this.UpdateFramework( + document, + navigator, + sources, + sourceFrameworks, + registrar, + out Framework chosenFramework); + + // Choose default architecture based on the framework. + // For .NET core, the default platform architecture should be based on the process. + Architecture defaultArchitecture = Architecture.X86; + if (chosenFramework.Name.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0 + || chosenFramework.Name.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) >= 0 // This is a special case for 1 version of Nuget.Frameworks that was shipped with using identifier NET5 instead of NETCoreApp5 for .NET 5. - || chosenFramework.Name.IndexOf("net5", StringComparison.OrdinalIgnoreCase) >= 0) - { + || chosenFramework.Name.IndexOf("net5", StringComparison.OrdinalIgnoreCase) >= 0) + { #if NETCOREAPP - // We are running in vstest.console that is either started via dotnet.exe - // or via vstest.console.exe .NET Core executable. For AnyCPU dlls this - // should resolve 32-bit SDK when running from 32-bit dotnet process and - // 64-bit SDK when running from 64-bit dotnet process. - // As default architecture we specify the expected test host architecture, - // it can be specified by user on the command line with --arch or through runsettings. - // If it's not specified by user will be filled by current processor architecture; - // should be the same as SDK. - defaultArchitecture = RunSettingsHelper.Instance.IsDefaultTargetArchitecture ? - TranslateToArchitecture(processHelper.GetCurrentProcessArchitecture()) : - runConfiguration.TargetPlatform; + // We are running in vstest.console that is either started via dotnet.exe + // or via vstest.console.exe .NET Core executable. For AnyCPU dlls this + // should resolve 32-bit SDK when running from 32-bit dotnet process and + // 64-bit SDK when running from 64-bit dotnet process. + // As default architecture we specify the expected test host architecture, + // it can be specified by user on the command line with --arch or through runsettings. + // If it's not specified by user will be filled by current processor architecture; + // should be the same as SDK. + defaultArchitecture = RunSettingsHelper.Instance.IsDefaultTargetArchitecture ? + TranslateToArchitecture(processHelper.GetCurrentProcessArchitecture()) : + runConfiguration.TargetPlatform; #else - // We are running in vstest.console.exe that was built against .NET - // Framework. This console prefers 32-bit because it needs to run as 32-bit - // to be compatible with QTAgent. It runs as 32-bit both under VS and in - // Developer console. Set the default architecture based on the OS - // architecture, to find 64-bit dotnet SDK when running AnyCPU dll on 64-bit - // system, and 32-bit SDK when running AnyCPU dll on 32-bit OS. - // We want to find 64-bit SDK because it is more likely to be installed. - defaultArchitecture = Environment.Is64BitOperatingSystem ? Architecture.X64 : Architecture.X86; + // We are running in vstest.console.exe that was built against .NET + // Framework. This console prefers 32-bit because it needs to run as 32-bit + // to be compatible with QTAgent. It runs as 32-bit both under VS and in + // Developer console. Set the default architecture based on the OS + // architecture, to find 64-bit dotnet SDK when running AnyCPU dll on 64-bit + // system, and 32-bit SDK when running AnyCPU dll on 32-bit OS. + // We want to find 64-bit SDK because it is more likely to be installed. + defaultArchitecture = Environment.Is64BitOperatingSystem ? Architecture.X64 : Architecture.X86; #endif - EqtTrace.Verbose($"Default architecture: {defaultArchitecture} IsDefaultTargetArchitecture: {RunSettingsHelper.Instance.IsDefaultTargetArchitecture}"); - } - - settingsUpdated |= this.UpdatePlatform( - document, - navigator, - sources, - sourcePlatforms, - defaultArchitecture, - out Architecture chosenPlatform); - this.CheckSourcesForCompatibility( - chosenFramework, - chosenPlatform, - defaultArchitecture, - sourcePlatforms, - sourceFrameworks, - registrar); - settingsUpdated |= this.UpdateDesignMode(document, runConfiguration); - settingsUpdated |= this.UpdateCollectSourceInformation(document, runConfiguration); - settingsUpdated |= this.UpdateTargetDevice(navigator, document, runConfiguration); - settingsUpdated |= this.AddOrUpdateConsoleLogger(document, runConfiguration, loggerRunSettings); - - updatedRunSettingsXml = navigator.OuterXml; + EqtTrace.Verbose($"Default architecture: {defaultArchitecture} IsDefaultTargetArchitecture: {RunSettingsHelper.Instance.IsDefaultTargetArchitecture}"); } + + settingsUpdated |= this.UpdatePlatform( + document, + navigator, + sources, + sourcePlatforms, + defaultArchitecture, + out Architecture chosenPlatform); + this.CheckSourcesForCompatibility( + chosenFramework, + chosenPlatform, + defaultArchitecture, + sourcePlatforms, + sourceFrameworks, + registrar); + settingsUpdated |= this.UpdateDesignMode(document, runConfiguration); + settingsUpdated |= this.UpdateCollectSourceInformation(document, runConfiguration); + settingsUpdated |= this.UpdateTargetDevice(navigator, document, runConfiguration); + settingsUpdated |= this.AddOrUpdateConsoleLogger(document, runConfiguration, loggerRunSettings); + + updatedRunSettingsXml = navigator.OuterXml; } return settingsUpdated; diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs index b6d03fbe33..c873484704 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogContainerTests.cs @@ -38,10 +38,14 @@ public class EventLogContainerTests public EventLogContainerTests() { - this.eventSources = new HashSet(); - this.eventSources.Add("Application"); - this.entryTypes = new HashSet(); - this.entryTypes.Add(EventLogEntryType.Error); + this.eventSources = new HashSet + { + "Application" + }; + this.entryTypes = new HashSet + { + EventLogEntryType.Error + }; this.logger = new Mock(); this.eventLog = new EventLog("Application"); diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs index 75099d3c41..c62786307a 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs @@ -112,9 +112,11 @@ public void InitializeShouldThrowExceptionIfLoggerIsNull() [TestMethod] public void InitializeShouldInitializeDefaultEventLogNames() { - List eventLogNames = new List(); - eventLogNames.Add("System"); - eventLogNames.Add("Application"); + List eventLogNames = new List + { + "System", + "Application" + }; this.eventLogDataCollector.Initialize(null, this.mockDataCollectionEvents.Object, this.mockDataCollectionSink, this.mockDataCollectionLogger.Object, this.dataCollectionEnvironmentContext); @@ -127,9 +129,11 @@ public void InitializeShouldInitializeCustomEventLogNamesIfSpecifiedInConfigurat string configurationString = @""; - List eventLogNames = new List(); - eventLogNames.Add("MyEventName"); - eventLogNames.Add("MyEventName2"); + List eventLogNames = new List + { + "MyEventName", + "MyEventName2" + }; XmlDocument expectedXmlDoc = new XmlDocument(); expectedXmlDoc.LoadXml(configurationString); @@ -142,10 +146,12 @@ public void InitializeShouldInitializeCustomEventLogNamesIfSpecifiedInConfigurat [TestMethod] public void InitializeShouldInitializeDefaultLogEntryTypes() { - List entryTypes = new List(); - entryTypes.Add(EventLogEntryType.Error); - entryTypes.Add(EventLogEntryType.Warning); - entryTypes.Add(EventLogEntryType.FailureAudit); + List entryTypes = new List + { + EventLogEntryType.Error, + EventLogEntryType.Warning, + EventLogEntryType.FailureAudit + }; this.eventLogDataCollector.Initialize(null, this.mockDataCollectionEvents.Object, this.mockDataCollectionSink, this.mockDataCollectionLogger.Object, this.dataCollectionEnvironmentContext); @@ -158,8 +164,10 @@ public void InitializeShouldInitializeEntryTypesIfSpecifiedInConfiguration() string configurationString = @""; - List entryTypes = new List(); - entryTypes.Add(EventLogEntryType.Error); + List entryTypes = new List + { + EventLogEntryType.Error + }; XmlDocument expectedXmlDoc = new XmlDocument(); expectedXmlDoc.LoadXml(configurationString); @@ -174,8 +182,10 @@ public void InitializeShouldInitializeEventSourcesIfSpecifiedInConfiguration() string configurationString = @""; - List eventSources = new List(); - eventSources.Add("MyEventSource"); + List eventSources = new List + { + "MyEventSource" + }; XmlDocument expectedXmlDoc = new XmlDocument(); expectedXmlDoc.LoadXml(configurationString); diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs index 3fedfc1ef2..46bc99ca57 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogSessionContextTests.cs @@ -20,8 +20,10 @@ public class EventLogSessionContextTests public EventLogSessionContextTests() { this.mockEventLogContainer = new DummyEventLogContainer(true); - this.eventLogContainersMap = new Dictionary(); - this.eventLogContainersMap.Add("LogName", this.mockEventLogContainer); + this.eventLogContainersMap = new Dictionary + { + { "LogName", this.mockEventLogContainer } + }; } [TestMethod] diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs b/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs index 9dc0f7baab..ea7bc33f5c 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs @@ -106,32 +106,30 @@ protected static string GetCoverageFileNameFromTrx(string trxFilePath, string re { Assert.IsTrue(File.Exists(trxFilePath), "Trx file not found: {0}", trxFilePath); XmlDocument doc = new XmlDocument(); - using (var trxStream = new FileStream(trxFilePath, FileMode.Open, FileAccess.Read)) + using var trxStream = new FileStream(trxFilePath, FileMode.Open, FileAccess.Read); + doc.Load(trxStream); + var deploymentElements = doc.GetElementsByTagName("Deployment"); + Assert.IsTrue(deploymentElements.Count == 1, + "None or more than one Deployment tags found in trx file:{0}", trxFilePath); + var deploymentDir = deploymentElements[0].Attributes.GetNamedItem("runDeploymentRoot")?.Value; + Assert.IsTrue(string.IsNullOrEmpty(deploymentDir) == false, + "runDeploymentRoot attribute not found in trx file:{0}", trxFilePath); + var collectors = doc.GetElementsByTagName("Collector"); + + string fileName = string.Empty; + for (int i = 0; i < collectors.Count; i++) { - doc.Load(trxStream); - var deploymentElements = doc.GetElementsByTagName("Deployment"); - Assert.IsTrue(deploymentElements.Count == 1, - "None or more than one Deployment tags found in trx file:{0}", trxFilePath); - var deploymentDir = deploymentElements[0].Attributes.GetNamedItem("runDeploymentRoot")?.Value; - Assert.IsTrue(string.IsNullOrEmpty(deploymentDir) == false, - "runDeploymentRoot attribute not found in trx file:{0}", trxFilePath); - var collectors = doc.GetElementsByTagName("Collector"); - - string fileName = string.Empty; - for (int i = 0; i < collectors.Count; i++) + if (string.Equals(collectors[i].Attributes.GetNamedItem("collectorDisplayName").Value, + "Code Coverage", StringComparison.OrdinalIgnoreCase)) { - if (string.Equals(collectors[i].Attributes.GetNamedItem("collectorDisplayName").Value, - "Code Coverage", StringComparison.OrdinalIgnoreCase)) - { - fileName = collectors[i].FirstChild?.FirstChild?.FirstChild?.Attributes.GetNamedItem("href") - ?.Value; - } + fileName = collectors[i].FirstChild?.FirstChild?.FirstChild?.Attributes.GetNamedItem("href") + ?.Value; } - - Assert.IsTrue(string.IsNullOrEmpty(fileName) == false, "Coverage file name not found in trx file: {0}", - trxFilePath); - return Path.Combine(resultsDirectory, deploymentDir, "In", fileName); } + + Assert.IsTrue(string.IsNullOrEmpty(fileName) == false, "Coverage file name not found in trx file: {0}", + trxFilePath); + return Path.Combine(resultsDirectory, deploymentDir, "In", fileName); } } } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/DataCollectionTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/DataCollectionTests.cs index 197aee8f83..02ed71df61 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/DataCollectionTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/DataCollectionTests.cs @@ -191,10 +191,8 @@ private static void CreateDataCollectionRunSettingsFile(string destinationRunset dataCollectorNode.SetAttribute(kvp.Key, kvp.Value); } - using (var stream = new FileHelper().GetStream(destinationRunsettingsPath, FileMode.Create)) - { - doc.Save(stream); - } + using var stream = new FileHelper().GetStream(destinationRunsettingsPath, FileMode.Create); + doc.Save(stream); } private void VaildateDataCollectorOutput(string resultsDir) @@ -247,10 +245,11 @@ private void VaildateDataCollectorOutput(string resultsDir) private string GetRunsettingsFilePath(string resultsDir) { var runsettingsPath = Path.Combine(resultsDir, "test_" + Guid.NewGuid() + ".runsettings"); - var dataCollectionAttributes = new Dictionary(); - - dataCollectionAttributes.Add("friendlyName", "SampleDataCollector"); - dataCollectionAttributes.Add("uri", "my://sample/datacollector"); + var dataCollectionAttributes = new Dictionary + { + { "friendlyName", "SampleDataCollector" }, + { "uri", "my://sample/datacollector" } + }; CreateDataCollectionRunSettingsFile(runsettingsPath, dataCollectionAttributes); return runsettingsPath; diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs b/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs index 8ab191cac0..2cfa228729 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs @@ -21,31 +21,30 @@ public class DotnetArchitectureSwitchTestsWindowsOnly : AcceptanceTestBase [DataRow("X86", "X64")] public void Use_EnvironmentVariables(string architectureFrom, string architectureTo) { - using (Workspace workSpace = new Workspace(GetResultsDirectory())) - { - string dotnetPath = GetDownloadedDotnetMuxerFromTools(architectureFrom); - string dotnetPathTo = GetDownloadedDotnetMuxerFromTools(architectureTo); - var vstestConsolePath = GetDotnetRunnerPath(); - var dotnetRunnerPath = workSpace.CreateDirectory("dotnetrunner"); - workSpace.CopyAll(new DirectoryInfo(Path.GetDirectoryName(vstestConsolePath)), dotnetRunnerPath); + using Workspace workSpace = new Workspace(GetResultsDirectory()); + string dotnetPath = GetDownloadedDotnetMuxerFromTools(architectureFrom); + string dotnetPathTo = GetDownloadedDotnetMuxerFromTools(architectureTo); + var vstestConsolePath = GetDotnetRunnerPath(); + var dotnetRunnerPath = workSpace.CreateDirectory("dotnetrunner"); + workSpace.CopyAll(new DirectoryInfo(Path.GetDirectoryName(vstestConsolePath)), dotnetRunnerPath); - // Patch the runner - string sdkVersion = GetLatestSdkVersion(dotnetPath); - string runtimeConfigFile = Path.Combine(dotnetRunnerPath.FullName, "vstest.console.runtimeconfig.json"); - JObject patchRuntimeConfig = JObject.Parse(File.ReadAllText(runtimeConfigFile)); - patchRuntimeConfig["runtimeOptions"]["framework"]["version"] = sdkVersion; - File.WriteAllText(runtimeConfigFile, patchRuntimeConfig.ToString()); + // Patch the runner + string sdkVersion = GetLatestSdkVersion(dotnetPath); + string runtimeConfigFile = Path.Combine(dotnetRunnerPath.FullName, "vstest.console.runtimeconfig.json"); + JObject patchRuntimeConfig = JObject.Parse(File.ReadAllText(runtimeConfigFile)); + patchRuntimeConfig["runtimeOptions"]["framework"]["version"] = sdkVersion; + File.WriteAllText(runtimeConfigFile, patchRuntimeConfig.ToString()); - var environmentVariables = new Dictionary - { - ["DOTNET_MULTILEVEL_LOOKUP"] = "0", - [$"DOTNET_ROOT_{architectureTo}"] = Path.GetDirectoryName(dotnetPathTo), - ["ExpectedArchitecture"] = architectureTo - }; - this.ExecuteApplication(dotnetPath, "new mstest", out string stdOut, out string stdError, out int exitCode, environmentVariables, workSpace.Path); + var environmentVariables = new Dictionary + { + ["DOTNET_MULTILEVEL_LOOKUP"] = "0", + [$"DOTNET_ROOT_{architectureTo}"] = Path.GetDirectoryName(dotnetPathTo), + ["ExpectedArchitecture"] = architectureTo + }; + this.ExecuteApplication(dotnetPath, "new mstest", out string stdOut, out string stdError, out int exitCode, environmentVariables, workSpace.Path); - // Patch test file - File.WriteAllText(Path.Combine(workSpace.Path, "UnitTest1.cs"), + // Patch test file + File.WriteAllText(Path.Combine(workSpace.Path, "UnitTest1.cs"), @" using Microsoft.VisualStudio.TestTools.UnitTesting; using System; @@ -62,28 +61,27 @@ public void TestMethod1() } }"); - this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); - Assert.AreEqual(0, exitCode, stdOut); + this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); + Assert.AreEqual(0, exitCode, stdOut); - environmentVariables = new Dictionary - { - ["DOTNET_MULTILEVEL_LOOKUP"] = "0", - ["DOTNET_ROOT"] = Path.GetDirectoryName(dotnetPathTo), - ["ExpectedArchitecture"] = architectureTo - }; - this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); - Assert.AreEqual(0, exitCode, stdOut); + environmentVariables = new Dictionary + { + ["DOTNET_MULTILEVEL_LOOKUP"] = "0", + ["DOTNET_ROOT"] = Path.GetDirectoryName(dotnetPathTo), + ["ExpectedArchitecture"] = architectureTo + }; + this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); + Assert.AreEqual(0, exitCode, stdOut); - environmentVariables = new Dictionary - { - ["DOTNET_MULTILEVEL_LOOKUP"] = "0", - [$"DOTNET_ROOT_{architectureTo}"] = Path.GetDirectoryName(dotnetPathTo), - ["DOTNET_ROOT"] = "WE SHOULD PICK THE ABOVE ONE BEFORE FALLBACK TO DOTNET_ROOT", - ["ExpectedArchitecture"] = architectureTo - }; - this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); - Assert.AreEqual(0, exitCode, stdOut); - } + environmentVariables = new Dictionary + { + ["DOTNET_MULTILEVEL_LOOKUP"] = "0", + [$"DOTNET_ROOT_{architectureTo}"] = Path.GetDirectoryName(dotnetPathTo), + ["DOTNET_ROOT"] = "WE SHOULD PICK THE ABOVE ONE BEFORE FALLBACK TO DOTNET_ROOT", + ["ExpectedArchitecture"] = architectureTo + }; + this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); + Assert.AreEqual(0, exitCode, stdOut); } private string GetLatestSdkVersion(string dotnetPath) diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.cs index fd2d314b98..bf2c4444ff 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.cs @@ -56,9 +56,11 @@ public void GlobalInstallation() var projectPath = this.GetProjectFullPath(projectName); var projectDirectory = Path.GetDirectoryName(projectPath); - var env = new Dictionary(); - env.Add("DOTNET_ROOT", null); - env.Add("DOTNET_MULTILEVEL_LOOKUP", "0"); + var env = new Dictionary + { + { "DOTNET_ROOT", null }, + { "DOTNET_MULTILEVEL_LOOKUP", "0" } + }; // Verify native architecture ExecuteApplication(GetDefaultDotnetMuxerLocation, $"test {projectPath} --framework net6.0", out string stdOut, out string stdError, out int exitCode, env, projectDirectory); @@ -108,9 +110,11 @@ public void DOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, bool dotnetRootX6 return; } - var env = new Dictionary(); - env["DOTNET_ROOT"] = null; - env["DOTNET_MULTILEVEL_LOOKUP"] = "0"; + var env = new Dictionary + { + ["DOTNET_ROOT"] = null, + ["DOTNET_MULTILEVEL_LOOKUP"] = "0" + }; var projectName = "ArchitectureSwitch.csproj"; var projectPath = this.GetProjectFullPath(projectName); @@ -169,9 +173,11 @@ public void PrivateX64BuildToGlobalArmInstallation() return; } - var env = new Dictionary(); - env["DOTNET_ROOT"] = null; - env["DOTNET_MULTILEVEL_LOOKUP"] = "0"; + var env = new Dictionary + { + ["DOTNET_ROOT"] = null, + ["DOTNET_MULTILEVEL_LOOKUP"] = "0" + }; string privateInstallationMuxer = Path.Combine(privateX64Installation, GetMuxerName); var projectName = "ArchitectureSwitch.csproj"; @@ -211,9 +217,11 @@ public void PrivateX64BuildToDOTNET_ROOTS_EnvironmentVariables(bool dotnetRoot, return; } - var env = new Dictionary(); - env["DOTNET_ROOT"] = null; - env["DOTNET_MULTILEVEL_LOOKUP"] = "0"; + var env = new Dictionary + { + ["DOTNET_ROOT"] = null, + ["DOTNET_MULTILEVEL_LOOKUP"] = "0" + }; string privateInstallationMuxer = Path.Combine(privateX64Installation, GetMuxerName); var projectName = "ArchitectureSwitch.csproj"; @@ -270,9 +278,11 @@ public void SilentlyForceX64() var projectPath = this.GetProjectFullPath(projectName); var projectDirectory = Path.GetDirectoryName(projectPath); - var env = new Dictionary(); - env["DOTNET_ROOT"] = null; - env["DOTNET_MULTILEVEL_LOOKUP"] = "0"; + var env = new Dictionary + { + ["DOTNET_ROOT"] = null, + ["DOTNET_MULTILEVEL_LOOKUP"] = "0" + }; ExecuteApplication(GetDefaultDotnetMuxerLocation, $"test {projectPath} --framework {GetFrameworkVersionToForceToX64}", out string stdOut, out string stdError, out int exitCode, env, projectDirectory); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs index 5187b01731..6d8af55ef7 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs @@ -135,10 +135,12 @@ private void VaildateDataCollectorOutput() var fileContent3 = File.ReadAllText(resultFiles[2]); var fileContent4 = File.ReadAllText(resultFiles[3]); - var eventIdsDics = new Dictionary(); - eventIdsDics.Add(new[] { "110", "111", "112" }, false); - eventIdsDics.Add(new[] { "220", "221", "222", "223" }, false); - eventIdsDics.Add(new[] { "330", "331", "332" }, false); + var eventIdsDics = new Dictionary + { + { new[] { "110", "111", "112" }, false }, + { new[] { "220", "221", "222", "223" }, false }, + { new[] { "330", "331", "332" }, false } + }; // Since there is no guaranty that test will run in a particular order, we will check file for all available list of ids Assert.IsTrue(this.VerifyOrder2(fileContent1, eventIdsDics), string.Format("Event log file content: {0}", fileContent1)); diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/LoggerTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/LoggerTests.cs index 1d142d3fe2..392f4cb23c 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/LoggerTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/LoggerTests.cs @@ -183,15 +183,13 @@ private bool IsValidXml(string xmlFilePath) { try { - using (var file = File.OpenRead(xmlFilePath)) - using (var reader = XmlReader.Create(file)) + using var file = File.OpenRead(xmlFilePath); + using var reader = XmlReader.Create(file); + while (reader.Read()) { - while (reader.Read()) - { - } - - return true; } + + return true; } catch (XmlException) { diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs index 23bb10bef8..cd28fc6d93 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs @@ -131,10 +131,8 @@ private void SHA1_TestRepetitionVector(char input, int repetition, string expect if (string.IsNullOrEmpty(expected)) { - using (var hasher = System.Security.Cryptography.SHA1.Create()) - { - expected = ToHex(hasher.ComputeHash(bytes)); - } + using var hasher = System.Security.Cryptography.SHA1.Create(); + expected = ToHex(hasher.ComputeHash(bytes)); } else { diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs index 3b80962f7b..7e11ade175 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs @@ -168,8 +168,10 @@ public void DiscoverAsyncShouldInvokeHandleDiscoveryStartofLoggerManager() public void HandleDiscoveryCompleteShouldCollectMetrics() { var mockMetricsCollector = new Mock(); - var dict = new Dictionary(); - dict.Add("DummyMessage", "DummyValue"); + var dict = new Dictionary + { + { "DummyMessage", "DummyValue" } + }; mockMetricsCollector.Setup(mc => mc.Metrics).Returns(dict); this.mockRequestData.Setup(rd => rd.MetricsCollection).Returns(mockMetricsCollector.Object); diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs index 15a5c2a44c..2cf8654791 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs @@ -486,8 +486,10 @@ public void HandleLogMessageShouldInvokeHandleLogMessageOfLoggerManager() public void HandleTestRunCompleteShouldCollectMetrics() { var mockMetricsCollector = new Mock(); - var dict = new Dictionary(); - dict.Add("DummyMessage", "DummyValue"); + var dict = new Dictionary + { + { "DummyMessage", "DummyValue" } + }; mockMetricsCollector.Setup(mc => mc.Metrics).Returns(dict); this.mockRequestData.Setup(rd => rd.MetricsCollection).Returns(mockMetricsCollector.Object); diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs index 4525781aca..9d1f23d667 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs @@ -32,11 +32,13 @@ public void AddExtensionsShouldNotThrowIfExtensionsIsNull() [TestMethod] public void AddExtensionsShouldNotThrowIfExistingExtensionCollectionIsNull() { - var testDiscoverers = new System.Collections.Generic.Dictionary(); - - testDiscoverers.Add( - "td", - new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + var testDiscoverers = new System.Collections.Generic.Dictionary + { + { + "td", + new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) + } + }; this.testExtensions.AddExtension(testDiscoverers); @@ -52,22 +54,27 @@ public void AddExtensionsShouldNotThrowIfExistingExtensionCollectionIsNull() [TestMethod] public void AddExtensionsShouldAddToExistingExtensionCollection() { - var testDiscoverers = new System.Collections.Generic.Dictionary(); - - testDiscoverers.Add("td1", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); - testDiscoverers.Add("td2", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + var testDiscoverers = new System.Collections.Generic.Dictionary + { + { "td1", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, + { "td2", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; - this.testExtensions.TestDiscoverers = new Dictionary(); - this.testExtensions.TestDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + this.testExtensions.TestDiscoverers = new Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; // Act. this.testExtensions.AddExtension(testDiscoverers); // Validate. - var expectedTestExtensions = new Dictionary(); - expectedTestExtensions.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); - expectedTestExtensions.Add("td1", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); - expectedTestExtensions.Add("td2", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + var expectedTestExtensions = new Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, + { "td1", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, + { "td2", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; CollectionAssert.AreEqual(this.testExtensions.TestDiscoverers.Keys, expectedTestExtensions.Keys); @@ -80,13 +87,15 @@ public void AddExtensionsShouldAddToExistingExtensionCollection() [TestMethod] public void AddExtensionsShouldNotAddAnAlreadyExistingExtensionToTheCollection() { - var testDiscoverers = new System.Collections.Generic.Dictionary(); - - testDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + var testDiscoverers = new System.Collections.Generic.Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; - this.testExtensions.TestDiscoverers = new System.Collections.Generic.Dictionary(); - - this.testExtensions.TestDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + this.testExtensions.TestDiscoverers = new System.Collections.Generic.Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; // Act. this.testExtensions.AddExtension(testDiscoverers); @@ -111,9 +120,10 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnNullIfNoExtensionsPre [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldNotThrowIfExtensionAssemblyIsNull() { - this.testExtensions.TestDiscoverers = new Dictionary(); - - this.testExtensions.TestDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + this.testExtensions.TestDiscoverers = new Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; Assert.IsNull(this.testExtensions.GetExtensionsDiscoveredFromAssembly(null)); } @@ -123,14 +133,18 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestDiscoverers() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; - this.testExtensions.TestDiscoverers = new Dictionary(); - this.testExtensions.TestDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); - this.testExtensions.TestDiscoverers.Add("td1", new TestDiscovererPluginInformation(typeof(TestExtensions))); + this.testExtensions.TestDiscoverers = new Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, + { "td1", new TestDiscovererPluginInformation(typeof(TestExtensions)) } + }; var extensions = this.testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); - var expectedExtensions = new Dictionary(); - expectedExtensions.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + var expectedExtensions = new Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestDiscoverers.Keys); } @@ -139,14 +153,18 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestExecutors() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; - this.testExtensions.TestExecutors = new Dictionary(); - this.testExtensions.TestExecutors.Add("te", new TestExecutorPluginInformation(typeof(TestExtensionsTests))); - this.testExtensions.TestExecutors.Add("te1", new TestExecutorPluginInformation(typeof(TestExtensions))); + this.testExtensions.TestExecutors = new Dictionary + { + { "te", new TestExecutorPluginInformation(typeof(TestExtensionsTests)) }, + { "te1", new TestExecutorPluginInformation(typeof(TestExtensions)) } + }; var extensions = this.testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); - var expectedExtensions = new Dictionary(); - expectedExtensions.Add("te", new TestExecutorPluginInformation(typeof(TestExtensionsTests))); + var expectedExtensions = new Dictionary + { + { "te", new TestExecutorPluginInformation(typeof(TestExtensionsTests)) } + }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestExecutors.Keys); } @@ -155,14 +173,18 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestSettingsProviders { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; - this.testExtensions.TestSettingsProviders = new Dictionary(); - this.testExtensions.TestSettingsProviders.Add("tsp", new TestSettingsProviderPluginInformation(typeof(TestExtensionsTests))); - this.testExtensions.TestSettingsProviders.Add("tsp1", new TestSettingsProviderPluginInformation(typeof(TestExtensions))); + this.testExtensions.TestSettingsProviders = new Dictionary + { + { "tsp", new TestSettingsProviderPluginInformation(typeof(TestExtensionsTests)) }, + { "tsp1", new TestSettingsProviderPluginInformation(typeof(TestExtensions)) } + }; var extensions = this.testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); - var expectedExtensions = new Dictionary(); - expectedExtensions.Add("tsp", new TestSettingsProviderPluginInformation(typeof(TestExtensionsTests))); + var expectedExtensions = new Dictionary + { + { "tsp", new TestSettingsProviderPluginInformation(typeof(TestExtensionsTests)) } + }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestSettingsProviders.Keys); } @@ -171,14 +193,18 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestLoggers() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; - this.testExtensions.TestLoggers = new Dictionary(); - this.testExtensions.TestLoggers.Add("tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests))); - this.testExtensions.TestLoggers.Add("tl1", new TestLoggerPluginInformation(typeof(TestExtensions))); + this.testExtensions.TestLoggers = new Dictionary + { + { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) }, + { "tl1", new TestLoggerPluginInformation(typeof(TestExtensions)) } + }; var extensions = this.testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); - var expectedExtensions = new Dictionary(); - expectedExtensions.Add("tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests))); + var expectedExtensions = new Dictionary + { + { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } + }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestLoggers.Keys); } @@ -187,20 +213,28 @@ public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestDiscoveresAndLogg { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; - this.testExtensions.TestDiscoverers = new Dictionary(); - this.testExtensions.TestDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + this.testExtensions.TestDiscoverers = new Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; - this.testExtensions.TestLoggers = new Dictionary(); - this.testExtensions.TestLoggers.Add("tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests))); + this.testExtensions.TestLoggers = new Dictionary + { + { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } + }; var extensions = this.testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); - var expectedDiscoverers = new Dictionary(); - expectedDiscoverers.Add("td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests))); + var expectedDiscoverers = new Dictionary + { + { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } + }; CollectionAssert.AreEqual(expectedDiscoverers.Keys, extensions.TestDiscoverers.Keys); - var expectedLoggers = new Dictionary(); - expectedLoggers.Add("tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests))); + var expectedLoggers = new Dictionary + { + { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } + }; CollectionAssert.AreEqual(expectedLoggers.Keys, extensions.TestLoggers.Keys); } } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs index 2f39dd1f73..bfd50cd445 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketCommunicationManagerTests.cs @@ -357,19 +357,15 @@ private void WriteOnSocket(Socket socket) private string ReadFromStream(Stream stream) { - using (var reader = new BinaryReader(stream, Encoding.UTF8, true)) - { - return reader.ReadString(); - } + using var reader = new BinaryReader(stream, Encoding.UTF8, true); + return reader.ReadString(); } private void WriteToStream(Stream stream, string data) { - using (var writer = new BinaryWriter(stream, Encoding.UTF8, true)) - { - writer.Write(data); - writer.Flush(); - } + using var writer = new BinaryWriter(stream, Encoding.UTF8, true); + writer.Write(data); + writer.Flush(); } } } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketTestsBase.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketTestsBase.cs index 575b1e3100..8a2b992042 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketTestsBase.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.PlatformTests/SocketTestsBase.cs @@ -44,18 +44,14 @@ public void SocketEndpointShouldNotifyChannelOnDataAvailable() protected static string ReadData(TcpClient client) { - using (BinaryReader reader = new BinaryReader(client.GetStream())) - { - return reader.ReadString(); - } + using BinaryReader reader = new BinaryReader(client.GetStream()); + return reader.ReadString(); } protected static void WriteData(TcpClient client) { - using (BinaryWriter writer = new BinaryWriter(client.GetStream())) - { - writer.Write(DUMMYDATA); - } + using BinaryWriter writer = new BinaryWriter(client.GetStream()); + writer.Write(DUMMYDATA); } protected abstract ICommunicationChannel SetupChannel(out ConnectedEventArgs connectedEventArgs); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs index 21c23451cc..502986d79b 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs @@ -74,15 +74,13 @@ public async Task SendShouldBeAbleToWriteUnicodeData() public async Task SendShouldFlushTheStream() { // A buffered stream doesn't immediately flush, it waits until buffer is filled in - using (var bufferedStream = new BufferedStream(this.stream, 2048)) - { - var communicationChannel = new LengthPrefixCommunicationChannel(bufferedStream); + using var bufferedStream = new BufferedStream(this.stream, 2048); + var communicationChannel = new LengthPrefixCommunicationChannel(bufferedStream); - await communicationChannel.Send("a"); + await communicationChannel.Send("a"); - SeekToBeginning(this.stream); - Assert.AreEqual("a", this.reader.ReadString()); - } + SeekToBeginning(this.stream); + Assert.AreEqual("a", this.reader.ReadString()); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs index a7660bb127..7ad95f6190 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs @@ -29,13 +29,9 @@ public void Cleanup() [TestMethod] public void GetStreamShouldAbleToGetTwoStreamSimultanouslyIfFileAccessIsRead() { - using (var stream1 = this.fileHelper.GetStream(this.tempFile, FileMode.Open, FileAccess.Read)) - { - using (var stream2 = - this.fileHelper.GetStream(this.tempFile, FileMode.Open, FileAccess.Read)) - { - } - } + using var stream1 = this.fileHelper.GetStream(this.tempFile, FileMode.Open, FileAccess.Read); + using var stream2 = + this.fileHelper.GetStream(this.tempFile, FileMode.Open, FileAccess.Read); } } } diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs index 825c8ad96f..218419ca0a 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs @@ -168,13 +168,9 @@ private string ReadLogFile() string log = null; try { - using (var fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - using (var sr = new StreamReader(fs)) - { - log = sr.ReadToEnd(); - } - } + using var fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var sr = new StreamReader(fs); + log = sr.ReadToEnd(); } catch(Exception ex) { diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs index 5cb90ddbcb..d96d861ad2 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs @@ -187,17 +187,15 @@ public void OncePausedNoFurtherJobsAreProcessedUntilResumeIsCalled() [TestMethod] public void ThrowsWhenBeingDisposedWhileQueueIsPaused() { - using (var queue = new JobQueue(GetEmptyProcessHandler(), "dp", int.MaxValue, int.MaxValue, false, (message) => { })) - { - queue.Pause(); + using var queue = new JobQueue(GetEmptyProcessHandler(), "dp", int.MaxValue, int.MaxValue, false, (message) => { }); + queue.Pause(); - Assert.ThrowsException(() => - { - queue.Dispose(); - }); + Assert.ThrowsException(() => + { + queue.Dispose(); + }); - queue.Resume(); - } + queue.Resume(); } [TestMethod] @@ -211,16 +209,14 @@ public void FlushMethodWaitsForAllJobsToBeProcessedBeforeReturning() }; // Queue several jobs and verify they have been processed when wait returns. - using (var queue = new JobQueue(processHandler, "dp", int.MaxValue, int.MaxValue, false, (message) => { })) - { - queue.QueueJob("dp", 0); - queue.QueueJob("dp", 0); - queue.QueueJob("dp", 0); + using var queue = new JobQueue(processHandler, "dp", int.MaxValue, int.MaxValue, false, (message) => { }); + queue.QueueJob("dp", 0); + queue.QueueJob("dp", 0); + queue.QueueJob("dp", 0); - queue.Flush(); + queue.Flush(); - Assert.AreEqual(3, jobsProcessed); - } + Assert.AreEqual(3, jobsProcessed); } [TestMethod] @@ -240,42 +236,40 @@ public void TestBlockAtEnqueueDueToLength() } }; - using (JobQueueWrapper queue = new JobQueueWrapper(processHandler, 5, int.MaxValue, true, allowJobProcessingHandlerToProceed)) + using JobQueueWrapper queue = new JobQueueWrapper(processHandler, 5, int.MaxValue, true, allowJobProcessingHandlerToProceed); + // run the same thing multiple times to ensure that the queue isn't in a erroneous state after being blocked. + for (int i = 0; i < 10; i++) { - // run the same thing multiple times to ensure that the queue isn't in a erroneous state after being blocked. - for (int i = 0; i < 10; i++) - { - queue.QueueJob("job1", 0); - queue.QueueJob("job2", 0); - queue.QueueJob("job3", 0); - queue.QueueJob("job4", 0); - queue.QueueJob("job5", 0); - - // At this point only 5 jobs have been queued. Even if all are still in queue, still the need to block shouldn't have - // risen. So queue.enteredBlockingMethod would be false. - Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method at a wrong time."); - - queue.QueueJob("job6", 0); - queue.QueueJob("job7", 0); - queue.QueueJob("job8", 0); - queue.QueueJob("job9", 0); - queue.QueueJob("job10", 0); - queue.QueueJob("job11", 0); - - // By this point surely the queue would have blocked at least once, hence setting queue.enteredBlockingMethod true. - Assert.IsTrue(queue.IsEnqueueBlocked, "Did not enter the over-ridden blocking method"); - - // We wait till all jobs are finished, so that for the next iteration the queue is in a deterministic state. - jobProcessed.WaitOne(); - - // queue.enteredBlockingMethod is set to false to check it again in next iteration. Also - // allowJobProcessingHandlerToProceed is reset to block the handler again in next iteration. - queue.IsEnqueueBlocked = false; - allowJobProcessingHandlerToProceed.Reset(); - - // if we reach here it means that the queue was successfully blocked at some point in between job6 and job11 - // and subsequently unblocked. - } + queue.QueueJob("job1", 0); + queue.QueueJob("job2", 0); + queue.QueueJob("job3", 0); + queue.QueueJob("job4", 0); + queue.QueueJob("job5", 0); + + // At this point only 5 jobs have been queued. Even if all are still in queue, still the need to block shouldn't have + // risen. So queue.enteredBlockingMethod would be false. + Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method at a wrong time."); + + queue.QueueJob("job6", 0); + queue.QueueJob("job7", 0); + queue.QueueJob("job8", 0); + queue.QueueJob("job9", 0); + queue.QueueJob("job10", 0); + queue.QueueJob("job11", 0); + + // By this point surely the queue would have blocked at least once, hence setting queue.enteredBlockingMethod true. + Assert.IsTrue(queue.IsEnqueueBlocked, "Did not enter the over-ridden blocking method"); + + // We wait till all jobs are finished, so that for the next iteration the queue is in a deterministic state. + jobProcessed.WaitOne(); + + // queue.enteredBlockingMethod is set to false to check it again in next iteration. Also + // allowJobProcessingHandlerToProceed is reset to block the handler again in next iteration. + queue.IsEnqueueBlocked = false; + allowJobProcessingHandlerToProceed.Reset(); + + // if we reach here it means that the queue was successfully blocked at some point in between job6 and job11 + // and subsequently unblocked. } } @@ -296,42 +290,40 @@ public void TestBlockAtEnqueueDueToSize() } }; - using (JobQueueWrapper queue = new JobQueueWrapper(processHandler, int.MaxValue, 40, true, allowJobProcessingHandlerToProceed)) + using JobQueueWrapper queue = new JobQueueWrapper(processHandler, int.MaxValue, 40, true, allowJobProcessingHandlerToProceed); + // run the same thing multiple times to ensure that the queue isn't in a erroneous state after being blocked. + for (int i = 0; i < 10; i++) { - // run the same thing multiple times to ensure that the queue isn't in a erroneous state after being blocked. - for (int i = 0; i < 10; i++) - { - queue.QueueJob("job1", 8); - queue.QueueJob("job2", 8); - queue.QueueJob("job3", 8); - queue.QueueJob("job4", 8); - queue.QueueJob("job5", 8); - - // At this point exactly 80 bytes have been queued. Even if all are still in queue, still the need to block shouldn't - // have risen. So queue.enteredBlockingMethod would be false. - Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method at a wrong time."); - - queue.QueueJob("job6", 8); - queue.QueueJob("job7", 8); - queue.QueueJob("job8", 8); - queue.QueueJob("job9", 8); - queue.QueueJob("job10", 10); - queue.QueueJob("job11", 10); - - // By this point surely the queue would have blocked at least once, hence setting queue.enteredBlockingMethod true. - Assert.IsTrue(queue.IsEnqueueBlocked, "Did not enter the over-ridden blocking method"); - - // We wait till all jobs are finished, so that for the next iteration the queue is in a deterministic state. - jobProcessed.WaitOne(); - - // queue.enteredBlockingMethod is set to false to check it again in next iteration. Also - // allowJobProcessingHandlerToProceed is reset to block the handler again in next iteration. - queue.IsEnqueueBlocked = false; - allowJobProcessingHandlerToProceed.Reset(); - - // if we reach here it means that the queue was successfully blocked at some point in between job6 and job11 - // and subsequently unblocked. - } + queue.QueueJob("job1", 8); + queue.QueueJob("job2", 8); + queue.QueueJob("job3", 8); + queue.QueueJob("job4", 8); + queue.QueueJob("job5", 8); + + // At this point exactly 80 bytes have been queued. Even if all are still in queue, still the need to block shouldn't + // have risen. So queue.enteredBlockingMethod would be false. + Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method at a wrong time."); + + queue.QueueJob("job6", 8); + queue.QueueJob("job7", 8); + queue.QueueJob("job8", 8); + queue.QueueJob("job9", 8); + queue.QueueJob("job10", 10); + queue.QueueJob("job11", 10); + + // By this point surely the queue would have blocked at least once, hence setting queue.enteredBlockingMethod true. + Assert.IsTrue(queue.IsEnqueueBlocked, "Did not enter the over-ridden blocking method"); + + // We wait till all jobs are finished, so that for the next iteration the queue is in a deterministic state. + jobProcessed.WaitOne(); + + // queue.enteredBlockingMethod is set to false to check it again in next iteration. Also + // allowJobProcessingHandlerToProceed is reset to block the handler again in next iteration. + queue.IsEnqueueBlocked = false; + allowJobProcessingHandlerToProceed.Reset(); + + // if we reach here it means that the queue was successfully blocked at some point in between job6 and job11 + // and subsequently unblocked. } } @@ -352,38 +344,36 @@ public void TestBlockingDisabled() } }; - using (JobQueueWrapper queue = new JobQueueWrapper(processHandler, 2, int.MaxValue, false, allowJobProcessingHandlerToProceed)) + using JobQueueWrapper queue = new JobQueueWrapper(processHandler, 2, int.MaxValue, false, allowJobProcessingHandlerToProceed); + // run the same thing multiple times to ensure that the queue isn't in a erroneous state after first run. + for (int i = 0; i < 10; i++) { - // run the same thing multiple times to ensure that the queue isn't in a erroneous state after first run. - for (int i = 0; i < 10; i++) - { - queue.QueueJob("job1", 0); - queue.QueueJob("job2", 0); + queue.QueueJob("job1", 0); + queue.QueueJob("job2", 0); - // At this point only 2 jobs have been queued. Even if all are still in queue, still the need to block shouldn't have - // risen. So queue.enteredBlockingMethod would be false regardless of the blocking disabled or not. - Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method at a wrong time."); + // At this point only 2 jobs have been queued. Even if all are still in queue, still the need to block shouldn't have + // risen. So queue.enteredBlockingMethod would be false regardless of the blocking disabled or not. + Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method at a wrong time."); - queue.QueueJob("job3", 0); - queue.QueueJob("job4", 0); - queue.QueueJob("job5", 0); + queue.QueueJob("job3", 0); + queue.QueueJob("job4", 0); + queue.QueueJob("job5", 0); - // queue.enteredBlockingMethod should still be false as the queue should not have blocked. - Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method though blocking is disabled."); + // queue.enteredBlockingMethod should still be false as the queue should not have blocked. + Assert.IsFalse(queue.IsEnqueueBlocked, "Entered the over-ridden blocking method though blocking is disabled."); - // allow handlers to proceed. - allowJobProcessingHandlerToProceed.Set(); + // allow handlers to proceed. + allowJobProcessingHandlerToProceed.Set(); - // We wait till all jobs are finished, so that for the next iteration the queue is in a deterministic state. - jobProcessed.WaitOne(); + // We wait till all jobs are finished, so that for the next iteration the queue is in a deterministic state. + jobProcessed.WaitOne(); - // queue.enteredBlockingMethod is set to false to check it again in next iteration. Also - // allowJobProcessingHandlerToProceed is reset to allow blocking the handler again in next iteration. - queue.IsEnqueueBlocked = false; - allowJobProcessingHandlerToProceed.Reset(); + // queue.enteredBlockingMethod is set to false to check it again in next iteration. Also + // allowJobProcessingHandlerToProceed is reset to allow blocking the handler again in next iteration. + queue.IsEnqueueBlocked = false; + allowJobProcessingHandlerToProceed.Reset(); - // if we reach here it means that the queue was never blocked. - } + // if we reach here it means that the queue was never blocked. } } @@ -398,20 +388,18 @@ public void TestLargeTestResultCanBeLoadedWithBlockingEnabled() jobProcessed.Set(); }; - using (JobQueueNonBlocking queue = new JobQueueNonBlocking(processHandler)) + using JobQueueNonBlocking queue = new JobQueueNonBlocking(processHandler); + // run the same thing multiple times to ensure that the queue isn't in a erroneous state after first run. + for (var i = 0; i < 10; i++) { - // run the same thing multiple times to ensure that the queue isn't in a erroneous state after first run. - for (var i = 0; i < 10; i++) - { - // we try to enqueue a job of size greater than bound on the queue. It should be queued without blocking as - // we check whether or not the queue size has exceeded the limit before actually queuing. - queue.QueueJob("job1", 8); - - // if queue.EnteredBlockingMethod is true, the enqueuing entered the overridden blocking method. This was not - // intended. - Assert.IsFalse(queue.EnteredBlockingMethod, "Entered the over-ridden blocking method."); - jobProcessed.WaitOne(); - } + // we try to enqueue a job of size greater than bound on the queue. It should be queued without blocking as + // we check whether or not the queue size has exceeded the limit before actually queuing. + queue.QueueJob("job1", 8); + + // if queue.EnteredBlockingMethod is true, the enqueuing entered the overridden blocking method. This was not + // intended. + Assert.IsFalse(queue.EnteredBlockingMethod, "Entered the over-ridden blocking method."); + jobProcessed.WaitOne(); } } @@ -421,37 +409,35 @@ public void TestDisposeUnblocksBlockedThreads() { var allowJobProcessingHandlerToProceed = new ManualResetEvent(false); - using (var gotBlocked = new ManualResetEvent(false)) + using var gotBlocked = new ManualResetEvent(false); + var job1Running = new ManualResetEvent(false); + + // process handler for the jobs in queue. It blocks on a job till the test method sets the + // event allowHandlerToProceed. + Action processHandler = (job) => { - var job1Running = new ManualResetEvent(false); + if (job.Equals("job1", StringComparison.OrdinalIgnoreCase)) + job1Running.Set(); - // process handler for the jobs in queue. It blocks on a job till the test method sets the - // event allowHandlerToProceed. - Action processHandler = (job) => - { - if (job.Equals("job1", StringComparison.OrdinalIgnoreCase)) - job1Running.Set(); - - allowJobProcessingHandlerToProceed.WaitOne(); - }; - - var jobQueue = new JobQueueWrapper(processHandler, 1, int.MaxValue, true, gotBlocked); - - var queueThread = new Thread( - source => - { - jobQueue.QueueJob("job1", 0); - job1Running.WaitOne(); - jobQueue.QueueJob("job2", 0); - jobQueue.QueueJob("job3", 0); - allowJobProcessingHandlerToProceed.Set(); - }); - queueThread.Start(); - - gotBlocked.WaitOne(); - jobQueue.Dispose(); - queueThread.Join(); - } + allowJobProcessingHandlerToProceed.WaitOne(); + }; + + var jobQueue = new JobQueueWrapper(processHandler, 1, int.MaxValue, true, gotBlocked); + + var queueThread = new Thread( + source => + { + jobQueue.QueueJob("job1", 0); + job1Running.WaitOne(); + jobQueue.QueueJob("job2", 0); + jobQueue.QueueJob("job3", 0); + allowJobProcessingHandlerToProceed.Set(); + }); + queueThread.Start(); + + gotBlocked.WaitOne(); + jobQueue.Dispose(); + queueThread.Join(); } #region Implementation diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs index 6212061853..f27356f435 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentsProcessorsFactoryTests.cs @@ -41,10 +41,12 @@ public void Cleanup() public void Create_ShouldReturnListOfAttachmentProcessors() { // arrange - List invokedDataCollectors = new List(); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("datacollector://Sample"), "Sample", typeof(SampleDataCollector).AssemblyQualifiedName, typeof(SampleDataCollector).Assembly.Location, true)); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("datacollector://SampleData2"), "SampleData2", typeof(SampleData2Collector).AssemblyQualifiedName, typeof(SampleData2Collector).Assembly.Location, true)); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("datacollector://SampleData3"), "SampleData3", typeof(SampleData3Collector).AssemblyQualifiedName, typeof(SampleData3Collector).Assembly.Location, true)); + List invokedDataCollectors = new List + { + new InvokedDataCollector(new Uri("datacollector://Sample"), "Sample", typeof(SampleDataCollector).AssemblyQualifiedName, typeof(SampleDataCollector).Assembly.Location, true), + new InvokedDataCollector(new Uri("datacollector://SampleData2"), "SampleData2", typeof(SampleData2Collector).AssemblyQualifiedName, typeof(SampleData2Collector).Assembly.Location, true), + new InvokedDataCollector(new Uri("datacollector://SampleData3"), "SampleData3", typeof(SampleData3Collector).AssemblyQualifiedName, typeof(SampleData3Collector).Assembly.Location, true) + }; // act var dataCollectorAttachmentsProcessors = dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -77,8 +79,10 @@ public void Create_EmptyOrNullInvokedDataCollector_ShouldReturnCodeCoverageDataA public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() { // arrange - List invokedDataCollectors = new List(); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", typeof(SampleData4Collector).AssemblyQualifiedName, typeof(SampleData4Collector).Assembly.Location, true)); + List invokedDataCollectors = new List + { + new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", typeof(SampleData4Collector).AssemblyQualifiedName, typeof(SampleData4Collector).Assembly.Location, true) + }; // act var dataCollectorAttachmentsProcessors = dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -92,8 +96,10 @@ public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() public void Create_ShouldAddTwoTimeCodeCoverageDataAttachmentsHandler() { // arrange - List invokedDataCollectors = new List(); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "SampleData5", typeof(SampleData5Collector).AssemblyQualifiedName, typeof(SampleData5Collector).Assembly.Location, true)); + List invokedDataCollectors = new List + { + new InvokedDataCollector(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "SampleData5", typeof(SampleData5Collector).AssemblyQualifiedName, typeof(SampleData5Collector).Assembly.Location, true) + }; // act var dataCollectorAttachmentsProcessors = dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -120,9 +126,11 @@ public void Create_ShouldLoadOrderingByFilePath() Directory.CreateDirectory(version2); File.Copy(dataCollectorFilePath, Path.Combine(version2, Path.GetFileName(dataCollectorFilePath)), true); - List invokedDataCollectors = new List(); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("my://sample/datacollector"), "sample", "AttachmentProcessorDataCollector.SampleDataCollectorV2", Path.Combine(version1, Path.GetFileName(dataCollectorFilePath)), true)); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("my://sample/datacollector"), "sample", "AttachmentProcessorDataCollector.SampleDataCollectorV2", Path.Combine(version2, Path.GetFileName(dataCollectorFilePath)), true)); + List invokedDataCollectors = new List + { + new InvokedDataCollector(new Uri("my://sample/datacollector"), "sample", "AttachmentProcessorDataCollector.SampleDataCollectorV2", Path.Combine(version1, Path.GetFileName(dataCollectorFilePath)), true), + new InvokedDataCollector(new Uri("my://sample/datacollector"), "sample", "AttachmentProcessorDataCollector.SampleDataCollectorV2", Path.Combine(version2, Path.GetFileName(dataCollectorFilePath)), true) + }; // act var dataCollectorAttachmentsProcessors = dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelDiscoveryDataAggregatorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelDiscoveryDataAggregatorTests.cs index c8d1e1ec8a..f5242b1496 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelDiscoveryDataAggregatorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelDiscoveryDataAggregatorTests.cs @@ -60,8 +60,10 @@ public void AggregateDiscoveryDataMetricsShouldAddTotalTestsDiscovered() { var aggregator = new ParallelDiscoveryDataAggregator(); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TotalTestsDiscovered, 2); + var dict = new Dictionary + { + { TelemetryDataConstants.TotalTestsDiscovered, 2 } + }; aggregator.AggregateDiscoveryDataMetrics(dict); aggregator.AggregateDiscoveryDataMetrics(dict); @@ -77,8 +79,10 @@ public void AggregateDiscoveryDataMetricsShouldAddTimeTakenToDiscoverTests() { var aggregator = new ParallelDiscoveryDataAggregator(); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter, .02091); + var dict = new Dictionary + { + { TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter, .02091 } + }; aggregator.AggregateDiscoveryDataMetrics(dict); aggregator.AggregateDiscoveryDataMetrics(dict); @@ -94,8 +98,10 @@ public void AggregateDiscoveryDataMetricsShouldAddTimeTakenByAllAdapters() { var aggregator = new ParallelDiscoveryDataAggregator(); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TimeTakenInSecByAllAdapters, .02091); + var dict = new Dictionary + { + { TelemetryDataConstants.TimeTakenInSecByAllAdapters, .02091 } + }; aggregator.AggregateDiscoveryDataMetrics(dict); aggregator.AggregateDiscoveryDataMetrics(dict); @@ -111,8 +117,10 @@ public void AggregateDiscoveryDataMetricsShouldAddTimeTakenToLoadAdapters() { var aggregator = new ParallelDiscoveryDataAggregator(); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TimeTakenToLoadAdaptersInSec, .02091); + var dict = new Dictionary + { + { TelemetryDataConstants.TimeTakenToLoadAdaptersInSec, .02091 } + }; aggregator.AggregateDiscoveryDataMetrics(dict); aggregator.AggregateDiscoveryDataMetrics(dict); @@ -128,8 +136,10 @@ public void AggregateDiscoveryDataMetricsShouldNotAggregateDiscoveryState() { var aggregator = new ParallelDiscoveryDataAggregator(); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.DiscoveryState, "Completed"); + var dict = new Dictionary + { + { TelemetryDataConstants.DiscoveryState, "Completed" } + }; aggregator.AggregateDiscoveryDataMetrics(dict); aggregator.AggregateDiscoveryDataMetrics(dict); @@ -170,8 +180,10 @@ public void GetDiscoveryDataMetricsShouldAddTotalAdaptersUsedIfMetricsIsNotEmpty { var aggregator = new ParallelDiscoveryDataAggregator(); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TotalTestsByAdapter, 2); + var dict = new Dictionary + { + { TelemetryDataConstants.TotalTestsByAdapter, 2 } + }; aggregator.AggregateDiscoveryDataMetrics(dict); aggregator.AggregateDiscoveryDataMetrics(dict); @@ -187,9 +199,11 @@ public void GetDiscoveryDataMetricsShouldAddNumberOfAdapterDiscoveredIfMetricsIs { var aggregator = new ParallelDiscoveryDataAggregator(); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter + "executor:MSTestV1", .02091); - dict.Add(TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter + "executor:MSTestV2", .02091); + var dict = new Dictionary + { + { TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter + "executor:MSTestV1", .02091 }, + { TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter + "executor:MSTestV2", .02091 } + }; aggregator.AggregateDiscoveryDataMetrics(dict); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs index ca4700c66e..15e6407891 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs @@ -344,11 +344,15 @@ public void StartTestRunShouldAggregateRunData() } Task.Delay(100).Wait(); - var stats = new Dictionary(); - stats.Add(TestOutcome.Passed, 3); - stats.Add(TestOutcome.Failed, 2); - var runAttachments = new Collection(); - runAttachments.Add(new AttachmentSet(new Uri("hello://x/"), "Hello")); + var stats = new Dictionary + { + { TestOutcome.Passed, 3 }, + { TestOutcome.Failed, 2 } + }; + var runAttachments = new Collection + { + new AttachmentSet(new Uri("hello://x/"), "Hello") + }; var executorUris = new List() { "hello1" }; bool isCanceled = false; bool isAborted = false; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs index 348005c78b..d02d4899ab 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs @@ -43,16 +43,20 @@ public void AggregateShouldAggregateRunCompleteAttachmentsCorrectly() { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var attachmentSet1 = new Collection(); - attachmentSet1.Add(new AttachmentSet(new Uri("x://hello1"), "hello1")); + var attachmentSet1 = new Collection + { + new AttachmentSet(new Uri("x://hello1"), "hello1") + }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, attachmentSet1, null); Assert.AreEqual(1, aggregator.RunCompleteArgsAttachments.Count, "RunCompleteArgsAttachments List must have data."); - var attachmentSet2 = new Collection(); - attachmentSet2.Add(new AttachmentSet(new Uri("x://hello2"), "hello2")); + var attachmentSet2 = new Collection + { + new AttachmentSet(new Uri("x://hello2"), "hello2") + }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, null, attachmentSet2, null); @@ -64,15 +68,19 @@ public void AggregateShouldAggregateRunContextAttachmentsCorrectly() { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var attachmentSet1 = new Collection(); - attachmentSet1.Add(new AttachmentSet(new Uri("x://hello1"), "hello1")); + var attachmentSet1 = new Collection + { + new AttachmentSet(new Uri("x://hello1"), "hello1") + }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, attachmentSet1, null, null); Assert.AreEqual(1, aggregator.RunContextAttachments.Count, "RunContextAttachments List must have data."); - var attachmentSet2 = new Collection(); - attachmentSet2.Add(new AttachmentSet(new Uri("x://hello2"), "hello2")); + var attachmentSet2 = new Collection + { + new AttachmentSet(new Uri("x://hello2"), "hello2") + }; aggregator.Aggregate(null, null, null, TimeSpan.Zero, false, false, attachmentSet2, null, null); @@ -235,12 +243,14 @@ public void AggregateShouldAggregateRunStatsCorrectly() var runStats = aggregator.GetAggregatedRunStats(); Assert.AreEqual(0, runStats.ExecutedTests, "RunStats must not have data."); - var stats1 = new Dictionary(); - stats1.Add(TestOutcome.Passed, 2); - stats1.Add(TestOutcome.Failed, 3); - stats1.Add(TestOutcome.Skipped, 1); - stats1.Add(TestOutcome.NotFound, 4); - stats1.Add(TestOutcome.None, 2); + var stats1 = new Dictionary + { + { TestOutcome.Passed, 2 }, + { TestOutcome.Failed, 3 }, + { TestOutcome.Skipped, 1 }, + { TestOutcome.NotFound, 4 }, + { TestOutcome.None, 2 } + }; aggregator.Aggregate(new TestRunStatistics(12, stats1), null, null, TimeSpan.Zero, false, false, null, null, null); @@ -253,12 +263,14 @@ public void AggregateShouldAggregateRunStatsCorrectly() Assert.AreEqual(2, runStats.Stats[TestOutcome.None], "RunStats must have aggregated data."); - var stats2 = new Dictionary(); - stats2.Add(TestOutcome.Passed, 3); - stats2.Add(TestOutcome.Failed, 2); - stats2.Add(TestOutcome.Skipped, 2); - stats2.Add(TestOutcome.NotFound, 1); - stats2.Add(TestOutcome.None, 3); + var stats2 = new Dictionary + { + { TestOutcome.Passed, 3 }, + { TestOutcome.Failed, 2 }, + { TestOutcome.Skipped, 2 }, + { TestOutcome.NotFound, 1 }, + { TestOutcome.None, 3 } + }; aggregator.Aggregate(new TestRunStatistics(11, stats2), null, null, TimeSpan.Zero, false, false, null, null, null); @@ -287,8 +299,10 @@ public void AggregateRunDataMetricsShouldAddTotalTestsRun() { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TotalTestsRanByAdapter, 2); + var dict = new Dictionary + { + { TelemetryDataConstants.TotalTestsRanByAdapter, 2 } + }; aggregator.AggregateRunDataMetrics(dict); aggregator.AggregateRunDataMetrics(dict); @@ -304,8 +318,10 @@ public void AggregateRunDataMetricsShouldAddTimeTakenToRunTests() { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter, .02091); + var dict = new Dictionary + { + { TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter, .02091 } + }; aggregator.AggregateRunDataMetrics(dict); aggregator.AggregateRunDataMetrics(dict); @@ -321,8 +337,10 @@ public void AggregateRunDataMetricsShouldAddTimeTakenByAllAdapters() { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TimeTakenByAllAdaptersInSec, .02091); + var dict = new Dictionary + { + { TelemetryDataConstants.TimeTakenByAllAdaptersInSec, .02091 } + }; aggregator.AggregateRunDataMetrics(dict); aggregator.AggregateRunDataMetrics(dict); @@ -338,8 +356,10 @@ public void AggregateRunDataMetricsShouldNotAggregateRunState() { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.RunState, "Completed"); + var dict = new Dictionary + { + { TelemetryDataConstants.RunState, "Completed" } + }; aggregator.AggregateRunDataMetrics(dict); aggregator.AggregateRunDataMetrics(dict); @@ -380,8 +400,10 @@ public void GetRunDataMetricsShouldAddTotalAdaptersUsedIfMetricsIsNotEmpty() { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TotalTestsRanByAdapter, 2); + var dict = new Dictionary + { + { TelemetryDataConstants.TotalTestsRanByAdapter, 2 } + }; aggregator.AggregateRunDataMetrics(dict); aggregator.AggregateRunDataMetrics(dict); @@ -397,9 +419,11 @@ public void GetRunDataMetricsShouldAddNumberOfAdapterDiscoveredIfMetricsIsEmpty( { var aggregator = new ParallelRunDataAggregator(Constants.EmptyRunSettings); - var dict = new Dictionary(); - dict.Add(TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter + "executor:MSTestV1", .02091); - dict.Add(TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter + "executor:MSTestV2", .02091); + var dict = new Dictionary + { + { TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter + "executor:MSTestV1", .02091 }, + { TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter + "executor:MSTestV2", .02091 } + }; aggregator.AggregateRunDataMetrics(dict); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs index d801a23c3d..61247b88cb 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DataCollectionTestRunEventsHandlerTests.cs @@ -108,8 +108,10 @@ public void HandleRawMessageShouldInvokeAfterTestRunEndPassingTrueIfRequestCance [TestMethod] public void HandleRawMessageShouldInvokeAfterTestRunEndAndReturnInvokedDataCollectors() { - var invokedDataCollectors = new Collection(); - invokedDataCollectors.Add(new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, true)); + var invokedDataCollectors = new Collection + { + new InvokedDataCollector(new Uri("datacollector://sample"), "sample", typeof(string).AssemblyQualifiedName, typeof(string).Assembly.Location, true) + }; var testRunCompleteEventArgs = new TestRunCompleteEventArgs(null, false, false, null, new Collection(), new Collection(), new TimeSpan()); this.mockDataSerializer.Setup(x => x.DeserializeMessage(It.IsAny())).Returns(new Message() { MessageType = MessageType.ExecutionComplete }); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs index 0b439bff1a..b3564bbb6f 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/InProcDataCollectionExtensionManagerTests.cs @@ -203,8 +203,10 @@ public void InProcDataCollectionExtensionManagerWillNotEnableDataCollectionForIn [TestMethod] public void TriggerSessionStartShouldBeCalledWithCorrectTestSources() { - var properties = new Dictionary(); - properties.Add("TestSources", new List() { "testsource1.dll", "testsource2.dll" }); + var properties = new Dictionary + { + { "TestSources", new List() { "testsource1.dll", "testsource2.dll" } } + }; var mockDataCollector = inProcDataCollectionManager.InProcDataCollectors.Values.FirstOrDefault() as MockDataCollector; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs index b4bc2403fe..e3c4dc6955 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyOutOfProcDataCollectionManagerTests.cs @@ -32,8 +32,10 @@ public ProxyOutOfProcDataCollectionManagerTests() var attachmentSet = new AttachmentSet(new Uri("my://datacollector"), "mydatacollector"); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri("my://attachment.txt"), string.Empty)); - this.attachmentSets = new Collection(); - this.attachmentSets.Add(attachmentSet); + this.attachmentSets = new Collection + { + attachmentSet + }; this.testcase = new TestCase(); this.testcase.Id = Guid.NewGuid(); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs index 16f4749e9b..a0597476f1 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs @@ -71,8 +71,10 @@ public void LoadTestsShouldReportWarningOnNoDiscoverers() () => { }); var sources = new List { typeof(DiscoveryResultCacheTests).GetTypeInfo().Assembly.Location }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; this.discovererEnumerator.LoadTests(extensionSourceMap, this.runSettingsMock.Object, null, this.messageLoggerMock.Object); @@ -93,8 +95,10 @@ public void LoadTestsShouldNotCallIntoDiscoverersIfNoneMatchesSources() () => { }); var sources = new List { "temp.jpeg" }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; this.discovererEnumerator.LoadTests(extensionSourceMap, this.runSettingsMock.Object, null, this.messageLoggerMock.Object); @@ -116,8 +120,10 @@ public void LoadTestsShouldCallOnlyNativeDiscovererIfNativeAssembliesPassed() "native.dll" }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; string testCaseFilter = "TestFilter"; @@ -144,8 +150,10 @@ public void LoadTestsShouldCallOnlyManagedDiscovererIfManagedAssembliesPassed() "managed.dll" }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; string testCaseFilter = "TestFilter"; @@ -177,8 +185,10 @@ public void LoadTestsShouldCallBothNativeAndManagedDiscoverersWithCorrectSources "managed.dll" }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", nativeSources.Concat(managedSources)); + var extensionSourceMap = new Dictionary> + { + { "_none_", nativeSources.Concat(managedSources) } + }; string testCaseFilter = "TestFilter"; @@ -206,8 +216,10 @@ public void LoadTestsShouldCallIntoADiscovererThatMatchesTheSources() typeof(DiscoveryResultCacheTests).GetTypeInfo().Assembly.Location }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; string testCaseFilter = "TestFilter"; this.discovererEnumerator.LoadTests(extensionSourceMap, this.runSettingsMock.Object, testCaseFilter, this.messageLoggerMock.Object); @@ -243,8 +255,10 @@ public void LoadTestsShouldCallIntoMultipleDiscoverersThatMatchesTheSources() var sources = new List(dllsources); sources.AddRange(jsonsources); - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; var runSettings = this.runSettingsMock.Object; @@ -282,8 +296,10 @@ public void LoadTestsShouldCallIntoOtherDiscoverersWhenCreatingOneFails() typeof(DiscoveryResultCacheTests).GetTypeInfo().Assembly.Location }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; var runSettings = this.runSettingsMock.Object; @@ -315,8 +331,10 @@ public void LoadTestsShouldCallIntoOtherDiscoverersEvenIfDiscoveryInOneFails() typeof(DiscoveryResultCacheTests).GetTypeInfo().Assembly.Location }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; var runSettings = this.runSettingsMock.Object; @@ -348,8 +366,10 @@ public void LoadTestsShouldCallIntoOtherDiscoverersEvenIfDiscoveryInOneFails() public void LoadTestsShouldCollectMetrics() { var mockMetricsCollector = new Mock(); - var dict = new Dictionary(); - dict.Add("DummyMessage", "DummyValue"); + var dict = new Dictionary + { + { "DummyMessage", "DummyValue" } + }; TestPluginCacheHelper.SetupMockExtensions( new string[] { typeof(DiscovererEnumeratorTests).GetTypeInfo().Assembly.Location }, @@ -361,8 +381,10 @@ public void LoadTestsShouldCollectMetrics() typeof(DiscoveryResultCacheTests).GetTypeInfo().Assembly.Location }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; mockMetricsCollector.Setup(mc => mc.Metrics).Returns(dict); this.mockRequestData.Setup(rd => rd.MetricsCollection).Returns(mockMetricsCollector.Object); @@ -483,9 +505,11 @@ public void LoadTestsShouldIterateOverAllExtensionsInTheMapAndDiscoverTests() "test2.json" }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add(typeof(DiscovererEnumeratorTests).GetTypeInfo().Assembly.Location, jsonsources); - extensionSourceMap.Add("_none_", dllsources); + var extensionSourceMap = new Dictionary> + { + { typeof(DiscovererEnumeratorTests).GetTypeInfo().Assembly.Location, jsonsources }, + { "_none_", dllsources } + }; var runSettings = this.runSettingsMock.Object; @@ -565,8 +589,10 @@ private static void SetupForNoTestsAvailableInGivenAssemblies( var objectModelAseeAssemblyLocation = typeof(TestCase).GetTypeInfo().Assembly.Location; var sources = new string[] { crossPlatEngineAssemblyLocation, objectModelAseeAssemblyLocation }; - extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; sourcesString = string.Join(" ", crossPlatEngineAssemblyLocation, objectModelAseeAssemblyLocation); } @@ -581,8 +607,10 @@ private void InvokeLoadTestWithMockSetup() typeof(DiscoveryResultCacheTests).GetTypeInfo().Assembly.Location }; - var extensionSourceMap = new Dictionary>(); - extensionSourceMap.Add("_none_", sources); + var extensionSourceMap = new Dictionary> + { + { "_none_", sources } + }; this.discovererEnumerator.LoadTests(extensionSourceMap, this.runSettingsMock.Object, null, this.messageLoggerMock.Object); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs index d7d956b4be..788b724302 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs @@ -221,8 +221,10 @@ public void DiscoverTestsShouldSendMetricsOnDiscoveryComplete() public void DiscoverTestsShouldCollectMetrics() { var mockMetricsCollector = new Mock(); - var dict = new Dictionary(); - dict.Add("DummyMessage", "DummyValue"); + var dict = new Dictionary + { + { "DummyMessage", "DummyValue" } + }; mockMetricsCollector.Setup(mc => mc.Metrics).Returns(dict); this.mockRequestData.Setup(rd => rd.MetricsCollection).Returns(mockMetricsCollector.Object); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs index a85aec8b51..44d7ea2355 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs @@ -231,8 +231,10 @@ public void ProcessRequestsExecutionInitializeShouldSetExtensionPaths() [TestMethod] public void ProcessRequestsExecutionStartShouldStartExecutionWithGivenSources() { - var asm = new Dictionary>(); - asm["mstestv2"] = new[] {"test1.dll", "test2.dll"}; + var asm = new Dictionary> + { + ["mstestv2"] = new[] { "test1.dll", "test2.dll" } + }; var testRunCriteriaWithSources = new TestRunCriteriaWithSources(asm, "runsettings", null, null); var message = this.dataSerializer.SerializePayload(MessageType.StartTestExecutionWithSources, testRunCriteriaWithSources); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs index c93cdf16e3..22933e9acd 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs @@ -686,8 +686,10 @@ public void RunTestsShouldSendMetricsOnTestRunComplete() TestRunCompleteEventArgs receivedRunCompleteArgs = null; var mockMetricsCollector = new Mock(); - var dict = new Dictionary(); - dict.Add("DummyMessage", "DummyValue"); + var dict = new Dictionary + { + { "DummyMessage", "DummyValue" } + }; // Setup mocks. mockMetricsCollector.Setup(mc => mc.Metrics).Returns(dict); @@ -723,8 +725,10 @@ public void RunTestsShouldSendMetricsOnTestRunComplete() public void RunTestsShouldCollectMetrics() { var mockMetricsCollector = new Mock(); - var dict = new Dictionary(); - dict.Add("DummyMessage", "DummyValue"); + var dict = new Dictionary + { + { "DummyMessage", "DummyValue" } + }; var assemblyLocation = typeof(BaseRunTestsTests).GetTypeInfo().Assembly.Location; var executorUriExtensionMap = new List> { diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs index ce5d24ea30..d0c90ce0de 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs @@ -119,8 +119,10 @@ public void StartTestRunShouldRunTestsInTheProvidedSources() TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add(assemblyLocation, new List { assemblyLocation }); + var adapterSourceMap = new Dictionary> + { + { assemblyLocation, new List { assemblyLocation } } + }; var mockTestRunEventsHandler = new Mock(); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs index b8754f6582..a2cdaeaf30 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs @@ -76,12 +76,16 @@ public void TestCleanup() [TestMethod] public void BeforeRaisingTestRunCompleteShouldWarnIfNoTestsAreRun() { - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("a", new List {"a", "aa"}); - adapterSourceMap.Add("b", new List { "b", "ab" }); + var adapterSourceMap = new Dictionary> + { + { "a", new List { "a", "aa" } }, + { "b", new List { "b", "ab" } } + }; - var executorUriVsSourceList = new Dictionary, IEnumerable>(); - executorUriVsSourceList.Add(new Tuple(new Uri("e://d/"), "A.dll"), new List {"s1.dll "}); + var executorUriVsSourceList = new Dictionary, IEnumerable> + { + { new Tuple(new Uri("e://d/"), "A.dll"), new List { "s1.dll " } } + }; this.runTestsInstance = new TestableRunTestsWithSources( adapterSourceMap, @@ -104,8 +108,10 @@ public void BeforeRaisingTestRunCompleteShouldWarnIfNoTestsAreRun() [TestMethod] public void GetExecutorUriExtensionMapShouldReturnEmptyOnInvalidSources() { - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("a", new List { "a", "aa" }); + var adapterSourceMap = new Dictionary> + { + { "a", new List { "a", "aa" } } + }; this.runTestsInstance = new TestableRunTestsWithSources( adapterSourceMap, @@ -126,9 +132,11 @@ public void GetExecutorUriExtensionMapShouldReturnDefaultExecutorUrisForTheDisco { var assemblyLocation = typeof (RunTestsWithSourcesTests).GetTypeInfo().Assembly.Location; - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("a", new List {"a", "aa"}); - adapterSourceMap.Add(assemblyLocation, new List {assemblyLocation}); + var adapterSourceMap = new Dictionary> + { + { "a", new List { "a", "aa" } }, + { assemblyLocation, new List { assemblyLocation } } + }; this.runTestsInstance = new TestableRunTestsWithSources( adapterSourceMap, @@ -149,9 +157,11 @@ public void GetExecutorUriExtensionMapShouldReturnDefaultExecutorUrisForTheDisco [TestMethod] public void InvokeExecutorShouldInvokeTestExecutorWithTheSources() { - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("a", new List { "a", "aa" }); - adapterSourceMap.Add("b", new List { "b", "ab" }); + var adapterSourceMap = new Dictionary> + { + { "a", new List { "a", "aa" } }, + { "b", new List { "b", "ab" } } + }; var executorUriVsSourceList = new Dictionary, IEnumerable>(); var executorUriExtensionTuple = new Tuple(new Uri("e://d/"), "A.dll"); @@ -182,9 +192,11 @@ public void RunTestsShouldRunTestsForTheSourcesSpecified() { var assemblyLocation = typeof(RunTestsWithSourcesTests).GetTypeInfo().Assembly.Location; - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("a", new List { "a", "aa" }); - adapterSourceMap.Add(assemblyLocation, new List { assemblyLocation }); + var adapterSourceMap = new Dictionary> + { + { "a", new List { "a", "aa" } }, + { assemblyLocation, new List { assemblyLocation } } + }; this.runTestsInstance = new TestableRunTestsWithSources( adapterSourceMap, @@ -254,8 +266,10 @@ public void RunTestsShouldLogWarningOnNoTestsAvailableInAssemblyWithLongTestCase [TestMethod] public void SendSessionStartShouldCallSessionStartWithCorrectTestSources() { - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("a", new List { "1.dll", "2.dll" }); + var adapterSourceMap = new Dictionary> + { + { "a", new List { "1.dll", "2.dll" } } + }; var mockTestCaseEventsHandler = new Mock(); this.runTestsInstance = new TestableRunTestsWithSources( @@ -278,8 +292,10 @@ public void SendSessionStartShouldCallSessionStartWithCorrectTestSources() [TestMethod] public void SendSessionEndShouldCallSessionEnd() { - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("a", new List { "1.dll", "2.dll" }); + var adapterSourceMap = new Dictionary> + { + { "a", new List { "1.dll", "2.dll" } } + }; var mockTestCaseEventsHandler = new Mock(); this.runTestsInstance = new TestableRunTestsWithSources( diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs index 5eaf9d64de..9fff14d3c3 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Utilities/TestSourcesUtilityTests.cs @@ -19,10 +19,12 @@ public class TestSourcesUtilityTests [TestMethod] public void GetSourcesShouldAggregateSourcesIfMultiplePresentInAdapterSourceMap() { - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("adapter1", new List() { "source1.dll", "source2.dll" }); - adapterSourceMap.Add("adapter2", new List() { "source1.dll", "source3.dll" }); - adapterSourceMap.Add("adapter3", new List() { "source1.dll"}); + var adapterSourceMap = new Dictionary> + { + { "adapter1", new List() { "source1.dll", "source2.dll" } }, + { "adapter2", new List() { "source1.dll", "source3.dll" } }, + { "adapter3", new List() { "source1.dll" } } + }; var sources = TestSourcesUtility.GetSources(adapterSourceMap); Assert.AreEqual(5, sources.Count()); @@ -66,8 +68,10 @@ public void GetDefaultCodeBasePathShouldReturnNullIfTestCaseListIsEmpty() [TestMethod] public void GetDefaultCodeBasePathShouldReturnDefaultDirectoryPathForAdapterSourceMap() { - var adapterSourceMap = new Dictionary>(); - adapterSourceMap.Add("adapter1", new List() { Path.Combine(temp, "folder1", "source1.dll"), Path.Combine(temp, "folder2", "source2.dll") }); + var adapterSourceMap = new Dictionary> + { + { "adapter1", new List() { Path.Combine(temp, "folder1", "source1.dll"), Path.Combine(temp, "folder2", "source2.dll") } } + }; var defaultCodeBase = TestSourcesUtility.GetDefaultCodebasePath(adapterSourceMap); Assert.AreEqual(Path.Combine(temp, "folder1"), defaultCodeBase); diff --git a/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs index 63976c48f2..f081222323 100644 --- a/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs @@ -402,9 +402,11 @@ public void TestCompleteHandlerShouldKeepTackOfSummary() [TestMethod] public void TestCompleteHandlerShouldCreateCustumHtmlFileNamewithLogFileNameKey() { - var parameters = new Dictionary(); - parameters[HtmlLoggerConstants.LogFileNameKey] = null; - parameters[DefaultLoggerParameterNames.TestRunDirectory] = "dsa"; + var parameters = new Dictionary + { + [HtmlLoggerConstants.LogFileNameKey] = null, + [DefaultLoggerParameterNames.TestRunDirectory] = "dsa" + }; var testCase1 = CreateTestCase("TestCase1"); var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed }; @@ -419,10 +421,12 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNamewithLogFileNameKey( [TestMethod] public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefix() { - var parameters = new Dictionary(); - parameters[HtmlLoggerConstants.LogFilePrefixKey] = "sample"; - parameters[DefaultLoggerParameterNames.TestRunDirectory] = "dsa"; - parameters[DefaultLoggerParameterNames.TargetFramework] = ".NETFramework,Version=4.5.1"; + var parameters = new Dictionary + { + [HtmlLoggerConstants.LogFilePrefixKey] = "sample", + [DefaultLoggerParameterNames.TestRunDirectory] = "dsa", + [DefaultLoggerParameterNames.TargetFramework] = ".NETFramework,Version=4.5.1" + }; var testCase1 = CreateTestCase("TestCase1"); var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed }; @@ -437,10 +441,12 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefix() [TestMethod] public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixIfTargetFrameworkIsNull() { - var parameters = new Dictionary(); - parameters[HtmlLoggerConstants.LogFilePrefixKey] = "sample"; - parameters[DefaultLoggerParameterNames.TestRunDirectory] = "dsa"; - parameters[DefaultLoggerParameterNames.TargetFramework] = ".NETFramework,Version=4.5.1"; + var parameters = new Dictionary + { + [HtmlLoggerConstants.LogFilePrefixKey] = "sample", + [DefaultLoggerParameterNames.TestRunDirectory] = "dsa", + [DefaultLoggerParameterNames.TargetFramework] = ".NETFramework,Version=4.5.1" + }; var testCase1 = CreateTestCase("TestCase1"); var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed }; @@ -455,10 +461,12 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixIfTarg [TestMethod] public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixNull() { - var parameters = new Dictionary(); - parameters[HtmlLoggerConstants.LogFilePrefixKey] = null; - parameters[DefaultLoggerParameterNames.TestRunDirectory] = "dsa"; - parameters[DefaultLoggerParameterNames.TargetFramework] = ".NETFramework,Version=4.5.1"; + var parameters = new Dictionary + { + [HtmlLoggerConstants.LogFilePrefixKey] = null, + [DefaultLoggerParameterNames.TestRunDirectory] = "dsa", + [DefaultLoggerParameterNames.TargetFramework] = ".NETFramework,Version=4.5.1" + }; var testCase1 = CreateTestCase("TestCase1"); var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed }; @@ -477,9 +485,11 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixNull() [TestMethod] public void TestCompleteHandlerShouldThrowExceptionWithLogPrefixIfTargetFrameworkKeyIsNotPresent() { - var parameters = new Dictionary(); - parameters[HtmlLoggerConstants.LogFilePrefixKey] = "sample.html"; - parameters[DefaultLoggerParameterNames.TestRunDirectory] = "dsa"; + var parameters = new Dictionary + { + [HtmlLoggerConstants.LogFilePrefixKey] = "sample.html", + [DefaultLoggerParameterNames.TestRunDirectory] = "dsa" + }; var testCase1 = CreateTestCase("TestCase1"); var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed }; var resultEventArg1 = new Mock(result1); diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs index 360eaaf83d..e4f2284c7f 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs @@ -45,9 +45,11 @@ public void Initialize() this.events = new Mock(); this.testableTrxLogger = new TestableTrxLogger(); - this.parameters = new Dictionary(2); - this.parameters[DefaultLoggerParameterNames.TestRunDirectory] = TrxLoggerTests.DefaultTestRunDirectory; - this.parameters[TrxLoggerConstants.LogFileNameKey] = TrxLoggerTests.DefaultLogFileNameParameterValue; + this.parameters = new Dictionary(2) + { + [DefaultLoggerParameterNames.TestRunDirectory] = TrxLoggerTests.DefaultTestRunDirectory, + [TrxLoggerConstants.LogFileNameKey] = TrxLoggerTests.DefaultLogFileNameParameterValue + }; this.testableTrxLogger.Initialize(this.events.Object, this.parameters); } @@ -750,9 +752,11 @@ public void GetCustomPropertyValueFromTestCaseShouldReadCategoryAttributesFromTe var converter = new Converter(new Mock().Object, new TrxFileHelper()); List listCategoriesActual = converter.GetCustomPropertyValueFromTestCase(testCase1, "MSTestDiscoverer.TestCategory"); - List listCategoriesExpected = new List(); - listCategoriesExpected.Add("ClassLevel"); - listCategoriesExpected.Add("AsmLevel"); + List listCategoriesExpected = new List + { + "ClassLevel", + "AsmLevel" + }; CollectionAssert.AreEqual(listCategoriesExpected, listCategoriesActual); } @@ -768,9 +772,11 @@ public void GetCustomPropertyValueFromTestCaseShouldReadWorkItemAttributesFromTe var converter = new Converter(new Mock().Object, new TrxFileHelper()); List listWorkItemsActual = converter.GetCustomPropertyValueFromTestCase(testCase1, "WorkItemIds"); - List listWorkItemsExpected = new List(); - listWorkItemsExpected.Add("99999"); - listWorkItemsExpected.Add("0"); + List listWorkItemsExpected = new List + { + "99999", + "0" + }; CollectionAssert.AreEqual(listWorkItemsExpected, listWorkItemsActual); } @@ -807,19 +813,15 @@ public void TestRunInformationShouldContainUtcDateTime() private void ValidateDateTimeInTrx(string trxFileName) { - using (FileStream file = File.OpenRead(trxFileName)) - { - using (XmlReader reader = XmlReader.Create(file)) - { - XDocument document = XDocument.Load(reader); - var timesNode = document.Descendants(document.Root.GetDefaultNamespace() + "Times").FirstOrDefault(); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("creation").FirstOrDefault().Value)); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("start").FirstOrDefault().Value)); - var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").FirstOrDefault(); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("endTime").FirstOrDefault().Value)); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("startTime").FirstOrDefault().Value)); - } - } + using FileStream file = File.OpenRead(trxFileName); + using XmlReader reader = XmlReader.Create(file); + XDocument document = XDocument.Load(reader); + var timesNode = document.Descendants(document.Root.GetDefaultNamespace() + "Times").FirstOrDefault(); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("creation").FirstOrDefault().Value)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("start").FirstOrDefault().Value)); + var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").FirstOrDefault(); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("endTime").FirstOrDefault().Value)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("startTime").FirstOrDefault().Value)); } [TestMethod] @@ -891,23 +893,19 @@ private void ValidateTestIdAndNameInTrx(bool isMstestAdapter) private void ValidateResultAttributesInTrx(string trxFileName, Guid testId, string testName, bool isMstestAdapter) { - using (FileStream file = File.OpenRead(trxFileName)) + using FileStream file = File.OpenRead(trxFileName); + using XmlReader reader = XmlReader.Create(file); + XDocument document = XDocument.Load(reader); + var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").FirstOrDefault(); + if (isMstestAdapter) { - using (XmlReader reader = XmlReader.Create(file)) - { - XDocument document = XDocument.Load(reader); - var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").FirstOrDefault(); - if (isMstestAdapter) - { - Assert.AreNotEqual(resultNode.Attributes("testId").FirstOrDefault().Value, testId.ToString()); - Assert.AreNotEqual(resultNode.Attributes("testName").FirstOrDefault().Value, testName); - } - else - { - Assert.AreEqual(resultNode.Attributes("testId").FirstOrDefault().Value, testId.ToString()); - Assert.AreEqual(resultNode.Attributes("testName").FirstOrDefault().Value, testName); - } - } + Assert.AreNotEqual(resultNode.Attributes("testId").FirstOrDefault().Value, testId.ToString()); + Assert.AreNotEqual(resultNode.Attributes("testName").FirstOrDefault().Value, testName); + } + else + { + Assert.AreEqual(resultNode.Attributes("testId").FirstOrDefault().Value, testId.ToString()); + Assert.AreEqual(resultNode.Attributes("testName").FirstOrDefault().Value, testName); } } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs index c02f0db37a..7e746fb3ae 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/DataCollector/Events/SessionEventsTests.cs @@ -14,9 +14,11 @@ public class SessionEventsTests public SessionEventsTests() { - var properties = new Dictionary(); - properties.Add("property1", 1); - properties.Add("property2", 2); + var properties = new Dictionary + { + { "property1", 1 }, + { "property2", 2 } + }; this.sessionStartEventArgs = new SessionStartEventArgs(properties); } diff --git a/test/Microsoft.TestPlatform.SmokeTests/DotnetHostArchitectureVerifierTests.cs b/test/Microsoft.TestPlatform.SmokeTests/DotnetHostArchitectureVerifierTests.cs index 24896d47f2..48d9a42ee4 100644 --- a/test/Microsoft.TestPlatform.SmokeTests/DotnetHostArchitectureVerifierTests.cs +++ b/test/Microsoft.TestPlatform.SmokeTests/DotnetHostArchitectureVerifierTests.cs @@ -20,30 +20,29 @@ public class DotnetHostArchitectureVerifierTests : IntegrationTestBase [DataRow("X86")] public void VerifyHostArchitecture(string architecture) { - using (Workspace workSpace = new Workspace(GetResultsDirectory())) - { - string dotnetPath = GetDownloadedDotnetMuxerFromTools(architecture); - var vstestConsolePath = GetDotnetRunnerPath(); - var dotnetRunnerPath = workSpace.CreateDirectory("dotnetrunner"); - workSpace.CopyAll(new DirectoryInfo(Path.GetDirectoryName(vstestConsolePath)), dotnetRunnerPath); + using Workspace workSpace = new Workspace(GetResultsDirectory()); + string dotnetPath = GetDownloadedDotnetMuxerFromTools(architecture); + var vstestConsolePath = GetDotnetRunnerPath(); + var dotnetRunnerPath = workSpace.CreateDirectory("dotnetrunner"); + workSpace.CopyAll(new DirectoryInfo(Path.GetDirectoryName(vstestConsolePath)), dotnetRunnerPath); - // Patch the runner - string sdkVersion = GetLatestSdkVersion(dotnetPath); - string runtimeConfigFile = Path.Combine(dotnetRunnerPath.FullName, "vstest.console.runtimeconfig.json"); - JObject patchRuntimeConfig = JObject.Parse(File.ReadAllText(runtimeConfigFile)); - patchRuntimeConfig["runtimeOptions"]["framework"]["version"] = sdkVersion; - File.WriteAllText(runtimeConfigFile, patchRuntimeConfig.ToString()); + // Patch the runner + string sdkVersion = GetLatestSdkVersion(dotnetPath); + string runtimeConfigFile = Path.Combine(dotnetRunnerPath.FullName, "vstest.console.runtimeconfig.json"); + JObject patchRuntimeConfig = JObject.Parse(File.ReadAllText(runtimeConfigFile)); + patchRuntimeConfig["runtimeOptions"]["framework"]["version"] = sdkVersion; + File.WriteAllText(runtimeConfigFile, patchRuntimeConfig.ToString()); - var environmentVariables = new Dictionary - { - ["DOTNET_MULTILEVEL_LOOKUP"] = "0", - ["ExpectedArchitecture"] = architecture - }; + var environmentVariables = new Dictionary + { + ["DOTNET_MULTILEVEL_LOOKUP"] = "0", + ["ExpectedArchitecture"] = architecture + }; - this.ExecuteApplication(dotnetPath, "new mstest", out string stdOut, out string stdError, out int exitCode, environmentVariables, workSpace.Path); + this.ExecuteApplication(dotnetPath, "new mstest", out string stdOut, out string stdError, out int exitCode, environmentVariables, workSpace.Path); - // Patch test file - File.WriteAllText(Path.Combine(workSpace.Path, "UnitTest1.cs"), + // Patch test file + File.WriteAllText(Path.Combine(workSpace.Path, "UnitTest1.cs"), @" using Microsoft.VisualStudio.TestTools.UnitTesting; using System; @@ -60,9 +59,8 @@ public void TestMethod1() } }"); - this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\"", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); - Assert.AreEqual(0, exitCode, stdOut); - } + this.ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\"", out stdOut, out stdError, out exitCode, environmentVariables, workSpace.Path); + Assert.AreEqual(0, exitCode, stdOut); } private string GetLatestSdkVersion(string dotnetPath) diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs index 4154f06f72..0c87818e53 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs @@ -604,79 +604,77 @@ protected void ExecuteApplication(string path, string args, out string stdOut, o var executableName = Path.GetFileName(path); - using (Process process = new Process()) - { - Console.WriteLine($"IntegrationTestBase.Execute: Starting {executableName}"); - process.StartInfo.FileName = path; - process.StartInfo.Arguments = args; - process.StartInfo.UseShellExecute = false; - process.StartInfo.RedirectStandardError = true; - process.StartInfo.RedirectStandardOutput = true; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.StandardOutputEncoding = Encoding.UTF8; - process.StartInfo.StandardErrorEncoding = Encoding.UTF8; - - if (workingDirectory != null) - { - process.StartInfo.WorkingDirectory = workingDirectory; - } + using Process process = new Process(); + Console.WriteLine($"IntegrationTestBase.Execute: Starting {executableName}"); + process.StartInfo.FileName = path; + process.StartInfo.Arguments = args; + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.CreateNoWindow = true; + process.StartInfo.StandardOutputEncoding = Encoding.UTF8; + process.StartInfo.StandardErrorEncoding = Encoding.UTF8; + + if (workingDirectory != null) + { + process.StartInfo.WorkingDirectory = workingDirectory; + } - if (environmentVariables != null) + if (environmentVariables != null) + { + foreach (var variable in environmentVariables) { - foreach (var variable in environmentVariables) + if (process.StartInfo.EnvironmentVariables.ContainsKey(variable.Key)) { - if (process.StartInfo.EnvironmentVariables.ContainsKey(variable.Key)) - { - process.StartInfo.EnvironmentVariables[variable.Key] = variable.Value; - } - else - { - process.StartInfo.EnvironmentVariables.Add(variable.Key, variable.Value); - } + process.StartInfo.EnvironmentVariables[variable.Key] = variable.Value; + } + else + { + process.StartInfo.EnvironmentVariables.Add(variable.Key, variable.Value); } } + } - var stdoutBuffer = new StringBuilder(); - var stderrBuffer = new StringBuilder(); - process.OutputDataReceived += (sender, eventArgs) => - { - stdoutBuffer.AppendLine(eventArgs.Data); - }; + var stdoutBuffer = new StringBuilder(); + var stderrBuffer = new StringBuilder(); + process.OutputDataReceived += (sender, eventArgs) => + { + stdoutBuffer.AppendLine(eventArgs.Data); + }; - process.ErrorDataReceived += (sender, eventArgs) => stderrBuffer.AppendLine(eventArgs.Data); + process.ErrorDataReceived += (sender, eventArgs) => stderrBuffer.AppendLine(eventArgs.Data); - Console.WriteLine("IntegrationTestBase.Execute: Path = {0}", process.StartInfo.FileName); - Console.WriteLine("IntegrationTestBase.Execute: Arguments = {0}", process.StartInfo.Arguments); + Console.WriteLine("IntegrationTestBase.Execute: Path = {0}", process.StartInfo.FileName); + Console.WriteLine("IntegrationTestBase.Execute: Arguments = {0}", process.StartInfo.Arguments); - Stopwatch stopwatch = new Stopwatch(); - stopwatch.Start(); + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); - process.Start(); - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - if (!process.WaitForExit(5 * 60 * 1000)) // 5 minutes - { - Console.WriteLine($"IntegrationTestBase.Execute: Timed out waiting for {executableName}. Terminating the process."); - process.Kill(); - } - else - { - // Ensure async buffers are flushed - process.WaitForExit(); - } + process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + if (!process.WaitForExit(5 * 60 * 1000)) // 5 minutes + { + Console.WriteLine($"IntegrationTestBase.Execute: Timed out waiting for {executableName}. Terminating the process."); + process.Kill(); + } + else + { + // Ensure async buffers are flushed + process.WaitForExit(); + } - stopwatch.Stop(); + stopwatch.Stop(); - Console.WriteLine($"IntegrationTestBase.Execute: Total execution time: {stopwatch.Elapsed.Duration()}"); + Console.WriteLine($"IntegrationTestBase.Execute: Total execution time: {stopwatch.Elapsed.Duration()}"); - stdError = stderrBuffer.ToString(); - stdOut = stdoutBuffer.ToString(); - exitCode = process.ExitCode; + stdError = stderrBuffer.ToString(); + stdOut = stdoutBuffer.ToString(); + exitCode = process.ExitCode; - Console.WriteLine("IntegrationTestBase.Execute: stdError = {0}", stdError); - Console.WriteLine("IntegrationTestBase.Execute: stdOut = {0}", stdOut); - Console.WriteLine($"IntegrationTestBase.Execute: Stopped {executableName}. Exit code = {0}", exitCode); - } + Console.WriteLine("IntegrationTestBase.Execute: stdError = {0}", stdError); + Console.WriteLine("IntegrationTestBase.Execute: stdOut = {0}", stdOut); + Console.WriteLine($"IntegrationTestBase.Execute: Stopped {executableName}. Exit code = {0}", exitCode); } private void FormatStandardOutCome() diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs index a56217f37d..3c55ec9b0b 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs @@ -278,25 +278,23 @@ private static Dictionary GetDependencies(string testPlatformRoo using (var reader = XmlReader.Create(dependencyPropsFile)) { reader.ReadToFollowing("PropertyGroup"); - using (var props = reader.ReadSubtree()) + using var props = reader.ReadSubtree(); + props.MoveToContent(); + props.Read(); // Read thru the PropertyGroup node + while (!props.EOF) { - props.MoveToContent(); - props.Read(); // Read thru the PropertyGroup node - while (!props.EOF) + if (props.IsStartElement() && !string.IsNullOrEmpty(props.Name)) { - if (props.IsStartElement() && !string.IsNullOrEmpty(props.Name)) + if (!dependencyProps.ContainsKey(props.Name)) { - if (!dependencyProps.ContainsKey(props.Name)) - { - dependencyProps.Add(props.Name, props.ReadElementContentAsString()); - } - else - { - dependencyProps[props.Name] = string.Join(", ", dependencyProps[props.Name], props.ReadElementContentAsString()); - } + dependencyProps.Add(props.Name, props.ReadElementContentAsString()); + } + else + { + dependencyProps[props.Name] = string.Join(", ", dependencyProps[props.Name], props.ReadElementContentAsString()); } - props.Read(); } + props.Read(); } } diff --git a/test/Microsoft.TestPlatform.TestUtilities/PerfInstrumentation/PerfAnalyzer.cs b/test/Microsoft.TestPlatform.TestUtilities/PerfInstrumentation/PerfAnalyzer.cs index 2cc24960b6..55da96f80e 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/PerfInstrumentation/PerfAnalyzer.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/PerfInstrumentation/PerfAnalyzer.cs @@ -68,44 +68,41 @@ public void DisableProvider() public void AnalyzeEventsData() { #if NETFRAMEWORK - using (var source = new ETWTraceEventSource(this.perfDataFileName)) - { - // Open the file - var parser = new DynamicTraceEventParser(source); - parser.All += delegate(TraceEvent data) + using var source = new ETWTraceEventSource(this.perfDataFileName); + // Open the file + var parser = new DynamicTraceEventParser(source); + parser.All += delegate (TraceEvent data) { + try + { + if (data.ProviderName.Equals("TestPlatform") && !data.EventName.Equals("ManifestData")) { - try + Console.WriteLine("Received Event : {0}", data.ToString()); + var key = data.ProcessID + "_" + data.ThreadID.ToString() + "_" + data.TaskName; + + if (!testPlatformTaskMap.ContainsKey(key)) { - if (data.ProviderName.Equals("TestPlatform") && !data.EventName.Equals("ManifestData")) - { - Console.WriteLine("Received Event : {0}", data.ToString()); - var key = data.ProcessID + "_" + data.ThreadID.ToString() + "_" + data.TaskName; - - if (!testPlatformTaskMap.ContainsKey(key)) - { - var list = new List { CreateTestPlatformTask(data) }; - testPlatformTaskMap.Add(key, list); - } - else - { - if (data.Opcode == TraceEventOpcode.Start) - { - testPlatformTaskMap[key].Add(CreateTestPlatformTask(data)); - } - else - { - UpdateTask(testPlatformTaskMap[key].Last(), data); - } - } - } + var list = new List { CreateTestPlatformTask(data) }; + testPlatformTaskMap.Add(key, list); } - catch (Exception ex) + else { - Console.WriteLine(ex.ToString()); + if (data.Opcode == TraceEventOpcode.Start) + { + testPlatformTaskMap[key].Add(CreateTestPlatformTask(data)); + } + else + { + UpdateTask(testPlatformTaskMap[key].Last(), data); + } } - }; - source.Process(); // Read the file, processing the callbacks. - } + } + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + }; + source.Process(); // Read the file, processing the callbacks. #endif } diff --git a/test/SettingsMigrator.UnitTests/MigratorTests.cs b/test/SettingsMigrator.UnitTests/MigratorTests.cs index 4fe25372a7..6589d28920 100644 --- a/test/SettingsMigrator.UnitTests/MigratorTests.cs +++ b/test/SettingsMigrator.UnitTests/MigratorTests.cs @@ -82,15 +82,13 @@ public void MigratorGeneratesCorrectRunsettingsWithDC() this.migrator.Migrate(this.oldRunsettingsPath, this.newRunsettingsPath); - using (XmlTextReader reader = new XmlTextReader(this.newRunsettingsPath)) - { - reader.Namespaces = false; - var document = new XmlDocument(); - document.Load(reader); - var root = document.DocumentElement; - var dataCollectorNode = root.SelectNodes(@"/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); - Assert.AreEqual(2, dataCollectorNode.Count, "Data collector is missing"); - } + using XmlTextReader reader = new XmlTextReader(this.newRunsettingsPath); + reader.Namespaces = false; + var document = new XmlDocument(); + document.Load(reader); + var root = document.DocumentElement; + var dataCollectorNode = root.SelectNodes(@"/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); + Assert.AreEqual(2, dataCollectorNode.Count, "Data collector is missing"); } [TestMethod] @@ -128,48 +126,46 @@ private static void Validate(string newRunsettingsPath) { Assert.IsTrue(File.Exists(newRunsettingsPath), "Run settings should be generated."); - using (XmlTextReader reader = new XmlTextReader(newRunsettingsPath)) - { - reader.Namespaces = false; + using XmlTextReader reader = new XmlTextReader(newRunsettingsPath); + reader.Namespaces = false; - var document = new XmlDocument(); - document.Load(reader); - var root = document.DocumentElement; + var document = new XmlDocument(); + document.Load(reader); + var root = document.DocumentElement; - Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/WebTestRunConfiguration/Browser/Headers/Header"), "There should be a WebTestRunConfiguration node"); - Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings"), "There should be a LegacySettings node"); - Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings/Deployment/DeploymentItem"), "There should be a DeploymentItem node"); + Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/WebTestRunConfiguration/Browser/Headers/Header"), "There should be a WebTestRunConfiguration node"); + Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings"), "There should be a LegacySettings node"); + Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings/Deployment/DeploymentItem"), "There should be a DeploymentItem node"); - var scriptNode = root.SelectSingleNode(@"/RunSettings/LegacySettings/Scripts"); - Assert.IsNotNull(scriptNode, "There should be a WebTestRunConfiguration node"); - Assert.AreEqual(".\\setup.bat", scriptNode.Attributes["setupScript"].Value, "setupScript does not match."); - Assert.AreEqual(".\\cleanup.bat", scriptNode.Attributes["cleanupScript"].Value, "cleanupScript does not match."); + var scriptNode = root.SelectSingleNode(@"/RunSettings/LegacySettings/Scripts"); + Assert.IsNotNull(scriptNode, "There should be a WebTestRunConfiguration node"); + Assert.AreEqual(".\\setup.bat", scriptNode.Attributes["setupScript"].Value, "setupScript does not match."); + Assert.AreEqual(".\\cleanup.bat", scriptNode.Attributes["cleanupScript"].Value, "cleanupScript does not match."); - var forcedLegacyNode = root.SelectSingleNode(@"/RunSettings/MSTest/ForcedLegacyMode"); - Assert.IsNotNull(forcedLegacyNode, "ForcedLegacy node should be present"); - Assert.AreEqual("true", forcedLegacyNode.InnerText, "Forced legacy should be true"); + var forcedLegacyNode = root.SelectSingleNode(@"/RunSettings/MSTest/ForcedLegacyMode"); + Assert.IsNotNull(forcedLegacyNode, "ForcedLegacy node should be present"); + Assert.AreEqual("true", forcedLegacyNode.InnerText, "Forced legacy should be true"); - var executionNode = root.SelectSingleNode(@" / RunSettings/LegacySettings/Execution"); - Assert.IsNotNull(executionNode, "There should be a Execution node"); - Assert.AreEqual("2", executionNode.Attributes["parallelTestCount"].Value, "parallelTestCount value does not match."); - Assert.AreEqual("MSIL", executionNode.Attributes["hostProcessPlatform"].Value, "hostProcessPlatform value does not match."); + var executionNode = root.SelectSingleNode(@" / RunSettings/LegacySettings/Execution"); + Assert.IsNotNull(executionNode, "There should be a Execution node"); + Assert.AreEqual("2", executionNode.Attributes["parallelTestCount"].Value, "parallelTestCount value does not match."); + Assert.AreEqual("MSIL", executionNode.Attributes["hostProcessPlatform"].Value, "hostProcessPlatform value does not match."); - Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings/Execution/Hosts"), "There should be a Hosts node"); + Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings/Execution/Hosts"), "There should be a Hosts node"); - var timeoutNode = root.SelectSingleNode(@"/RunSettings/LegacySettings/Execution/Timeouts"); - Assert.IsNotNull(timeoutNode, "There should be a Timeouts node"); - Assert.AreEqual("120000", timeoutNode.Attributes["testTimeout"].Value, "testTimeout value does not match."); + var timeoutNode = root.SelectSingleNode(@"/RunSettings/LegacySettings/Execution/Timeouts"); + Assert.IsNotNull(timeoutNode, "There should be a Timeouts node"); + Assert.AreEqual("120000", timeoutNode.Attributes["testTimeout"].Value, "testTimeout value does not match."); - Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings/Execution/TestTypeSpecific/UnitTestRunConfig/AssemblyResolution/TestDirectory"), "There should be a Assembly resolution node"); + Assert.IsNotNull(root.SelectSingleNode(@"/RunSettings/LegacySettings/Execution/TestTypeSpecific/UnitTestRunConfig/AssemblyResolution/TestDirectory"), "There should be a Assembly resolution node"); - var testSessionTimeoutNode = root.SelectSingleNode(@"/RunSettings/RunConfiguration/TestSessionTimeout"); - Assert.IsNotNull(testSessionTimeoutNode, "There should be a TestSessionTimeout node"); - Assert.AreEqual("60000", testSessionTimeoutNode.InnerText, "Timeout value does not match."); + var testSessionTimeoutNode = root.SelectSingleNode(@"/RunSettings/RunConfiguration/TestSessionTimeout"); + Assert.IsNotNull(testSessionTimeoutNode, "There should be a TestSessionTimeout node"); + Assert.AreEqual("60000", testSessionTimeoutNode.InnerText, "Timeout value does not match."); - var dataCollectorNode = root.SelectSingleNode(@"/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); - Assert.IsNotNull(dataCollectorNode, "There should be a DataCollector node"); - Assert.AreEqual("Event Log", dataCollectorNode.Attributes["friendlyName"].Value, "Data collector does not match."); - } + var dataCollectorNode = root.SelectSingleNode(@"/RunSettings/DataCollectionRunSettings/DataCollectors/DataCollector"); + Assert.IsNotNull(dataCollectorNode, "There should be a DataCollector node"); + Assert.AreEqual("Event Log", dataCollectorNode.Attributes["friendlyName"].Value, "Data collector does not match."); } } } diff --git a/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs b/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs index 4040508d97..f5fc7f113a 100644 --- a/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs +++ b/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs @@ -49,14 +49,12 @@ public void BeforeTestRunStartShouldGetEnviornmentVariables() { var dataCollectionRequestSender = new DataCollectionRequestSender(); - using (var proxyDataCollectionManager = new ProxyDataCollectionManager(this.mockRequestData.Object, this.runSettings, this.testSources, dataCollectionRequestSender, this.processHelper, this.dataCollectionLauncher)) - { - proxyDataCollectionManager.Initialize(); + using var proxyDataCollectionManager = new ProxyDataCollectionManager(this.mockRequestData.Object, this.runSettings, this.testSources, dataCollectionRequestSender, this.processHelper, this.dataCollectionLauncher); + proxyDataCollectionManager.Initialize(); - var result = proxyDataCollectionManager.BeforeTestRunStart(true, true, this.mockTestMessageEventHandler.Object); + var result = proxyDataCollectionManager.BeforeTestRunStart(true, true, this.mockTestMessageEventHandler.Object); - Assert.AreEqual(1, result.EnvironmentVariables.Count); - } + Assert.AreEqual(1, result.EnvironmentVariables.Count); } [TestMethod] @@ -64,18 +62,16 @@ public void AfterTestRunShouldSendGetAttachments() { var dataCollectionRequestSender = new DataCollectionRequestSender(); - using (var proxyDataCollectionManager = new ProxyDataCollectionManager(this.mockRequestData.Object, this.runSettings, this.testSources, dataCollectionRequestSender, this.processHelper, this.dataCollectionLauncher)) - { - proxyDataCollectionManager.Initialize(); + using var proxyDataCollectionManager = new ProxyDataCollectionManager(this.mockRequestData.Object, this.runSettings, this.testSources, dataCollectionRequestSender, this.processHelper, this.dataCollectionLauncher); + proxyDataCollectionManager.Initialize(); - proxyDataCollectionManager.BeforeTestRunStart(true, true, this.mockTestMessageEventHandler.Object); + proxyDataCollectionManager.BeforeTestRunStart(true, true, this.mockTestMessageEventHandler.Object); - var dataCollectionResult = proxyDataCollectionManager.AfterTestRunEnd(false, this.mockTestMessageEventHandler.Object); + var dataCollectionResult = proxyDataCollectionManager.AfterTestRunEnd(false, this.mockTestMessageEventHandler.Object); - Assert.AreEqual("CustomDataCollector", dataCollectionResult.Attachments[0].DisplayName); - Assert.AreEqual("my://custom/datacollector", dataCollectionResult.Attachments[0].Uri.ToString()); - Assert.IsTrue(dataCollectionResult.Attachments[0].Attachments[0].Uri.ToString().Contains("filename.txt")); - } + Assert.AreEqual("CustomDataCollector", dataCollectionResult.Attachments[0].DisplayName); + Assert.AreEqual("my://custom/datacollector", dataCollectionResult.Attachments[0].Uri.ToString()); + Assert.IsTrue(dataCollectionResult.Attachments[0].Attachments[0].Uri.ToString().Contains("filename.txt")); } [TestMethod] @@ -85,23 +81,21 @@ public void AfterTestRunShouldHandleSocketFailureGracefully() var dataCollectionRequestSender = new DataCollectionRequestSender(socketCommManager, JsonDataSerializer.Instance); var dataCollectionLauncher = DataCollectionLauncherFactory.GetDataCollectorLauncher(this.processHelper, this.runSettings); - using (var proxyDataCollectionManager = new ProxyDataCollectionManager(this.mockRequestData.Object, this.runSettings, this.testSources, dataCollectionRequestSender, this.processHelper, dataCollectionLauncher)) - { - proxyDataCollectionManager.Initialize(); - proxyDataCollectionManager.BeforeTestRunStart(true, true, this.mockTestMessageEventHandler.Object); + using var proxyDataCollectionManager = new ProxyDataCollectionManager(this.mockRequestData.Object, this.runSettings, this.testSources, dataCollectionRequestSender, this.processHelper, dataCollectionLauncher); + proxyDataCollectionManager.Initialize(); + proxyDataCollectionManager.BeforeTestRunStart(true, true, this.mockTestMessageEventHandler.Object); - var result = Process.GetProcessById(dataCollectionLauncher.DataCollectorProcessId); - Assert.IsNotNull(result); + var result = Process.GetProcessById(dataCollectionLauncher.DataCollectorProcessId); + Assert.IsNotNull(result); - socketCommManager.StopClient(); + socketCommManager.StopClient(); - var attachments = proxyDataCollectionManager.AfterTestRunEnd(false, this.mockTestMessageEventHandler.Object); + var attachments = proxyDataCollectionManager.AfterTestRunEnd(false, this.mockTestMessageEventHandler.Object); - Assert.IsNull(attachments); + Assert.IsNull(attachments); - // Give time to datacollector process to exit. - Assert.IsTrue(result.WaitForExit(500)); - } + // Give time to datacollector process to exit. + Assert.IsTrue(result.WaitForExit(500)); } } } \ No newline at end of file diff --git a/test/vstest.console.UnitTests/CommandLine/TestRunResultAggregatorTests.cs b/test/vstest.console.UnitTests/CommandLine/TestRunResultAggregatorTests.cs index 5795a32591..9ca435ffa7 100644 --- a/test/vstest.console.UnitTests/CommandLine/TestRunResultAggregatorTests.cs +++ b/test/vstest.console.UnitTests/CommandLine/TestRunResultAggregatorTests.cs @@ -67,8 +67,10 @@ public void TestRunCompletionHandlerForTestRunStatisticsNullSetsOutcomeToFailed( [TestMethod] public void TestRunCompletionHandlerForTestRunStatsWithOneOrMoreFailingTestsSetsOutcomeToFailed() { - var testOutcomeDict = new System.Collections.Generic.Dictionary(); - testOutcomeDict.Add(TestOutcome.Failed, 1); + var testOutcomeDict = new System.Collections.Generic.Dictionary + { + { TestOutcome.Failed, 1 } + }; var stats = new TestableTestRunStats(testOutcomeDict); var messageArgs = new TestRunCompleteEventArgs(stats, false, false, null, null, null, new TimeSpan()); @@ -79,8 +81,10 @@ public void TestRunCompletionHandlerForTestRunStatsWithOneOrMoreFailingTestsSets [TestMethod] public void TestRunCompletionHandlerForCanceledRunShouldSetsOutcomeToFailed() { - var testOutcomeDict = new System.Collections.Generic.Dictionary(); - testOutcomeDict.Add(TestOutcome.Passed, 1); + var testOutcomeDict = new System.Collections.Generic.Dictionary + { + { TestOutcome.Passed, 1 } + }; var stats = new TestableTestRunStats(testOutcomeDict); var messageArgs = new TestRunCompleteEventArgs(stats, true, false, null, null, null, new TimeSpan()); @@ -91,8 +95,10 @@ public void TestRunCompletionHandlerForCanceledRunShouldSetsOutcomeToFailed() [TestMethod] public void TestRunCompletionHandlerForAbortedRunShouldSetsOutcomeToFailed() { - var testOutcomeDict = new System.Collections.Generic.Dictionary(); - testOutcomeDict.Add(TestOutcome.Passed, 1); + var testOutcomeDict = new System.Collections.Generic.Dictionary + { + { TestOutcome.Passed, 1 } + }; var stats = new TestableTestRunStats(testOutcomeDict); var messageArgs = new TestRunCompleteEventArgs(stats, false, true, null, null, null, new TimeSpan()); diff --git a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs index 91f7e136a2..45d79ed8a4 100644 --- a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs +++ b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs @@ -220,8 +220,10 @@ private void SetupForTestMessageHandler(out InternalTestLoggerEvents loggerEvent { loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); } @@ -461,8 +463,10 @@ public void TestResultHandlerShouldShowStdErrMessagesBannerIfStdErrIsNotEmpty() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testcase = new TestCase("TestName", new Uri("some://uri"), "TestSource"); @@ -511,8 +515,10 @@ public void TestResultHandlerShouldShowAdditionalInfoBannerIfAdditionalInfoIsNot { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testcase = new TestCase("TestName", new Uri("some://uri"), "TestSource"); @@ -563,8 +569,10 @@ public void TestResultHandlerShouldShowPassedTestsForNormalVebosity() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); foreach (var testResult in this.GetTestResultsObject()) @@ -673,8 +681,10 @@ public void TestResultHandlerShouldNotShowNotStdOutMsgOfPassedTestIfVerbosityIsN { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testcase = new TestCase("TestName", new Uri("some://uri"), "TestSource"); @@ -698,8 +708,10 @@ public void TestResultHandlerShouldNotShowDbgTrcMsg() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testcase = new TestCase("TestName", new Uri("some://uri"), "TestSource"); @@ -780,8 +792,10 @@ public void TestResultHandlerForTestResultWithDurationShouldPrintDurationInfo(st { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var TestResultWithHrMinSecMs = new ObjectModel.TestResult(new TestCase("DymmyNamespace.DummyClass.TestName", new Uri("some://uri"), "TestSource") { DisplayName = "TestName" }) { @@ -801,8 +815,10 @@ public void TestResultHandlerForTestResultWithDurationLessThanOneMsShouldPrintDu { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var TestResultWithHrMinSecMs = new ObjectModel.TestResult(new TestCase("DymmyNamespace.DummyClass.TestName", new Uri("some://uri"), "TestSource") { DisplayName = "TestName" }) { @@ -822,8 +838,10 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsPass() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); foreach (var testResult in this.GetTestResultObject(TestOutcome.Passed)) @@ -845,8 +863,10 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsFail() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); foreach (var testResult in this.GetTestResultObject(TestOutcome.Failed)) @@ -891,8 +911,10 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsCanceledWithoutRunn { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); loggerEvents.CompleteTestRun(null, true, false, null, null, null, new TimeSpan(1, 0, 0, 0)); @@ -905,8 +927,10 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsAborted() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); foreach (var testResult in this.GetTestResultObject(TestOutcome.Failed)) @@ -924,8 +948,10 @@ public void TestRunCompleteHandlerShouldWriteToConsoleIfTestsAbortedWithoutRunni { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); loggerEvents.CompleteTestRun(null, false, true, null, null, null, new TimeSpan(1, 0, 0, 0)); @@ -948,8 +974,10 @@ public void TestRunStartHandlerShouldWriteNumberOfTestSourcesDiscoveredOnConsole CommandLineOptions.Instance.AddSource(testFilePath); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testRunStartEventArgs = new TestRunStartEventArgs(new TestRunCriteria(new List { testFilePath }, 1)); @@ -978,8 +1006,10 @@ public void TestRunStartHandlerShouldWriteTestSourcesDiscoveredOnConsoleIfVerbos CommandLineOptions.Instance.AddSource(testFilePath); CommandLineOptions.Instance.AddSource(testFilePath2); - var parameters = new Dictionary(); - parameters.Add("verbosity", "detailed"); + var parameters = new Dictionary + { + { "verbosity", "detailed" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testRunStartEventArgs = new TestRunStartEventArgs(new TestRunCriteria(new List { testFilePath }, 1)); @@ -1010,8 +1040,10 @@ public void TestRunStartHandlerShouldNotWriteTestSourcesDiscoveredOnConsoleIfVer CommandLineOptions.Instance.AddSource(testFilePath); CommandLineOptions.Instance.AddSource(testFilePath2); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testRunStartEventArgs = new TestRunStartEventArgs(new TestRunCriteria(new List { testFilePath }, 1)); @@ -1028,8 +1060,10 @@ public void PrintTimeHandlerShouldPrintElapsedTimeOnConsole() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); foreach (var testResult in this.GetTestResultObject(TestOutcome.Passed)) @@ -1053,8 +1087,10 @@ public void DisplayFullInformationShouldWriteErrorMessageAndStackTraceToConsole( { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testresults = this.GetTestResultObject(TestOutcome.Failed); @@ -1077,8 +1113,10 @@ public void DisplayFullInformationShouldWriteStdMessageWithNewLine() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "detailed"); + var parameters = new Dictionary + { + { "verbosity", "detailed" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testresults = this.GetTestResultObject(TestOutcome.Passed); @@ -1101,8 +1139,10 @@ public void GetTestMessagesShouldWriteMessageAndStackTraceToConsole() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var testresults = this.GetTestResultObject(TestOutcome.Failed); @@ -1136,8 +1176,10 @@ public void AttachmentInformationShouldBeWrittenToConsoleIfAttachmentsArePresent { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", verbosityLevel); + var parameters = new Dictionary + { + { "verbosity", verbosityLevel } + }; this.consoleLogger.Initialize(loggerEvents, parameters); var attachmentSet = new AttachmentSet(new Uri("test://uri"), "myattachmentset"); @@ -1160,8 +1202,10 @@ public void ResultsInHeirarchichalOrderShouldReportCorrectCount() { var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - var parameters = new Dictionary(); - parameters.Add("verbosity", "normal"); + var parameters = new Dictionary + { + { "verbosity", "normal" } + }; this.consoleLogger.Initialize(loggerEvents, parameters); TestCase testCase1 = CreateTestCase("TestCase1"); diff --git a/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs index 63309d5341..ea68b12b50 100644 --- a/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ListFullyQualifiedTestsArgumentProcessorTests.cs @@ -310,9 +310,11 @@ private void RunListFullyQualifiedTestArgumentProcessorWithTraits(Mock mockDiscoveryRequest, Mock mockConsoleOutput, bool legitPath = true) { var mockTestPlatform = new Mock(); - var list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + var list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockDiscoveryRequest.Object); diff --git a/test/vstest.console.UnitTests/Processors/ListTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ListTestsArgumentProcessorTests.cs index 8c00ed0477..dd6f84f324 100644 --- a/test/vstest.console.UnitTests/Processors/ListTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ListTestsArgumentProcessorTests.cs @@ -257,9 +257,11 @@ public void ListTestArgumentProcessorExecuteShouldInstrumentDiscoveryRequestStop private void RunListTestArgumentProcessorExecuteWithMockSetup(Mock mockDiscoveryRequest, Mock mockConsoleOutput) { var mockTestPlatform = new Mock(); - var list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + var list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockDiscoveryRequest.Object); diff --git a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs index b100a49197..7b97eca643 100644 --- a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs @@ -185,9 +185,11 @@ public void ExecutorExecuteForValidSourceWithTestCaseFilterShouldRunTests() this.ResetAndAddSourceToCommandLineOptions(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -267,9 +269,11 @@ public void ExecutorExecuteShouldThrowTestPlatformExceptionThrownDuringExecution var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(dr => dr.ExecuteAsync()).Throws(new TestPlatformException("DummyTestPlatformException")); @@ -292,9 +296,11 @@ public void ExecutorExecuteShouldThrowSettingsExceptionThrownDuringExecution() var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(dr => dr.ExecuteAsync()).Throws(new SettingsException("DummySettingsException")); @@ -317,9 +323,11 @@ public void ExecutorExecuteShouldThrowInvalidOperationExceptionThrownDuringExecu var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(dr => dr.ExecuteAsync()).Throws(new InvalidOperationException("DummySettingsException")); @@ -390,8 +398,10 @@ public void ExecutorExecuteShouldForValidSourcesAndValidSelectedTestsRunsTestsAn this.ResetAndAddSourceToCommandLineOptions(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -415,9 +425,11 @@ public void ExecutorShouldRunTestsWhenTestsAreCommaSeparated() ResetAndAddSourceToCommandLineOptions(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -442,9 +454,11 @@ public void ExecutorShouldRunTestsWhenTestsAreFiltered() ResetAndAddSourceToCommandLineOptions(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -469,8 +483,10 @@ public void ExecutorShouldWarnWhenTestsAreNotAvailable() ResetAndAddSourceToCommandLineOptions(); - List list = new List(); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1")); + List list = new List + { + new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -495,9 +511,11 @@ public void ExecutorShouldRunTestsWhenTestsAreCommaSeparatedWithEscape() ResetAndAddSourceToCommandLineOptions(); - List list = new List(); - list.Add(new TestCase("Test1(a,b)", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2(c,d)", new Uri("http://FooTestUri1"), "Source1")); + List list = new List + { + new TestCase("Test1(a,b)", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2(c,d)", new Uri("http://FooTestUri1"), "Source1") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateTestRunRequest(It.IsAny(), It.IsAny(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -521,9 +539,11 @@ public void ExecutorShouldDisplayWarningIfNoTestsAreExecuted() var mockDiscoveryRequest = new Mock(); var mockTestRunStats = new Mock(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(tr => tr.ExecuteAsync()).Returns(1).Raises(tr => tr.OnRunCompletion += null, @@ -550,9 +570,11 @@ public void ExecutorShouldNotDisplayWarningIfTestsAreExecuted() var mockDiscoveryRequest = new Mock(); var testRunStats = new TestRunStatistics(1, new Dictionary { { TestOutcome.Passed, 1 } }); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestRunRequest.Setup(tr => tr.ExecuteAsync()).Returns(1).Raises(tr => tr.OnRunCompletion += null, diff --git a/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs index 4a58431e54..c1bdc7c3d1 100644 --- a/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs @@ -244,9 +244,11 @@ private ArgumentProcessorResult RunRunArgumentProcessorExecuteWithMockSetup(ITes var mockTestPlatform = new Mock(); var mockConsoleOutput = new Mock(); - List list = new List(); - list.Add(new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1")); - list.Add(new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2")); + List list = new List + { + new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), + new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") + }; var mockTestRunStats = new Mock(); var args = new TestRunCompleteEventArgs(mockTestRunStats.Object, false, false, null, null, null, new TimeSpan());