Skip to content

Commit

Permalink
use some collection expressions (#5055)
Browse files Browse the repository at this point in the history
* use some collection expressions

* Update RunSpecificTestsArgumentProcessor.cs

* Update Converter.cs

* Update RunSettingsUtilities.cs

* Update DiscovererEnumerator.cs

* Update PostProcessingTestRunAttachmentsProcessingEventsHandler.cs

* Update RunSpecificTestsArgumentProcessor.cs

* Update TestTaskUtilsTests.cs

* Update GenerateFakesUtilitiesTests.cs

* Update ProxyOperationManagerTests.cs

* Update InProcessProxyDiscoveryManagerTests.cs

* Update InProcessProxyexecutionManagerTests.cs

* Update ProxyDiscoveryManagerTests.cs

* Update ProxyDiscoveryManagerTests.cs

* Update CLIRunSettingsArgumentProcessorTests.cs

* Fix code style

* Fix tests

---------

Co-authored-by: Jakub Jareš <me@jakubjares.com>
  • Loading branch information
SimonCropp and nohwnd authored Jul 10, 2024
1 parent a98de4e commit c211b20
Show file tree
Hide file tree
Showing 136 changed files with 591 additions and 656 deletions.
4 changes: 2 additions & 2 deletions shared/NullableAttributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ internal sealed class MemberNotNullAttribute : Attribute
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullAttribute(string member) => Members = new[] { member };
public MemberNotNullAttribute(string member) => Members = [member];

/// <summary>Initializes the attribute with the list of field and property members.</summary>
/// <param name="members">
Expand All @@ -122,7 +122,7 @@ internal sealed class MemberNotNullWhenAttribute : Attribute
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = new[] { member };
Members = [member];
}

/// <summary>Initializes the attribute with the specified return value condition and list of field and property members.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ protected override void Dispose(bool disposing)
private static ISet<string> ParseCommaSeparatedList(string commaSeparatedList)
{
ISet<string> strings = new HashSet<string>();
string[] items = commaSeparatedList.Split(new char[] { ',' });
string[] items = commaSeparatedList.Split([',']);
foreach (string item in items)
{
strings.Add(item.Trim());
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.TestPlatform.Build/Tasks/VSTestTask2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -271,7 +271,7 @@ private bool TryGetMessage(string singleLine, out string name, out string?[] dat
}

name = string.Empty;
data = Array.Empty<string>();
data = [];
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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;
Expand Down
8 changes: 4 additions & 4 deletions src/Microsoft.TestPlatform.Client/TestPlatform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ private static void AddExtensionAssembliesFromExtensionDirectory()
TestAdapterLoadingStrategy strategy = runConfiguration.TestAdapterLoadingStrategy;

FileHelper fileHelper = new();
IEnumerable<string> defaultExtensionPaths = Enumerable.Empty<string>();
IEnumerable<string> defaultExtensionPaths = [];

// Explicit adapter loading
if (strategy.HasFlag(TestAdapterLoadingStrategy.Explicit))
Expand Down Expand Up @@ -354,7 +354,7 @@ private static IEnumerable<string> ExpandAdaptersWithExplicitStrategy(string pat
{
if (!strategy.HasFlag(TestAdapterLoadingStrategy.Explicit))
{
return Enumerable.Empty<string>();
return [];
}

if (fileHelper.Exists(path))
Expand All @@ -377,7 +377,7 @@ private static IEnumerable<string> ExpandAdaptersWithExplicitStrategy(string pat
}

EqtTrace.Warning($"{nameof(TestPlatform)}.{nameof(ExpandAdaptersWithExplicitStrategy)} AdapterPath Not Found: {path}");
return Enumerable.Empty<string>();
return [];
}

private static IEnumerable<string> ExpandAdaptersWithDefaultStrategy(string path, IFileHelper fileHelper)
Expand All @@ -388,7 +388,7 @@ private static IEnumerable<string> ExpandAdaptersWithDefaultStrategy(string path
{
EqtTrace.Warning($"{nameof(TestPlatform)}.{nameof(ExpandAdaptersWithDefaultStrategy)} AdapterPath Not Found: {path}");

return Enumerable.Empty<string>();
return [];
}

return fileHelper.EnumerateFiles(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ private IEnumerable<string> 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");
Expand All @@ -99,8 +99,8 @@ private IEnumerable<string> GetTestExtensionsInternal(string extensionType)

if (extensionManager != null)
{
installedExtensions = ExtensionManagerServiceType.GetMethod("GetEnabledExtensionContentLocations", new Type[] { typeof(string) })?.Invoke(
extensionManager, new object[] { extensionType }) as IEnumerable<string>;
installedExtensions = ExtensionManagerServiceType.GetMethod("GetEnabledExtensionContentLocations", [typeof(string)])?.Invoke(
extensionManager, [extensionType]) as IEnumerable<string>;
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ private static void ProcessOperator(Stack<FilterExpression> filterStack, Operato
if (null == properties)
{
// if null, initialize to empty list so that invalid properties can be found.
properties = Enumerable.Empty<string>();
properties = [];
}

return IterateFilterExpression<string[]?>((current, result) =>
Expand All @@ -132,7 +132,7 @@ private static void ProcessOperator(Stack<FilterExpression> 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"];

/// <summary>
/// Initializes a new instance of the <see cref="AssemblyResolver"/> class.
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.TestPlatform.Common/Utilities/FakesUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>) });
var method = type?.GetMethod(NetFrameworkConfiguratorMethodName, [typeof(IEnumerable<string>)]);
if (method != null)
{
return (Func<IEnumerable<string>, string>)method.CreateDelegate(typeof(Func<IEnumerable<string>, string>));
Expand All @@ -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<string, FrameworkVersion>) });
var method = type?.GetMethod(CrossPlatformConfiguratorMethodName, [typeof(IDictionary<string, FrameworkVersion>)]);
if (method != null)
{
return (Func<IDictionary<string, FrameworkVersion>, DataCollectorSettings>)method.CreateDelegate(typeof(Func<IDictionary<string, FrameworkVersion>, DataCollectorSettings>));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
};
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ internal static class MetadataReaderExtensionsHelper
{
private const string TestExtensionTypesAttributeV2 = "Microsoft.VisualStudio.TestPlatform.TestExtensionTypesV2Attribute";
private static readonly ConcurrentDictionary<string, Type[]> 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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -176,12 +175,12 @@ public static IEnumerable<string> GetTestAdaptersPaths(string? runSettings)
{
var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings);

IEnumerable<string> testAdaptersPaths = Enumerable.Empty<string>();
IEnumerable<string> testAdaptersPaths = [];
if (runConfiguration != null)
{
if (runConfiguration.TestAdaptersPathsSet)
{
testAdaptersPaths = runConfiguration.TestAdaptersPaths.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
testAdaptersPaths = runConfiguration.TestAdaptersPaths.Split([';'], StringSplitOptions.RemoveEmptyEntries);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/// <inheritdoc/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public IEnumerable<string> EnumerateFiles(
{
if (endsWithSearchPatterns == null || endsWithSearchPatterns.Length == 0)
{
return Enumerable.Empty<string>();
return [];
}

var files = Directory.EnumerateFiles(directory, "*", searchOption);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public DataCollectorAttachmentProcessorAppDomain(InvokedDataCollector invokedDat
false,
BindingFlags.Default,
null,
new[] { _pipeShutdownMessagePrefix },
[_pipeShutdownMessagePrefix],
null,
null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public void DiscoverTests(DiscoveryCriteria discoveryCriteria, ITestDiscoveryEve

var discoveryCompeleteEventsArg = new DiscoveryCompleteEventArgs(-1, true);

eventHandler.HandleDiscoveryComplete(discoveryCompeleteEventsArg, Enumerable.Empty<TestCase>());
eventHandler.HandleDiscoveryComplete(discoveryCompeleteEventsArg, []);
}
});
}
Expand Down Expand Up @@ -103,15 +103,15 @@ public void Abort(ITestDiscoveryEventsHandler2 eventHandler)

private void InitializeExtensions(IEnumerable<string> sources)
{
var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, Enumerable.Empty<string>());
var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, []);
if (extensionsFromSource.Any())
{
TestPluginCache.Instance.UpdateExtensions(extensionsFromSource, false);
}

// 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<string>(), null);
_discoveryManager.Initialize([], null);
}

public void InitializeDiscovery(DiscoveryCriteria discoveryCriteria, ITestDiscoveryEventsHandler2 eventHandler, bool skipDefaultAdapters)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,15 +135,15 @@ public void Close()

private void InitializeExtensions(IEnumerable<string> sources)
{
var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, Enumerable.Empty<string>());
var extensionsFromSource = _testHostManager.GetTestPlatformExtensions(sources, []);
if (extensionsFromSource.Any())
{
TestPluginCache.Instance.UpdateExtensions(extensionsFromSource, false);
}

// 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<string>(), null);
_executionManager.Initialize([], null);
}

public void InitializeTestRun(TestRunCriteria testRunCriteria, IInternalTestRunEventsHandler eventHandler)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ private void ClearCompletedSlot(TManager completedManager)

private static string GetSourcesForSlotExpensive(ParallelOperationManager<TManager, TEventHandler, TWorkload>.Slot slot)
{
return string.Join(", ", (slot.Work as DiscoveryCriteria)?.Sources ?? (slot.Work as TestRunCriteria)?.Sources ?? Array.Empty<string>());
return string.Join(", ", (slot.Work as DiscoveryCriteria)?.Sources ?? (slot.Work as TestRunCriteria)?.Sources ?? []);
}

public void DoActionOnAllManagers(Action<TManager> action, bool doActionsInParallel = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ private List<ProviderSpecificWorkload<DiscoveryCriteria>> SplitToWorkloads(Disco
if (!_isParallel && testhostProviderInfo.Shared)
{
// Create one big source batch that will be single workload for single testhost.
sourceBatches = new List<string[]> { group.Select(w => w.Work).ToArray() };
sourceBatches = [group.Select(w => w.Work).ToArray()];
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ private List<ProviderSpecificWorkload<TestRunCriteria>> SplitToWorkloads(TestRun
if (!_isParallel && testhostProviderInfo.Shared)
{
// Create one big batch of testcases that will be single workload for single testhost.
testCaseBatches = new List<TestCase[]> { group.SelectMany(w => sourceToTestCasesMap[w.Work]).ToArray() };
testCaseBatches = [group.SelectMany(w => sourceToTestCasesMap[w.Work]).ToArray()];
}
else
{
Expand Down Expand Up @@ -319,7 +319,7 @@ private List<ProviderSpecificWorkload<TestRunCriteria>> SplitToWorkloads(TestRun
if (!_isParallel && testhostProviderInfo.Shared)
{
// Create one big source batch that will be single workload for single testhost.
sourceBatches = new List<string[]> { group.Select(w => w.Work).ToArray() };
sourceBatches = [group.Select(w => w.Work).ToArray()];
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading

0 comments on commit c211b20

Please sign in to comment.