Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use some collection expressions #5055

Merged
merged 21 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
06c2128
use some collection expressions
SimonCropp May 23, 2024
3494ab3
Update RunSpecificTestsArgumentProcessor.cs
SimonCropp May 23, 2024
a234ffc
Merge remote-tracking branch 'upstream/main' into use-some-collection…
SimonCropp May 23, 2024
72cfc2f
Update Converter.cs
SimonCropp May 23, 2024
cbd64af
Update RunSettingsUtilities.cs
SimonCropp May 23, 2024
b5382ec
Update DiscovererEnumerator.cs
SimonCropp May 23, 2024
e81b6a8
Update PostProcessingTestRunAttachmentsProcessingEventsHandler.cs
SimonCropp May 23, 2024
666d476
Update RunSpecificTestsArgumentProcessor.cs
SimonCropp May 23, 2024
884ffbc
Update TestTaskUtilsTests.cs
SimonCropp May 23, 2024
eef8f08
Update GenerateFakesUtilitiesTests.cs
SimonCropp May 23, 2024
38127fb
Update ProxyOperationManagerTests.cs
SimonCropp May 23, 2024
0f0374e
Update InProcessProxyDiscoveryManagerTests.cs
SimonCropp May 23, 2024
100f23b
Update InProcessProxyexecutionManagerTests.cs
SimonCropp May 23, 2024
cecff2d
Update ProxyDiscoveryManagerTests.cs
SimonCropp May 23, 2024
4050641
Update ProxyDiscoveryManagerTests.cs
SimonCropp May 23, 2024
e3e75c7
Update CLIRunSettingsArgumentProcessorTests.cs
SimonCropp May 23, 2024
4395146
Merge branch 'main' into use-some-collection-expressions
nohwnd Jun 17, 2024
382240a
Merge branch 'main' into use-some-collection-expressions
nohwnd Jun 17, 2024
7e0156f
Fix code style
nohwnd Jul 10, 2024
e53512f
Merge branch 'main' into use-some-collection-expressions
nohwnd Jul 10, 2024
9e2ed1e
Fix tests
nohwnd Jul 10, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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