diff --git a/shared/NullableAttributes.cs b/shared/NullableAttributes.cs index ded53a2c9f..845ee9bdfa 100644 --- a/shared/NullableAttributes.cs +++ b/shared/NullableAttributes.cs @@ -96,7 +96,7 @@ internal sealed class MemberNotNullAttribute : Attribute /// /// The field or property member that is promised to be not-null. /// - public MemberNotNullAttribute(string member) => Members = new[] { member }; + public MemberNotNullAttribute(string member) => Members = [member]; /// Initializes the attribute with the list of field and property members. /// @@ -122,7 +122,7 @@ internal sealed class MemberNotNullWhenAttribute : Attribute public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; - Members = new[] { member }; + Members = [member]; } /// Initializes the attribute with the specified return value condition and list of field and property members. diff --git a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs index 6d93832971..9296983499 100644 --- a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs +++ b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogDataCollector.cs @@ -326,7 +326,7 @@ protected override void Dispose(bool disposing) private static ISet ParseCommaSeparatedList(string commaSeparatedList) { ISet strings = new HashSet(); - string[] items = commaSeparatedList.Split(new char[] { ',' }); + string[] items = commaSeparatedList.Split([',']); foreach (string item in items) { strings.Add(item.Trim()); diff --git a/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask2.cs b/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask2.cs index 1443725e62..cbc866d928 100644 --- a/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask2.cs +++ b/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask2.cs @@ -48,7 +48,7 @@ public class VSTestTask2 : ToolTask, ITestTask protected override Encoding StandardOutputEncoding => _disableUtf8ConsoleEncoding ? base.StandardOutputEncoding : Encoding.UTF8; private readonly string _messageSplitter = "||||"; - private readonly string[] _messageSplitterArray = new[] { "||||" }; + private readonly string[] _messageSplitterArray = ["||||"]; private readonly string _ansiReset = "\x1b[39;49m"; private readonly bool _disableUtf8ConsoleEncoding; @@ -271,7 +271,7 @@ private bool TryGetMessage(string singleLine, out string name, out string?[] dat } name = string.Empty; - data = Array.Empty(); + data = []; return false; } diff --git a/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs b/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs index b3e59ba1c5..f64f20374e 100644 --- a/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs +++ b/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs @@ -334,7 +334,7 @@ public int LaunchCustomHost(TestProcessStartInfo testProcessStartInfo, Cancellat // Even if TP has a timeout here, there is no way TP can abort or stop the thread/task that is hung in IDE or LUT // Even if TP can abort the API somehow, TP is essentially putting IDEs or Clients in inconsistent state without having info on // Since the IDEs own user-UI-experience here, TP will let the custom host launch as much time as IDEs define it for their users - WaitHandle.WaitAny(new WaitHandle[] { waitHandle, cancellationToken.WaitHandle }); + WaitHandle.WaitAny([waitHandle, cancellationToken.WaitHandle]); cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested(); @@ -387,7 +387,7 @@ public bool AttachDebuggerToProcess(AttachDebuggerInfo attachDebuggerInfo, Cance _communicationManager.SendMessage(MessageType.EditorAttachDebugger2, payload); } - WaitHandle.WaitAny(new WaitHandle[] { waitHandle, cancellationToken.WaitHandle }); + WaitHandle.WaitAny([waitHandle, cancellationToken.WaitHandle]); cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested(); onAttachDebuggerAckRecieved = null; diff --git a/src/Microsoft.TestPlatform.Client/TestPlatform.cs b/src/Microsoft.TestPlatform.Client/TestPlatform.cs index 45ee1303a1..73b7a47627 100644 --- a/src/Microsoft.TestPlatform.Client/TestPlatform.cs +++ b/src/Microsoft.TestPlatform.Client/TestPlatform.cs @@ -283,7 +283,7 @@ private static void AddExtensionAssembliesFromExtensionDirectory() TestAdapterLoadingStrategy strategy = runConfiguration.TestAdapterLoadingStrategy; FileHelper fileHelper = new(); - IEnumerable defaultExtensionPaths = Enumerable.Empty(); + IEnumerable defaultExtensionPaths = []; // Explicit adapter loading if (strategy.HasFlag(TestAdapterLoadingStrategy.Explicit)) @@ -354,7 +354,7 @@ private static IEnumerable ExpandAdaptersWithExplicitStrategy(string pat { if (!strategy.HasFlag(TestAdapterLoadingStrategy.Explicit)) { - return Enumerable.Empty(); + return []; } if (fileHelper.Exists(path)) @@ -377,7 +377,7 @@ private static IEnumerable ExpandAdaptersWithExplicitStrategy(string pat } EqtTrace.Warning($"{nameof(TestPlatform)}.{nameof(ExpandAdaptersWithExplicitStrategy)} AdapterPath Not Found: {path}"); - return Enumerable.Empty(); + return []; } private static IEnumerable ExpandAdaptersWithDefaultStrategy(string path, IFileHelper fileHelper) @@ -388,7 +388,7 @@ private static IEnumerable ExpandAdaptersWithDefaultStrategy(string path { EqtTrace.Warning($"{nameof(TestPlatform)}.{nameof(ExpandAdaptersWithDefaultStrategy)} AdapterPath Not Found: {path}"); - return Enumerable.Empty(); + return []; } return fileHelper.EnumerateFiles( diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs index cec8312fe0..d4e5224d26 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/VSExtensionManager.cs @@ -85,7 +85,7 @@ private IEnumerable GetTestExtensionsInternal(string extensionType) var resolutionPaths = installContext.GetVisualStudioCommonLocations(vsInstallPath); using (var assemblyResolver = new AssemblyResolver(resolutionPaths)) { - var settingsManager = SettingsManagerType.GetMethod("CreateForApplication", new Type[] { typeof(string) })?.Invoke(null, new object[] { installContext.GetVisualStudioPath(vsInstallPath) }); + var settingsManager = SettingsManagerType.GetMethod("CreateForApplication", [typeof(string)])?.Invoke(null, [installContext.GetVisualStudioPath(vsInstallPath)]); if (settingsManager == null) { EqtTrace.Warning("VSExtensionManager : Unable to create settings manager"); @@ -99,8 +99,8 @@ private IEnumerable GetTestExtensionsInternal(string extensionType) if (extensionManager != null) { - installedExtensions = ExtensionManagerServiceType.GetMethod("GetEnabledExtensionContentLocations", new Type[] { typeof(string) })?.Invoke( - extensionManager, new object[] { extensionType }) as IEnumerable; + installedExtensions = ExtensionManagerServiceType.GetMethod("GetEnabledExtensionContentLocations", [typeof(string)])?.Invoke( + extensionManager, [extensionType]) as IEnumerable; } else { diff --git a/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs b/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs index 417d10fae4..a587d1a98d 100644 --- a/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs +++ b/src/Microsoft.TestPlatform.Common/Filtering/FilterExpression.cs @@ -122,7 +122,7 @@ private static void ProcessOperator(Stack filterStack, Operato if (null == properties) { // if null, initialize to empty list so that invalid properties can be found. - properties = Enumerable.Empty(); + properties = []; } return IterateFilterExpression((current, result) => @@ -132,7 +132,7 @@ private static void ProcessOperator(Stack filterStack, Operato { var valid = current._condition.ValidForProperties(properties, propertyProvider); // If it's not valid will add it to the function's return array. - return !valid ? new string[1] { current._condition.Name } : null; + return !valid ? [current._condition.Name] : null; } // Concatenate the children node's result to get their parent result. diff --git a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs index 6181dcd5b4..6682231730 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/AssemblyResolver.cs @@ -40,7 +40,7 @@ internal class AssemblyResolver : IDisposable private readonly IAssemblyLoadContext _platformAssemblyLoadContext; - private static readonly string[] SupportedFileExtensions = { ".dll", ".exe" }; + private static readonly string[] SupportedFileExtensions = [".dll", ".exe"]; /// /// Initializes a new instance of the class. diff --git a/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs index c493b0c380..feac1e682c 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs @@ -231,7 +231,7 @@ private static void EnsureSettingsNode(XmlDocument settings, TestRunSettings set { var assembly = LoadTestPlatformAssembly(); var type = assembly?.GetType(ConfiguratorAssemblyQualifiedName, false); - var method = type?.GetMethod(NetFrameworkConfiguratorMethodName, new Type[] { typeof(IEnumerable) }); + var method = type?.GetMethod(NetFrameworkConfiguratorMethodName, [typeof(IEnumerable)]); if (method != null) { return (Func, string>)method.CreateDelegate(typeof(Func, string>)); @@ -251,7 +251,7 @@ private static void EnsureSettingsNode(XmlDocument settings, TestRunSettings set { var assembly = LoadTestPlatformAssembly(); var type = assembly?.GetType(ConfiguratorAssemblyQualifiedName, false, false); - var method = type?.GetMethod(CrossPlatformConfiguratorMethodName, new Type[] { typeof(IDictionary) }); + var method = type?.GetMethod(CrossPlatformConfiguratorMethodName, [typeof(IDictionary)]); if (method != null) { return (Func, DataCollectorSettings>)method.CreateDelegate(typeof(Func, DataCollectorSettings>)); diff --git a/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs b/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs index 6c0c0bebaa..4783921204 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/InstallationContext.cs @@ -48,13 +48,13 @@ public string GetVisualStudioPath(string visualStudioDirectory) [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Part of the public API")] public string[] GetVisualStudioCommonLocations(string visualStudioDirectory) { - return new[] - { + return + [ Path.Combine(visualStudioDirectory, PrivateAssembliesDirName), Path.Combine(visualStudioDirectory, PublicAssembliesDirName), Path.Combine(visualStudioDirectory, "CommonExtensions", "Microsoft", "TestWindow"), Path.Combine(visualStudioDirectory, "CommonExtensions", "Microsoft", "TeamFoundation", "Team Explorer"), visualStudioDirectory - }; + ]; } } diff --git a/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs b/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs index e515ab5950..a8a6887df7 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/MetadataReaderHelper.cs @@ -42,7 +42,7 @@ internal static class MetadataReaderExtensionsHelper { private const string TestExtensionTypesAttributeV2 = "Microsoft.VisualStudio.TestPlatform.TestExtensionTypesV2Attribute"; private static readonly ConcurrentDictionary AssemblyCache = new(); - private static readonly Type[] EmptyTypeArray = new Type[0]; + private static readonly Type[] EmptyTypeArray = []; public static Type[] DiscoverTestExtensionTypesV2Attribute(Assembly loadedAssembly, string assemblyFilePath) => AssemblyCache.GetOrAdd(assemblyFilePath, DiscoverTestExtensionTypesV2AttributeInternal(loadedAssembly, assemblyFilePath)); diff --git a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs index a66a6ec57b..f9fb02e684 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsUtilities.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; @@ -176,12 +175,12 @@ public static IEnumerable GetTestAdaptersPaths(string? runSettings) { var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings); - IEnumerable testAdaptersPaths = Enumerable.Empty(); + IEnumerable testAdaptersPaths = []; if (runConfiguration != null) { if (runConfiguration.TestAdaptersPathsSet) { - testAdaptersPaths = runConfiguration.TestAdaptersPaths.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + testAdaptersPaths = runConfiguration.TestAdaptersPaths.Split([';'], StringSplitOptions.RemoveEmptyEntries); } } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs index f7fabcdbf7..fdc615a411 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestObjectConverter.cs @@ -102,12 +102,12 @@ internal class TestObjectConverter7 : JsonConverter { // Empty is not present everywhere #pragma warning disable CA1825 // Avoid zero-length array allocations - private static readonly object[] EmptyObjectArray = new object[0]; + private static readonly object[] EmptyObjectArray = []; #pragma warning restore CA1825 // Avoid zero-length array allocations public TestObjectConverter7() { - TestPropertyCtor = typeof(TestProperty).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null); + TestPropertyCtor = typeof(TestProperty).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, [], null); } /// diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs index ad0b614463..89f7369dbd 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs @@ -217,7 +217,7 @@ public bool WaitForRequestHandlerConnection(int connectionTimeout, CancellationT // Wait until either connection is successful, handled by connected.WaitHandle // or operation is canceled, handled by cancellationToken.WaitHandle // or testhost exits unexpectedly, handled by clientExited.WaitHandle - var waitIndex = WaitHandle.WaitAny(new WaitHandle[] { _connected.WaitHandle, cancellationToken.WaitHandle, _clientExited.WaitHandle }, connectionTimeout); + var waitIndex = WaitHandle.WaitAny([_connected.WaitHandle, cancellationToken.WaitHandle, _clientExited.WaitHandle], connectionTimeout); EqtTrace.Verbose("TestRequestSender.WaitForRequestHandlerConnection: waiting took {0} ms, with timeout {1} ms, and result {2}, which is {3}.", sw.ElapsedMilliseconds, connectionTimeout, waitIndex, waitIndex == 0 ? "success" : "failure"); diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs index 6b75f6b8a1..7179155386 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs @@ -50,7 +50,7 @@ public IEnumerable EnumerateFiles( { if (endsWithSearchPatterns == null || endsWithSearchPatterns.Length == 0) { - return Enumerable.Empty(); + return []; } var files = Directory.EnumerateFiles(directory, "*", searchOption); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs index 28ef57dbd8..744b346976 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs @@ -63,7 +63,7 @@ public DataCollectorAttachmentProcessorAppDomain(InvokedDataCollector invokedDat false, BindingFlags.Default, null, - new[] { _pipeShutdownMessagePrefix }, + [_pipeShutdownMessagePrefix], null, null); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyDiscoveryManager.cs index a416e5a2f6..093664b8c7 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyDiscoveryManager.cs @@ -74,7 +74,7 @@ public void DiscoverTests(DiscoveryCriteria discoveryCriteria, ITestDiscoveryEve var discoveryCompeleteEventsArg = new DiscoveryCompleteEventArgs(-1, true); - eventHandler.HandleDiscoveryComplete(discoveryCompeleteEventsArg, Enumerable.Empty()); + eventHandler.HandleDiscoveryComplete(discoveryCompeleteEventsArg, []); } }); } @@ -103,7 +103,7 @@ public void Abort(ITestDiscoveryEventsHandler2 eventHandler) private void InitializeExtensions(IEnumerable sources) { - var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, Enumerable.Empty()); + var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, []); if (extensionsFromSource.Any()) { TestPluginCache.Instance.UpdateExtensions(extensionsFromSource, false); @@ -111,7 +111,7 @@ private void InitializeExtensions(IEnumerable sources) // We don't need to pass list of extension as we are running inside vstest.console and // it will use TestPluginCache of vstest.console - _discoveryManager.Initialize(Enumerable.Empty(), null); + _discoveryManager.Initialize([], null); } public void InitializeDiscovery(DiscoveryCriteria discoveryCriteria, ITestDiscoveryEventsHandler2 eventHandler, bool skipDefaultAdapters) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyexecutionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyexecutionManager.cs index 27def5dde1..4dd1772c99 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyexecutionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/InProcessProxyexecutionManager.cs @@ -135,7 +135,7 @@ public void Close() private void InitializeExtensions(IEnumerable sources) { - var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, Enumerable.Empty()); + var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, []); if (extensionsFromSource.Any()) { TestPluginCache.Instance.UpdateExtensions(extensionsFromSource, false); @@ -143,7 +143,7 @@ private void InitializeExtensions(IEnumerable sources) // We don't need to pass list of extension as we are running inside vstest.console and // it will use TestPluginCache of vstest.console - _executionManager.Initialize(Enumerable.Empty(), null); + _executionManager.Initialize([], null); } public void InitializeTestRun(TestRunCriteria testRunCriteria, IInternalTestRunEventsHandler eventHandler) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelOperationManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelOperationManager.cs index df2ef9133a..9003a84790 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelOperationManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelOperationManager.cs @@ -312,7 +312,7 @@ private void ClearCompletedSlot(TManager completedManager) private static string GetSourcesForSlotExpensive(ParallelOperationManager.Slot slot) { - return string.Join(", ", (slot.Work as DiscoveryCriteria)?.Sources ?? (slot.Work as TestRunCriteria)?.Sources ?? Array.Empty()); + return string.Join(", ", (slot.Work as DiscoveryCriteria)?.Sources ?? (slot.Work as TestRunCriteria)?.Sources ?? []); } public void DoActionOnAllManagers(Action action, bool doActionsInParallel = false) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs index 7b871e4e91..5cae5c4eea 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyDiscoveryManager.cs @@ -222,7 +222,7 @@ private List> SplitToWorkloads(Disco if (!_isParallel && testhostProviderInfo.Shared) { // Create one big source batch that will be single workload for single testhost. - sourceBatches = new List { group.Select(w => w.Work).ToArray() }; + sourceBatches = [group.Select(w => w.Work).ToArray()]; } else { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs index b586cfe934..4329d4620f 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelProxyExecutionManager.cs @@ -261,7 +261,7 @@ private List> SplitToWorkloads(TestRun if (!_isParallel && testhostProviderInfo.Shared) { // Create one big batch of testcases that will be single workload for single testhost. - testCaseBatches = new List { group.SelectMany(w => sourceToTestCasesMap[w.Work]).ToArray() }; + testCaseBatches = [group.SelectMany(w => sourceToTestCasesMap[w.Work]).ToArray()]; } else { @@ -319,7 +319,7 @@ private List> SplitToWorkloads(TestRun if (!_isParallel && testhostProviderInfo.Shared) { // Create one big source batch that will be single workload for single testhost. - sourceBatches = new List { group.Select(w => w.Work).ToArray() }; + sourceBatches = [group.Select(w => w.Work).ToArray()]; } else { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs index 947c1bad04..232a31145e 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs @@ -543,7 +543,7 @@ private bool InitializeLoggerByType(string assemblyQualifiedName, string codeBas // Create logger instance var constructorInfo = loggerType?.GetConstructor(Type.EmptyTypes); - var logger = constructorInfo?.Invoke(new object[] { }); + var logger = constructorInfo?.Invoke([]); // Handle logger null scenario. if (logger == null) diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs index f8cdcf9837..466b8d16b4 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/InProcDataCollector.cs @@ -79,7 +79,7 @@ internal InProcDataCollector(string codeBase, string assemblyQualifiedName, Type // Coverlet collector is consumed as nuget package we need to add assemblies directory to resolver to correctly load references. TPDebug.Assert(Path.IsPathRooted(codeBase), "Absolute path expected"); - testPluginCache.AddResolverSearchDirectories(new string[] { Path.GetDirectoryName(codeBase)! }); + testPluginCache.AddResolverSearchDirectories([Path.GetDirectoryName(codeBase)!]); } else { @@ -112,24 +112,24 @@ public void LoadDataCollector(IDataCollectionSink inProcDataCollectionSink) /// Arguments for the method public void TriggerInProcDataCollectionMethod(string methodName, InProcDataCollectionArgs methodArg) { - var methodInfo = GetMethodInfoFromType(_dataCollectorObject?.GetType(), methodName, new[] { methodArg.GetType() }); + var methodInfo = GetMethodInfoFromType(_dataCollectorObject?.GetType(), methodName, [methodArg.GetType()]); if (methodName.Equals(Constants.TestSessionStartMethodName)) { var testSessionStartArgs = (TestSessionStartArgs)methodArg; testSessionStartArgs.Configuration = _configXml!; - methodInfo?.Invoke(_dataCollectorObject, new object[] { testSessionStartArgs }); + methodInfo?.Invoke(_dataCollectorObject, [testSessionStartArgs]); } else { - methodInfo?.Invoke(_dataCollectorObject, new object[] { methodArg }); + methodInfo?.Invoke(_dataCollectorObject, [methodArg]); } } private static void InitializeDataCollector(object? obj, IDataCollectionSink inProcDataCollectionSink) { - var initializeMethodInfo = GetMethodInfoFromType(obj?.GetType(), "Initialize", new Type[] { typeof(IDataCollectionSink) }); - initializeMethodInfo?.Invoke(obj, new object[] { inProcDataCollectionSink }); + var initializeMethodInfo = GetMethodInfoFromType(obj?.GetType(), "Initialize", [typeof(IDataCollectionSink)]); + initializeMethodInfo?.Invoke(obj, [inProcDataCollectionSink]); } private static MethodInfo? GetMethodInfoFromType(Type? type, string funcName, Type[] argumentTypes) @@ -140,7 +140,7 @@ private static void InitializeDataCollector(object? obj, IDataCollectionSink inP private static object? CreateObjectFromType(Type? type) { var constructorInfo = type?.GetConstructor(Type.EmptyTypes); - object? obj = constructorInfo?.Invoke(new object[] { }); + object? obj = constructorInfo?.Invoke([]); return obj; } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs index 4600200c39..87c19a472e 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs @@ -619,7 +619,7 @@ private void RaiseTestRunComplete( UpdateTestCaseSourceToPackage(lastChunkTestResults, null, out lastChunkTestResults, out _); } - var testRunChangedEventArgs = new TestRunChangedEventArgs(runStats, lastChunkTestResults, Enumerable.Empty()); + var testRunChangedEventArgs = new TestRunChangedEventArgs(runStats, lastChunkTestResults, []); // Adding Metrics along with Test Run Complete Event Args Collection? attachments = FrameworkHandle?.Attachments; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs index 291e7a5671..2049a17bcf 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithTests.cs @@ -131,7 +131,7 @@ private static Dictionary, List> GetExecutorVsTestC } else { - testList = new List { test }; + testList = [test]; result.Add(executorUriExtensionTuple, testList); } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs index 686a83d0d0..668f5d4cf4 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/PostProcessing/PostProcessingTestRunAttachmentsProcessingEventsHandler.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; @@ -50,7 +49,7 @@ public void HandleProcessedAttachmentsChunk(IEnumerable attachmen public void HandleTestRunAttachmentsProcessingComplete(TestRunAttachmentsProcessingCompleteEventArgs attachmentsProcessingCompleteEventArgs, IEnumerable? lastChunk) { - foreach (var attachment in lastChunk ?? Enumerable.Empty()) + foreach (var attachment in lastChunk ?? []) { _attachmentsSet.Add(attachment); } diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs index 1f3f483d29..3628a29c89 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs @@ -356,7 +356,7 @@ private void ValidateAndAddCrashProcessDumpParameters(XmlElement collectDumpNode && !string.Equals(attribute.Value, Constants.FalseConfigurationValue, StringComparison.OrdinalIgnoreCase)) || !bool.TryParse(attribute.Value, out _collectDumpAlways)) { - _logger.LogWarning(_context.SessionDataCollectionContext, FormatBlameParameterValueIncorrectMessage(attribute, new[] { Constants.TrueConfigurationValue, Constants.FalseConfigurationValue })); + _logger.LogWarning(_context.SessionDataCollectionContext, FormatBlameParameterValueIncorrectMessage(attribute, [Constants.TrueConfigurationValue, Constants.FalseConfigurationValue])); } break; diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/NetClientCrashDumper.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/NetClientCrashDumper.cs index 333a123a21..f705eadf19 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/NetClientCrashDumper.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/NetClientCrashDumper.cs @@ -35,7 +35,7 @@ public IEnumerable GetDumpFiles(bool _) { return _fileHelper.DirectoryExists(_outputDirectory) ? _fileHelper.GetFiles(_outputDirectory, "*_crashdump*.dmp", SearchOption.AllDirectories) - : Array.Empty(); + : []; } public void WaitForDumpToFinish() diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs index a4130d6d2c..1c6e39a935 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs @@ -241,7 +241,7 @@ public IEnumerable GetDumpFiles(bool processCrashed) { var allDumps = _fileHelper.DirectoryExists(_outputDirectory) ? _fileHelper.GetFiles(_outputDirectory, "*_crashdump*.dmp", SearchOption.AllDirectories) - : Array.Empty(); + : []; // We are always collecting dump on exit even when collectAlways option is false, to make sure we collect // dump for Environment.FailFast. So there always can be a dump if the process already exited. In most cases diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessDumpUtility.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessDumpUtility.cs index fc42574303..e5eb1be159 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessDumpUtility.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessDumpUtility.cs @@ -60,7 +60,7 @@ public IEnumerable GetDumpFiles(bool warnOnNoDumpFiles, bool processCras IEnumerable hangDumps = _fileHelper.DirectoryExists(_hangDumpDirectory) ? _fileHelper.GetFiles(_hangDumpDirectory, "*_hangdump*.dmp", SearchOption.TopDirectoryOnly) - : Array.Empty(); + : []; var foundDumps = new List(); foreach (var dumpPath in crashDumps.Concat(hangDumps)) diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs index bcef64a85f..2b37511660 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs @@ -342,11 +342,11 @@ internal void TestRunCompleteHandler(object? sender, TestRunCompleteEventArgs e) helper.SaveIEnumerable(_entries.Values, rootElement, "TestEntries", ".", "TestEntry", parameters); // Save default categories - List categories = new() - { + List categories = + [ TestListCategory.UncategorizedResults, TestListCategory.AllResults - }; + ]; helper.SaveList(categories, rootElement, "TestLists", ".", "TestList", parameters); // Save summary @@ -357,7 +357,7 @@ internal void TestRunCompleteHandler(object? sender, TestRunCompleteEventArgs e) TestResultOutcome = ChangeTestOutcomeIfNecessary(TestResultOutcome); - List errorMessages = new(); + List errorMessages = []; List collectorEntries = _converter.ToCollectionEntries(e.AttachmentSets, LoggerTestRun, _testResultsDirPath); IList resultFiles = _converter.ToResultFiles(e.AttachmentSets, LoggerTestRun, _testResultsDirPath, errorMessages); diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs index bddab2bb64..3a8a7b69c1 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs @@ -278,10 +278,10 @@ public static List GetCustomPropertyValueFromTestCase(TestCase testCase, if (customProperty != null) { var cateogryValues = (string[]?)testCase.GetPropertyValue(customProperty); - return cateogryValues != null ? cateogryValues.ToList() : Enumerable.Empty().ToList(); + return cateogryValues != null ? cateogryValues.ToList() : []; } - return Enumerable.Empty().ToList(); + return []; } /// diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs index 58b2f6df05..8104df9806 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs @@ -183,7 +183,7 @@ public static string MakePathRelative(string path, string basePath) path = Path.GetFullPath(path); basePath = Path.GetFullPath(basePath); - char[] delimiters = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; + char[] delimiters = [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]; basePath = basePath.TrimEnd(delimiters); path = path.TrimEnd(delimiters); diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs index 8808c57314..1bae61bb92 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs @@ -706,7 +706,7 @@ private static string ReplaceInvalidCharacterWithUniCodeEscapeSequence(Match mat } else { - string[] parts = location.Split(new char[] { '/' }, 2); + string[] parts = location.Split(['/'], 2); string firstPart = parts[0]; XmlNode? firstChild = LocationToXmlNode(xml, firstPart); @@ -805,7 +805,7 @@ private string ProcessXPathQuery(string queryIn) } // fix the empty namespaces to a temp prefix, so xpath query can understand them - string[] parts = queryIn.Split(new char[] { '/' }, StringSplitOptions.None); + string[] parts = queryIn.Split(['/'], StringSplitOptions.None); StringBuilder query = new(); diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs index 583f2882c8..0f882551bd 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs @@ -133,7 +133,7 @@ public int CompareTo(object? obj) RequestId? other = obj as RequestId; return other == null - ? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Common_ObjectMustBeOfType, new object[] { typeof(RequestId).Name }), nameof(obj)) + ? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Common_ObjectMustBeOfType, [typeof(RequestId).Name]), nameof(obj)) : Id.CompareTo(other.Id); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs index 9f691969a4..45aed5c42c 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs @@ -60,7 +60,7 @@ public FileTransferInformation(DataCollectionContext context, string path, bool // Make sure the file exists. if (!_fileHelper.Exists(path)) { - throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Common_FileNotExist, new object[] { path }), path); + throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Common_FileNotExist, [path]), path); } // Make sure the path we have is a full path (not relative). diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs index d247c22514..1130173962 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/DiaSession.cs @@ -20,7 +20,7 @@ public class DiaSession : INavigationSession /// /// Characters that should be stripped off the end of test names. /// - private static readonly char[] TestNameStripChars = { '(', ')', ' ' }; + private static readonly char[] TestNameStripChars = ['(', ')', ' ']; /// /// The symbol reader. diff --git a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultFrameworkMappings.cs b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultFrameworkMappings.cs index b1492de902..cc943d021a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultFrameworkMappings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultFrameworkMappings.cs @@ -11,7 +11,8 @@ internal sealed class DefaultFrameworkMappings : IFrameworkMappings { private static Lazy[]> IdentifierSynonymsLazy = new(() => { - return new[]{ + return + [ // .NET new KeyValuePair("NETFramework", FrameworkConstants.FrameworkIdentifiers.Net), new KeyValuePair(".NET", FrameworkConstants.FrameworkIdentifiers.Net), @@ -31,8 +32,8 @@ internal sealed class DefaultFrameworkMappings : IFrameworkMappings new KeyValuePair("XamarinPlayStationThree", FrameworkConstants.FrameworkIdentifiers.XamarinPlayStation3), new KeyValuePair("Xamarin.PlayStationFour", FrameworkConstants.FrameworkIdentifiers.XamarinPlayStation4), new KeyValuePair("XamarinPlayStationFour", FrameworkConstants.FrameworkIdentifiers.XamarinPlayStation4), - new KeyValuePair("XamarinPlayStationVita", FrameworkConstants.FrameworkIdentifiers.XamarinPlayStationVita), - }; + new KeyValuePair("XamarinPlayStationVita", FrameworkConstants.FrameworkIdentifiers.XamarinPlayStationVita) + ]; }); public IEnumerable> IdentifierSynonyms @@ -45,8 +46,8 @@ public IEnumerable> IdentifierSynonyms private static readonly Lazy[]> IdentifierShortNamesLazy = new(() => { - return new[] - { + return + [ new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.NetCoreApp, "netcoreapp"), new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.NetStandardApp, "netstandardapp"), new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.NetStandard, "netstandard"), @@ -79,8 +80,8 @@ public IEnumerable> IdentifierSynonyms new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.WinRT, "winrt"), // legacy new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.UAP, "uap"), new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.Tizen, "tizen"), - new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.NanoFramework, "netnano"), - }; + new KeyValuePair(FrameworkConstants.FrameworkIdentifiers.NanoFramework, "netnano") + ]; }); public IEnumerable> IdentifierShortNames @@ -93,14 +94,14 @@ public IEnumerable> IdentifierShortNames private static readonly Lazy ProfileShortNamesLazy = new(() => { - return new[] - { + return + [ new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Net, "Client", "Client"), new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Net, "CF", "CompactFramework"), new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Net, "Full", string.Empty), new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Silverlight, "WP", "WindowsPhone"), - new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Silverlight, "WP71", "WindowsPhone71"), - }; + new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Silverlight, "WP71", "WindowsPhone71") + ]; }); public IEnumerable ProfileShortNames @@ -113,8 +114,8 @@ public IEnumerable ProfileShortNames private static readonly Lazy[]> EquivalentFrameworksLazy = new(() => { - return new[] - { + return + [ // UAP 0.0 <-> UAP 10.0 new KeyValuePair( new NuGetFramework(FrameworkConstants.FrameworkIdentifiers.UAP, FrameworkConstants.EmptyVersion), @@ -219,8 +220,8 @@ public IEnumerable ProfileShortNames // dnxcore50 <-> aspnetcore50 new KeyValuePair( FrameworkConstants.CommonFrameworks.DnxCore50, - FrameworkConstants.CommonFrameworks.AspNetCore50), - }; + FrameworkConstants.CommonFrameworks.AspNetCore50) + ]; }); public IEnumerable> EquivalentFrameworks @@ -233,14 +234,14 @@ public IEnumerable> EquivalentFrame private static readonly Lazy EquivalentProfilesLazy = new(() => { - return new[] - { + return + [ // The client profile, for the purposes of NuGet, is the same as the full framework new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Net, "Client", string.Empty), new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Net, "Full", string.Empty), new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.Silverlight, "WindowsPhone71", "WindowsPhone"), - new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.WindowsPhone, "WindowsPhone71", "WindowsPhone"), - }; + new FrameworkSpecificMapping(FrameworkConstants.FrameworkIdentifiers.WindowsPhone, "WindowsPhone71", "WindowsPhone") + ]; }); public IEnumerable EquivalentProfiles @@ -253,8 +254,8 @@ public IEnumerable EquivalentProfiles private static readonly Lazy[]> SubSetFrameworksLazy = new(() => { - return new[] - { + return + [ // .NET is a subset of DNX new KeyValuePair( FrameworkConstants.FrameworkIdentifiers.Net, @@ -269,7 +270,7 @@ public IEnumerable EquivalentProfiles new KeyValuePair( FrameworkConstants.FrameworkIdentifiers.NetStandard, FrameworkConstants.FrameworkIdentifiers.NetStandardApp) - }; + ]; }); public IEnumerable> SubSetFrameworks @@ -553,13 +554,13 @@ private static IEnumerable CreateGenerationAndS private static readonly Lazy NonPackageBasedFrameworkPrecedenceLazy = new(() => { - return new[] - { + return + [ FrameworkConstants.FrameworkIdentifiers.Net, FrameworkConstants.FrameworkIdentifiers.NetCore, FrameworkConstants.FrameworkIdentifiers.Windows, FrameworkConstants.FrameworkIdentifiers.WindowsPhoneApp - }; + ]; }); public IEnumerable NonPackageBasedFrameworkPrecedence @@ -572,13 +573,13 @@ public IEnumerable NonPackageBasedFrameworkPrecedence private static readonly Lazy PackageBasedFrameworkPrecedenceLazy = new(() => { - return new[] - { + return + [ FrameworkConstants.FrameworkIdentifiers.NetCoreApp, FrameworkConstants.FrameworkIdentifiers.NetStandardApp, FrameworkConstants.FrameworkIdentifiers.NetStandard, FrameworkConstants.FrameworkIdentifiers.NetPlatform - }; + ]; }); public IEnumerable PackageBasedFrameworkPrecedence @@ -591,8 +592,8 @@ public IEnumerable PackageBasedFrameworkPrecedence private static readonly Lazy EquivalentFrameworkPrecedenceLazy = new(() => { - return new[] - { + return + [ FrameworkConstants.FrameworkIdentifiers.Windows, FrameworkConstants.FrameworkIdentifiers.NetCore, FrameworkConstants.FrameworkIdentifiers.WinRT, @@ -605,7 +606,7 @@ public IEnumerable PackageBasedFrameworkPrecedence FrameworkConstants.FrameworkIdentifiers.Dnx, FrameworkConstants.FrameworkIdentifiers.AspNet - }; + ]; }); public IEnumerable EquivalentFrameworkPrecedence @@ -618,10 +619,10 @@ public IEnumerable EquivalentFrameworkPrecedence private static readonly Lazy[]> ShortNameReplacementsLazy = new(() => { - return new[] - { + return + [ new KeyValuePair(FrameworkConstants.CommonFrameworks.DotNet50, FrameworkConstants.CommonFrameworks.DotNet) - }; + ]; }); public IEnumerable> ShortNameReplacements @@ -634,10 +635,10 @@ public IEnumerable> ShortNameReplac private static readonly Lazy[]> FullNameReplacementsLazy = new(() => { - return new[] - { + return + [ new KeyValuePair(FrameworkConstants.CommonFrameworks.DotNet, FrameworkConstants.CommonFrameworks.DotNet50) - }; + ]; }); public IEnumerable> FullNameReplacements diff --git a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultPortableFrameworkMappings.cs b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultPortableFrameworkMappings.cs index d36320d326..bcb22c4a3e 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultPortableFrameworkMappings.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/DefaultPortableFrameworkMappings.cs @@ -32,8 +32,8 @@ internal class DefaultPortableFrameworkMappings : IPortableFrameworkMappings var wpa81 = FrameworkConstants.CommonFrameworks.WPA81; - return new[] - { + return + [ // v4.6 CreateProfileFrameworks(31, win81, wp81), CreateProfileFrameworks(32, win81, wpa81), @@ -82,8 +82,8 @@ internal class DefaultPortableFrameworkMappings : IPortableFrameworkMappings CreateProfileFrameworks(255, net45, sl5, win8, wpa81), CreateProfileFrameworks(328, net4, sl5, win8, wpa81, wp8), CreateProfileFrameworks(336, net403, sl5, win8, wpa81, wp8), - CreateProfileFrameworks(344, net45, sl5, win8, wpa81, wp8), - }; + CreateProfileFrameworks(344, net45, sl5, win8, wpa81, wp8) + ]; }); public IEnumerable> ProfileFrameworks @@ -101,9 +101,9 @@ private static KeyValuePair CreateProfileFrameworks(int p // profiles that also support monotouch1+monoandroid1 private static readonly int[] ProfilesWithOptionalFrameworks = - { - 5, 6, 7, 14, 19, 24, 37, 42, 44, 47, 49, 78, 92, 102, 111, 136, 147, 151, 158, 225, 255, 259, 328, 336, 344 - }; + [ + 5, 6, 7, 14, 19, 24, 37, 42, 44, 47, 49, 78, 92, 102, 111, 136, 147, 151, 158, 225, 255, 259, 328, 336, 344 + ]; private static readonly Lazy>> ProfileOptionalFrameworksLazy = new(() => { @@ -135,8 +135,8 @@ public IEnumerable> ProfileOptionalFramework private static readonly Lazy[]> CompatibilityMappingsLazy = new(() => { - return new[] - { + return + [ CreateStandardMapping(7, FrameworkConstants.CommonFrameworks.NetStandard11), CreateStandardMapping(31, FrameworkConstants.CommonFrameworks.NetStandard10), CreateStandardMapping(32, FrameworkConstants.CommonFrameworks.NetStandard12), @@ -148,7 +148,7 @@ public IEnumerable> ProfileOptionalFramework CreateStandardMapping(151, FrameworkConstants.CommonFrameworks.NetStandard12), CreateStandardMapping(157, FrameworkConstants.CommonFrameworks.NetStandard10), CreateStandardMapping(259, FrameworkConstants.CommonFrameworks.NetStandard10) - }; + ]; }); public IEnumerable> CompatibilityMappings diff --git a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkNameProvider.cs b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkNameProvider.cs index 4c810b6564..1a52d91003 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkNameProvider.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkNameProvider.cs @@ -341,7 +341,7 @@ private HashSet RemoveDuplicateFramework(IEnumerable RemoveDuplicateFramework(IEnumerable - /// Get all equivalent frameworks including the given framework - /// + /// + /// Get all equivalent frameworks including the given framework + /// private HashSet GetAllEquivalentFrameworks(NuGetFramework framework) { - // Loop through the frameworks, all frameworks that are not in results yet - // will be added to toProcess to get the equivalent frameworks + // Loop through the frameworks, all frameworks that are not in results yet + // will be added to toProcess to get the equivalent frameworks var toProcess = new Stack(); var results = new HashSet(); @@ -486,7 +486,7 @@ public bool TryGetPortableFrameworks(string shortPortableProfiles, [NotNullWhen( throw new ArgumentNullException(nameof(shortPortableProfiles)); } - var shortNames = shortPortableProfiles.Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries); + var shortNames = shortPortableProfiles.Split(['+'], StringSplitOptions.RemoveEmptyEntries); var result = new List(); foreach (var name in shortNames) @@ -545,7 +545,7 @@ public bool TryGetPortableFrameworks(string profile, bool includeOptional, [NotN return true; } - frameworks = Enumerable.Empty(); + frameworks = []; return false; } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkReducer.cs b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkReducer.cs index 097ee2f7ac..9c2ab2fd57 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkReducer.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/FrameworkReducer.cs @@ -442,7 +442,7 @@ private IEnumerable ExplodePortableFramework(NuGetFramework pcl, if (!_mappings.TryGetPortableFrameworks(pcl.Profile, includeOptional, out IEnumerable? frameworks)) { Debug.Fail("Unable to get portable frameworks from: " + pcl.ToString()); - frameworks = Enumerable.Empty(); + frameworks = []; } return frameworks; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/NuGetFrameworkFactory.cs b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/NuGetFrameworkFactory.cs index 6d5329f20d..019fde8102 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/NuGetFrameworkFactory.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Nuget.Frameworks/NuGetFrameworkFactory.cs @@ -136,7 +136,7 @@ internal static NuGetFramework ParseComponents(string targetFrameworkMoniker, st return result; } - private static readonly char[] CommaSeparator = new char[] { ',' }; + private static readonly char[] CommaSeparator = [',']; private static string[] GetParts(string targetPlatformMoniker) { diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs b/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs index d949ede703..b9c260fb9f 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestCase.cs @@ -339,7 +339,7 @@ public static class TestCaseProperties public static readonly TestProperty LineNumber = TestProperty.Register("TestCase.LineNumber", LineNumberLabel, typeof(int), TestPropertyAttributes.Hidden, typeof(TestCase)); internal static TestProperty[] Properties { get; } = - { + [ CodeFilePath, DisplayName, ExecutorUri, @@ -347,7 +347,7 @@ public static class TestCaseProperties Id, LineNumber, Source - }; + ]; private static bool ValidateName(object? value) { diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs index b1baf611a5..75f4742a45 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestProperty/CustomKeyValueConverter.cs @@ -45,7 +45,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source using var stream = new MemoryStream(Encoding.Unicode.GetBytes(data)); // Converting Json data to array of KeyValuePairs with duplicate keys. var listOfTraitObjects = _serializer.ReadObject(stream) as TraitObject[]; - return listOfTraitObjects?.Select(trait => new KeyValuePair(trait.Key, trait.Value)).ToArray() ?? new KeyValuePair[0]; + return listOfTraitObjects?.Select(trait => new KeyValuePair(trait.Key, trait.Value)).ToArray() ?? []; } return null; diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs b/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs index 35838f1b31..7e9c33c528 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs @@ -320,7 +320,7 @@ public static class TestResultProperties public static readonly TestProperty ErrorStackTrace = TestProperty.Register("TestResult.ErrorStackTrace", Resources.Resources.TestResultPropertyErrorStackTraceLabel, typeof(string), typeof(TestResult)); #endif internal static TestProperty[] Properties { get; } = - { + [ ComputerName, DisplayName, Duration, @@ -329,7 +329,7 @@ public static class TestResultProperties ErrorStackTrace, Outcome, StartTime - }; + ]; private static bool ValidateOutcome(object? value) { diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs index 545e3bcfad..aefba93a27 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/AssemblyLoadWorker.cs @@ -96,7 +96,7 @@ internal static string GetTargetFrameworkStringFromAssembly(Assembly assembly) AssemblyName[] assemblies = a.GetReferencedAssemblies(); return assemblies == null || assemblies.Length == 0 - ? (new string[0]) + ? ([]) : (from assembly in assemblies select assembly.FullName).ToArray(); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs index 7056264d71..eda82c44ca 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/FilterHelper.cs @@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; public static class FilterHelper { public const char EscapeCharacter = '\\'; - private static readonly char[] SpecialCharacters = { '\\', '(', ')', '&', '|', '=', '!', '~' }; + private static readonly char[] SpecialCharacters = ['\\', '(', ')', '&', '|', '=', '!', '~']; private static readonly HashSet SpecialCharactersSet = new(SpecialCharacters); /// diff --git a/src/Microsoft.TestPlatform.Utilities/CodeCoverageDataAttachmentsHandler.cs b/src/Microsoft.TestPlatform.Utilities/CodeCoverageDataAttachmentsHandler.cs index be2a1030f3..2a8241906c 100644 --- a/src/Microsoft.TestPlatform.Utilities/CodeCoverageDataAttachmentsHandler.cs +++ b/src/Microsoft.TestPlatform.Utilities/CodeCoverageDataAttachmentsHandler.cs @@ -129,7 +129,7 @@ public async Task> ProcessAttachmentSetsAsync(XmlElem TPDebug.Assert(s_mergeOperationEnumValues != null); - var task = (Task)s_mergeMethodInfo.Invoke(s_classInstance, new object[] { files[0], files, s_mergeOperationEnumValues.GetValue(0)!, true, cancellationToken })!; + var task = (Task)s_mergeMethodInfo.Invoke(s_classInstance, [files[0], files, s_mergeOperationEnumValues.GetValue(0)!, true, cancellationToken])!; await task.ConfigureAwait(false); if (task.GetType().GetProperty("Result")!.GetValue(task, null) is not IList mergedResults) @@ -176,6 +176,6 @@ private static void LoadCodeCoverageAssembly() var types = s_codeCoverageAssembly.GetTypes(); var mergeOperationEnum = Array.Find(types, d => d.Name == CoverageMergeOperationName)!; s_mergeOperationEnumValues = Enum.GetValues(mergeOperationEnum); - s_mergeMethodInfo = classType.GetMethod(MergeMethodName, new[] { typeof(string), typeof(IList), mergeOperationEnum, typeof(bool), typeof(CancellationToken) })!; + s_mergeMethodInfo = classType.GetMethod(MergeMethodName, [typeof(string), typeof(IList), mergeOperationEnum, typeof(bool), typeof(CancellationToken)])!; } } diff --git a/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs b/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs index 2488ff2d4d..8d28e6c5dc 100644 --- a/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs +++ b/src/Microsoft.TestPlatform.Utilities/InferRunSettingsHelper.cs @@ -55,7 +55,11 @@ public class InferRunSettingsHelper private const string LegacyElementsString = "Elements"; private const string DeploymentAttributesString = "DeploymentAttributes"; private const string ExecutionAttributesString = "ExecutionAttributes"; - private static readonly List ExecutionNodesPaths = new() { @"/RunSettings/LegacySettings/Execution/TestTypeSpecific/UnitTestRunConfig/AssemblyResolution", @"/RunSettings/LegacySettings/Execution/Timeouts", @"/RunSettings/LegacySettings/Execution/Hosts" }; + private static readonly List ExecutionNodesPaths = + [ + @"/RunSettings/LegacySettings/Execution/TestTypeSpecific/UnitTestRunConfig/AssemblyResolution", + @"/RunSettings/LegacySettings/Execution/Timeouts", @"/RunSettings/LegacySettings/Execution/Hosts" + ]; /// /// Make runsettings compatible with testhost of version 15.0.0-preview diff --git a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs index ea17ec6555..e3b99521c7 100644 --- a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs +++ b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs @@ -1155,7 +1155,7 @@ public Task ProcessTestRunAttachmentsAsync( bool collectMetrics, ITestRunAttachmentsProcessingEventsHandler testSessionEventsHandler, CancellationToken cancellationToken) - => ProcessTestRunAttachmentsAsync(attachments, Enumerable.Empty(), processingSettings, isLastBatch, collectMetrics, testSessionEventsHandler, cancellationToken); + => ProcessTestRunAttachmentsAsync(attachments, [], processingSettings, isLastBatch, collectMetrics, testSessionEventsHandler, cancellationToken); #endregion diff --git a/src/testhost.x86/AppDomainEngineInvoker.cs b/src/testhost.x86/AppDomainEngineInvoker.cs index 0401e6bc32..344790949b 100644 --- a/src/testhost.x86/AppDomainEngineInvoker.cs +++ b/src/testhost.x86/AppDomainEngineInvoker.cs @@ -106,7 +106,7 @@ private static IEngineInvoker CreateInvokerInAppDomain(AppDomain appDomain) false, BindingFlags.Default, null, - new object?[] { CultureInfo.DefaultThreadCurrentUICulture?.Name, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) }, + [CultureInfo.DefaultThreadCurrentUICulture?.Name, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)], null, null); @@ -247,7 +247,7 @@ public CustomAssemblySetup(string uiCulture, string testPlatformPath) CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(uiCulture); } - _resolverPaths = new string[] { testPlatformPath, Path.Combine(testPlatformPath, "Extensions") }; + _resolverPaths = [testPlatformPath, Path.Combine(testPlatformPath, "Extensions")]; _resolvedAssemblies = new Dictionary(); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } diff --git a/src/testhost.x86/UnitTestClient.cs b/src/testhost.x86/UnitTestClient.cs index b28b0f4ce8..de0f39cfa6 100644 --- a/src/testhost.x86/UnitTestClient.cs +++ b/src/testhost.x86/UnitTestClient.cs @@ -55,6 +55,6 @@ internal static string[] SplitArguments(string commandLine) parmChars[index] = '\n'; } - return (new string(parmChars)).Split(new[] { '\n' }); + return (new string(parmChars)).Split(['\n']); } } diff --git a/src/vstest.console/CommandLine/Executor.cs b/src/vstest.console/CommandLine/Executor.cs index beb8185b71..951a4166e1 100644 --- a/src/vstest.console/CommandLine/Executor.cs +++ b/src/vstest.console/CommandLine/Executor.cs @@ -141,7 +141,7 @@ internal int Execute(params string[]? args) if (args == null || args.Length == 0 || args.Any(StringUtils.IsNullOrWhiteSpace)) { Output.Error(true, CommandLineResources.NoArgumentsProvided); - args = new string[] { HelpArgumentProcessor.CommandName }; + args = [HelpArgumentProcessor.CommandName]; exitCode = 1; } diff --git a/src/vstest.console/Internal/FilePatternParser.cs b/src/vstest.console/Internal/FilePatternParser.cs index 918d7a3805..804739ca7e 100644 --- a/src/vstest.console/Internal/FilePatternParser.cs +++ b/src/vstest.console/Internal/FilePatternParser.cs @@ -27,7 +27,7 @@ public class FilePatternParser { private readonly Matcher _matcher; private readonly IFileHelper _fileHelper; - private readonly char[] _wildCardCharacters = { '*' }; + private readonly char[] _wildCardCharacters = ['*']; public FilePatternParser() : this(new Matcher(), new FileHelper()) diff --git a/src/vstest.console/Processors/CollectArgumentProcessor.cs b/src/vstest.console/Processors/CollectArgumentProcessor.cs index 2a6ea0761f..c050e85f22 100644 --- a/src/vstest.console/Processors/CollectArgumentProcessor.cs +++ b/src/vstest.console/Processors/CollectArgumentProcessor.cs @@ -241,7 +241,7 @@ private static bool DoesDataCollectorSettingsExist(string friendlyName, internal static void AddDataCollectorToRunSettings(string arguments, IRunSettingsProvider runSettingsManager, IFileHelper fileHelper) { - AddDataCollectorToRunSettings(new string[] { arguments }, runSettingsManager, fileHelper, string.Empty); + AddDataCollectorToRunSettings([arguments], runSettingsManager, fileHelper, string.Empty); } internal static void AddDataCollectorToRunSettings(string[] arguments, IRunSettingsProvider runSettingsManager, IFileHelper fileHelper, string exceptionMessage) diff --git a/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs b/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs index 783e2d967c..21b04d3976 100644 --- a/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableCodeCoverageArgumentProcessor.cs @@ -77,7 +77,8 @@ internal class EnableCodeCoverageArgumentExecutor : IArgumentExecutor internal const string FriendlyName = "Code Coverage"; private static readonly string XPathSeperator = "/"; - private static readonly string[] NodeNames = new string[] { Constants.RunSettingsName, Constants.DataCollectionRunSettingsName, Constants.DataCollectorsSettingName, Constants.DataCollectorSettingName }; + private static readonly string[] NodeNames = [Constants.RunSettingsName, Constants.DataCollectionRunSettingsName, Constants.DataCollectorsSettingName, Constants.DataCollectorSettingName + ]; #region Default CodeCoverage Settings String @@ -258,7 +259,7 @@ private static string GetMissingNodesTextIfAny(string existingPath, string fullp { var xmlText = "{0}"; var nonExistingPath = fullpath.Substring(existingPath.Length); - var requiredNodeNames = nonExistingPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + var requiredNodeNames = nonExistingPath.Split(['/'], StringSplitOptions.RemoveEmptyEntries); var format = "<{0}>{1}"; foreach (var nodeName in requiredNodeNames) diff --git a/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs b/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs index 92b4a73e74..5fcb2d2b99 100644 --- a/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs +++ b/src/vstest.console/Processors/TestAdapterLoadingStrategyArgumentProcessor.cs @@ -195,7 +195,7 @@ private void ForceIsolation() private void ValidateTestAdapterPaths(TestAdapterLoadingStrategy strategy) { - var testAdapterPaths = _commandLineOptions.TestAdapterPath ?? new string[0]; + var testAdapterPaths = _commandLineOptions.TestAdapterPath ?? []; if (!_commandLineOptions.TestAdapterPathsSet) { testAdapterPaths = TestAdapterPathArgumentExecutor.SplitPaths(_runSettingsManager.QueryRunSettingsNode(TestAdapterPathArgumentExecutor.RunSettingsPath)).Union(testAdapterPaths).Distinct().ToArray(); diff --git a/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs b/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs index 2c1ab3f7b0..701d1b37ce 100644 --- a/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs +++ b/src/vstest.console/Processors/TestAdapterPathArgumentProcessor.cs @@ -96,7 +96,7 @@ internal class TestAdapterPathArgumentExecutor : IArgumentExecutor /// /// Separators for multiple paths in argument. /// - internal readonly static char[] ArgumentSeparators = new[] { ';' }; + internal readonly static char[] ArgumentSeparators = [';']; public const string RunSettingsPath = "RunConfiguration.TestAdaptersPaths"; @@ -132,7 +132,7 @@ public void Initialize(string? argument) // VSTS task add double quotes around TestAdapterpath. For example if user has given TestAdapter path C:\temp, // Then VSTS task will add TestAdapterPath as "/TestAdapterPath:\"C:\Temp\"". // Remove leading and trailing ' " ' chars... - argument = argument.Trim().Trim(new char[] { '\"' }); + argument = argument.Trim().Trim(['\"']); // Get test adapter paths from RunSettings. var testAdapterPathsInRunSettings = _runSettingsManager.QueryRunSettingsNode(RunSettingsPath); @@ -167,6 +167,6 @@ public ArgumentProcessorResult Execute() /// Paths. internal static string[] SplitPaths(string? paths) { - return paths.IsNullOrWhiteSpace() ? new string[0] : paths.Split(ArgumentSeparators, StringSplitOptions.RemoveEmptyEntries); + return paths.IsNullOrWhiteSpace() ? [] : paths.Split(ArgumentSeparators, StringSplitOptions.RemoveEmptyEntries); } } diff --git a/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs b/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs index a5744648cd..99f9130d39 100644 --- a/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs +++ b/src/vstest.console/Processors/Utilities/ArgumentProcessorUtilities.cs @@ -8,8 +8,8 @@ namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities; internal class ArgumentProcessorUtilities { - public static readonly char[] SemiColonArgumentSeparator = { ';' }; - public static readonly char[] EqualNameValueSeparator = { '=' }; + public static readonly char[] SemiColonArgumentSeparator = [';']; + public static readonly char[] EqualNameValueSeparator = ['=']; /// /// Get argument list from raw argument using argument separator. diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs index abf09de509..43923342e1 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs @@ -95,11 +95,11 @@ public void InitializeShouldThrowExceptionIfLoggerIsNull() [TestMethod] public void InitializeShouldInitializeDefaultEventLogNames() { - List eventLogNames = new() - { + List eventLogNames = + [ "System", "Application" - }; + ]; _eventLogDataCollector.Initialize(null, _mockDataCollectionEvents.Object, _mockDataCollectionSink, _mockDataCollectionLogger.Object, _dataCollectionEnvironmentContext); @@ -113,11 +113,11 @@ public void InitializeShouldInitializeCustomEventLogNamesIfSpecifiedInConfigurat string configurationString = @""; - List eventLogNames = new() - { + List eventLogNames = + [ "MyEventName", "MyEventName2" - }; + ]; XmlDocument expectedXmlDoc = new(); expectedXmlDoc.LoadXml(configurationString); @@ -131,12 +131,12 @@ public void InitializeShouldInitializeCustomEventLogNamesIfSpecifiedInConfigurat [TestMethod] public void InitializeShouldInitializeDefaultLogEntryTypes() { - List entryTypes = new() - { + List entryTypes = + [ EventLogEntryType.Error, EventLogEntryType.Warning, EventLogEntryType.FailureAudit - }; + ]; _eventLogDataCollector.Initialize(null, _mockDataCollectionEvents.Object, _mockDataCollectionSink, _mockDataCollectionLogger.Object, _dataCollectionEnvironmentContext); @@ -150,10 +150,7 @@ public void InitializeShouldInitializeEntryTypesIfSpecifiedInConfiguration() string configurationString = @""; - List entryTypes = new() - { - EventLogEntryType.Error - }; + List entryTypes = [EventLogEntryType.Error]; XmlDocument expectedXmlDoc = new(); expectedXmlDoc.LoadXml(configurationString); @@ -169,10 +166,7 @@ public void InitializeShouldInitializeEventSourcesIfSpecifiedInConfiguration() string configurationString = @""; - List eventSources = new() - { - "MyEventSource" - }; + List eventSources = ["MyEventSource"]; XmlDocument expectedXmlDoc = new(); expectedXmlDoc.LoadXml(configurationString); diff --git a/test/Intent/Runner.cs b/test/Intent/Runner.cs index 6edf62eb0f..cbe7706cba 100644 --- a/test/Intent/Runner.cs +++ b/test/Intent/Runner.cs @@ -62,7 +62,7 @@ public static void Run(IEnumerable paths, IRunLogger logger) // Declaring type cannot be really null for types you define in C# // without doing any reflection magic. var instance = Activator.CreateInstance(method.DeclaringType!); - var testResult = method.Invoke(instance, Array.Empty()); + var testResult = method.Invoke(instance, []); if (testResult is Task task) { // When the result is a task we need to await it. diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs index 02d4bd56f9..b36ace80bc 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/BlameDataCollectorTests.cs @@ -305,7 +305,7 @@ private static bool IsAdministrator() private void ValidateDump(int expectedDumpCount = 1) { - var attachments = StdOutWithWhiteSpace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) + var attachments = StdOutWithWhiteSpace.Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries) .SkipWhile(l => !l.Contains("Attachments:")).Skip(1) .Where(l => !string.IsNullOrWhiteSpace(l)) .ToList(); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs index a48cedbd97..9698a81144 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectionTests.cs @@ -106,7 +106,7 @@ public void DataCollectorAttachmentProcessor(RunnerInfo runnerInfo) string runSettings = GetRunsettingsFilePath(TempDirectory.Path); string diagFileName = Path.Combine(TempDirectory.Path, "diaglog.txt"); var extensionsPath = Path.GetDirectoryName(GetTestDllForFramework("AttachmentProcessorDataCollector.dll", "netstandard2.0")); - var arguments = PrepareArguments(new string[] { assemblyPath, secondAssemblyPath }, null, runSettings, FrameworkArgValue, runnerInfo.InIsolationValue, resultsDirectory: TempDirectory.Path); + var arguments = PrepareArguments([assemblyPath, secondAssemblyPath], null, runSettings, FrameworkArgValue, runnerInfo.InIsolationValue, resultsDirectory: TempDirectory.Path); arguments = string.Concat(arguments, $" /Diag:{diagFileName}", $" /TestAdapterPath:{extensionsPath}"); XElement runSettingsXml = XElement.Load(runSettings); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs index 4bf3b42e52..5a7284c7cf 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DataCollectorAttachmentsProcessorsFactoryTests.cs @@ -42,12 +42,12 @@ public void Cleanup() public void Create_ShouldReturnListOfAttachmentProcessors() { // arrange - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ 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); @@ -69,7 +69,7 @@ public void Create_ShouldReturnListOfAttachmentProcessors() public void Create_EmptyOrNullInvokedDataCollector_ShouldReturnCodeCoverageDataAttachmentsHandler(bool empty) { // act - var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(empty ? Array.Empty() : null, null); + var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(empty ? [] : null, null); //assert Assert.AreEqual(1, dataCollectorAttachmentsProcessors.Length); @@ -80,10 +80,12 @@ public void Create_EmptyOrNullInvokedDataCollector_ShouldReturnCodeCoverageDataA public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() { // arrange - List invokedDataCollectors = new() - { - new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", typeof(SampleData4Collector).AssemblyQualifiedName!, typeof(SampleData4Collector).Assembly.Location, true) - }; + List invokedDataCollectors = + [ + new InvokedDataCollector(new Uri("datacollector://SampleData4"), "SampleData4", + typeof(SampleData4Collector).AssemblyQualifiedName!, typeof(SampleData4Collector).Assembly.Location, + true) + ]; // act var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollectors.ToArray(), null); @@ -97,10 +99,10 @@ public void Create_ShouldNotFailIfWrongDataCollectorAttachmentProcessor() public void Create_ShouldAddTwoTimeCodeCoverageDataAttachmentsHandler() { // arrange - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ 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); @@ -129,11 +131,11 @@ public void Create_ShouldLoadOrderingByFilePath() Directory.CreateDirectory(version2); File.Copy(dataCollectorFilePath, Path.Combine(version2, Path.GetFileName(dataCollectorFilePath)), true); - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ 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.Acceptance.IntegrationTests/DiscoveryTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs index 12658fd877..5fc1cd39a3 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/DiscoveryTests.cs @@ -97,11 +97,12 @@ public void TypesToLoadAttributeTests() var extensionsDirectory = IntegrationTestEnvironment.ExtensionsDirectory; var extensionsToVerify = new Dictionary { - {"Microsoft.TestPlatform.Extensions.EventLogCollector.dll", new[] { "Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector"} }, - {"Microsoft.TestPlatform.Extensions.BlameDataCollector.dll", new[] { "Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameLogger", "Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameCollector" } }, - {"Microsoft.VisualStudio.TestPlatform.Extensions.Html.TestLogger.dll", new[] { "Microsoft.VisualStudio.TestPlatform.Extensions.HtmlLogger.HtmlLogger" } }, - {"Microsoft.VisualStudio.TestPlatform.Extensions.Trx.TestLogger.dll", new[] { "Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger.TrxLogger" } }, - {"Microsoft.TestPlatform.TestHostRuntimeProvider.dll", new[] { "Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DefaultTestHostManager", "Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager" } } + {"Microsoft.TestPlatform.Extensions.EventLogCollector.dll", ["Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector"] }, + {"Microsoft.TestPlatform.Extensions.BlameDataCollector.dll", ["Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameLogger", "Microsoft.TestPlatform.Extensions.BlameDataCollector.BlameCollector"] }, + {"Microsoft.VisualStudio.TestPlatform.Extensions.Html.TestLogger.dll", ["Microsoft.VisualStudio.TestPlatform.Extensions.HtmlLogger.HtmlLogger"] }, + {"Microsoft.VisualStudio.TestPlatform.Extensions.Trx.TestLogger.dll", ["Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger.TrxLogger"] }, + {"Microsoft.TestPlatform.TestHostRuntimeProvider.dll", ["Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DefaultTestHostManager", "Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager"] + } }; foreach (var extension in extensionsToVerify.Keys) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs index cc0979cd53..abadb1e3e5 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/EventLogCollectorTests.cs @@ -102,9 +102,9 @@ private void VaildateDataCollectorOutput(TempDirectory tempDirectory) var eventIdsDics = new Dictionary { - { new[] { "110", "111", "112" }, false }, - { new[] { "220", "221", "222", "223" }, false }, - { new[] { "330", "331", "332" }, false } + { ["110", "111", "112"], false }, + { ["220", "221", "222", "223"], false }, + { ["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 @@ -112,7 +112,7 @@ private void VaildateDataCollectorOutput(TempDirectory tempDirectory) Assert.IsTrue(VerifyOrder2(fileContent2, eventIdsDics), $"Event log file content: {fileContent2}"); Assert.IsTrue(VerifyOrder2(fileContent3, eventIdsDics), $"Event log file content: {fileContent3}"); - Assert.IsTrue(VerifyOrder(fileContent4, new[] { "110", "111", "112", "220", "221", "222", "223", "330", "331", "332" }), $"Event log file content: {fileContent4}"); + Assert.IsTrue(VerifyOrder(fileContent4, ["110", "111", "112", "220", "221", "222", "223", "330", "331", "332"]), $"Event log file content: {fileContent4}"); } private static bool VerifyOrder2(string content, Dictionary eventIdsDics) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs index c34315c42f..d798463ae2 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/CompatibilityRowsBuilder.cs @@ -155,7 +155,7 @@ public List CreateData() allRows[i].Index = i; } - return JustRow == null ? allRows : new List { allRows[JustRow.Value] }; + return JustRow == null ? allRows : [allRows[JustRow.Value]]; } private static SemanticVersion ParseAndPatchSemanticVersion(string? version) @@ -244,7 +244,7 @@ private void AddEveryVersionOfHost(List dataRows) // .NET Framework testhost ships with the runner, and the version from the // runner directory is always the same as the runner. There are no variations // so we just need to add host versions for .NET testhosts. - var hostVersions = isNetFramework ? Array.Empty() : _hostVersions.ToArray(); + var hostVersions = isNetFramework ? [] : _hostVersions.ToArray(); foreach (var hostVersion in hostVersions) { foreach (var _ in _adapters) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs index 478c595d3d..7af2fedb77 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreRunnerAttribute.cs @@ -59,7 +59,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } return dataRows; @@ -67,6 +67,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs index 5cc808dd7f..a227c37af1 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetCoreTargetFrameworkDataSourceAttribute.cs @@ -57,7 +57,7 @@ private void AddRunnerDataRow(List dataRows, string runnerFramework, s DebugVSTestConsole = DebugVSTestConsole, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } public IEnumerable GetData(MethodInfo methodInfo) @@ -83,6 +83,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs index 3ade381b25..037bb03a1a 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFrameworkRunnerAttribute.cs @@ -62,7 +62,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } return dataRows; @@ -70,6 +70,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs index c38cdde9cf..eeec157d7e 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/NetFullTargetFrameworkDataSourceAttribute.cs @@ -65,7 +65,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } if (_useDesktopRunner && isWindows) @@ -85,7 +85,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } if (_inProcess) @@ -103,7 +103,7 @@ public IEnumerable GetData(MethodInfo methodInfo) DebugDataCollector = DebugDataCollector, DebugStopAtEntrypoint = DebugStopAtEntrypoint, }; - dataRows.Add(new object[] { runnerInfo }); + dataRows.Add([runnerInfo]); } } @@ -112,6 +112,6 @@ public IEnumerable GetData(MethodInfo methodInfo) public string GetDisplayName(MethodInfo methodInfo, object?[]? data) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? Array.Empty())); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", methodInfo.Name, string.Join(",", data ?? [])); } } diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs index 8b334fcb4f..d67d02f975 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/Extension/TestDataSourceAttribute.cs @@ -18,7 +18,7 @@ public abstract class TestDataSourceAttribute : Attribute, ITestDataSource w public void AddData(T1 value1) { - _data.Add(new object[] { value1 }); + _data.Add([value1]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1) @@ -49,7 +49,7 @@ public abstract class TestDataSourceAttribute : Attribute, ITestDataSour public void AddData(T1 value1, T2 value2) { - _data.Add(new object[] { value1, value2 }); + _data.Add([value1, value2]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1, T2 value2) @@ -81,7 +81,7 @@ public abstract class TestDataSourceAttribute : Attribute, ITestData public void AddData(T1 value1, T2 value2, T3 value3) { - _data.Add(new object[] { value1, value2, value3 }); + _data.Add([value1, value2, value3]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1, T2 value2, T3 value3) @@ -108,13 +108,13 @@ public abstract class TestDataSourceAttribute : Attribute, ITest where T3 : notnull where T4 : notnull { - private readonly List _data = new(); + private readonly List _data = []; public abstract void CreateData(MethodInfo methodInfo); public void AddData(T1 value1, T2 value2, T3 value3, T4 value4) { - _data.Add(new object[] { value1, value2, value3, value4 }); + _data.Add([value1, value2, value3, value4]); } public virtual string GetDisplayName(MethodInfo methodInfo, T1 value1, T2 value2, T3 value3, T4 value4) diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs index 04ba1df6eb..a7f30c2ad9 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/FilePatternParserTests.cs @@ -67,7 +67,7 @@ public void WildCardPatternShouldCorrectlyWorkForRelativeAssemblyPath(RunnerInfo var testAssembly = GetSampleTestAssembly(); testAssembly = testAssembly.Replace("SimpleTestProject.dll", "*TestProj*.dll"); - var wildCardIndex = testAssembly.IndexOfAny(new char[] { '*' }); + var wildCardIndex = testAssembly.IndexOfAny(['*']); var testAssemblyDirectory = testAssembly.Substring(0, wildCardIndex); testAssembly = testAssembly.Substring(wildCardIndex); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs index a3092eb8d5..4bf30e4da6 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/LoggerTests.cs @@ -233,7 +233,7 @@ private static void IsFileAndContentEqual(string filePath) } string filePathContent = sb.ToString(); - string[] divs = { "Total tests", "Passed", "Failed", "Skipped", "Run duration", "Pass percentage", "PassingTest" }; + string[] divs = ["Total tests", "Passed", "Failed", "Skipped", "Run duration", "Pass percentage", "PassingTest"]; foreach (string str in divs) { StringAssert.Contains(filePathContent, str); diff --git a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs index 7a22fea29d..9675f8766c 100644 --- a/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs +++ b/test/Microsoft.TestPlatform.Acceptance.IntegrationTests/RunsettingsTests.cs @@ -47,13 +47,12 @@ public void CommandLineRunSettingsShouldWinAmongAllOptions(RunnerInfo runnerInfo var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(runConfigurationDictionary, runSettingsArgs, additionalArgs, testhostProcessName, expectedNumOfProcessCreated); } @@ -82,13 +81,12 @@ public void CLIRunsettingsShouldWinBetweenCLISwitchesAndCLIRunsettings(RunnerInf // Pass non parallel var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(null, runSettingsArgs, additionalArgs, testhostProcessName, expectedNumOfProcessCreated); } @@ -170,13 +168,12 @@ public void RunSettingsParamsAsArguments(RunnerInfo runnerInfo) var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(null, runSettingsArgs, null, testhostProcessName, expectedNumOfProcessCreated); } @@ -206,13 +203,12 @@ public void RunSettingsAndRunSettingsParamsAsArguments(RunnerInfo runnerInfo) var runSettingsArgs = string.Join( " ", - new string[] - { + [ "RunConfiguration.MaxCpuCount=1", string.Concat("RunConfiguration.TargetPlatform=",targetPlatform), string.Concat("RunConfiguration.TargetFrameworkVersion=" , GetTargetFrameworkForRunsettings()), string.Concat("RunConfiguration.TestAdaptersPaths=" , GetTestAdapterPath()) - }); + ]); RunTestWithRunSettings(runConfigurationDictionary, runSettingsArgs, null, testhostProcessName, expectedNumOfProcessCreated); } diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs index 9587f844c0..826de8e0d1 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/ManagedNameUtilities/ManagedNameParserTests.cs @@ -45,11 +45,11 @@ void AssertParse(string expectedMethod, int expectedArity, string[] expectedPara Assert.AreEqual(("Method", 0, null), Parse("Method")); Assert.AreEqual(("Method", 0, null), Parse("Method()")); Assert.AreEqual(("Method", 2, null), Parse("Method`2()")); - AssertParse("Method", 0, new string[] { "System.Int32" }, "Method(System.Int32)"); - AssertParse("Method", 0, new string[] { "TypeA", "List" }, "Method(TypeA,List)"); - AssertParse("Method", 1, new string[] { "B", "List" }, "Method`1(B,List)"); - AssertParse("Method", 0, new string[] { "B[]" }, "Method(B[])"); - AssertParse("Method", 0, new string[] { "A[,]", "B[,,][]" }, "Method(A[,],B[,,][])"); + AssertParse("Method", 0, ["System.Int32"], "Method(System.Int32)"); + AssertParse("Method", 0, ["TypeA", "List"], "Method(TypeA,List)"); + AssertParse("Method", 1, ["B", "List"], "Method`1(B,List)"); + AssertParse("Method", 0, ["B[]"], "Method(B[])"); + AssertParse("Method", 0, ["A[,]", "B[,,][]"], "Method(A[,],B[,,][])"); // An F# method that would look like this in code: member _.``method that does not pass`` () = // And like this in CIL: instance void 'method that does not pass' () cil managed diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs index 18232380ee..175ea9bcb2 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/CompatibilityTests.cs @@ -12,16 +12,16 @@ namespace Microsoft.TestPlatform.AdapterUtilities.UnitTests.TestIdProvider; public class CompatibilityTests { [TestMethod] - [DataRow(new[] { "eea339da-6b5e-0d4b-3255-bfef95601890", "" })] - [DataRow(new[] { "740b9afc-3350-4257-ca01-5bd47799147d", "adapter://", "name1" })] // less than one block - [DataRow(new[] { "119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://namesamplenam.testname" })] // 1 full block - [DataRow(new[] { "2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://namesamplenamespace.testname" })] // 1 full block and extra - [DataRow(new[] { "119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://", "name", "samplenam", ".", "testname" })] // 1 full block - [DataRow(new[] { "2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://", "name", "samplenamespace", ".", "testname" })] // 1 full block and extra - [DataRow(new[] { "1fc07043-3d2d-1401-c732-3b507feec548", "adapter://namesamplenam.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks - [DataRow(new[] { "24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://namesamplenamespace.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks and extra - [DataRow(new[] { "1fc07043-3d2d-1401-c732-3b507feec548", "adapter://", "name", "samplenam", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks - [DataRow(new[] { "24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://", "name", "samplenamespace", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" })] // 2 full blocks and extra + [DataRow(["eea339da-6b5e-0d4b-3255-bfef95601890", ""])] + [DataRow(["740b9afc-3350-4257-ca01-5bd47799147d", "adapter://", "name1"])] // less than one block + [DataRow(["119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://namesamplenam.testname"])] // 1 full block + [DataRow(["2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://namesamplenamespace.testname"])] // 1 full block and extra + [DataRow(["119c5b31-c0fb-1c12-6d1a-d617bb2bd996", "adapter://", "name", "samplenam", ".", "testname"])] // 1 full block + [DataRow(["2a4c33ec-6115-4bd7-2e94-71f2fd3a5ee3", "adapter://", "name", "samplenamespace", ".", "testname"])] // 1 full block and extra + [DataRow(["1fc07043-3d2d-1401-c732-3b507feec548", "adapter://namesamplenam.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks + [DataRow(["24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://namesamplenamespace.testnameaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks and extra + [DataRow(["1fc07043-3d2d-1401-c732-3b507feec548", "adapter://", "name", "samplenam", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks + [DataRow(["24e8a50b-2766-6a12-f461-9f8e4fa1cbb5", "adapter://", "name", "samplenamespace", ".", "testname", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])] // 2 full blocks and extra public void IdCompatibilityTests(string[] data) { // Arrange diff --git a/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs b/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs index 7c464bb381..a8ed80b8f1 100644 --- a/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs +++ b/test/Microsoft.TestPlatform.Build.UnitTests/TestTaskUtilsTests.cs @@ -3,7 +3,6 @@ using System.Text.RegularExpressions; -using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.TestPlatform.Build.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -47,7 +46,7 @@ public void CreateArgumentShouldAddCLIRunSettingsArgAtEnd() { const string codeCoverageOption = "Code Coverage"; - _vsTestTask.VSTestCollect = new string[] { codeCoverageOption }; + _vsTestTask.VSTestCollect = [codeCoverageOption]; _vsTestTask.VSTestBlame = true; const string arg1 = "RunConfiguration.ResultsDirectory=Path having Space"; @@ -79,7 +78,7 @@ public void CreateArgumentShouldPassResultsDirectoryCorrectly() public void CreateArgumentShouldNotSetConsoleLoggerVerbosityIfConsoleLoggerIsGivenInArgs() { _vsTestTask.VSTestVerbosity = "diag"; - _vsTestTask.VSTestLogger = new string[] { "Console;Verbosity=quiet" }; + _vsTestTask.VSTestLogger = ["Console;Verbosity=quiet"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -210,7 +209,7 @@ public void CreateArgumentShouldSetConsoleLoggerVerbosityToQuietIfConsoleLoggerI [TestMethod] public void CreateArgumentShouldPreserveWhiteSpaceInLogger() { - _vsTestTask.VSTestLogger = new string[] { "trx;LogFileName=foo bar.trx" }; + _vsTestTask.VSTestLogger = ["trx;LogFileName=foo bar.trx"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -234,7 +233,7 @@ public void CreateArgumentShouldAddOneCollectArgumentForEachCollect() [TestMethod] public void CreateArgumentShouldAddMultipleTestAdapterPaths() { - _vsTestTask.VSTestTestAdapterPath = new ITaskItem[] { new TaskItem("path1"), new TaskItem("path2") }; + _vsTestTask.VSTestTestAdapterPath = [new TaskItem("path1"), new TaskItem("path2")]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -245,7 +244,7 @@ public void CreateArgumentShouldAddMultipleTestAdapterPaths() [TestMethod] public void CreateArgumentShouldAddMultipleLoggers() { - _vsTestTask.VSTestLogger = new string[] { "trx;LogFileName=foo bar.trx", "console" }; + _vsTestTask.VSTestLogger = ["trx;LogFileName=foo bar.trx", "console"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); StringAssert.Contains(commandline, "--logger:\"trx;LogFileName=foo bar.trx\""); @@ -257,7 +256,7 @@ public void CreateArgumentShouldAddTraceCollectorDirectoryPathAsTestAdapterForCo { const string traceDataCollectorDirectoryPath = @"c:\path\to\tracedata collector"; _vsTestTask.VSTestTraceDataCollectorDirectoryPath = new TaskItem(traceDataCollectorDirectoryPath); - _vsTestTask.VSTestCollect = new string[] { "code coverage" }; + _vsTestTask.VSTestCollect = ["code coverage"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -270,7 +269,7 @@ public void CreateArgumentShouldNotAddTraceCollectorDirectoryPathAsTestAdapterFo { const string traceDataCollectorDirectoryPath = @"c:\path\to\tracedata collector"; _vsTestTask.VSTestTraceDataCollectorDirectoryPath = new TaskItem(traceDataCollectorDirectoryPath); - _vsTestTask.VSTestCollect = new string[] { "not code coverage" }; + _vsTestTask.VSTestCollect = ["not code coverage"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); @@ -296,7 +295,7 @@ public void CreateArgumentShouldNotAddTestAdapterPathIfVSTestTraceDataCollectorD { _vsTestTask.VSTestTraceDataCollectorDirectoryPath = null; _vsTestTask.VSTestSetting = @"c:\path\to\sample.runsettings"; - _vsTestTask.VSTestCollect = new string[] { "code coverage" }; + _vsTestTask.VSTestCollect = ["code coverage"]; var commandline = TestTaskUtils.CreateCommandLineArguments(_vsTestTask); diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs index 7ffc09294b..1a64538b9a 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Discovery/DiscoveryRequestTests.cs @@ -136,7 +136,7 @@ public void HandleDiscoveryCompleteShouldCloseDiscoveryManager() { var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), []); _discoveryManager.Verify(dm => dm.Close(), Times.Once); } @@ -148,7 +148,7 @@ public void HandleDiscoveryCompleteShouldCloseDiscoveryManagerBeforeRaiseDiscove _discoveryRequest.OnDiscoveryComplete += (s, e) => events.Add("complete"); var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(new DiscoveryCompleteEventArgs(1, false), []); Assert.AreEqual(2, events.Count); Assert.AreEqual("close", events[0]); @@ -198,7 +198,7 @@ public void HandleDiscoveryCompleteShouldCollectMetrics() discoveryCompleteEventArgs.Metrics = dict; // Act - eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, []); // Verify. mockMetricsCollector.Verify(rd => rd.Add(TelemetryDataConstants.TimeTakenInSecForDiscovery, It.IsAny()), Times.Once); @@ -247,7 +247,7 @@ public void HandleRawMessageShouldInvokeHandleDiscoveryCompleteOfLoggerManager() { TotalTests = 1, IsAborted = false, - LastDiscoveredTests = Enumerable.Empty() + LastDiscoveredTests = [] }); _discoveryRequest.HandleRawMessage(string.Empty); @@ -260,7 +260,7 @@ public void HandleDiscoveryCompleteShouldInvokeHandleDiscoveryCompleteOfLoggerMa { var discoveryCompleteEventArgs = new DiscoveryCompleteEventArgs(1, false); var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, []); _loggerManager.Verify(lm => lm.HandleDiscoveryComplete(discoveryCompleteEventArgs), Times.Once); } @@ -270,7 +270,7 @@ public void HandleDiscoveryCompleteShouldNotInvokeHandleDiscoveredTestsIfLastChu { var discoveryCompleteEventArgs = new DiscoveryCompleteEventArgs(1, false); var eventsHandler = _discoveryRequest as ITestDiscoveryEventsHandler2; - eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, Enumerable.Empty()); + eventsHandler.HandleDiscoveryComplete(discoveryCompleteEventArgs, []); _loggerManager.Verify(lm => lm.HandleDiscoveredTests(It.IsAny()), Times.Never); } diff --git a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs index e07fbe9de9..d77e39fda6 100644 --- a/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs +++ b/test/Microsoft.TestPlatform.Client.UnitTests/Execution/TestRunRequestTests.cs @@ -508,7 +508,7 @@ public void HandleTestRunCompleteShouldHandleListAttachments() bool attachmentsFound = false; _testRunRequest.OnRunCompletion += (s, e) => attachmentsFound = e.AttachmentSets != null && e.AttachmentSets.Count == 1; - List attachmentSets = new() { new AttachmentSet(new Uri("datacollector://attachment"), "datacollectorAttachment") }; + List attachmentSets = [new AttachmentSet(new Uri("datacollector://attachment"), "datacollectorAttachment")]; _testRunRequest.ExecuteAsync(); var testRunCompleteEventsArgs = new TestRunCompleteEventArgs( diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs index 2bb19a3ca6..a44997fd80 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/ExtensionDecoratorTests.cs @@ -121,7 +121,7 @@ public void SerialTestRunDecorator_Disabled(string falseValue, bool nullRunSetti testCases.Add(new TestCase() { Id = Guid.NewGuid() }); } - string[] sourcesName = new string[] { "testSource.dll" }; + string[] sourcesName = ["testSource.dll"]; _settingsMock.Setup(x => x.SettingsXml).Returns(nullRunSettings ? null : runsettings); _contextMock.Setup(x => x.RunSettings).Returns(_settingsMock.Object); diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs index ff82d8f17b..30612dfc6e 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/TestPluginCacheTests.cs @@ -30,7 +30,7 @@ public TestPluginCacheTests() // Reset the singleton. TestPluginCache.Instance = null; _mockFileHelper = new Mock(); - _testablePluginCache = new TestableTestPluginCache(new List { typeof(TestPluginCacheTests).Assembly.Location }); + _testablePluginCache = new TestableTestPluginCache([typeof(TestPluginCacheTests).Assembly.Location]); _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs index a26d10ac56..aed57338cf 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs @@ -287,28 +287,28 @@ public void MergedDictionaryShouldBeEquivalentToTheExpectedDictionary() var first = new Dictionary> { // Merged with "key1" from the next set. - { "key1", new HashSet(new List() { "ext1", "ext2", "ext3" }) }, + { "key1", ["ext1", "ext2", "ext3"] }, // Empty hashset, will be removed from the result. - { "key2", new HashSet() }, + { "key2", [] }, // Added as is. - { "key5", new HashSet(new List() { "ext1", "ext2" }) } + { "key5", ["ext1", "ext2"] } }; var second = new Dictionary> { // Merged with "key1" from the previous set. - { "key1", new HashSet(new List() { "ext2", "ext3", "ext3", "ext4", "ext5" }) }, + { "key1", ["ext2", "ext3", "ext3", "ext4", "ext5"] }, // Empty hashset, will be removed from the result. - { "key2", new HashSet() }, + { "key2", [] }, // Empty hashset, will be removed from the result. - { "key3", new HashSet() }, + { "key3", [] }, // Added as is. - { "key4", new HashSet(new List() { "ext1" }) } + { "key4", ["ext1"] } }; var expected = new Dictionary> { - { "key1", new HashSet(new List() { "ext1", "ext2", "ext3", "ext4", "ext5" }) }, - { "key4", new HashSet(new List() { "ext1" }) }, - { "key5", new HashSet(new List() { "ext1", "ext2" }) } + { "key1", ["ext1", "ext2", "ext3", "ext4", "ext5"] }, + { "key4", ["ext1"] }, + { "key5", ["ext1", "ext2"] } }; // Merge the two dictionaries. @@ -329,9 +329,9 @@ public void AddExtensionTelemetryShouldAddJsonFormattedDiscoveredExtensionsTelem var telemetryData = new Dictionary(); var extensions = new Dictionary> { - { "key1", new HashSet(new List() { "ext1", "ext2", "ext3", "ext4", "ext5" }) }, - { "key4", new HashSet(new List() { "ext1" }) }, - { "key5", new HashSet(new List() { "ext1", "ext2" }) } + { "key1", ["ext1", "ext2", "ext3", "ext4", "ext5"] }, + { "key4", ["ext1"] }, + { "key5", ["ext1", "ext2"] } }; var expectedTelemetry = diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs index 849484134a..5077e68760 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Logging/InternalTestLoggerEventsTests.cs @@ -250,7 +250,7 @@ public void RaiseDiscoveredTestsShouldThrowExceptionIfNullDiscoveredTestsEventAr public void RaiseDiscoveredTestsShouldThrowExceptionIfAlreadyDisposed() { var loggerEvents = GetDisposedLoggerEvents(); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); Assert.ThrowsException(() => loggerEvents.RaiseDiscoveredTests(discoveredTestsEventArgs)); @@ -266,7 +266,7 @@ public void RaiseDiscoveredTestsShouldInvokeRegisteredEventHandler() DiscoveredTestsEventArgs? receivedEventArgs = null; EventWaitHandle waitHandle = new AutoResetEvent(false); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); // Register for the discovered tests event. diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs index 1b1b598cdc..a26dbdcdc1 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/FakesUtilitiesTests.cs @@ -25,14 +25,14 @@ public void FakesSettingsShouldThrowExceptionIfSourcesArePassedAsNull() [TestMethod] public void FakesSettingsShouldThrowExceptionIfRunSettingsIsPassedAsNull() { - Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration(Array.Empty(), null!)); + Assert.ThrowsException(() => FakesUtilities.GenerateFakesSettingsForRunConfiguration([], null!)); } [TestMethod] public void FakesSettingsShouldBeNotGeneratedIfFakeConfiguratorAssemblyIsNotPresent() { string runSettingsXml = @""; - var generatedRunSettings = FakesUtilities.GenerateFakesSettingsForRunConfiguration(new string[] { @"C:\temp\UT.dll" }, runSettingsXml); + var generatedRunSettings = FakesUtilities.GenerateFakesSettingsForRunConfiguration([@"C:\temp\UT.dll"], runSettingsXml); Assert.AreEqual(generatedRunSettings, runSettingsXml); } diff --git a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs index 767417c4a8..f0b1133c56 100644 --- a/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Common.UnitTests/Utilities/RunSettingsUtilitiesTests.cs @@ -95,7 +95,7 @@ public void GetMaxCpuCountWithInvalidCpuCountShouldReturnDefaultCpuCount() public void GetTestAdaptersPaths() { string settingXml = @"C:\testadapterpath;D:\secondtestadapterpath"; - string[] expectedResult = new string[] { @"C:\testadapterpath", @"D:\secondtestadapterpath" }; + string[] expectedResult = [@"C:\testadapterpath", @"D:\secondtestadapterpath"]; string[] result = (string[])RunSettingsUtilities.GetTestAdaptersPaths(settingXml); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs index db25959ca0..7d352a6327 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.Platform.UnitTests/SocketCommunicationManagerTests.cs @@ -358,7 +358,7 @@ private static void WriteOnSocket(Socket socket) { for (int i = 0; i < 10; i++) { - socket.Send(new byte[2] { 0x1, 0x0 }); + socket.Send([0x1, 0x0]); } } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs index 81245148c2..311230f716 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestSenderTests.cs @@ -44,7 +44,7 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachments() attachment.Attachments.Add(new UriDataAttachment(attachmentUri, "filename.txt")); var invokedDataCollector = new InvokedDataCollector(datacollectorUri, displayName, typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false); _mockDataSerializer.Setup(x => x.DeserializePayload(It.IsAny())).Returns( - new AfterTestRunEndResult(new Collection() { attachment }, new Collection() { invokedDataCollector }, new Dictionary())); + new AfterTestRunEndResult([attachment], new Collection() { invokedDataCollector }, new Dictionary())); _mockCommunicationManager.SetupSequence(x => x.ReceiveRawMessage()).Returns(rawMessage1).Returns(rawMessage2); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage1)).Returns(new Message() { MessageType = MessageType.TelemetryEventMessage, Payload = null }); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage2)).Returns(new Message() { MessageType = MessageType.AfterTestRunEndResult, Payload = null }); @@ -80,7 +80,7 @@ public void SendAfterTestRunEndAndGetResultShouldReturnAttachmentsAndPropagateTe attachment.Attachments.Add(new UriDataAttachment(attachmentUri, "filename.txt")); var invokedDataCollector = new InvokedDataCollector(datacollectorUri, displayName, typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false); _mockDataSerializer.Setup(x => x.DeserializePayload(It.IsAny())).Returns( - new AfterTestRunEndResult(new Collection() { attachment }, new Collection() { invokedDataCollector }, new Dictionary())); + new AfterTestRunEndResult([attachment], new Collection() { invokedDataCollector }, new Dictionary())); _mockCommunicationManager.SetupSequence(x => x.ReceiveRawMessage()).Returns(rawMessage1).Returns(rawMessage2); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage1)).Returns(new Message() { MessageType = MessageType.TelemetryEventMessage, Payload = null }); _mockDataSerializer.Setup(x => x.DeserializeMessage(rawMessage2)).Returns(new Message() { MessageType = MessageType.AfterTestRunEndResult, Payload = null }); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs index 3fa3d0c968..8cdeb06831 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs @@ -35,7 +35,7 @@ public class TestRequestSenderTests private readonly Mock _mockDataSerializer; private readonly Mock _mockChannel; - private readonly List _pathToAdditionalExtensions = new() { "Hello", "World" }; + private readonly List _pathToAdditionalExtensions = ["Hello", "World"]; private readonly Mock _mockDiscoveryEventsHandler; private readonly Mock _mockExecutionEventsHandler; private readonly TestRunCriteriaWithSources _testRunCriteriaWithSources; diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs index 7f9b7cf5f0..1b7ec113d6 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs @@ -33,7 +33,7 @@ public void GetArgumentsDictionaryShouldIgnoreValuesWithoutPreceedingHypen() Assert.AreEqual("2312", argsDictionary["--parentprocessid"]); Assert.AreEqual(@"C:\temp\1.dll", argsDictionary["--testsourcepath"]); - args = new List() { "--port", "12312", "--parentprocessid", "2312", "testsourcepath", @"C:\temp\1.dll" }; + args = ["--port", "12312", "--parentprocessid", "2312", "testsourcepath", @"C:\temp\1.dll"]; argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); Assert.IsTrue(argsDictionary.Count == 2); @@ -81,7 +81,7 @@ public void GetArgumentsDictionaryShouldReturnEmptyDictionaryIfEmptyArgIsPassed( var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(null); Assert.IsTrue(argsDictionary.Count == 0); - argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(System.Array.Empty()); + argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary([]); Assert.IsTrue(argsDictionary.Count == 0); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs index 24da177a5d..54bb5e48e6 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/TestRunAttachmentsProcessingManagerTests.cs @@ -56,11 +56,10 @@ public TestRunAttachmentsProcessingManagerTests() _mockAttachmentHandler1.Setup(h => h.GetExtensionUris()).Returns(new[] { new Uri(Uri1) }); _mockAttachmentHandler2.Setup(h => h.GetExtensionUris()).Returns(new[] { new Uri(Uri2) }); _mockDataCollectorAttachmentsProcessorsFactory.Setup(p => p.Create(It.IsAny(), It.IsAny())) - .Returns(new DataCollectorAttachmentProcessor[] - { + .Returns([ new( "friendlyNameA", _mockAttachmentHandler1.Object ), new( "friendlyNameB" ,_mockAttachmentHandler2.Object ) - }); + ]); _manager = new TestRunAttachmentsProcessingManager(_mockEventSource.Object, _mockDataCollectorAttachmentsProcessorsFactory.Object); @@ -114,10 +113,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnNoAttachments_IfNoA public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttachmentThroughEventsHandler_If1NotRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri3), "uri3_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri3), "uri3_input")]; // act await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _mockEventsHandler.Object, _cancellationTokenSource.Token); @@ -138,10 +134,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttach public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttachment_If1NotRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri3), "uri3_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri3), "uri3_input")]; // act var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); @@ -161,15 +154,9 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1NotProcessedAttach public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachmentThroughEventsHandler_IfRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; - List outputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachments); @@ -192,15 +179,9 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachmen public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachment_IfRelatedAttachmentOnInput() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; - List outputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachments); @@ -224,10 +205,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturn1ProcessedAttachmen public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsThroughEventsHandler_IfRelatedAttachmentOnInputButHandlerThrowsException() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; var exceptionToThrow = new Exception("exception message"); _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).Throws(exceptionToThrow); @@ -251,10 +229,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsT public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_IfRelatedAttachmentOnInputButHandlerThrowsException() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).Throws(new Exception("exception message")); @@ -277,10 +252,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsT { // arrange _cancellationTokenSource.Cancel(); - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; // act await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _mockEventsHandler.Object, _cancellationTokenSource.Token); @@ -301,10 +273,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ { // arrange _cancellationTokenSource.Cancel(); - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; // act var result = await _manager.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, inputAttachments, Array.Empty(), _cancellationTokenSource.Token); @@ -324,24 +293,18 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachmentsThroughEventsHandler_IfRelatedAttachmentsOnInput() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri1), "uri1_input2"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input2"), - new AttachmentSet(new Uri(Uri3), "uri3_input1"), - }; + new AttachmentSet(new Uri(Uri3), "uri3_input1") + ]; - List outputAttachmentsForHandler1 = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachmentsForHandler1 = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; - List outputAttachmentsForHandler2 = new() - { - new AttachmentSet(new Uri(Uri2), "uri2_output") - }; + List outputAttachmentsForHandler2 = [new AttachmentSet(new Uri(Uri2), "uri2_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler1); _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(null!, It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler2); @@ -365,24 +328,18 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachment public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachments_IfRelatedAttachmentsOnInput() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri1), "uri1_input2"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input2"), - new AttachmentSet(new Uri(Uri3), "uri3_input1"), - }; + new AttachmentSet(new Uri(Uri3), "uri3_input1") + ]; - List outputAttachmentsForHandler1 = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_output") - }; + List outputAttachmentsForHandler1 = [new AttachmentSet(new Uri(Uri1), "uri1_output")]; - List outputAttachmentsForHandler2 = new() - { - new AttachmentSet(new Uri(Uri2), "uri2_output") - }; + List outputAttachmentsForHandler2 = [new AttachmentSet(new Uri(Uri2), "uri2_output")]; _mockAttachmentHandler1.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler1); _mockAttachmentHandler2.Setup(h => h.ProcessAttachmentSetsAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny(), It.IsAny())).ReturnsAsync(outputAttachmentsForHandler2); @@ -407,10 +364,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProcessedAttachment public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsThroughEventsHandler_IfOperationCancelled() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; ICollection outputAttachments = new List { @@ -491,10 +445,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachmentsT public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_IfOperationCancelled() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input")]; ICollection outputAttachments = new List { @@ -552,11 +503,11 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnInitialAttachments_ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProperlySendProgressEvents_IfHandlersPropagesEvents() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input"), new AttachmentSet(new Uri(Uri2), "uri2_input") - }; + ]; ICollection outputAttachments1 = new List { @@ -628,11 +579,11 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldReturnProperlySendProgres public async Task ProcessTestRunAttachmentsAsync_ShouldNotFailIfRunsettingsIsNull() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input"), new AttachmentSet(new Uri(Uri2), "uri2_input") - }; + ]; ICollection outputAttachments = new List { new(new Uri(Uri2), "uri2_output") @@ -658,16 +609,16 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldNotFailIfRunsettingsIsNul public async Task ProcessTestRunAttachmentsAsync_ShouldFlowCorrectDataCollectorConfiguration(bool withConfig) { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input"), new AttachmentSet(new Uri(Uri2), "uri2_input") - }; + ]; - List invokedDataCollectors = new() - { + List invokedDataCollectors = + [ new InvokedDataCollector(new Uri(Uri1), withConfig ? "friendlyNameA" : "friendlyNameB", typeof(string).AssemblyQualifiedName!, typeof(string).Assembly.Location, false) - }; + ]; string runSettingsXml = $@" @@ -716,10 +667,7 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldFlowCorrectDataCollectorC public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfProcessorFails() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input_1") - }; + List inputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input_1")]; inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file1", "Sample1")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file2", "Sample2")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file3", "Sample3")); @@ -778,10 +726,10 @@ public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfPr public async Task ProcessTestRunAttachmentsAsync_ShouldNotConsumeAttachmentsIfAllProcessorsFail() { // arrange - List inputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input_1"), - }; + List inputAttachments = + [ + new AttachmentSet(new Uri(Uri1), "uri1_input_1") + ]; inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file1", "Sample1")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file2", "Sample2")); inputAttachments[0].Attachments.Add(UriDataAttachment.CreateFrom("file3", "Sample3")); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs index 879ef89150..4e0c03058d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyDiscoveryManagerTests.cs @@ -40,7 +40,7 @@ public InProcessProxyDiscoveryManagerTests() public void DiscoverTestsShouldCallInitialize() { var manualResetEvent = new ManualResetEvent(false); - _mockDiscoveryManager.Setup(o => o.Initialize(Enumerable.Empty(), null)).Callback( + _mockDiscoveryManager.Setup(o => o.Initialize(Array.Empty(), null)).Callback( () => manualResetEvent.Set()); var discoveryCriteria = new DiscoveryCriteria(new[] { "test.dll" }, 1, string.Empty); @@ -53,7 +53,7 @@ public void DiscoverTestsShouldCallInitialize() public void DiscoverTestsShouldUpdateTestPluginCacheWithExtensionsReturnByTestHost() { var manualResetEvent = new ManualResetEvent(false); - _mockDiscoveryManager.Setup(o => o.Initialize(Enumerable.Empty(), null)).Callback( + _mockDiscoveryManager.Setup(o => o.Initialize(Array.Empty(), null)).Callback( () => manualResetEvent.Set()); var path = Path.Combine(Path.GetTempPath(), "DiscoveryDummy.dll"); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs index 6ef4ea3f74..4122e2cbdc 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/InProcessProxyexecutionManagerTests.cs @@ -44,7 +44,7 @@ public void StartTestRunShouldCallInitialize() var mockTestMessageEventHandler = new Mock(); _inProcessProxyExecutionManager.StartTestRun(testRunCriteria, null!); - _mockExecutionManager.Verify(o => o.Initialize(Enumerable.Empty(), It.IsAny()), Times.Once, "StartTestRun should call Initialize if not already initialized"); + _mockExecutionManager.Verify(o => o.Initialize(Array.Empty(), It.IsAny()), Times.Once, "StartTestRun should call Initialize if not already initialized"); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs index 066afb05cb..37cfb2764d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyDiscoveryManagerTests.cs @@ -30,7 +30,7 @@ public class ParallelProxyDiscoveryManagerTests private readonly List> _usedMockManagers; private readonly Func _createMockManager; private readonly Mock _mockEventHandler; - private readonly List _sources = new() { "1.dll", "2.dll" }; + private readonly List _sources = ["1.dll", "2.dll"]; private readonly DiscoveryCriteria _discoveryCriteriaWith2Sources; private readonly List _runtimeProviders; private int _createMockManagerCalled; @@ -70,11 +70,10 @@ public ParallelProxyDiscoveryManagerTests() _mockEventHandler = new Mock(); _discoveryCriteriaWith2Sources = new DiscoveryCriteria(_sources, 100, null); _runtimeProviders = new List { - new(typeof(ITestRuntimeProvider), false, "", new List - { + new(typeof(ITestRuntimeProvider), false, "", [ new() { Source = _sources[0], Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, new() { Source = _sources[1], Architecture = Architecture.X86, Framework = Framework.DefaultFramework } - }) + ]) }; // This event is Set by callback from _mockEventHandler in SetupDiscoveryManager diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs index 061e6c00a2..2ac3486f2f 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelProxyExecutionManagerTests.cs @@ -73,13 +73,12 @@ public ParallelProxyExecutionManagerTests() _processedSources = new List(); _testRunCriteriaWith2Sources = new TestRunCriteria(_sources, 100, false, string.Empty, TimeSpan.MaxValue, null, "Name~Test", new FilterOptions() { FilterRegEx = @"^[^\s\(]+" }); _runtimeProviders = new List { - new(typeof(ITestRuntimeProvider), false, "", new List - { + new(typeof(ITestRuntimeProvider), false, "", [ new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, new() { Source = "2.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, // For testcases on the bottom. - new() { Source = "3.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, - }) + new() { Source = "3.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } + ]) }; // Configure testcases diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs index a9774c1367..b78ab647f8 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyDiscoveryManagerTests.cs @@ -222,7 +222,7 @@ public void DiscoverTestsShouldQueryTestHostManagerForExtensions() TestPluginCache.Instance = null; try { - TestPluginCacheHelper.SetupMockAdditionalPathExtensions(new[] { "c:\\e1.dll" }); + TestPluginCacheHelper.SetupMockAdditionalPathExtensions(["c:\\e1.dll"]); _mockFileHelper.Setup(fh => fh.Exists(It.IsAny())).Returns(true); _mockRequestSender.Setup(s => s.WaitForRequestHandlerConnection(It.IsAny(), It.IsAny())).Returns(true); _mockTestHostManager.Setup(th => th.GetTestPlatformExtensions(It.IsAny>(), It.IsAny>())).Returns(new[] { "he1.dll", "c:\\e1.dll" }); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs index 416a12ca8c..286c193f53 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs @@ -320,7 +320,7 @@ public void SetupChannelShouldThrowExceptionWithAllSourcesIfTestHostExitedBefore _mockRequestSender.Setup(s => s.WaitForRequestHandlerConnection(It.IsAny(), It.IsAny())).Returns(false); _mockTestHostManager.Setup(tmh => tmh.LaunchTestHostAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(true)).Callback(() => _mockTestHostManager.Raise(t => t.HostExited += null, new HostProviderEventArgs("I crashed!"))); - Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.Resources.TestHostExitedWithError, string.Join("', '", new[] { "source1.dll", "source2.dll" }), "I crashed!"), Assert.ThrowsException(() => _testExecutionManager.SetupChannel(new List { "source1.dll", "source2.dll" }, runsettings)).Message); + Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.Resources.TestHostExitedWithError, string.Join("', '", ["source1.dll", "source2.dll"]), "I crashed!"), Assert.ThrowsException(() => _testExecutionManager.SetupChannel(new List { "source1.dll", "source2.dll" }, runsettings)).Message); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs index 6e1dc96b61..a38583a79e 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; @@ -72,10 +71,10 @@ public void SetupChannelShouldLaunchTestHost() var expectedStartInfo = new TestProcessStartInfo(); _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); _mockTestHostManager.Setup( - th => th.GetTestHostProcessStartInfo(Enumerable.Empty(), It.IsAny>(), It.IsAny())) + th => th.GetTestHostProcessStartInfo(Array.Empty(), It.IsAny>(), It.IsAny())) .Returns(expectedStartInfo); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify(thl => thl.LaunchTestHostAsync(It.Is(si => si == expectedStartInfo), It.IsAny()), Times.Once); } @@ -86,7 +85,7 @@ public void SetupChannelShouldCreateTimestampedLogFileForHost() _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); EqtTrace.InitializeTrace("log.txt", PlatformTraceLevel.Verbose); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify( th => @@ -125,7 +124,7 @@ public void SetupChannelOutcomeShouldTakeTesthostSessionSupportIntoAccount( }; Assert.IsTrue(testOperationManager.IsTesthostCompatibleWithTestSessions() == expectedCompatibilityCheckResult); - Assert.IsTrue(testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings) == expectedSetupResult); + Assert.IsTrue(testOperationManager.SetupChannel([], DefaultRunSettings) == expectedSetupResult); } [TestMethod] @@ -133,7 +132,7 @@ public void SetupChannelShouldAddRunnerProcessIdForTestHost() { _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); #if NET5_0_OR_GREATER var pid = Environment.ProcessId; @@ -161,7 +160,7 @@ public void SetupChannelShouldAddCorrectTraceLevelForTestHost() #endif _mockRequestSender.Setup(rs => rs.InitializeCommunication()).Returns(123); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify( th => @@ -174,7 +173,7 @@ public void SetupChannelShouldAddCorrectTraceLevelForTestHost() [TestMethod] public void SetupChannelShouldSetupServerForCommunication() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(s => s.InitializeCommunication(), Times.Once); } @@ -201,7 +200,7 @@ public void SetupChannelShouldCallHostServerIfRunnerIsServer() var localTestOperationManager = new TestableProxyOperationManager(_mockRequestData.Object, testRequestSender, _mockTestHostManager.Object); - localTestOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + localTestOperationManager.SetupChannel([], DefaultRunSettings); mockCommunicationServer.Verify(s => s.Start(IPAddress.Loopback.ToString() + ":0"), Times.Once); } @@ -229,7 +228,7 @@ public void SetupChannelShouldCallSetupClientIfRunnerIsClient() var localTestOperationManager = new TestableProxyOperationManager(_mockRequestData.Object, testRequestSender, _mockTestHostManager.Object); - localTestOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + localTestOperationManager.SetupChannel([], DefaultRunSettings); mockCommunicationEndpoint.Verify(s => s.Start(It.IsAny()), Times.Once); } @@ -237,8 +236,8 @@ public void SetupChannelShouldCallSetupClientIfRunnerIsClient() [TestMethod] public void SetupChannelShouldNotInitializeIfConnectionIsAlreadyInitialized() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(s => s.InitializeCommunication(), Times.Once); } @@ -246,7 +245,7 @@ public void SetupChannelShouldNotInitializeIfConnectionIsAlreadyInitialized() [TestMethod] public void SetupChannelShouldWaitForTestHostConnection() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny()), Times.Once); } @@ -254,8 +253,8 @@ public void SetupChannelShouldWaitForTestHostConnection() [TestMethod] public void SetupChannelShouldNotWaitForTestHostConnectionIfConnectionIsInitialized() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny()), Times.Exactly(1)); } @@ -266,7 +265,7 @@ public void SetupChannelShouldHonorTimeOutSetByUser() Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, "100"); _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(100000, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.WaitForRequestHandlerConnection(100000, It.IsAny()), Times.Exactly(1)); } @@ -279,7 +278,7 @@ public void SetupChannelShouldThrowIfWaitForTestHostConnectionTimesOut() var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Assert.AreEqual(message, TimoutErrorMessage); } @@ -293,7 +292,7 @@ public void SetupChannelShouldThrowTestPlatformExceptionIfRequestCancelled() var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object, cancellationTokenSource); cancellationTokenSource.Cancel(); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Equals("Canceling the operation as requested.", message); } @@ -308,7 +307,7 @@ public void SetupChannelShouldThrowTestPlatformExceptionIfRequestCancelledDuring var cancellationTokenSource = new CancellationTokenSource(); var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object, cancellationTokenSource); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Equals("Canceling the operation as requested.", message); } @@ -322,7 +321,7 @@ public void SetupChannelShouldThrowTestPlatformExceptionIfRequestCancelledPostHo _mockTestHostManager.Setup(rs => rs.LaunchTestHostAsync(It.IsAny(), It.IsAny())).Callback(() => cancellationTokenSource.Cancel()); var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object, cancellationTokenSource); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Equals("Canceling the operation as requested.", message); } @@ -334,14 +333,14 @@ public void SetupChannelShouldThrowIfLaunchTestHostFails() var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object); - var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; + var message = Assert.ThrowsException(() => operationManager.SetupChannel([], DefaultRunSettings)).Message; Assert.AreEqual(message, Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Resources.Resources.InitializationFailed); } [TestMethod] public void SetupChannelShouldCheckVersionWithTestHost() { - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.CheckVersionWithTestHost(), Times.Once); } @@ -350,7 +349,7 @@ public void SetupChannelShouldThrowExceptionIfVersionCheckFails() { // Make the version check fail _mockRequestSender.Setup(rs => rs.CheckVersionWithTestHost()).Throws(new TestPlatformException("Version check failed")); - Assert.ThrowsException(() => _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)); + Assert.ThrowsException(() => _testOperationManager.SetupChannel([], DefaultRunSettings)); } [TestMethod] @@ -362,7 +361,7 @@ public void SetupChannelForDotnetHostManagerWithIsVersionCheckRequiredFalseShoul var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, testHostManager); - operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + operationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.CheckVersionWithTestHost(), Times.Never); } @@ -375,7 +374,7 @@ public void SetupChannelForDotnetHostManagerWithIsVersionCheckRequiredTrueShould testHostManager.Initialize(new NullMessageLogger(), DefaultRunSettings); var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, testHostManager); - operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + operationManager.SetupChannel([], DefaultRunSettings); _mockRequestSender.Verify(rs => rs.CheckVersionWithTestHost(), Times.Once); } @@ -384,7 +383,7 @@ public void SetupChannelForDotnetHostManagerWithIsVersionCheckRequiredTrueShould public void CloseShouldEndSessionIfHostWasLaunched() { _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _testOperationManager.Close(); @@ -412,11 +411,11 @@ public void CloseShouldResetChannelInitialization() { SetupWaitForTestHostExit(); _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _testOperationManager.Close(); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _mockTestHostManager.Verify(th => th.LaunchTestHostAsync(It.IsAny(), It.IsAny()), Times.Exactly(2)); } @@ -425,7 +424,7 @@ public void CloseShouldTerminateTesthostProcessIfWaitTimesout() { // Ensure testhost start returns a dummy process id _mockRequestSender.Setup(rs => rs.WaitForRequestHandlerConnection(ConnectionTimeout, It.IsAny())).Returns(true); - _testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + _testOperationManager.SetupChannel([], DefaultRunSettings); _testOperationManager.Close(); @@ -472,7 +471,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgTrueIfTelem .Returns(Task.FromResult(true)); // Act. - testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + testOperationManager.SetupChannel([], DefaultRunSettings); // Verify. Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin true")); @@ -495,7 +494,7 @@ public void UpdateTestProcessStartInfoShouldUpdateTelemetryOptedInArgFalseIfTele .Returns(Task.FromResult(true)); // Act. - testOperationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings); + testOperationManager.SetupChannel([], DefaultRunSettings); // Verify. Assert.IsTrue(receivedTestProcessInfo.Arguments!.Contains("--telemetryoptedin false")); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs index 615c62c2bd..853bfa8486 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyTestSessionManagerTests.cs @@ -108,14 +108,14 @@ public ProxyTestSessionManagerTests() _fakeTestSourcesToRuntimeProviderMap = new Dictionary { - [_fakeTestSources[0]] = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, _fakeRunSettings, new List - { - new() { + [_fakeTestSources[0]] = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, _fakeRunSettings, [ + new() + { Source = _fakeTestSources[0], Architecture = Architecture.X86, Framework = Framework.DefaultFramework } - }) + ]) }; } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs index 681ac0e675..bb923e63bb 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ParallelDataCollectionEventsHandlerTests.cs @@ -54,17 +54,14 @@ public ParallelDataCollectionEventsHandlerTests() public void HandleTestRunComplete_ShouldCallProcessTestRunAttachmentsAsyncWithAttachmentsAndUseResults() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri3), "uri3_input1") - }; + ]; - Collection outputAttachments = new() - { - new AttachmentSet(new Uri(Uri1), "uri1_input1") - }; + Collection outputAttachments = [new AttachmentSet(new Uri(Uri1), "uri1_input1")]; _mockTestRunAttachmentsProcessingManager.Setup(f => f.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult(outputAttachments)); @@ -80,12 +77,12 @@ public void HandleTestRunComplete_ShouldCallProcessTestRunAttachmentsAsyncWithAt public void HandleTestRunComplete_ShouldCallProcessTestRunAttachmentsAsyncWithAttachmentsAndNotUserResults_IfManagerReturnsNull() { // arrange - List inputAttachments = new() - { + List inputAttachments = + [ new AttachmentSet(new Uri(Uri1), "uri1_input1"), new AttachmentSet(new Uri(Uri2), "uri2_input1"), new AttachmentSet(new Uri(Uri3), "uri3_input1") - }; + ]; _mockTestRunAttachmentsProcessingManager.Setup(f => f.ProcessTestRunAttachmentsAsync(Constants.EmptyRunSettings, _mockRequestData.Object, It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult((Collection)null!)); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs index ec44ce64b4..3215c024a3 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs @@ -49,7 +49,8 @@ public DiscovererEnumeratorTests() _discovererEnumerator = new DiscovererEnumerator(_mockRequestData.Object, _discoveryResultCache, _mockTestPlatformEventSource.Object, _mockAssemblyProperties.Object, _cancellationTokenSource.Token); _runSettingsMock = new Mock(); _messageLoggerMock = new Mock(); - TestPluginCacheHelper.SetupMockExtensions(new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + TestPluginCacheHelper.SetupMockExtensions( + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); TestDiscoveryExtensionManager.Destroy(); } @@ -70,7 +71,7 @@ public void Cleanup() public void LoadTestsShouldReportWarningOnNoDiscoverers() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(TestPluginCache).Assembly.Location }, + [typeof(TestPluginCache).Assembly.Location], () => { }); var sources = new List { typeof(DiscoveryResultCacheTests).Assembly.Location }; @@ -90,7 +91,7 @@ public void LoadTestsShouldReportWarningOnNoDiscoverers() public void LoadTestsShouldNotCallIntoDiscoverersIfNoneMatchesSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List { "temp.jpeg" }; @@ -115,7 +116,7 @@ public void LoadTestsShouldNotCallIntoDiscoverersIfNoneMatchesSources() public void LoadTestsShouldCallOnlyNativeDiscovererIfNativeAssembliesPassed() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); _mockAssemblyProperties.Setup(pe => pe.GetAssemblyType("native.dll")).Returns(AssemblyType.Native); @@ -150,7 +151,7 @@ public void LoadTestsShouldCallOnlyNativeDiscovererIfNativeAssembliesPassed() public void LoadTestsShouldCallOnlyManagedDiscovererIfManagedAssembliesPassed() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); _mockAssemblyProperties.Setup(pe => pe.GetAssemblyType("managed.dll")).Returns(AssemblyType.Managed); @@ -185,7 +186,7 @@ public void LoadTestsShouldCallOnlyManagedDiscovererIfManagedAssembliesPassed() public void LoadTestsShouldCallBothNativeAndManagedDiscoverersWithCorrectSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); _mockAssemblyProperties.Setup(pe => pe.GetAssemblyType("native.dll")).Returns(AssemblyType.Native); @@ -228,7 +229,7 @@ public void LoadTestsShouldCallBothNativeAndManagedDiscoverersWithCorrectSources public void LoadTestsShouldCallIntoADiscovererThatMatchesTheSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -269,7 +270,7 @@ public void LoadTestsShouldCallIntoADiscovererThatMatchesTheSources() public void LoadTestsShouldCallIntoMultipleDiscoverersThatMatchesTheSources() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var dllsources = new List @@ -350,7 +351,7 @@ public void LoadTestsShouldCallIntoMultipleDiscoverersThatMatchesTheSources() public void LoadTestsShouldCallIntoOtherDiscoverersWhenCreatingOneFails() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -394,7 +395,7 @@ public void LoadTestsShouldCallIntoOtherDiscoverersWhenCreatingOneFails() public void LoadTestsShouldCallIntoOtherDiscoverersEvenIfDiscoveryInOneFails() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -449,7 +450,7 @@ public void LoadTestsShouldCollectMetrics() }; TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -484,7 +485,7 @@ public void LoadTestsShouldCollectMetrics() public void LoadTestsShouldNotCallIntoDiscoverersWhenCancelled() { // Setup - string[] extensions = new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }; + string[] extensions = [typeof(DiscovererEnumeratorTests).Assembly.Location]; TestPluginCacheHelper.SetupMockExtensions(extensions, () => { }); var dllsources = new List @@ -572,7 +573,7 @@ public void LoadTestShouldInstrumentAdapterDiscoveryStop() public void LoadTestsShouldIterateOverAllExtensionsInTheMapAndDiscoverTests() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var dllsources = new List @@ -696,7 +697,7 @@ private static void SetupForNoTestsAvailableInGivenAssemblies( private void InvokeLoadTestWithMockSetup() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs index dca3280bf7..86fee2b8d9 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscoveryManagerTests.cs @@ -160,7 +160,7 @@ public void DiscoverTestsShouldLogIfThereAreNoValidSources() public void DiscoverTestsShouldLogIfTheSameSourceIsSpecifiedTwice() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -187,7 +187,7 @@ public void DiscoverTestsShouldLogIfTheSameSourceIsSpecifiedTwice() public void DiscoverTestsShouldDiscoverTestsInTheSpecifiedSource() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -215,7 +215,7 @@ public void DiscoverTestsShouldSendMetricsOnDiscoveryComplete() DiscoveryCompleteEventArgs? receivedDiscoveryCompleteEventArgs = null; TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -253,7 +253,7 @@ public void DiscoverTestsShouldCollectMetrics() _mockRequestData.Setup(rd => rd.MetricsCollection).Returns(mockMetricsCollector.Object); TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(DiscovererEnumeratorTests).Assembly.Location }, + [typeof(DiscovererEnumeratorTests).Assembly.Location], () => { }); var sources = new List @@ -278,7 +278,7 @@ public void DiscoveryInitializeShouldVerifyWarningMessageIfAdapterFailedToLoad() var assemblyLocation = typeof(DiscoveryManagerTests).Assembly.Location; var mockLogger = new Mock(); TestPluginCacheHelper.SetupMockExtensions( - new string[] { assemblyLocation }, + [assemblyLocation], () => { }); //Act diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs index 89b6b64aa6..f57cf09db5 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs @@ -200,7 +200,7 @@ public void ProcessRequestsDiscoveryStartShouldStartDiscoveryWithGivenCriteria() [TestMethod] public void DiscoveryCompleteShouldSendDiscoveryCompletePayloadOnChannel() { - var discoveryComplete = new DiscoveryCompletePayload { TotalTests = 1, LastDiscoveredTests = Enumerable.Empty(), IsAborted = false }; + var discoveryComplete = new DiscoveryCompletePayload { TotalTests = 1, LastDiscoveredTests = [], IsAborted = false }; var message = _dataSerializer.SerializePayload(MessageType.DiscoveryComplete, discoveryComplete); ProcessRequestsAsync(_mockTestHostManagerFactory.Object); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs index b1aeeffeaa..4f7194fd83 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs @@ -91,7 +91,7 @@ public BaseRunTestsTests() new PlatformThread(), _mockDataSerializer.Object); - TestPluginCacheHelper.SetupMockExtensions(new string[] { typeof(BaseRunTestsTests).Assembly.Location }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([typeof(BaseRunTestsTests).Assembly.Location], () => { }); } [TestCleanup] @@ -809,7 +809,7 @@ private void SetupForExecutionThreadApartmentStateTests(PlatformApartmentState a _mockThread.Object, _mockDataSerializer.Object); - TestPluginCacheHelper.SetupMockExtensions(new string[] { typeof(BaseRunTestsTests).Assembly.Location }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([typeof(BaseRunTestsTests).Assembly.Location], () => { }); var assemblyLocation = typeof(BaseRunTestsTests).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 72da52e034..bea628a470 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/ExecutionManagerTests.cs @@ -78,7 +78,7 @@ public void InitializeShouldLoadAndInitializeAllExtensions() var commonAssemblyLocation = typeof(ExecutionManagerTests).Assembly.Location; var mockTestMessageEventHandler = new Mock(); TestPluginCacheHelper.SetupMockExtensions( - new string[] { commonAssemblyLocation }, + [commonAssemblyLocation], () => { }); @@ -142,7 +142,7 @@ public void StartTestRunShouldRunTestsInTheProvidedSources() { var assemblyLocation = typeof(ExecutionManagerTests).Assembly.Location; TestPluginCacheHelper.SetupMockExtensions( - new string[] { assemblyLocation }, + [assemblyLocation], () => { }); TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); @@ -205,7 +205,7 @@ public void StartTestRunShouldRunTestsForTheProvidedTests() "A.dll")); fh!.RecordResult(tr); }; - TestPluginCacheHelper.SetupMockExtensions(new string[] { assemblyLocation }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([assemblyLocation], () => { }); _executionManager.StartTestRun(tests, null, null, _testExecutionContext, null, mockTestRunEventsHandler.Object); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs index d0b676eb03..ba5b3dd728 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs @@ -56,7 +56,7 @@ public RunTestsWithSourcesTests() _mockRequestData.Setup(rd => rd.MetricsCollection).Returns(_mockMetricsCollection.Object); TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(RunTestsWithSourcesTests).Assembly.Location }, + [typeof(RunTestsWithSourcesTests).Assembly.Location], () => { }); TestPluginCache.Instance.DiscoverTestExtensions(TestPlatformConstants.TestAdapterEndsWithPattern); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs index f38dfc2eee..909ac63b15 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/PostProcessing/ArtifactProcessingTests.cs @@ -140,7 +140,7 @@ public async Task PostProcessArtifactsAsync_ShouldRunPostProcessing() // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[2] { "/tmp/sessionId/runsettings.xml", "/tmp/sessionId/executionComplete.json" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/runsettings.xml", "/tmp/sessionId/executionComplete.json"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { @@ -188,7 +188,7 @@ public async Task PostProcessArtifactsAsync_NullRunSettings_ShouldRunPostProcess // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[1] { "/tmp/sessionId/executionComplete.json" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/executionComplete.json"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { @@ -231,7 +231,7 @@ public async Task PostProcessArtifactsAsync_EmptyInvokedDataCollectors_ShouldRun // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[1] { "/tmp/sessionId/runsettings.xml" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/runsettings.xml"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { @@ -266,7 +266,7 @@ public async Task PostProcessArtifactsAsync_DeserializationException_ShouldStopP // arrange _fileHelperMock.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); _fileHelperMock.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((string path, string pattern, SearchOption so) => new string[1] { "/tmp/sessionId/executionComplete.json" }); + .Returns((string path, string pattern, SearchOption so) => ["/tmp/sessionId/executionComplete.json"]); _fileHelperMock.Setup(x => x.GetStream(It.IsAny(), It.IsAny(), It.IsAny())) .Returns((string path, FileMode mode, FileAccess access) => { diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs index 7608bee072..420f2ab44c 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestEngineTests.cs @@ -31,7 +31,7 @@ public class TestEngineTests public TestEngineTests() { - TestPluginCacheHelper.SetupMockExtensions(new[] { typeof(TestEngineTests).Assembly.Location }, () => { }); + TestPluginCacheHelper.SetupMockExtensions([typeof(TestEngineTests).Assembly.Location], () => { }); _mockProcessHelper = new Mock(); _mockRequestData = new Mock(); _mockMetricsCollection = new Mock(); @@ -1042,7 +1042,7 @@ public void CreatingNonParallelExecutionManagerShouldReturnExecutionManagerWithD var testRunCriteria = new TestRunCriteria(new List { "1.dll" }, 100, false, settingXml); var runtimeProviderInfo = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, settingXml, - new List { new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } }); + [new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }]); var nonParallelExecutionManager = _testEngine.CreateNonParallelExecutionManager(_mockRequestData.Object, testRunCriteria, true, runtimeProviderInfo); Assert.IsNotNull(nonParallelExecutionManager); @@ -1068,10 +1068,10 @@ public void CreatedNonParallelExecutionManagerShouldBeInitialzedWithCorrectTestS "; var runtimeProviderInfo = new TestRuntimeProviderInfo(typeof(ITestRuntimeProvider), false, settingXml, - new List { - new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, - new() { Source = "2.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } - }); + [ + new() { Source = "1.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework }, + new() { Source = "2.dll", Architecture = Architecture.X86, Framework = Framework.DefaultFramework } + ]); var nonParallelExecutionManager = _testEngine.CreateNonParallelExecutionManager(_mockRequestData.Object, testRunCriteria, true, runtimeProviderInfo); Assert.IsInstanceOfType(nonParallelExecutionManager, typeof(ProxyExecutionManagerWithDataCollection)); diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs index e72987971c..7510928451 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/TestLoggerManagerTests.cs @@ -36,7 +36,7 @@ public class TestLoggerManagerTests public void Initialize() { TestPluginCacheHelper.SetupMockExtensions( - new string[] { typeof(TestLoggerManagerTests).Assembly.Location }, + [typeof(TestLoggerManagerTests).Assembly.Location], () => { }); } @@ -409,7 +409,7 @@ public void HandleDiscoveredTestsShouldInvokeDiscoveredTestsHandlerOfLoggers() s_counter = 0; WaitHandle.Reset(); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); // setup TestLogger @@ -430,7 +430,7 @@ public void HandleDiscoveredTestsShouldNotInvokeDiscoveredTestsHandlerOfLoggersI s_counter = 0; WaitHandle.Reset(); - List testCases = new() { new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName") }; + List testCases = [new TestCase("This is a string.", new Uri("some://uri"), "DummySourceFileName")]; DiscoveredTestsEventArgs discoveredTestsEventArgs = new(testCases); // setup TestLogger diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs index 629b94f369..03e9c234ac 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs @@ -44,7 +44,7 @@ public void GetDumpFileWillThrowExceptionIfNoDumpfile() var testResultsDirectory = "D:\\TestResults"; _mockFileHelper.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(System.Array.Empty()); + .Returns([]); _mockProcessHelper.Setup(x => x.GetProcessName(processId)) .Returns(process); diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs index 91a2b72fa6..9c1cc94e27 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs @@ -739,11 +739,11 @@ public void GetCustomPropertyValueFromTestCaseShouldReadCategoryAttributesFromTe List listCategoriesActual = Converter.GetCustomPropertyValueFromTestCase(testCase1, "MSTestDiscoverer.TestCategory"); - List listCategoriesExpected = new() - { + List listCategoriesExpected = + [ "ClassLevel", "AsmLevel" - }; + ]; CollectionAssert.AreEqual(listCategoriesExpected, listCategoriesActual); } @@ -758,11 +758,11 @@ public void GetCustomPropertyValueFromTestCaseShouldReadWorkItemAttributesFromTe List listWorkItemsActual = Converter.GetCustomPropertyValueFromTestCase(testCase1, "WorkItemIds"); - List listWorkItemsExpected = new() - { + List listWorkItemsExpected = + [ "99999", "0" - }; + ]; CollectionAssert.AreEqual(listWorkItemsExpected, listWorkItemsActual); } diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs index f5eb8b75bd..a459932bfc 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs @@ -96,7 +96,7 @@ public void ToTestElementShouldAssignTestCategoryOfUnitTestElement() var unitTestElement = Converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testCase.DisplayName, TrxLoggerConstants.UnitTestType, testCase); - object[] expected = new[] { "MethodLevel", "ClassLevel", "AsmLevel" }; + object[] expected = ["MethodLevel", "ClassLevel", "AsmLevel"]; CollectionAssert.AreEqual(expected, unitTestElement.TestCategories.ToArray().OrderByDescending(x => x).ToArray()); } @@ -112,7 +112,7 @@ public void ToTestElementShouldAssignWorkItemOfUnitTestElement() var unitTestElement = Converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testCase.DisplayName, TrxLoggerConstants.UnitTestType, testCase); - int[] expected = new[] { 0, 3, 99999 }; + int[] expected = [0, 3, 99999]; CollectionAssert.AreEquivalent(expected, unitTestElement.WorkItems.ToArray()); } @@ -227,10 +227,7 @@ private static void SetupForToCollectionEntries(out string tempDir, out List - { - new(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "Code Coverage") - }; + attachmentSets = [new(new Uri("datacollector://microsoft/CodeCoverage/2.0"), "Code Coverage")]; testRun = new TestRun(Guid.NewGuid()); testRun.RunConfiguration = new TestRunConfiguration("Testrun 1", new TrxFileHelper()); diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs index 9b36182524..0055035827 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DefaultTestHostManagerTests.cs @@ -60,7 +60,7 @@ public DefaultTestHostManagerTests() _testHostManager = new DefaultTestHostManager(_mockProcessHelper.Object, _mockFileHelper.Object, _mockDotnetHostHelper.Object, _mockEnvironment.Object, _mockEnvironmentVariable.Object); _testHostManager.Initialize(_mockMessageLogger.Object, $" {Architecture.X64} {Framework.DefaultFramework} {false} "); - _startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + _startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); } [TestMethod] @@ -68,7 +68,7 @@ public void ConstructorShouldSetX86ProcessForX86Architecture() { _testHostManager.Initialize(_mockMessageLogger.Object, $" {Architecture.X86} {Framework.DefaultFramework} {false} "); - var info = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var info = _testHostManager.GetTestHostProcessStartInfo([], null, default); StringAssert.EndsWith(info.FileName, "testhost.x86.exe"); } @@ -84,7 +84,7 @@ public void GetTestHostProcessStartInfoShouldIncludeFileNameFromSubFolderTestHos { _mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("dotnet.exe"); _mockFileHelper.Setup(x => x.Exists(It.IsAny())).Returns(false); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); Assert.IsTrue(startInfo.FileName!.EndsWith(Path.Combine("TestHostNetFramework", "testhost.exe"))); } @@ -94,7 +94,7 @@ public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTest { _mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("dotnet.exe"); _mockFileHelper.Setup(x => x.Exists(It.IsAny())).Returns(true); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); Assert.IsFalse(startInfo.FileName!.EndsWith(Path.Combine("TestHost", "testhost.exe"))); Assert.IsTrue(startInfo.FileName!.EndsWith("testhost.exe")); @@ -104,7 +104,7 @@ public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTest public void GetTestHostProcessStartInfoShouldNotIncludeFileNameFromSubFolderTestHostWhenCurrentProcessIsIde() { _mockProcessHelper.Setup(ph => ph.GetCurrentProcessFileName()).Returns("devenv.exe"); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); Assert.IsFalse(startInfo.FileName!.EndsWith(Path.Combine("TestHost", "testhost.exe"))); Assert.IsTrue(startInfo.FileName!.EndsWith("testhost.exe")); @@ -115,7 +115,7 @@ public void GetTestHostProcessStartInfoShouldIncludeConnectionInfo() { var connectionInfo = new TestRunnerConnectionInfo { Port = 123, ConnectionInfo = new TestHostConnectionInfo { Endpoint = "127.0.0.0:123", Role = ConnectionRole.Client, Transport = Transport.Sockets }, RunnerProcessId = 101 }; var info = _testHostManager.GetTestHostProcessStartInfo( - Enumerable.Empty(), + [], null, connectionInfo); @@ -148,7 +148,7 @@ public void GetTestHostProcessStartInfoShouldIncludeEnvironmentVariables() { var environmentVariables = new Dictionary { { "k1", "v1" } }; - var info = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), environmentVariables, default); + var info = _testHostManager.GetTestHostProcessStartInfo([], environmentVariables, default); Assert.AreEqual(environmentVariables, info.EnvironmentVariables); } @@ -213,7 +213,7 @@ public void GetTestHostProcessStartInfoShouldNotUseMonoAsHostOnNonWindowsIfStart public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesListIsEmpty() { _testHostManager.Initialize(_mockMessageLogger.Object, $" "); - List currentList = new() { @"FooExtension.dll" }; + List currentList = [@"FooExtension.dll"]; // Act var resultExtensions = _testHostManager.GetTestPlatformExtensions(new List(), currentList).ToList(); @@ -226,7 +226,7 @@ public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesList public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesListIsNull() { _testHostManager.Initialize(_mockMessageLogger.Object, $" "); - List currentList = new() { @"FooExtension.dll" }; + List currentList = [@"FooExtension.dll"]; // Act var resultExtensions = _testHostManager.GetTestPlatformExtensions(null, currentList).ToList(); @@ -238,17 +238,17 @@ public void GetTestPlatformExtensionsShouldReturnExtensionsListAsIsIfSourcesList [TestMethod] public void GetTestPlatformExtensionsShouldNotExcludeOutputDirectoryExtensionsIfTestAdapterPathIsSet() { - List sourcesDir = new() { @"C:\Source1" }; - List sources = new() { @"C:\Source1\source1.dll" }; + List sourcesDir = [@"C:\Source1"]; + List sources = [@"C:\Source1\source1.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.EnumerateFiles(sourcesDir[0], SearchOption.TopDirectoryOnly, "TestAdapter.dll")).Returns(extensionsList1); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[1])).Returns(new Version(5, 5)); _testHostManager.Initialize(_mockMessageLogger.Object, $" C:\\Foo "); - List currentList = new() { @"FooExtension.dll", @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; + List currentList = [@"FooExtension.dll", @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; // Act var resultExtensions = _testHostManager.GetTestPlatformExtensions(sources, currentList).ToList(); @@ -261,11 +261,11 @@ public void GetTestPlatformExtensionsShouldNotExcludeOutputDirectoryExtensionsIf [TestCategory("Windows")] public void GetTestPlatformExtensionsShouldIncludeOutputDirectoryExtensionsIfTestAdapterPathIsNotSet() { - List sourcesDir = new() { "C:\\Source1", "C:\\Source2" }; - List sources = new() { @"C:\Source1\source1.dll", @"C:\Source2\source2.dll" }; + List sourcesDir = ["C:\\Source1", "C:\\Source2"]; + List sources = [@"C:\Source1\source1.dll", @"C:\Source2\source2.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; - List extensionsList2 = new() { @"C:\Source2\ext1.TestAdapter.dll", @"C:\Source2\ext2.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; + List extensionsList2 = [@"C:\Source2\ext1.TestAdapter.dll", @"C:\Source2\ext2.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[1])).Returns(new Version(5, 5)); @@ -281,7 +281,7 @@ public void GetTestPlatformExtensionsShouldIncludeOutputDirectoryExtensionsIfTes var resultExtensions = _testHostManager.GetTestPlatformExtensions(sources, new List()).ToList(); // Verify - List expectedList = new() { @"C:\Source2\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll" }; + List expectedList = [@"C:\Source2\ext1.TestAdapter.dll", @"C:\Source1\ext2.TestAdapter.dll"]; CollectionAssert.AreEqual(expectedList, resultExtensions); _mockMessageLogger.Verify(ml => ml.SendMessage(TestMessageLevel.Warning, "Multiple versions of same extension found. Selecting the highest version." + Environment.NewLine + " ext1.TestAdapter : 2.2\n ext2.TestAdapter : 5.5"), Times.Once); } @@ -290,11 +290,11 @@ public void GetTestPlatformExtensionsShouldIncludeOutputDirectoryExtensionsIfTes [TestCategory("Windows")] public void GetTestPlatformExtensionsShouldReturnPathTheHigherVersionedFileExtensions() { - List sourcesDir = new() { "C:\\Source1", "C:\\Source2" }; - List sources = new() { @"C:\Source1\source1.dll", @"C:\Source2\source2.dll" }; + List sourcesDir = ["C:\\Source1", "C:\\Source2"]; + List sources = [@"C:\Source1\source1.dll", @"C:\Source2\source2.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll" }; - List extensionsList2 = new() { @"C:\Source2\ext1.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll"]; + List extensionsList2 = [@"C:\Source2\ext1.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList2[0])).Returns(new Version(2, 2)); @@ -316,11 +316,11 @@ public void GetTestPlatformExtensionsShouldReturnPathTheHigherVersionedFileExten [TestCategory("Windows")] public void GetTestPlatformExtensionsShouldReturnPathToSingleFileExtensionOfATypeIfVersionsAreSame() { - List sourcesDir = new() { "C:\\Source1", "C:\\Source2" }; - List sources = new() { @"C:\Source1\source1.dll", @"C:\Source2\source2.dll" }; + List sourcesDir = ["C:\\Source1", "C:\\Source2"]; + List sources = [@"C:\Source1\source1.dll", @"C:\Source2\source2.dll"]; - List extensionsList1 = new() { @"C:\Source1\ext1.TestAdapter.dll" }; - List extensionsList2 = new() { @"C:\Source2\ext1.TestAdapter.dll" }; + List extensionsList1 = [@"C:\Source1\ext1.TestAdapter.dll"]; + List extensionsList2 = [@"C:\Source2\ext1.TestAdapter.dll"]; _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList1[0])).Returns(new Version(2, 0)); _mockFileHelper.Setup(fh => fh.GetFileVersion(extensionsList2[0])).Returns(new Version(2, 0)); @@ -353,7 +353,7 @@ public void LaunchTestHostShouldReturnTestHostProcessId() It.IsAny>())).Returns(Process.GetCurrentProcess()); _testHostManager.Initialize(_mockMessageLogger.Object, $" {Architecture.X64} {Framework.DefaultFramework} {false} "); - var startInfo = _testHostManager.GetTestHostProcessStartInfo(Enumerable.Empty(), null, default); + var startInfo = _testHostManager.GetTestHostProcessStartInfo([], null, default); _testHostManager.HostLaunched += TestHostManagerHostLaunched; diff --git a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs index af5ee66ec3..7d643fcae4 100644 --- a/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs +++ b/test/Microsoft.TestPlatform.TestHostProvider.UnitTests/Hosting/DotnetTestHostManagerTests.cs @@ -42,7 +42,7 @@ public class DotnetTestHostManagerTests private readonly Mock _mockEnvironment; private readonly Mock _mockRunsettingHelper; private readonly TestRunnerConnectionInfo _defaultConnectionInfo; - private readonly string[] _testSource = { "test.dll" }; + private readonly string[] _testSource = ["test.dll"]; private readonly string _defaultTestHostPath; private readonly TestProcessStartInfo _defaultTestProcessStartInfo; private readonly TestableDotnetTestHostManager _dotnetHostManager; @@ -548,7 +548,7 @@ public void GetTestHostProcessStartInfoShouldIncludeSourceDirectoryAsWorkingDire public void GetTestPlatformExtensionsShouldReturnEmptySetIfSourceDirectoryDoesNotExist() { _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(false); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, Enumerable.Empty()); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, []); Assert.AreEqual(0, extensions.Count()); } @@ -558,7 +558,7 @@ public void GetTestPlatformExtensionsShouldReturnLibrariesFromSourceDirectory() { _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); _mockFileHelper.Setup(fh => fh.EnumerateFiles(It.IsAny(), SearchOption.TopDirectoryOnly, It.IsAny())).Returns(new[] { "foo.TestAdapter.dll" }); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, Enumerable.Empty()); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(new[] { $".{Path.DirectorySeparatorChar}foo.dll" }, []); CollectionAssert.AreEqual(new[] { "foo.TestAdapter.dll" }, extensions.ToArray()); } @@ -569,7 +569,7 @@ public void GetTestPlatformExtensionsShouldReturnEmptySetIfSourceDirectoryIsEmpt // Parent directory is empty since the input source is file "test.dll" _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); _mockFileHelper.Setup(fh => fh.EnumerateFiles(It.IsAny(), SearchOption.TopDirectoryOnly, It.IsAny())).Returns(new[] { "foo.dll" }); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, Enumerable.Empty()); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, []); Assert.AreEqual(0, extensions.Count()); } @@ -579,7 +579,7 @@ public void GetTestPlatformExtensionsShouldNotAddNonCoverletDataCollectorsExtens { _mockFileHelper.Setup(fh => fh.DirectoryExists(It.IsAny())).Returns(true); _mockFileHelper.Setup(fh => fh.EnumerateFiles(It.IsAny(), SearchOption.TopDirectoryOnly, It.IsAny())).Returns(new[] { "foo.dll" }); - var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, new List { "abc.dataollector.dll" }); + var extensions = _dotnetHostManager.GetTestPlatformExtensions(_testSource, ["abc.dataollector.dll"]); Assert.AreEqual(0, extensions.Count()); } diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs index 0fe2212be4..123a0167a7 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs @@ -174,7 +174,7 @@ public static string PrepareArguments(string[] testAssemblies, string? testAdapt /// Command line arguments string. public static string PrepareArguments(string testAssembly, string? testAdapterPath, string? runSettings, string framework, string? inIsolation = "", string? resultsDirectory = null) - => PrepareArguments(new string[] { testAssembly }, testAdapterPath, runSettings, framework, inIsolation, resultsDirectory); + => PrepareArguments([testAssembly], testAdapterPath, runSettings, framework, inIsolation, resultsDirectory); /// diff --git a/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs b/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs index a36eee6046..e9c401a7b6 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs @@ -17,7 +17,7 @@ public static class TestPluginCacheHelper public static TestableTestPluginCache SetupMockAdditionalPathExtensions(Type callingTest) { return SetupMockAdditionalPathExtensions( - new string[] { callingTest.Assembly.Location }); + [callingTest.Assembly.Location]); } public static TestableTestPluginCache SetupMockAdditionalPathExtensions(string[] extensions) @@ -42,7 +42,7 @@ public static void SetupMockExtensions(Type callingTest, Mock? mock public static void SetupMockExtensions(Type callingTest, Action callback, Mock? mockFileHelper = null) { - SetupMockExtensions(new[] { callingTest.Assembly.Location }, callback, mockFileHelper); + SetupMockExtensions([callingTest.Assembly.Location], callback, mockFileHelper); } public static void SetupMockExtensions(string[] extensions, Action callback, Mock? mockFileHelper = null) diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs index 0761e61d69..0dfa24dd46 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs @@ -86,7 +86,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnly1Atta var attachmentSet = new AttachmentSet(new Uri("datacollector://microsoft/CodeCoverage/2.0"), string.Empty); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\aa.coverage"), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -106,7 +106,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIf2Differen attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file1Path), "coverage")); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file2Path), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -127,7 +127,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIf2SameForm attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file1Path), "coverage")); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri(file1Path), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -144,7 +144,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnly1Logs var attachmentSet = new AttachmentSet(new Uri("datacollector://microsoft/CodeCoverage/2.0"), string.Empty); attachmentSet.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\aa.logs"), "coverage")); - Collection attachment = new() { attachmentSet }; + Collection attachment = [attachmentSet]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -165,7 +165,7 @@ public async Task HandleDataCollectionAttachmentSetsShouldReturnInputIfOnlySever attachmentSet1.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\aa.logs"), "coverage")); attachmentSet1.Attachments.Add(new UriDataAttachment(new Uri("C:\\temp\\bb.logs"), "coverage")); - Collection attachment = new() { attachmentSet, attachmentSet1 }; + Collection attachment = [attachmentSet, attachmentSet1]; ICollection resultAttachmentSets = await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, CancellationToken.None); @@ -183,11 +183,11 @@ public async Task HandleDataCollectionAttachmentSetsShouldThrowIfCancellationReq CancellationTokenSource cts = new(); cts.Cancel(); - Collection attachment = new() - { + Collection attachment = + [ attachmentSet, attachmentSet - }; + ]; await Assert.ThrowsExceptionAsync(async () => await _coverageDataAttachmentsHandler.ProcessAttachmentSetsAsync(_configurationElement, attachment, _mockProgressReporter.Object, null, cts.Token)); diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs index 30789efec3..c1106695a7 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs @@ -24,9 +24,9 @@ private static void VerifyCommandLineSplitter(string commandLine, string[] expec [TestMethod] public void TestCommandLineSplitter() { - VerifyCommandLineSplitter("", System.Array.Empty()); - VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\"", new[] { @"/testadapterpath:c:\Path" }); - VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\"", new[] { @"/testadapterpath:c:\Path", "/logger:trx" }); - VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\" /diag:\"log.txt\"", new[] { @"/testadapterpath:c:\Path", "/logger:trx", "/diag:log.txt" }); + VerifyCommandLineSplitter("", []); + VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\"", [@"/testadapterpath:c:\Path"]); + VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\"", [@"/testadapterpath:c:\Path", "/logger:trx"]); + VerifyCommandLineSplitter("/testadapterpath:\"c:\\Path\" /logger:\"trx\" /diag:\"log.txt\"", [@"/testadapterpath:c:\Path", "/logger:trx", "/diag:log.txt"]); } } diff --git a/test/SettingsMigrator.UnitTests/PathResolverTests.cs b/test/SettingsMigrator.UnitTests/PathResolverTests.cs index 7df59759f3..678865ddd4 100644 --- a/test/SettingsMigrator.UnitTests/PathResolverTests.cs +++ b/test/SettingsMigrator.UnitTests/PathResolverTests.cs @@ -22,49 +22,49 @@ public PathResolverTests() [TestMethod] public void PathResolverShouldReturnNullForEmptyArguments() { - var newFilePath = _pathResolver.GetTargetPath(Array.Empty()); + var newFilePath = _pathResolver.GetTargetPath([]); Assert.IsNull(newFilePath, "Empty arguments should return null"); } [TestMethod] public void PathResolverShouldReturnNullForInvalidArguments() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "asd", "asd", "asd" }); + var newFilePath = _pathResolver.GetTargetPath(["asd", "asd", "asd"]); Assert.IsNull(newFilePath, "Invalid arguments should return null"); } [TestMethod] public void PathResolverShouldReturnNullForRelativePaths() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "asd.testsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["asd.testsettings"]); Assert.IsNull(newFilePath, "Relative paths should return null"); } [TestMethod] public void PathResolverShouldReturnNullForRelativePathsWithTwoArguments() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "asd.Testsettings", "C:\\asd.runsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["asd.Testsettings", "C:\\asd.runsettings"]); Assert.IsNull(newFilePath, "Relative paths should return null"); } [TestMethod] public void PathResolverShouldNotReturnNullForPathsWithExtensionInCapitals() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "C:\\asd.TestSEettings", "C:\\asd.RuNSettings" }); + var newFilePath = _pathResolver.GetTargetPath(["C:\\asd.TestSEettings", "C:\\asd.RuNSettings"]); Assert.IsNotNull(newFilePath, "Relative paths should not return null"); } [TestMethod] public void PathResolverShouldReturnNullForRelativePathsForRunsettings() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "C:\\asd.testsettings", "asd.runsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["C:\\asd.testsettings", "asd.runsettings"]); Assert.IsNull(newFilePath, "Relative paths should return null"); } [TestMethod] public void PathResolverShouldReturnRunsettingsPathOfSameLocationAsTestSettings() { - var newFilePath = _pathResolver.GetTargetPath(new string[] { "C:\\asd.testsettings" }); + var newFilePath = _pathResolver.GetTargetPath(["C:\\asd.testsettings"]); Assert.IsNotNull(newFilePath, "File path should not be null."); Assert.IsTrue(string.Equals(Path.GetExtension(newFilePath), ".runsettings"), "File path should be .runsettings"); Assert.IsTrue(newFilePath!.Contains("C:\\asd_"), "File should be of same name as testsettings"); diff --git a/test/SettingsMigrator.UnitTests/ProgramTests.cs b/test/SettingsMigrator.UnitTests/ProgramTests.cs index 5025e97963..9e4ef90675 100644 --- a/test/SettingsMigrator.UnitTests/ProgramTests.cs +++ b/test/SettingsMigrator.UnitTests/ProgramTests.cs @@ -11,14 +11,14 @@ public class ProgramTests [TestMethod] public void MoreThanTwoArgumentsShouldNotBeAccepted() { - int returnCode = Program.Main(new string[] { "asd", "asd", "asd" }); + int returnCode = Program.Main(["asd", "asd", "asd"]); Assert.AreEqual(1, returnCode, "More than 2 arguments should not be accepted."); } [TestMethod] public void NoArgumentsShouldNotBeAccepted() { - int returnCode = Program.Main(System.Array.Empty()); + int returnCode = Program.Main([]); Assert.AreEqual(1, returnCode, "No arguments should not be accepted."); } } diff --git a/test/TranslationLayer.UnitTests/TestSessionTests.cs b/test/TranslationLayer.UnitTests/TestSessionTests.cs index f6eb5fac6a..5b2220d1bc 100644 --- a/test/TranslationLayer.UnitTests/TestSessionTests.cs +++ b/test/TranslationLayer.UnitTests/TestSessionTests.cs @@ -22,12 +22,12 @@ namespace Microsoft.TestPlatform.VsTestConsole.TranslationLayer.UnitTests; public class TestSessionTests { private readonly string _testSettings = "TestSettings"; - private readonly List _testSources = new() { "Hello", "World" }; - private readonly List _testCases = new() - { + private readonly List _testSources = ["Hello", "World"]; + private readonly List _testCases = + [ new TestCase("a.b.c", new Uri("d://uri"), "a.dll"), new TestCase("d.e.f", new Uri("g://uri"), "d.dll") - }; + ]; private readonly TestSessionInfo _testSessionInfo; private readonly ITestSession _testSession; diff --git a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs index 71d0689dcb..b2d496d208 100644 --- a/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs +++ b/test/TranslationLayer.UnitTests/VsTestConsoleRequestSenderTests.cs @@ -436,13 +436,13 @@ public void DiscoverTestsShouldCompleteWithSingleFullyDiscoveredSource() var mockHandler = new Mock(); - List sources = new() { "1.dll" }; + List sources = ["1.dll"]; var testCase = new TestCase("hello", new Uri("world://how"), source: sources[0]); var testsFound = new Message() { MessageType = MessageType.TestCasesFound, - Payload = JToken.FromObject(new List() { testCase }) + Payload = JToken.FromObject(new List { testCase }) }; var payload = new DiscoveryCompletePayload() { TotalTests = 1, LastDiscoveredTests = null, IsAborted = false, FullyDiscoveredSources = sources }; @@ -476,7 +476,7 @@ public void DiscoverTestsShouldCompleteWithCorrectAbortedValuesIfAbortingWasRequ var mockHandler = new Mock(); - List sources = new() { "1.dll" }; + List sources = ["1.dll"]; var testCase = new TestCase("hello", new Uri("world://how"), source: sources[0]); var testsFound = new Message() diff --git a/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs b/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs index 5b7ad29759..e3ba446662 100644 --- a/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs +++ b/test/TranslationLayer.UnitTests/VsTestConsoleWrapperTests.cs @@ -28,12 +28,12 @@ public class VsTestConsoleWrapperTests private readonly Mock _mockProcessManager; private readonly Mock _mockProcessHelper; private readonly Mock _mockRequestSender; - private readonly List _testSources = new() { "Hello", "World" }; - private readonly List _testCases = new() - { + private readonly List _testSources = ["Hello", "World"]; + private readonly List _testCases = + [ new TestCase("a.b.c", new Uri("d://uri"), "a.dll"), new TestCase("d.e.f", new Uri("g://uri"), "d.dll") - }; + ]; private readonly ConsoleParameters _consoleParameters; private readonly Mock _telemetryEventsHandler; diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index e13553f3d0..7cf8a2a93a 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -359,7 +359,7 @@ public void SessionEndedShouldReturnAttachments() var attachment = new AttachmentSet(new Uri("my://custom/datacollector"), "CustomDataCollector"); attachment.Attachments.Add(new UriDataAttachment(new Uri("my://filename.txt"), "filename.txt")); - _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns(new List() { attachment }); + _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns([attachment]); _dataCollectionManager.InitializeDataCollectors(_dataCollectorSettings); var sessionStartEventArgs = new SessionStartEventArgs(); @@ -387,7 +387,7 @@ public void SessionEndedShouldContinueDataCollectionIfExceptionIsThrownWhileSend var attachment = new AttachmentSet(new Uri("my://custom/datacollector"), "CustomDataCollector"); attachment.Attachments.Add(new UriDataAttachment(new Uri("my://filename.txt"), "filename.txt")); - _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns(new List() { attachment }); + _mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny())).Returns([attachment]); SetupMockDataCollector((XmlElement a, DataCollectionEvents b, DataCollectionSink c, DataCollectionLogger d, DataCollectionEnvironmentContext e) => b.SessionEnd += (sender, ev) => diff --git a/test/datacollector.UnitTests/DataCollectorMainTests.cs b/test/datacollector.UnitTests/DataCollectorMainTests.cs index 8c83ca950b..59103a2949 100644 --- a/test/datacollector.UnitTests/DataCollectorMainTests.cs +++ b/test/datacollector.UnitTests/DataCollectorMainTests.cs @@ -20,9 +20,9 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.DataCollector.UnitTests; [TestClass] public class DataCollectorMainTests { - private readonly string[] _args = { "--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "3" }; - private readonly string[] _argsWithEmptyDiagArg = { "--port", "1025", "--parentprocessid", "100", "--diag", "", "--tracelevel", "3" }; - private readonly string[] _argsWithInvalidTraceLevel = { "--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "5" }; + private readonly string[] _args = ["--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "3"]; + private readonly string[] _argsWithEmptyDiagArg = ["--port", "1025", "--parentprocessid", "100", "--diag", "", "--tracelevel", "3"]; + private readonly string[] _argsWithInvalidTraceLevel = ["--port", "1025", "--parentprocessid", "100", "--diag", "abc.txt", "--tracelevel", "5"]; private static readonly string TimeoutErrorMessage = "datacollector process failed to connect to vstest.console process after 90 seconds. This may occur due to machine slowness, please set environment variable VSTEST_CONNECTION_TIMEOUT to increase timeout."; diff --git a/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs b/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs index f5df113f53..8d33f23acb 100644 --- a/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs +++ b/test/vstest.ProgrammerTests/Fakes/StringExtensions.cs @@ -17,6 +17,6 @@ public static string JoinBy(this IEnumerable value, string delimiter) public static List AsList(this T value) { - return new List { value }; + return [value]; } } diff --git a/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs b/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs index 9ff6c075f7..36c9822d57 100644 --- a/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs +++ b/test/vstest.ProgrammerTests/MultiTFMRunAndDiscovery.cs @@ -668,7 +668,7 @@ internal static string GetRawMessage(this Message request) s_messageProperty = request.GetType().GetProperty("RawMessage")!.GetGetMethod(); } - return (string)s_messageProperty!.Invoke(request, Array.Empty())!; + return (string)s_messageProperty!.Invoke(request, [])!; } } diff --git a/test/vstest.ProgrammerTests/Program.cs b/test/vstest.ProgrammerTests/Program.cs index 22f4c0e949..f6d0f025be 100644 --- a/test/vstest.ProgrammerTests/Program.cs +++ b/test/vstest.ProgrammerTests/Program.cs @@ -9,6 +9,6 @@ internal class Program { static void Main() { - Intent.Console.Program.Main(new[] { Assembly.GetExecutingAssembly().Location }); + Intent.Console.Program.Main([Assembly.GetExecutingAssembly().Location]); } } diff --git a/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs b/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs index 65f5013af7..201ee8312c 100644 --- a/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs +++ b/test/vstest.console.UnitTests/CommandLine/GenerateFakesUtilitiesTests.cs @@ -37,7 +37,7 @@ public void FakesShouldNotBeGeneratedIfDisableAutoFakesSetToTrue() CommandLineOptions.Instance.DisableAutoFakes = true; string runSettingsXml = @".netstandard,Version=5.0"; - runSettingsXml = GenerateFakesUtilities.GenerateFakesSettings(CommandLineOptions.Instance, System.Array.Empty(), runSettingsXml); + runSettingsXml = GenerateFakesUtilities.GenerateFakesSettings(CommandLineOptions.Instance, [], runSettingsXml); Assert.AreEqual(runSettingsXml, _runSettings); } diff --git a/test/vstest.console.UnitTests/ExecutorUnitTests.cs b/test/vstest.console.UnitTests/ExecutorUnitTests.cs index e8102f24da..313ec26a25 100644 --- a/test/vstest.console.UnitTests/ExecutorUnitTests.cs +++ b/test/vstest.console.UnitTests/ExecutorUnitTests.cs @@ -171,7 +171,7 @@ public void ExecuteShouldInstrumentVsTestConsoleStop() [TestMethod] public void ExecuteShouldExitWithErrorOnResponseFileException() { - string[] args = { "@FileDoesNotExist.rsp" }; + string[] args = ["@FileDoesNotExist.rsp"]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); @@ -226,7 +226,7 @@ public void ExecuteShouldNotThrowSettingsExceptionButLogOutput() File.WriteAllText(runSettingsFile, fileContents); var testSourceDllPath = Path.GetTempFileName(); - string[] args = { testSourceDllPath, "/settings:" + runSettingsFile }; + string[] args = [testSourceDllPath, "/settings:" + runSettingsFile]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); @@ -264,7 +264,7 @@ public void ExecuteShouldReturnNonZeroExitCodeIfSettingsException() File.WriteAllText(runSettingsFile, fileContents); - string[] args = { "/settings:" + runSettingsFile }; + string[] args = ["/settings:" + runSettingsFile]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); @@ -299,7 +299,7 @@ public void ExecutorShouldShowRightErrorMessage() File.WriteAllText(runSettingsFile, fileContents); - string[] args = { "/settings:" + runSettingsFile }; + string[] args = ["/settings:" + runSettingsFile]; var mockOutput = new MockOutput(); var exitCode = new Executor(mockOutput, _mockTestPlatformEventSource.Object, new ProcessHelper(), new PlatformEnvironment()).Execute(args); diff --git a/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs b/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs index 3556acb841..78fea1b91f 100644 --- a/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs +++ b/test/vstest.console.UnitTests/Processors/ArtifactProcessingPostProcessModeProcessorTest.cs @@ -64,10 +64,10 @@ public void ProcessorExecutorInitialize_ExceptionShouldNotBubbleUp() public void ArtifactProcessingPostProcessMode_ContainsPostProcessCommand() { _featureFlagMock.Setup(x => x.IsSet(It.IsAny())).Returns(false); - Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "--artifactsProcessingMode-postprocess" }, _featureFlagMock.Object)); - Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "--ARTIfactsProcessingMode-postprocess" }, _featureFlagMock.Object)); - Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "-ARTIfactsProcessingMode-postprocess" }, _featureFlagMock.Object)); - Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(new string[] { "--ARTIfactsProcessingMode-postproces" }, _featureFlagMock.Object)); + Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["--artifactsProcessingMode-postprocess"], _featureFlagMock.Object)); + Assert.IsTrue(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["--ARTIfactsProcessingMode-postprocess"], _featureFlagMock.Object)); + Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["-ARTIfactsProcessingMode-postprocess"], _featureFlagMock.Object)); + Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(["--ARTIfactsProcessingMode-postproces"], _featureFlagMock.Object)); Assert.IsFalse(ArtifactProcessingPostProcessModeProcessor.ContainsPostProcessCommand(null, _featureFlagMock.Object)); } } diff --git a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs index a27be02e89..3a40e52bfb 100644 --- a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs @@ -114,7 +114,7 @@ public void InitializeShouldNotThrowExceptionIfArgumentIsNull() [TestMethod] public void InitializeShouldNotThrowExceptionIfArgumentIsEmpty() { - _executor.Initialize(Array.Empty()); + _executor.Initialize([]); Assert.IsNull(_settingsProvider.ActiveRunSettings); } @@ -122,7 +122,7 @@ public void InitializeShouldNotThrowExceptionIfArgumentIsEmpty() [TestMethod] public void InitializeShouldCreateEmptyRunSettingsIfArgumentsHasOnlyWhiteSpace() { - _executor.Initialize(new string[] { " " }); + _executor.Initialize([" "]); Assert.IsNull(_settingsProvider.ActiveRunSettings); } @@ -344,42 +344,43 @@ public static IEnumerable TestRunParameterArgInvalidTestCases() return InvalidTestCases; } - private static readonly List InvalidTestCases = new() - { - new object[] { "TestRunParameters.Parameter(name=asf,value=rgq)" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq\" )" }, - new object[] { "TestRunParameters.Parameter( name=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParametersParameter(name=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Paramete(name=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parametername=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(ame=\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name\"asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\" value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",alue=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq\"" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq\")wfds" }, - new object[] { "TestRunParameters.Parameter(name=\"\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"\")" }, - new object[] { "TestRunParameters.Parameter(name=asf\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf,value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"asf\",value=\"rgq)" }, - new object[] { "TestRunParameters.Parameter(name=\"asf@#!\",value=\"rgq\")" }, - new object[] { "TestRunParameters.Parameter(name=\"\",value=\"fgf\")" }, - new object[] { "TestRunParameters.Parameter(name=\"gag\",value=\"\")" }, - new object[] { "TestRunParameters.Parameter(name=\"gag\")" } - }; + private static readonly List InvalidTestCases = + [ + ["TestRunParameters.Parameter(name=asf,value=rgq)"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq\" )"], + ["TestRunParameters.Parameter( name=\"asf\",value=\"rgq\")"], + ["TestRunParametersParameter(name=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Paramete(name=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parametername=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(ame=\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name\"asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\" value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",alue=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq\""], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq\")wfds"], + ["TestRunParameters.Parameter(name=\"\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"\")"], + ["TestRunParameters.Parameter(name=asf\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf,value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=rgq\")"], + ["TestRunParameters.Parameter(name=\"asf\",value=\"rgq)"], + ["TestRunParameters.Parameter(name=\"asf@#!\",value=\"rgq\")"], + ["TestRunParameters.Parameter(name=\"\",value=\"fgf\")"], + ["TestRunParameters.Parameter(name=\"gag\",value=\"\")"], + ["TestRunParameters.Parameter(name=\"gag\")"] + ]; public static IEnumerable TestRunParameterArgValidTestCases() { return ValidTestCases; } - private static readonly List ValidTestCases = new() - { - new object[] { "TestRunParameters.Parameter(name=\"weburl\",value=\"&><\")" , - string.Join(Environment.NewLine, "", + private static readonly List ValidTestCases = + [ + [ + "TestRunParameters.Parameter(name=\"weburl\",value=\"&><\")", string.Join(Environment.NewLine, + "", "", " ", " ", @@ -388,9 +389,10 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - new object[] { "TestRunParameters.Parameter(name=\"weburl\",value=\"http://localhost//abc\")" , - string.Join(Environment.NewLine, "", + ], + [ + "TestRunParameters.Parameter(name=\"weburl\",value=\"http://localhost//abc\")", string.Join( + Environment.NewLine, "", "", " ", " ", @@ -399,8 +401,9 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - new object[] { "TestRunParameters.Parameter(name= \"a_sf123_12\",value= \"2324346a!@#$%^*()_+-=':;.,/?{}[]|\")" , + ], + [ + "TestRunParameters.Parameter(name= \"a_sf123_12\",value= \"2324346a!@#$%^*()_+-=':;.,/?{}[]|\")", string.Join(Environment.NewLine, "", "", " ", @@ -410,9 +413,10 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - new object[] { "TestRunParameters.Parameter(name = \"weburl\" , value = \"http://localhost//abc\")" , - string.Join(Environment.NewLine, "", + ], + [ + "TestRunParameters.Parameter(name = \"weburl\" , value = \"http://localhost//abc\")", string.Join( + Environment.NewLine, "", "", " ", " ", @@ -421,8 +425,8 @@ public static IEnumerable TestRunParameterArgValidTestCases() " ", " ", "") - }, - }; + ] + ]; #endregion [TestMethod] @@ -459,7 +463,7 @@ public void InitializeShouldMergeTestRunParametersWithSpaces() "value=\"myValue 2\")", }; - var runsettings = string.Join(Environment.NewLine, new[]{ + var runsettings = string.Join(Environment.NewLine, [ "", "", " ", @@ -469,7 +473,8 @@ public void InitializeShouldMergeTestRunParametersWithSpaces() " ", " ", " ", - ""}); + "" + ]); _executor.Initialize(args); diff --git a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs index 418be5202e..eaffa017fc 100644 --- a/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunSpecificTestsArgumentProcessorTests.cs @@ -191,11 +191,11 @@ public void ExecutorExecuteForValidSourceWithTestCaseFilterShouldRunTests() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List 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(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -275,11 +275,11 @@ public void ExecutorExecuteShouldThrowTestPlatformExceptionThrownDuringExecution var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new() - { + List 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")); @@ -302,11 +302,11 @@ public void ExecutorExecuteShouldThrowSettingsExceptionThrownDuringExecution() var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new() - { + List 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")); @@ -329,11 +329,11 @@ public void ExecutorExecuteShouldThrowInvalidOperationExceptionThrownDuringExecu var mockTestRunRequest = new Mock(); var mockDiscoveryRequest = new Mock(); - List list = new() - { + List 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")); @@ -359,7 +359,7 @@ public void ExecutorExecuteShouldForValidSourcesAndNoTestsDiscoveredShouldLogWar ResetAndAddSourceToCommandLineOptions(); // Setting some test adapter path - CommandLineOptions.Instance.TestAdapterPath = new[] { @"C:\Foo" }; + CommandLineOptions.Instance.TestAdapterPath = [@"C:\Foo"]; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(new List())); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(mockDiscoveryRequest.Object); @@ -404,10 +404,7 @@ public void ExecutorExecuteShouldForValidSourcesAndValidSelectedTestsRunsTestsAn ResetAndAddSourceToCommandLineOptions(); - List list = new() - { - new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1") - }; + List 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(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -431,11 +428,11 @@ public void ExecutorShouldRunTestsWhenTestsAreCommaSeparated() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List 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(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -460,11 +457,11 @@ public void ExecutorShouldRunTestsWhenTestsAreFiltered() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List 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(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -489,10 +486,7 @@ public void ExecutorShouldWarnWhenTestsAreNotAvailable() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { - new TestCase("Test2", new Uri("http://FooTestUri1"), "Source1") - }; + List 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(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -517,11 +511,11 @@ public void ExecutorShouldRunTestsWhenTestsAreCommaSeparatedWithEscape() ResetAndAddSourceToCommandLineOptions(); - List list = new() - { + List 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(), It.IsAny>(), It.IsAny())).Returns(mockTestRunRequest.Object); @@ -545,11 +539,11 @@ public void ExecutorShouldDisplayWarningIfNoTestsAreExecuted() var mockDiscoveryRequest = new Mock(); var mockTestRunStats = new Mock(); - List list = new() - { + List 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, @@ -576,11 +570,11 @@ public void ExecutorShouldNotDisplayWarningIfTestsAreExecuted() var mockDiscoveryRequest = new Mock(); var testRunStats = new TestRunStatistics(1, new Dictionary { { TestOutcome.Passed, 1 } }); - List list = new() - { + List 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 2ed759112b..0c31c47d9d 100644 --- a/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/RunTestsArgumentProcessorTests.cs @@ -252,11 +252,11 @@ private ArgumentProcessorResult RunRunArgumentProcessorExecuteWithMockSetup(ITes var mockTestPlatform = new Mock(); var mockConsoleOutput = new Mock(); - List list = new() - { + List 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()); diff --git a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs index 4859fe631a..01f9acf5f0 100644 --- a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs +++ b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorFactoryTests.cs @@ -84,7 +84,7 @@ public void CreateArgumentProcessorShouldReturnNullIfInvalidCommandIsPassed() ArgumentProcessorFactory factory = ArgumentProcessorFactory.Create(); - IArgumentProcessor result = factory.CreateArgumentProcessor(command, new string[] { "" })!; + IArgumentProcessor result = factory.CreateArgumentProcessor(command, [""])!; Assert.IsNull(result); } @@ -96,7 +96,7 @@ public void CreateArgumentProcessorShouldReturnCliRunSettingsArgumentProcessorIf ArgumentProcessorFactory factory = ArgumentProcessorFactory.Create(); - IArgumentProcessor result = factory.CreateArgumentProcessor(command, new string[] { "" })!; + IArgumentProcessor result = factory.CreateArgumentProcessor(command, [""])!; Assert.AreEqual(typeof(CliRunSettingsArgumentProcessor), result.GetType()); } diff --git a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs index c7cb234b47..a597af523d 100644 --- a/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs +++ b/test/vstest.console.UnitTests/Processors/Utilities/ArgumentProcessorUtilitiesTests.cs @@ -40,7 +40,7 @@ public void GetArgumentListShouldReturnCorrectArgumentList(string argument) } [TestMethod] - [DataRow(new string[] { "key1=value1", "invalidPair", "key2=value2" })] + [DataRow(["key1=value1", "invalidPair", "key2=value2"])] public void GetArgumentParametersShouldThrowErrorOnInvalidParameters(string[] parameterArgs) { try