diff --git a/.editorconfig b/.editorconfig index 430647d9df..dfbcbe5b01 100644 --- a/.editorconfig +++ b/.editorconfig @@ -689,8 +689,8 @@ resharper_empty_constructor_highlighting = warning # Redundant empty argument list on object creation expression resharper_redundant_empty_object_creation_argument_list_highlighting = warning -# IDE0300: Simplify collection initialization -dotnet_style_prefer_collection_expression = false +# IDE0300-IDE0306: Simplify collection initialization +dotnet_style_prefer_collection_expression = true # IDE0065: using directive placement csharp_using_directive_placement = outside_namespace:warning diff --git a/samples/Playground/Program.cs b/samples/Playground/Program.cs index 205088910d..c5c842a040 100644 --- a/samples/Playground/Program.cs +++ b/samples/Playground/Program.cs @@ -57,7 +57,7 @@ public static async Task Main(string[] args) using TestingPlatformClient client = await TestingPlatformClientFactory.StartAsServerAndConnectToTheClientAsync(Environment.ProcessPath!); await client.InitializeAsync(); - List testNodeUpdates = new(); + List testNodeUpdates = []; ResponseListener discoveryResponse = await client.DiscoverTestsAsync(Guid.NewGuid(), node => { testNodeUpdates.AddRange(node); @@ -65,7 +65,7 @@ public static async Task Main(string[] args) }); await discoveryResponse.WaitCompletionAsync(); - ResponseListener runRequest = await client.RunTestsAsync(Guid.NewGuid(), testNodeUpdates.Select(x => x.Node).ToArray(), _ => Task.CompletedTask); + ResponseListener runRequest = await client.RunTestsAsync(Guid.NewGuid(), [.. testNodeUpdates.Select(x => x.Node)], _ => Task.CompletedTask); await runRequest.WaitCompletionAsync(); await client.ExitAsync(); @@ -86,7 +86,7 @@ internal sealed class DummyAdapter : ITestFramework, IDataProducer public string Description => string.Empty; - public Type[] DataTypesProduced => new[] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesProduced => [typeof(TestNodeUpdateMessage)]; public Task CloseTestSessionAsync(CloseTestSessionContext context) => Task.FromResult(new CloseTestSessionResult { IsSuccess = true }); diff --git a/samples/Playground/ServerMode/TestNodeUpdateCollector.cs b/samples/Playground/ServerMode/TestNodeUpdateCollector.cs index 067a4f4410..799aab6ab5 100644 --- a/samples/Playground/ServerMode/TestNodeUpdateCollector.cs +++ b/samples/Playground/ServerMode/TestNodeUpdateCollector.cs @@ -10,7 +10,7 @@ public class TestNodeUpdateCollector private readonly TaskCompletionSource _taskCompletionSource = new(); private readonly Func? _completeCollector; - public ConcurrentBag TestNodeUpdates { get; } = new(); + public ConcurrentBag TestNodeUpdates { get; } = []; public TestNodeUpdateCollector(Func? completeCollectorWhen = null) => _completeCollector = completeCollectorWhen; diff --git a/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs b/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs index 3b40c4d341..5d1a5b917c 100644 --- a/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs +++ b/samples/Playground/ServerMode/v1.0.0/TestingPlatformClient.cs @@ -171,11 +171,9 @@ private sealed class TargetHandler private readonly ConcurrentDictionary _listeners = new(); - private readonly ConcurrentBag _logListeners - = new(); + private readonly ConcurrentBag _logListeners = []; - private readonly ConcurrentBag _telemetryPayloads - = new(); + private readonly ConcurrentBag _telemetryPayloads = []; public void RegisterTelemetryListener(TelemetryCollector listener) => _telemetryPayloads.Add(listener); diff --git a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs index 9d3cf88a38..0b83379dc2 100644 --- a/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs +++ b/src/Adapter/MSTest.Engine/Engine/BFSTestNodeVisitor.cs @@ -29,12 +29,12 @@ public BFSTestNodeVisitor(IEnumerable rootTestNodes, ITestExecutionFil _testArgumentsManager = testArgumentsManager; } - internal KeyValuePair>[] DuplicatedNodes { get; private set; } = Array.Empty>>(); + internal KeyValuePair>[] DuplicatedNodes { get; private set; } = []; public async Task VisitAsync(Func onIncludedTestNodeAsync) { // This is case sensitive, and culture insensitive, to keep UIDs unique, and comparable between different system. - Dictionary> testNodesByUid = new(); + Dictionary> testNodesByUid = []; Queue<(TestNode CurrentNode, TestNodeUid? ParentNodeUid, StringBuilder NodeFullPath)> queue = new(); foreach (TestNode node in _rootTestNodes) { @@ -47,7 +47,7 @@ public async Task VisitAsync(Func onIncludedTestNo if (!testNodesByUid.TryGetValue(currentNode.StableUid, out List? testNodes)) { - testNodes = new(); + testNodes = []; testNodesByUid.Add(currentNode.StableUid, testNodes); } @@ -94,7 +94,7 @@ public async Task VisitAsync(Func onIncludedTestNo } } - DuplicatedNodes = testNodesByUid.Where(x => x.Value.Count > 1).ToArray(); + DuplicatedNodes = [.. testNodesByUid.Where(x => x.Value.Count > 1)]; } private static PropertyBag CreatePropertyBagForFilter(IProperty[] properties) diff --git a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs index 1003fe27ef..095208b484 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestArgumentsManager.cs @@ -7,7 +7,7 @@ namespace Microsoft.Testing.Framework; internal sealed class TestArgumentsManager : ITestArgumentsManager { - private readonly Dictionary> _testArgumentsEntryProviders = new(); + private readonly Dictionary> _testArgumentsEntryProviders = []; private bool _isRegistrationFrozen; public void RegisterTestArgumentsEntryProvider( @@ -53,8 +53,8 @@ internal async Task ExpandTestNodeAsync(TestNode currentNode) }; } - HashSet expandedTestNodeUids = new(); - List expandedTestNodes = new(currentNode.Tests); + HashSet expandedTestNodeUids = []; + List expandedTestNodes = [.. currentNode.Tests]; switch (currentNode) { case IParameterizedTestNode parameterizedTestNode: @@ -98,7 +98,7 @@ internal async Task ExpandTestNodeAsync(TestNode currentNode) DisplayName = currentNode.DisplayName, OverriddenEdgeName = currentNode.OverriddenEdgeName, Properties = currentNode.Properties, - Tests = expandedTestNodes.ToArray(), + Tests = [.. expandedTestNodes], }; return expandedNode; diff --git a/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs b/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs index 4c26895bc4..3553ebc4ef 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestFixtureManager.cs @@ -10,13 +10,13 @@ namespace Microsoft.Testing.Framework; internal sealed class TestFixtureManager : ITestFixtureManager { - private readonly Dictionary>> _fixtureInstancesByFixtureId = new(); - private readonly Dictionary _fixtureIdsUsedByTestNode = new(); + private readonly Dictionary>> _fixtureInstancesByFixtureId = []; + private readonly Dictionary _fixtureIdsUsedByTestNode = []; // We could improve this by doing some optimistic lock but we expect a rather low contention on this. // We use a dictionary as performance improvement because we know that when the registration is complete // we will only read the collection (so no need for concurrency handling). - private readonly Dictionary _fixtureUses = new(); + private readonly Dictionary _fixtureUses = []; private readonly CancellationToken _cancellationToken; private bool _isRegistrationFrozen; private bool _isUsageRegistrationFrozen; @@ -79,7 +79,7 @@ internal void RegisterFixtureUsage(TestNode testNode, string[] fixtureIds) return; } - _fixtureIdsUsedByTestNode.Add(testNode, fixtureIds.Select(x => new FixtureId(x)).ToArray()); + _fixtureIdsUsedByTestNode.Add(testNode, [.. fixtureIds.Select(x => new FixtureId(x))]); foreach (string fixtureId in fixtureIds) { if (!_fixtureUses.TryGetValue(fixtureId, out CountHolder? uses)) diff --git a/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs b/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs index f78f930f7a..0855e884df 100644 --- a/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs +++ b/src/Adapter/MSTest.Engine/Engine/TestFrameworkEngine.cs @@ -38,8 +38,7 @@ public TestFrameworkEngine(TestFrameworkConfiguration testFrameworkConfiguration _configuration = new(configuration); } - public Type[] DataTypesProduced { get; } - = new Type[1] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesProduced { get; } = [typeof(TestNodeUpdateMessage)]; public string Uid => _extension.Uid; @@ -62,7 +61,7 @@ public async Task ExecuteRequestAsync(TestExecutionRequest testExecution private async Task ExecuteTestNodeRunAsync(RunTestExecutionRequest request, IMessageBus messageBus, CancellationToken cancellationToken) { - List allRootTestNodes = new(); + List allRootTestNodes = []; TestFixtureManager fixtureManager = new(cancellationToken); TestArgumentsManager argumentsManager = new(); TestSessionContext testSessionContext = new(_configuration, fixtureManager, argumentsManager, request.Session.SessionUid, @@ -96,7 +95,7 @@ await testNodesVisitor.VisitAsync((testNode, parentTestNodeUid) => .OfType() .SingleOrDefault() .UsedFixtureIds - ?? Array.Empty(); + ?? []; fixtureManager.RegisterFixtureUsage(testNode, fixtureIds); return Task.CompletedTask; @@ -142,7 +141,7 @@ Task PublishDataAsync(IData data) private async Task ExecuteTestNodeDiscoveryAsync(DiscoverTestExecutionRequest request, IMessageBus messageBus, CancellationToken cancellationToken) { - List allRootTestNodes = new(); + List allRootTestNodes = []; TestFixtureManager fixtureManager = new(cancellationToken); TestArgumentsManager argumentsManager = new(); TestSessionContext testSessionContext = new(_configuration, fixtureManager, argumentsManager, request.Session.SessionUid, diff --git a/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs b/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs index 3ef4aa070f..f8d32269cc 100644 --- a/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs +++ b/src/Adapter/MSTest.Engine/Engine/ThreadPoolTestNodeRunner.cs @@ -16,7 +16,7 @@ namespace Microsoft.Testing.Framework; internal sealed class ThreadPoolTestNodeRunner : IDisposable { private readonly SemaphoreSlim? _maxParallelTests; - private readonly ConcurrentBag> _runningTests = new(); + private readonly ConcurrentBag> _runningTests = []; private readonly ConcurrentDictionary _runningTestNodeUids = new(); private readonly CountdownEvent _ensureTaskQueuedCountdownEvent = new(1); private readonly Func _publishDataAsync; diff --git a/src/Adapter/MSTest.Engine/Helpers/Result.cs b/src/Adapter/MSTest.Engine/Helpers/Result.cs index 6f6a70af1d..881c9fa4d1 100644 --- a/src/Adapter/MSTest.Engine/Helpers/Result.cs +++ b/src/Adapter/MSTest.Engine/Helpers/Result.cs @@ -5,7 +5,7 @@ namespace Microsoft.Testing.Framework; internal sealed class Result { - private readonly List _reasons = new(); + private readonly List _reasons = []; private Result() { diff --git a/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs b/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs index 1fb61c5f9d..e43320b5bd 100644 --- a/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs +++ b/src/Adapter/MSTest.Engine/TestFramework/TestFramework.cs @@ -23,8 +23,8 @@ internal sealed class TestFramework : IDisposable, ITestFramework private readonly TestingFrameworkExtension _extension; private readonly CountdownEvent _incomingRequestCounter = new(1); private readonly TestFrameworkEngine _engine; - private readonly List _sessionWarningMessages = new(); - private readonly List _sessionErrorMessages = new(); + private readonly List _sessionWarningMessages = []; + private readonly List _sessionErrorMessages = []; private SessionUid? _sessionId; public TestFramework(TestFrameworkConfiguration testFrameworkConfiguration, ITestNodesBuilder[] testNodesBuilders, TestingFrameworkExtension extension, diff --git a/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs b/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs index 868a1e63db..434251ea82 100644 --- a/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs +++ b/src/Adapter/MSTest.Engine/TestFramework/TestFrameworkCapabilities.cs @@ -18,7 +18,7 @@ public TestFrameworkCapabilities(ITestNodesBuilder[] testNodesBuilders, IBannerM } public IReadOnlyCollection Capabilities - => new[] { new TestFrameworkCapabilitiesSet(_testNodesBuilders), _bannerMessageOwnerCapability }; + => [new TestFrameworkCapabilitiesSet(_testNodesBuilders), _bannerMessageOwnerCapability]; } internal sealed class TestFrameworkCapabilitiesSet : diff --git a/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs b/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs index 8f2b9bc3b6..eaad6454de 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/FactoryTestNodesBuilder.cs @@ -15,8 +15,7 @@ public FactoryTestNodesBuilder(Func testNodesFactory) public bool IsSupportingTrxProperties { get; } - IReadOnlyCollection ICapabilities.Capabilities - => Array.Empty(); + IReadOnlyCollection ICapabilities.Capabilities => []; public Task BuildAsync(ITestSessionContext _) => Task.FromResult(_testNodesFactory()); } diff --git a/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs b/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs index 718e6b8b40..3c61f91f6c 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/FrameworkTestNodeProperties.cs @@ -9,5 +9,5 @@ internal readonly struct FrameworkEngineMetadataProperty() : IProperty { public bool PreventArgumentsExpansion { get; init; } - public string[] UsedFixtureIds { get; init; } = Array.Empty(); + public string[] UsedFixtureIds { get; init; } = []; } diff --git a/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs b/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs index 58f015c055..8119973fde 100644 --- a/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs +++ b/src/Adapter/MSTest.Engine/TestNodes/TestNode.cs @@ -17,7 +17,7 @@ public class TestNode /// public string? OverriddenEdgeName { get; init; } - public IProperty[] Properties { get; init; } = Array.Empty(); + public IProperty[] Properties { get; init; } = []; - public TestNode[] Tests { get; init; } = Array.Empty(); + public TestNode[] Tests { get; init; } = []; } diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs index 6dfe08c60b..34c6e1b21a 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumerator.cs @@ -65,7 +65,7 @@ public AssemblyEnumerator(MSTestSettings settings) => /// A collection of Test Elements. internal AssemblyEnumerationResult EnumerateAssembly(string assemblyFileName) { - List warnings = new(); + List warnings = []; DebugEx.Assert(!StringEx.IsNullOrWhiteSpace(assemblyFileName), "Invalid assembly file name."); var tests = new List(); // Contains list of assembly/class names for which we have already added fixture tests. @@ -350,7 +350,7 @@ private static bool TryUnfoldITestDataSources(UnitTestElement test, DiscoveryTes IEnumerable testDataSources = ReflectHelper.Instance.GetAttributes(testMethodInfo.MethodInfo, inherit: false).OfType(); // We need to use a temporary list to avoid adding tests to the main list if we fail to expand any data source. - List tempListOfTests = new(); + List tempListOfTests = []; try { diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs index 7e14d56e6b..5633389cbd 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/AssemblyEnumeratorWrapper.cs @@ -26,7 +26,7 @@ internal sealed class AssemblyEnumeratorWrapper /// A collection of test elements. internal ICollection? GetTests(string? assemblyFileName, IRunSettings? runSettings, out List warnings) { - warnings = new List(); + warnings = []; if (StringEx.IsNullOrEmpty(assemblyFileName)) { diff --git a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs index 52c8becccc..78342edf83 100644 --- a/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs +++ b/src/Adapter/MSTest.TestAdapter/Discovery/TypeEnumerator.cs @@ -110,11 +110,10 @@ internal List GetTests(List warnings) currentType = currentType.BaseType; } - return tests.GroupBy( + return [.. tests.GroupBy( t => t.TestMethod.Name, (_, elements) => - elements.OrderBy(t => inheritanceDepths[t.TestMethod.DeclaringClassFullName ?? t.TestMethod.FullClassName]).First()) - .ToList(); + elements.OrderBy(t => inheritanceDepths[t.TestMethod.DeclaringClassFullName ?? t.TestMethod.FullClassName]).First())]; } /// @@ -153,7 +152,7 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT DoNotParallelize = _reflectHelper.IsDoNotParallelizeSet(method, _type), Priority = _reflectHelper.GetPriority(method), DeploymentItems = PlatformServiceProvider.Instance.TestDeployment.GetDeploymentItems(method, _type, warnings), - Traits = _reflectHelper.GetTestPropertiesAsTraits(method).ToArray(), + Traits = [.. _reflectHelper.GetTestPropertiesAsTraits(method)], }; Attribute[] attributes = _reflectHelper.GetCustomAttributesCached(method, inherit: true); @@ -184,7 +183,7 @@ internal UnitTestElement GetTestFromMethod(MethodInfo method, bool isDeclaredInT IEnumerable workItemAttributes = attributes.OfType(); if (workItemAttributes.Any()) { - testElement.WorkItemIds = workItemAttributes.Select(x => x.Id.ToString(CultureInfo.InvariantCulture)).ToArray(); + testElement.WorkItemIds = [.. workItemAttributes.Select(x => x.Id.ToString(CultureInfo.InvariantCulture))]; } // In production, we always have a TestMethod attribute because GetTestFromMethod is called under IsValidTestMethod diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs index 2315b67113..8ae3f43e28 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestCaseDiscoverySink.cs @@ -14,7 +14,7 @@ internal sealed class TestCaseDiscoverySink : ITestCaseDiscoverySink /// /// Gets the tests. /// - public ICollection Tests { get; } = new List(); + public ICollection Tests { get; } = []; /// /// Sends the test case. diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs index dc4ae10a17..ba55a398c4 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestClassInfo.cs @@ -102,25 +102,25 @@ internal set /// Gets the timeout for the class initialize methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary ClassInitializeMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary ClassInitializeMethodTimeoutMilliseconds { get; } = []; /// /// Gets the timeout for the class cleanup methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary ClassCleanupMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary ClassCleanupMethodTimeoutMilliseconds { get; } = []; /// /// Gets the timeout for the test initialize methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary TestInitializeMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary TestInitializeMethodTimeoutMilliseconds { get; } = []; /// /// Gets the timeout for the test cleanup methods. /// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy. /// - internal Dictionary TestCleanupMethodTimeoutMilliseconds { get; } = new(); + internal Dictionary TestCleanupMethodTimeoutMilliseconds { get; } = []; /// /// Gets a value indicating whether class initialize has executed. @@ -138,9 +138,9 @@ internal set [Obsolete("API will be dropped in v4")] public Stack BaseClassCleanupMethodsStack { get; } = new(); - internal List BaseClassInitMethods { get; } = new(); + internal List BaseClassInitMethods { get; } = []; - internal List BaseClassCleanupMethods { get; } = new(); + internal List BaseClassCleanupMethods { get; } = []; /// /// Gets the exception thrown during method invocation. diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs index bd5dde9130..5fe5f07078 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestExecutionManager.cs @@ -389,8 +389,8 @@ private async Task ExecuteTestsInSourceAsync(IEnumerable tests, IRunCo int parallelWorkers = sourceSettings.Workers; ExecutionScope parallelScope = sourceSettings.Scope; - TestCase[] testsToRun = tests.Where(t => MatchTestFilter(filterExpression, t, _testMethodFilter)).ToArray(); - UnitTestElement[] unitTestElements = testsToRun.Select(e => e.ToUnitTestElement(source)).ToArray(); + TestCase[] testsToRun = [.. tests.Where(t => MatchTestFilter(filterExpression, t, _testMethodFilter))]; + UnitTestElement[] unitTestElements = [.. testsToRun.Select(e => e.ToUnitTestElement(source))]; // Create an instance of a type defined in adapter so that adapter gets loaded in the child app domain var testRunner = (UnitTestRunner)isolationHost.CreateInstanceForType( typeof(UnitTestRunner), diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs index b736e57bd9..7429314707 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs @@ -121,7 +121,7 @@ internal TestMethodInfo( /// Whether or not getting the attributes that are inherited. /// An array of the attributes. public Attribute[]? GetAllAttributes(bool inherit) - => ReflectHelper.Instance.GetAttributes(TestMethod, inherit).ToArray(); + => [.. ReflectHelper.Instance.GetAttributes(TestMethod, inherit)]; /// /// Gets all attributes of the test method. @@ -131,7 +131,7 @@ internal TestMethodInfo( /// An array of the attributes. public TAttributeType[] GetAttributes(bool inherit) where TAttributeType : Attribute - => ReflectHelper.Instance.GetAttributes(TestMethod, inherit).ToArray(); + => [.. ReflectHelper.Instance.GetAttributes(TestMethod, inherit)]; /// public virtual TestResult Invoke(object?[]? arguments) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs index 15240f0c41..1d04d00e3f 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestMethodRunner.cs @@ -93,7 +93,7 @@ internal async Task ExecuteAsync(string initializationLogs, string PlatformServiceProvider.Instance.AdapterTraceLogger.LogError(ex.ToString()); } - return results ?? Array.Empty(); + return results ?? []; } else { @@ -245,7 +245,7 @@ internal async Task RunTestMethodAsync() results.Add(emptyResult); } - return results.ToArray(); + return [.. results]; } private async Task TryExecuteDataSourceBasedTestsAsync(List results) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs index fbd7b24255..51516465c7 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs @@ -17,7 +17,7 @@ public class TestRunCancellationToken /// Callbacks to be invoked when canceled. /// Needs to be a concurrent collection, see https://github.com/microsoft/testfx/issues/3953. /// - private readonly ConcurrentBag<(Action, object?)> _registeredCallbacks = new(); + private readonly ConcurrentBag<(Action, object?)> _registeredCallbacks = []; /// /// Gets a value indicating whether the test run is canceled. diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs index bf6100502f..bf00aec70e 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TypeCache.cs @@ -736,7 +736,7 @@ private MethodInfo GetMethodInfoForTestMethod(TestMethod testMethod, TestClassIn } else if (methodBase != null) { - Type[] parameters = methodBase.GetParameters().Select(i => i.ParameterType).ToArray(); + Type[] parameters = [.. methodBase.GetParameters().Select(i => i.ParameterType)]; // TODO: Should we pass true for includeNonPublic? testMethodInfo = PlatformServiceProvider.Instance.ReflectionOperations.GetRuntimeMethod(methodBase.DeclaringType!, methodBase.Name, parameters, includeNonPublic: false); } diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs index 940f96fb55..69b9818219 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/Extensions/MethodInfoExtensions.cs @@ -166,9 +166,9 @@ internal static bool IsValidReturnType(this MethodInfo method, ReflectHelper? re methodInfo.DeclaringType!.FullName, methodInfo.Name, methodParametersLengthOrZero, - string.Join(", ", methodParameters?.Select(p => p.ParameterType.Name) ?? Array.Empty()), + string.Join(", ", methodParameters?.Select(p => p.ParameterType.Name) ?? []), argumentsLengthOrZero, - string.Join(", ", arguments?.Select(a => a?.GetType().Name ?? "null") ?? Array.Empty())), ex); + string.Join(", ", arguments?.Select(a => a?.GetType().Name ?? "null") ?? [])), ex); } } diff --git a/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs b/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs index 35f2d18207..44a8247390 100644 --- a/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs +++ b/src/Adapter/MSTest.TestAdapter/Extensions/TestCaseExtensions.cs @@ -102,7 +102,7 @@ internal static UnitTestElement ToUnitTestElement(this TestCase testCase, string if (testCase.Traits.Any()) { - testElement.Traits = testCase.Traits.ToArray(); + testElement.Traits = [.. testCase.Traits]; } string? cssIteration = testCase.GetPropertyValue(Constants.CssIterationProperty, null); diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs index 7eff98c5ff..40f114585f 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs @@ -125,7 +125,7 @@ internal virtual bool IsMethodDeclaredInSameAssemblyAsType(MethodInfo method, Ty IEnumerable typeCategories = GetAttributes(owningType, inherit: true); IEnumerable assemblyCategories = GetAttributes(owningType.Assembly, inherit: true); - return methodCategories.Concat(typeCategories).Concat(assemblyCategories).SelectMany(c => c.TestCategories).ToArray(); + return [.. methodCategories.Concat(typeCategories).Concat(assemblyCategories).SelectMany(c => c.TestCategories)]; } /// @@ -311,7 +311,7 @@ static Attribute[] GetAttributes(ICustomAttributeProvider attributeProvider, boo try { object[]? attributes = NotCachedReflectionAccessor.GetCustomAttributesNotCached(attributeProvider, inherit); - return attributes is null ? [] : attributes as Attribute[] ?? attributes.Cast().ToArray(); + return attributes is null ? [] : attributes as Attribute[] ?? [.. attributes.Cast()]; } catch (Exception ex) { diff --git a/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs b/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs index ddac9f6ded..db7144303b 100644 --- a/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs +++ b/src/Adapter/MSTest.TestAdapter/Helpers/TestDataSourceHelpers.cs @@ -44,7 +44,7 @@ public static bool TryHandleTupleDataSource(object? data, ParameterInfo[] testMe if (testMethodParameters.Length == 1 && data?.GetType().IsAssignableTo(testMethodParameters[0].ParameterType) == true) { - array = Array.Empty(); + array = []; return false; } @@ -103,7 +103,7 @@ static void ProcessTuple(object data, object?[] array, int startingIndex) } #endif - array = Array.Empty(); + array = []; return false; } diff --git a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs b/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs index 54bcc8fb98..5d5055f537 100644 --- a/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs +++ b/src/Adapter/MSTest.TestAdapter/ObjectModel/UnitTestElement.cs @@ -126,7 +126,7 @@ internal TestCase ToTestCase() IReadOnlyCollection hierarchy = TestMethod.Hierarchy; if (hierarchy is { Count: > 0 }) { - testCase.SetHierarchy(hierarchy.ToArray()); + testCase.SetHierarchy([.. hierarchy]); } // Set declaring type if present so the correct method info can be retrieved diff --git a/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs b/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs index 1ac452a754..39ee56ac55 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/AssemblyResolver.cs @@ -408,7 +408,7 @@ protected virtual return null; } - s_currentlyLoading ??= new List(); + s_currentlyLoading ??= []; s_currentlyLoading.Add(assemblyPath); // Push isPushed = true; } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs b/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs index f2af39ca11..90c377b952 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Data/TestDataConnectionSql.cs @@ -282,7 +282,7 @@ public string PrepareNameForSql(string tableName) return null; } - return parts.ToArray(); + return [.. parts]; } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs index 323487a79f..ac9d21964f 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Deployment/AssemblyLoadWorker.cs @@ -41,7 +41,7 @@ public IReadOnlyCollection GetFullPathToDependentAssemblies(string assem { DebugEx.Assert(!StringEx.IsNullOrEmpty(assemblyPath), "assemblyPath"); - warnings = new List(); + warnings = []; Assembly? assembly; try { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs index 2e37b5afba..b1bf6dcfbb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/ReflectionOperations.cs @@ -27,7 +27,7 @@ public class ReflectionOperations : IReflectionOperations [return: NotNullIfNotNull(nameof(memberInfo))] public object[]? GetCustomAttributes(MemberInfo memberInfo, bool inherit) #if NETFRAMEWORK - => ReflectionUtility.GetCustomAttributes(memberInfo, inherit).ToArray(); + => [.. ReflectionUtility.GetCustomAttributes(memberInfo, inherit)]; #else { object[] attributes = memberInfo.GetCustomAttributes(typeof(Attribute), inherit); @@ -51,7 +51,7 @@ public class ReflectionOperations : IReflectionOperations [return: NotNullIfNotNull(nameof(memberInfo))] public object[]? GetCustomAttributes(MemberInfo memberInfo, Type type, bool inherit) => #if NETFRAMEWORK - ReflectionUtility.GetCustomAttributes(memberInfo, type, inherit).ToArray(); + [.. ReflectionUtility.GetCustomAttributes(memberInfo, type, inherit)]; #else memberInfo.GetCustomAttributes(type, inherit); #endif diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs index c0cbeab9cd..de06dce3fb 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/TestSource.cs @@ -33,16 +33,16 @@ public class TestSource : ITestSource // Constants.DllExtension }; - private static readonly HashSet SystemAssemblies = new(new string[] - { + private static readonly HashSet SystemAssemblies = + [ "MICROSOFT.CSHARP.DLL", "MICROSOFT.VISUALBASIC.DLL", "CLRCOMPRESSION.DLL", - }); + ]; // Well known platform assemblies. - private static readonly HashSet PlatformAssemblies = new(new string[] - { + private static readonly HashSet PlatformAssemblies = + [ "MICROSOFT.VISUALSTUDIO.TESTPLATFORM.TESTFRAMEWORK.DLL", "MICROSOFT.VISUALSTUDIO.TESTPLATFORM.TESTFRAMEWORK.EXTENSIONS.CORE.DLL", "MICROSOFT.VISUALSTUDIO.TESTPLATFORM.CORE.DLL", @@ -54,7 +54,7 @@ public class TestSource : ITestSource "VSTEST_EXECUTIONENGINE_PLATFORMBRIDGE.DLL", "VSTEST_EXECUTIONENGINE_PLATFORMBRIDGE.WINMD", "VSTEST.EXECUTIONENGINE.WINDOWSPHONE.DLL", - }); + ]; #endif /// diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs index 821e25829d..95a4de695d 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Services/ThreadSafeStringWriter.cs @@ -183,7 +183,7 @@ internal static void CleanState() { lock (StaticLockObject) { - State.Value = new(); + State.Value = []; } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs index bd8c0d78e6..e274bbf7c3 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentItemUtility.cs @@ -212,7 +212,7 @@ private static List GetDeploymentItems(IEnumerable deploymentIte return deploymentItemList1; } - IList result = new List(deploymentItemList1); + IList result = [.. deploymentItemList1]; foreach (DeploymentItem item in deploymentItemList2) { @@ -247,7 +247,7 @@ private static List GetDeploymentItems(IEnumerable deploymentIte } } - return result.ToArray(); + return [.. result]; } private static IList? FromKeyValuePairs(KeyValuePair[] deploymentItemsData) @@ -257,7 +257,7 @@ private static List GetDeploymentItems(IEnumerable deploymentIte return null; } - IList result = new List(); + IList result = []; foreach ((string? key, string? value) in deploymentItemsData) { diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs index 21de3f1a79..7b2f77a9a6 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/DeploymentUtilityBase.cs @@ -407,7 +407,7 @@ private bool Deploy(string source, IRunContext? runContext, ITestExecutionRecord // Do the deployment. EqtTrace.InfoIf(EqtTrace.IsInfoEnabled, "MSTestExecutor: Using deployment directory {0} for source {1}.", runDirectories.OutDirectory, source); - IEnumerable warnings = Deploy(new List(deploymentItems), source, runDirectories.OutDirectory, GetTestResultsDirectory(runContext)); + IEnumerable warnings = Deploy([.. deploymentItems], source, runDirectories.OutDirectory, GetTestResultsDirectory(runContext)); // Log warnings LogWarnings(testExecutionRecorder, warnings); diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs index b9fe555b32..1ef57c713c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Utilities/ReflectionUtility.cs @@ -126,7 +126,7 @@ internal static List GetCustomAttributes(Assembly assembly, Type type { if (!assembly.ReflectionOnly) { - return assembly.GetCustomAttributes(type).ToList(); + return [.. assembly.GetCustomAttributes(type)]; } List customAttributes = [.. CustomAttributeData.GetCustomAttributes(assembly)]; @@ -195,8 +195,8 @@ internal static List GetCustomAttributes(Assembly assembly, Type type constructorArguments.Add(list.ToArray(parameterType.GetElementType())); } - ConstructorInfo constructor = attributeType.GetConstructor(constructorParameters.ToArray()); - attribute = constructor.Invoke(constructorArguments.ToArray()); + ConstructorInfo constructor = attributeType.GetConstructor([.. constructorParameters]); + attribute = constructor.Invoke([.. constructorArguments]); foreach (CustomAttributeNamedArgument namedArgument in attributeData.NamedArguments) { diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs index efeecd6dbd..b2005cc8c6 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferConstructorOverTestInitializeFixer.cs @@ -81,7 +81,7 @@ private static async Task ReplaceTestInitializeWithConstructorAsync(Do // If a constructor already exists, append the body of the TestInitialize method to it if (existingConstructor.Body != null) { - BlockSyntax newConstructorBody = existingConstructor.Body.AddStatements(testInitializeStatements ?? Array.Empty()); + BlockSyntax newConstructorBody = existingConstructor.Body.AddStatements(testInitializeStatements ?? []); newConstructor = existingConstructor.WithBody(newConstructorBody); } else diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs index 9911ee7287..0f47efc748 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferDisposeOverTestCleanupFixer.cs @@ -98,7 +98,7 @@ private static async Task AddDisposeAndBaseClassAsync( MethodDeclarationSyntax newDisposeMethod; if (existingDisposeMethod.Body != null) { - BlockSyntax newDisposeBody = existingDisposeMethod.Body.AddStatements(cleanupStatements ?? Array.Empty()); + BlockSyntax newDisposeBody = existingDisposeMethod.Body.AddStatements(cleanupStatements ?? []); newDisposeMethod = existingDisposeMethod.WithBody(newDisposeBody); } else diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs index 9ea85da311..5961aa1747 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/PreferTestInitializeOverConstructorFixer.cs @@ -86,7 +86,7 @@ private static async Task ReplaceConstructorWithTestInitializeAsync(Do MethodDeclarationSyntax newTestInitialize; if (existingTestInitialize.Body != null) { - BlockSyntax newTestInitializeBody = existingTestInitialize.Body.AddStatements(constructorStatements ?? Array.Empty()); + BlockSyntax newTestInitializeBody = existingTestInitialize.Body.AddStatements(constructorStatements ?? []); newTestInitialize = existingTestInitialize.WithBody(newTestInitializeBody); } else diff --git a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs index c15765fa46..a504d42fb0 100644 --- a/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs +++ b/src/Analyzers/MSTest.Analyzers.CodeFixes/TestContextShouldBeValidFixer.cs @@ -103,7 +103,7 @@ private static async Task FixMemberDeclarationAsync(Document document, AccessorDeclarationSyntax setAccessor = accessors.FirstOrDefault(a => a.Kind() == SyntaxKind.SetAccessorDeclaration) ?? SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - newMemberDeclaration = propertyDeclaration.WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List(new[] { getAccessor, setAccessor }))); + newMemberDeclaration = propertyDeclaration.WithAccessorList(SyntaxFactory.AccessorList(SyntaxFactory.List([getAccessor, setAccessor]))); } // Create a new member declaration with the updated modifiers. @@ -121,13 +121,13 @@ private static PropertyDeclarationSyntax ConvertFieldToProperty(FieldDeclaration PropertyDeclarationSyntax propertyDeclaration = SyntaxFactory.PropertyDeclaration(type, TestContextShouldBeValidAnalyzer.TestContextPropertyName) .WithModifiers(SyntaxFactory.TokenList(fieldDeclaration.Modifiers)) .WithAccessorList(SyntaxFactory.AccessorList( - SyntaxFactory.List(new[] - { + SyntaxFactory.List( + [ SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)), - }))); + .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) + ]))); return propertyDeclaration; } diff --git a/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs index 1742bf29c9..4e903b6a2b 100644 --- a/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DataRowShouldBeValidAnalyzer.cs @@ -91,7 +91,7 @@ private static void AnalyzeSymbol( var methodSymbol = (IMethodSymbol)context.Symbol; bool isTestMethod = false; - List dataRowAttributes = new(); + List dataRowAttributes = []; foreach (AttributeData methodAttribute in methodSymbol.GetAttributes()) { // Current method should be a test method or should inherit from the TestMethod attribute. @@ -184,7 +184,7 @@ private static void AnalyzeAttribute(SymbolAnalysisContext context, AttributeDat AnalyzeGenericMethod(context, dataRowSyntax, methodSymbol, constructorArguments); // Check constructor argument types match method parameter types. - List<(int ConstructorArgumentIndex, int MethodParameterIndex)> typeMismatchIndices = new(); + List<(int ConstructorArgumentIndex, int MethodParameterIndex)> typeMismatchIndices = []; for (int currentArgumentIndex = 0; currentArgumentIndex < constructorArguments.Length; currentArgumentIndex++) { // Null is considered as default for non-nullable types. diff --git a/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs index e326e9cff5..99f2fca090 100644 --- a/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/DoNotUseShadowingAnalyzer.cs @@ -64,7 +64,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo Dictionary> membersByName = GetBaseMembers(namedTypeSymbol); foreach (ISymbol member in namedTypeSymbol.GetMembers()) { - foreach (ISymbol baseMember in membersByName.GetValueOrDefault(member.Name, new List())) + foreach (ISymbol baseMember in membersByName.GetValueOrDefault(member.Name, [])) { // Check if the member is shadowing a base class member if (IsMemberShadowing(member, baseMember)) @@ -77,7 +77,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo private static Dictionary> GetBaseMembers(INamedTypeSymbol namedTypeSymbol) { - Dictionary> membersByName = new(); + Dictionary> membersByName = []; INamedTypeSymbol? currentType = namedTypeSymbol.BaseType; while (currentType is not null) { @@ -91,7 +91,7 @@ private static Dictionary> GetBaseMembers(INamedTypeSymbol if (!membersByName.TryGetValue(member.Name, out List? members)) { - members = new List(); + members = []; membersByName[member.Name] = members; } diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs index c719ef7aae..9e09a07c97 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/DiagnosticDescriptorHelper.cs @@ -31,7 +31,7 @@ public static DiagnosticDescriptor Create( public static DiagnosticDescriptor WithMessage(this DiagnosticDescriptor diagnosticDescriptor, LocalizableResourceString messageFormat) => new(diagnosticDescriptor.Id, diagnosticDescriptor.Title, messageFormat, diagnosticDescriptor.Category, diagnosticDescriptor.DefaultSeverity, - diagnosticDescriptor.IsEnabledByDefault, diagnosticDescriptor.Description, diagnosticDescriptor.HelpLinkUri, diagnosticDescriptor.CustomTags.ToArray()); + diagnosticDescriptor.IsEnabledByDefault, diagnosticDescriptor.Description, diagnosticDescriptor.HelpLinkUri, [.. diagnosticDescriptor.CustomTags]); private static string[] CreateCustomTags(bool isReportedAtCompilationEnd, bool escalateToErrorInRecommended, bool disableInAllMode, string[] customTags) { diff --git a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs index 7316c3ebb5..dbed1d2ae6 100644 --- a/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs +++ b/src/Analyzers/MSTest.Analyzers/RoslynAnalyzerHelpers/DiagnosticExtensions.cs @@ -169,7 +169,7 @@ public static void ReportNoLocationDiagnostic( { #pragma warning disable RS0030 // The symbol 'DiagnosticDescriptor.DiagnosticDescriptor.#ctor' is banned in this project: Use 'DiagnosticDescriptorHelper.Create' instead rule = new DiagnosticDescriptor(rule.Id, rule.Title, rule.MessageFormat, rule.Category, - effectiveSeverity.Value, rule.IsEnabledByDefault, rule.Description, rule.HelpLinkUri, rule.CustomTags.ToArray()); + effectiveSeverity.Value, rule.IsEnabledByDefault, rule.Description, rule.HelpLinkUri, [.. rule.CustomTags]); #pragma warning restore RS0030 } diff --git a/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs index 10bb626e00..6838d3bbc7 100644 --- a/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/TestContextShouldBeValidAnalyzer.cs @@ -212,7 +212,7 @@ public override void Initialize(AnalysisContext context) return; } - fieldsAssignedInConstructor = new(); + fieldsAssignedInConstructor = []; context.RegisterOperationBlockAction(context => { diff --git a/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs b/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs index d0940b34f5..9eb780c850 100644 --- a/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs +++ b/src/Analyzers/MSTest.GlobalConfigsGenerator/GlobalConfigBuilder.cs @@ -6,7 +6,7 @@ internal sealed class GlobalConfigBuilder { private readonly StringBuilder _builder = new(); - private readonly Dictionary _severityDictionary = new(); + private readonly Dictionary _severityDictionary = []; public GlobalConfigBuilder(MSTestAnalysisMode mode) { diff --git a/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs b/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs index c841f5d90d..aa42fbb24a 100644 --- a/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs +++ b/src/Analyzers/MSTest.SourceGeneration/Generators/TestNodesGenerator.cs @@ -50,10 +50,9 @@ private static void AddAssemblyTestNode(SourceProductionContext context, (string sourceStringBuilder.AppendAutoGeneratedHeader(); sourceStringBuilder.AppendLine(); - TestNamespaceInfo[] uniqueUsedNamespaces = testClasses + TestNamespaceInfo[] uniqueUsedNamespaces = [.. testClasses .Select(x => x.ContainingNamespace) - .Distinct() - .ToArray(); + .Distinct()]; string? safeAssemblyName = null; IDisposable? namespaceBlock = null; @@ -148,7 +147,7 @@ private static void AddAssemblyTestNode(SourceProductionContext context, (string private static void AppendAssemblyTestNodeBuilderContent(IndentedStringBuilder sourceStringBuilder, string assemblyName, ImmutableArray testClasses) { - Dictionary rootVariablesPerNamespace = new(); + Dictionary rootVariablesPerNamespace = []; int variableIndex = 1; IEnumerable> classesPerNamespaces = testClasses.GroupBy(x => x.ContainingNamespace); foreach (IGrouping namespaceClasses in classesPerNamespaces) @@ -169,7 +168,7 @@ private static void AppendAssemblyTestNodeBuilderContent(IndentedStringBuilder s sourceStringBuilder.Append("MSTF::TestNode root = "); - using (sourceStringBuilder.AppendTestNode(assemblyName, assemblyName, Array.Empty(), ';')) + using (sourceStringBuilder.AppendTestNode(assemblyName, assemblyName, [], ';')) { foreach (IGrouping group in classesPerNamespaces) { diff --git a/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs b/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs index 7a3645233e..f3e2817245 100644 --- a/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs +++ b/src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs @@ -81,7 +81,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. /// @@ -107,7 +107,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/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs index 5380802d1d..b085453536 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/DataRowTestMethodArgumentsInfo.cs @@ -43,7 +43,7 @@ public void AppendArguments(IndentedStringBuilder nodeBuilder) string argumentsEntry = arguments.Length > 1 ? "(" + string.Join(", ", arguments) + ")" : arguments[0]; - string argumentsUid = GetArgumentsUid(_parametersInfo.Parameters.Select(x => x.Name).ToArray(), arguments); + string argumentsUid = GetArgumentsUid([.. _parametersInfo.Parameters.Select(x => x.Name)], arguments); nodeBuilder.AppendLine($"new {TestMethodInfo.TestArgumentsEntryTypeName}<{_parametersInfo.ParametersTuple}>({argumentsEntry}, \"{argumentsUid}\"),"); } } diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs index 4cad071a97..708dce9b17 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestMethodInfo.cs @@ -89,10 +89,10 @@ private TestMethodInfo(IMethodSymbol methodSymbol, INamedTypeSymbol typeUsingMet return null; } - List dataRowAttributes = new(); - List dynamicDataAttributes = new(); - List testPropertyAttributes = new(); - List<(string RuleId, string Description)> pragmas = new(); + List dataRowAttributes = []; + List dynamicDataAttributes = []; + List testPropertyAttributes = []; + List<(string RuleId, string Description)> pragmas = []; TimeSpan? testExecutionTimeout = null; foreach (AttributeData attribute in attributes) { diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs index a17a31fc11..308a04ebea 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestNamespaceInfo.cs @@ -30,8 +30,7 @@ public TestNamespaceInfo(INamespaceSymbol namespaceSymbol) public void AppendNamespaceTestNode(IndentedStringBuilder nodeStringBuilder, string testsVariableName) { - using (nodeStringBuilder.AppendTestNode(_containingAssembly + "." + _nameOrGlobalNamespace, _nameOrGlobalNamespace, - Array.Empty(), testsVariableName)) + using (nodeStringBuilder.AppendTestNode(_containingAssembly + "." + _nameOrGlobalNamespace, _nameOrGlobalNamespace, [], testsVariableName)) { } } diff --git a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs index 60d46150ed..c1ec3a610e 100644 --- a/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs +++ b/src/Analyzers/MSTest.SourceGeneration/ObjectModels/TestTypeInfo.cs @@ -156,7 +156,7 @@ public void AppendTestNode(IndentedStringBuilder sourceStringBuilder) private void AppendTestNodeCreation(IndentedStringBuilder sourceStringBuilder) { - List properties = new(); + List properties = []; foreach ((string filePath, int startLine, int endLine) in _declarationReferences) { properties.Add($"new Msg::TestFileLocationProperty(@\"{filePath}\", new(new({startLine}, -1), new({endLine}, -1))),"); diff --git a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs index 9e7093ba63..580002941d 100644 --- a/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsReporter.cs @@ -23,7 +23,7 @@ internal sealed class AzureDevOpsReporter : private readonly IOutputDevice _outputDisplay; private readonly ILogger _logger; - private static readonly char[] NewlineCharacters = new char[] { '\r', '\n' }; + private static readonly char[] NewlineCharacters = ['\r', '\n']; private readonly ICommandLineOptions _commandLine; private readonly IEnvironment _environment; private readonly IFileSystem _fileSystem; diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs index 9469725e51..7ca615581c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/HangDumpActivityIndicator.cs @@ -140,7 +140,7 @@ private async Task CallbackAsync(IRequest request) if (request is GetInProgressTestsRequest) { await _logger.LogDebugAsync($"Received '{nameof(GetInProgressTestsRequest)}'"); - return new GetInProgressTestsResponse(_testsCurrentExecutionState.Select(x => (x.Value.Name, (int)_clock.UtcNow.Subtract(x.Value.StartTime).TotalSeconds)).ToArray()); + return new GetInProgressTestsResponse([.. _testsCurrentExecutionState.Select(x => (x.Value.Name, (int)_clock.UtcNow.Subtract(x.Value.StartTime).TotalSeconds))]); } else if (request is ExitSignalActivityIndicatorTaskRequest) { diff --git a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs index da92375d71..04344f941c 100644 --- a/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs +++ b/src/Platform/Microsoft.Testing.Extensions.HangDump/Serializers/GetInProgressTestsResponse.cs @@ -26,7 +26,7 @@ public object Deserialize(Stream stream) tests.Add((testName, unixTimeSeconds)); } - return new GetInProgressTestsResponse(tests.ToArray()); + return new GetInProgressTestsResponse([.. tests]); } public void Serialize(object objectToSerialize, Stream stream) diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs index 954fb4dfe9..5a5e521ca2 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryCommandLineOptionsProvider.cs @@ -24,9 +24,8 @@ internal sealed class RetryCommandLineOptionsProvider : ICommandLineOptionsProvi public string Description => ExtensionResources.RetryFailedTestsExtensionDescription; - public IReadOnlyCollection GetCommandLineOptions() - => new CommandLineOption[] - { + public IReadOnlyCollection GetCommandLineOptions() => + [ // Hide the extension for now, we will add tests and we will re-enable when will be good. // We'd like to have some iteration in prod with our dogfooders before. new(RetryFailedTestsOptionName, ExtensionResources.RetryFailedTestsOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), @@ -34,8 +33,8 @@ public IReadOnlyCollection GetCommandLineOptions() new(RetryFailedTestsMaxTestsOptionName, ExtensionResources.RetryFailedTestsMaxTestsOptionDescription, ArgumentArity.ExactlyOne, false, isBuiltIn: true), // Hidden internal args - new(RetryFailedTestsPipeNameOptionName, "Communication between the test host and the retry infra.", ArgumentArity.ExactlyOne, isHidden: true, isBuiltIn: true), - }; + new(RetryFailedTestsPipeNameOptionName, "Communication between the test host and the retry infra.", ArgumentArity.ExactlyOne, isHidden: true, isBuiltIn: true) + ]; public Task IsEnabledAsync() => Task.FromResult(true); diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs index 8b92f00072..d81ebe0fb0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryDataConsumer.cs @@ -28,7 +28,7 @@ public RetryDataConsumer(IServiceProvider serviceProvider) _commandLineOptions = _serviceProvider.GetCommandLineOptions(); } - public Type[] DataTypesConsumed => new[] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesConsumed => [typeof(TestNodeUpdateMessage)]; public string Uid => nameof(RetryDataConsumer); diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs index 1beb0961e0..0c28e544c0 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryExecutionFilterFactory.cs @@ -38,8 +38,7 @@ public Task IsEnabledAsync() _retryFailedTestsLifecycleCallbacks = _serviceProvider.GetRequiredService(); if (_retryFailedTestsLifecycleCallbacks.FailedTestsIDToRetry?.Length > 0) { - return (true, new TestNodeUidListFilter(_retryFailedTestsLifecycleCallbacks.FailedTestsIDToRetry - .Select(x => new TestNodeUid(x)).ToArray())); + return (true, new TestNodeUidListFilter([.. _retryFailedTestsLifecycleCallbacks.FailedTestsIDToRetry.Select(x => new TestNodeUid(x))])); } else { diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs index 21032e0497..b516672563 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryFailedTestsPipeServer.cs @@ -54,7 +54,7 @@ private Task CallbackAsync(IRequest request) { if (request is FailedTestRequest failed) { - FailedUID ??= new(); + FailedUID ??= []; FailedUID.Add(failed.Uid); return Task.FromResult((IResponse)VoidResponse.CachedInstance); } diff --git a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs index 59df6004f2..94bc289dd5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Retry/RetryOrchestrator.cs @@ -93,8 +93,8 @@ public async Task OrchestrateTestHostExecutionAsync() int userMaxRetryCount = int.Parse(cmdRetries[0], CultureInfo.InvariantCulture); // Find out the retry args index inside the arguments to after cleanup the command line when we restart - List indexToCleanup = new(); - string[] executableArguments = executableInfo.Arguments.ToArray(); + List indexToCleanup = []; + string[] executableArguments = [.. executableInfo.Arguments]; int argIndex = GetOptionArgumentIndex(RetryCommandLineOptionsProvider.RetryFailedTestsOptionName, executableArguments); if (argIndex < 0) { @@ -128,12 +128,12 @@ public async Task OrchestrateTestHostExecutionAsync() // Override the result directory with the attempt one string resultDirectory = configuration.GetTestResultDirectory(); - List exitCodes = new(); + List exitCodes = []; IOutputDevice outputDevice = _serviceProvider.GetOutputDevice(); IFileSystem fileSystem = _serviceProvider.GetFileSystem(); int attemptCount = 0; - List finalArguments = new(); + List finalArguments = []; string[]? lastListOfFailedId = null; string? currentTryResultFolder = null; bool thresholdPolicyKickedIn = false; @@ -160,7 +160,7 @@ public async Task OrchestrateTestHostExecutionAsync() finalArguments.Add(currentTryResultFolder); // Prepare the pipeserver - using RetryFailedTestsPipeServer retryFailedTestsPipeServer = new(_serviceProvider, lastListOfFailedId ?? Array.Empty(), logger); + using RetryFailedTestsPipeServer retryFailedTestsPipeServer = new(_serviceProvider, lastListOfFailedId ?? [], logger); finalArguments.Add($"--{RetryCommandLineOptionsProvider.RetryFailedTestsPipeNameOptionName}"); finalArguments.Add(retryFailedTestsPipeServer.PipeName); diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs index 959180a64a..070495036b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/AppInsightsProvider.cs @@ -108,7 +108,7 @@ public AppInsightsProvider( #else // Keep the custom thread to avoid to waste one from thread pool. // We have some await but we should stay on the custom thread if not for special cases like trace log or exception. - _payloads = new(); + _payloads = []; _telemetryTask = _task.RunLongRunning(IngestLoopAsync, "Telemetry AppInsightsProvider", _testApplicationCancellationTokenSource.CancellationToken); #endif diff --git a/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs b/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs index b90059537b..0ac25bde4a 100644 --- a/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs +++ b/src/Platform/Microsoft.Testing.Extensions.Telemetry/CIEnvironmentDetectorForTelemetry.cs @@ -33,8 +33,8 @@ internal sealed class CIEnvironmentDetectorForTelemetry ]; // Systems where every variable must be present and not-null before returning true - private static readonly string[][] AllNotNullVariables = new string[][] - { + private static readonly string[][] AllNotNullVariables = + [ // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html ["CODEBUILD_BUILD_ID", "AWS_REGION"], @@ -43,7 +43,7 @@ internal sealed class CIEnvironmentDetectorForTelemetry // Google Cloud Build - https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values#using_default_substitutions ["BUILD_ID", "PROJECT_ID"], - }; + ]; // Systems where the variable must be present and not-null private static readonly string[] IfNonNullVariables = diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs index c79cb5c062..2373e481b5 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxCompareTool.cs @@ -55,10 +55,10 @@ public async Task RunAsync() XNamespace trxNamespace = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; - List<(string TestName, string Outcome, string Storage)> baseLineResults = new(); - List baseLineIssues = new(); - List<(string TestName, string Outcome, string Storage)> comparedResults = new(); - List comparedIssues = new(); + List<(string TestName, string Outcome, string Storage)> baseLineResults = []; + List baseLineIssues = []; + List<(string TestName, string Outcome, string Storage)> comparedResults = []; + List comparedIssues = []; await _task.WhenAll( _task.Run(() => CollectEntriesAndErrors(baselineFilePaths[0], trxNamespace, baseLineResults, baseLineIssues)), _task.Run(() => CollectEntriesAndErrors(comparedFilePaths[0], trxNamespace, comparedResults, comparedIssues))); @@ -202,11 +202,10 @@ private static void CollectEntriesAndErrors(string trxFile, XNamespace ns, List< continue; } - XElement[] matchingUnitTestDefinitions = trxTestRun + XElement[] matchingUnitTestDefinitions = [.. trxTestRun .Elements(ns + "TestDefinitions") .Elements(ns + "UnitTest") - .Where(x => x.Attribute("id")?.Value == testId) - .ToArray(); + .Where(x => x.Attribute("id")?.Value == testId)]; if (matchingUnitTestDefinitions.Length > 1) { issues.Add($"Found more than one entry in 'TestDefinitions.UnitTest' matching the test ID '{testId}'."); diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs index 7999b00d47..6157ecc217 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxDataConsumer.cs @@ -40,7 +40,7 @@ internal sealed class TrxReportGenerator : private readonly TrxTestApplicationLifecycleCallbacks? _trxTestApplicationLifecycleCallbacks; private readonly ILogger _logger; private readonly List _tests = []; - private readonly Dictionary> _artifactsByExtension = new(); + private readonly Dictionary> _artifactsByExtension = []; private readonly bool _isEnabled; private DateTimeOffset? _testStartTime; @@ -227,7 +227,7 @@ public async Task OnTestSessionFinishingAsync(SessionUid sessionUid, Cancellatio int exitCode = _testApplicationProcessExitCode.GetProcessExitCode(); TrxReportEngine trxReportGeneratorEngine = new(_testApplicationModuleInfo, _environment, _commandLineOptionsService, _configuration, - _clock, _tests.ToArray(), _failedTestsCount, _passedTestsCount, _notExecutedTestsCount, _timeoutTestsCount, _artifactsByExtension, + _clock, [.. _tests], _failedTestsCount, _passedTestsCount, _notExecutedTestsCount, _timeoutTestsCount, _artifactsByExtension, _adapterSupportTrxCapability, _testFramework, _testStartTime.Value, exitCode, cancellationToken); (string reportFileName, string? warning) = await trxReportGeneratorEngine.GenerateReportAsync(); if (warning is not null) diff --git a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs index 903579a21a..9277a8b3ef 100644 --- a/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs +++ b/src/Platform/Microsoft.Testing.Extensions.TrxReport/TrxProcessLifetimeHandler.cs @@ -44,7 +44,7 @@ internal sealed class TrxProcessLifetimeHandler : private readonly IOutputDevice _outputDevice; private readonly ILogger _logger; private readonly PipeNameDescription _pipeNameDescription; - private readonly Dictionary> _fileArtifacts = new(); + private readonly Dictionary> _fileArtifacts = []; private readonly DateTimeOffset _startTime; private NamedPipeServer? _singleConnectionNamedPipeServer; @@ -144,7 +144,7 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH return; } - Dictionary> artifacts = new(); + Dictionary> artifacts = []; foreach (KeyValuePair> prodArtifacts in _fileArtifacts) { diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs index 90d9101af0..e5b628d9b4 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/Condition.cs @@ -164,7 +164,7 @@ internal static Condition Parse(string? conditionString) ThrownFormatExceptionForInvalidCondition(conditionString); } - string[] parts = TokenizeFilterConditionString(conditionString).ToArray(); + string[] parts = [.. TokenizeFilterConditionString(conditionString)]; if (parts.Length == 1) { // If only parameter values is passed, create condition with default property name, diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs index 456384b72c..aab3a4cf06 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FastFilter.cs @@ -37,7 +37,7 @@ internal FastFilter(ImmutableDictionary> filterProperties, ? null : FilterProperties.Keys.All(name => properties.Contains(name)) ? null - : FilterProperties.Keys.Where(name => !properties.Contains(name)).ToArray(); + : [.. FilterProperties.Keys.Where(name => !properties.Contains(name))]; internal bool Evaluate(Func propertyValueProvider) { diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs index 4f771bfc0f..be6f23da2b 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/FilterExpression.cs @@ -136,7 +136,7 @@ private static void ProcessOperator(Stack filterStack, Operato } else if (invalidRight != null) { - invalidProperties = invalidProperties.Concat(invalidRight).ToArray(); + invalidProperties = [.. invalidProperties, .. invalidRight]; } return invalidProperties; diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs index 43cecb9491..85fc64ea49 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/ObjectModelConverters.cs @@ -150,7 +150,7 @@ public static TestNode ToTestNode(this TestResult testResult, bool isTrxEnabled, throw new InvalidOperationException("Unable to parse fully qualified type name from test case: " + testResult.TestCase.FullyQualifiedName); } - testNode.Properties.Add(new TrxMessagesProperty(testResult.Messages + testNode.Properties.Add(new TrxMessagesProperty([.. testResult.Messages .Select(msg => msg.Category switch { @@ -158,8 +158,7 @@ public static TestNode ToTestNode(this TestResult testResult, bool isTrxEnabled, string x when x == TestResultMessage.StandardOutCategory => new StandardOutputTrxMessage(msg.Text), string x when x == TestResultMessage.DebugTraceCategory => new DebugOrTraceTrxMessage(msg.Text), _ => new TrxMessage(msg.Text), - }) - .ToArray())); + })])); } testNode.Properties.Add(new TimingProperty(new(testResult.StartTime, testResult.EndTime, testResult.Duration), [])); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs index 85cc81e2e2..97fa572220 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/ObjectModel/RunSettingsPatcher.cs @@ -107,7 +107,7 @@ private static void PatchTestRunParameters(XDocument runSettingsDocument, IComma runSettingsElement.Add(testRunParametersElement); } - XElement[] testRunParametersNodes = testRunParametersElement.Nodes().OfType().ToArray(); + XElement[] testRunParametersNodes = [.. testRunParametersElement.Nodes().OfType()]; foreach (string testRunParameter in testRunParameters) { string[] parts = testRunParameter.Split(TestRunParameterSeparator, 2); diff --git a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs index 57ae617299..a9f70fbcdf 100644 --- a/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs +++ b/src/Platform/Microsoft.Testing.Extensions.VSTestBridge/SynchronizedSingleSessionVSTestAndTestAnywhereAdapter.cs @@ -150,7 +150,7 @@ protected sealed override Task ExecuteRequestAsync(TestExecutionRequest request, => ExecuteRequestWithRequestCountGuardAsync(async () => { #pragma warning disable IL3000 // Avoid accessing Assembly file path when publishing as a single file - string[] testAssemblyPaths = _getTestAssemblies().Select(x => x.Location).ToArray(); + string[] testAssemblyPaths = [.. _getTestAssemblies().Select(x => x.Location)]; #pragma warning restore IL3000 // Avoid accessing Assembly file path when publishing as a single file switch (request) { diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs index ed0cbe17ec..fd765fce0b 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/InvokeTestingPlatformTask.cs @@ -32,7 +32,7 @@ public class InvokeTestingPlatformTask : Build.Utilities.ToolTask, IDisposable private readonly IFileSystem _fileSystem; private readonly PipeNameDescription _pipeNameDescription; private readonly CancellationTokenSource _waitForConnections = new(); - private readonly List _connections = new(); + private readonly List _connections = []; private readonly StringBuilder _output = new(); private readonly Lock _initLock = new(); private readonly Architecture _currentProcessArchitecture = RuntimeInformation.ProcessArchitecture; diff --git a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs index 818749ffad..f1d1018d35 100644 --- a/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs +++ b/src/Platform/Microsoft.Testing.Platform.MSBuild/Tasks/TestingPlatformAutoRegisteredExtensions.cs @@ -156,7 +156,7 @@ private static ITaskItem[] Reorder(ITaskItem[] items) result.Add(items[wellKnownBuilderHook_MicrosoftTestingPlatformExtensions_index]); } - return result.ToArray(); + return [.. result]; } private static void GenerateCode(string language, string? rootNamespace, ITaskItem[] taskItems, ITaskItem testingPlatformEntryPointSourcePath, IFileSystem fileSystem, TaskLoggingHelper taskLoggingHelper) diff --git a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs index b1cd776b62..b5f7d81720 100644 --- a/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs +++ b/src/Platform/Microsoft.Testing.Platform/Builder/TestApplication.cs @@ -47,10 +47,10 @@ public static Task CreateServerModeBuilderAsync(string[ if (args.Contains($"--{PlatformCommandLineProvider.ServerOptionKey}") || args.Contains($"-{PlatformCommandLineProvider.ServerOptionKey}")) { // Remove the --server option from the args so that the builder can be created. - args = args.Where(arg => arg.Trim('-') != PlatformCommandLineProvider.ServerOptionKey).ToArray(); + args = [.. args.Where(arg => arg.Trim('-') != PlatformCommandLineProvider.ServerOptionKey)]; } - return CreateBuilderAsync(args.Append($"--{PlatformCommandLineProvider.ServerOptionKey}").ToArray(), testApplicationOptions); + return CreateBuilderAsync([.. args, $"--{PlatformCommandLineProvider.ServerOptionKey}"], testApplicationOptions); } /// diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs index 1f6a1e0365..ac42242e50 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/CommandLineHandler.cs @@ -248,11 +248,10 @@ static string GetApplicationName(ITestApplicationModuleInfo testApplicationModul async Task PrintOptionsAsync(IEnumerable optionProviders, bool builtInOnly = false) { CommandLineOption[] options = - optionProviders + [.. optionProviders .SelectMany(provider => provider.GetCommandLineOptions()) .Where(option => !option.IsHidden && option.IsBuiltIn == builtInOnly) - .OrderBy(option => option.Name) - .ToArray(); + .OrderBy(option => option.Name)]; if (options.Length == 0) { @@ -281,9 +280,7 @@ async Task PrintApplicationUsageAsync(string applicationName) "System command line options should not have any tool option registered."); await outputDevice.DisplayAsync(this, new TextOutputDeviceData(PlatformResources.HelpOptions)); ICommandLineOptionsProvider[] nonToolsExtensionProviders = - ExtensionsCommandLineOptionsProviders - .Where(provider => provider is not IToolCommandLineOptionsProvider) - .ToArray(); + [.. ExtensionsCommandLineOptionsProviders.Where(provider => provider is not IToolCommandLineOptionsProvider)]; // By default, only system options are built-in but some extensions (e.g. retry) are considered as built-in too, // so we need to union the 2 collections before printing the options. await PrintOptionsAsync(SystemCommandLineOptionsProviders.Union(nonToolsExtensionProviders), builtInOnly: true); diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs index 6e3de38051..1a39282dc7 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ParseResult.cs @@ -129,7 +129,7 @@ public bool TryGetOptionArgumentList(string optionName, [NotNullWhen(true)] out IEnumerable result = Options.Where(x => x.Name == optionName); if (result.Any()) { - arguments = result.SelectMany(x => x.Arguments).ToArray(); + arguments = [.. result.SelectMany(x => x.Arguments)]; return true; } diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs index 8e4d3e44b1..f8f6306d22 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/Parser.cs @@ -72,7 +72,7 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi } else { - options.Add(new(currentOption, currentOptionArguments.ToArray())); + options.Add(new(currentOption, [.. currentOptionArguments])); currentOptionArguments.Clear(); ParseOptionAndSeparators(args[i], out currentOption, out currentArg); argumentHandled = true; @@ -122,7 +122,7 @@ private static CommandLineParseResult Parse(List args, IEnvironment envi } } - options.Add(new(currentOption, currentOptionArguments.ToArray())); + options.Add(new(currentOption, [.. currentOptionArguments])); } return new CommandLineParseResult(toolName, options, errors); diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs index c448fa0bf4..d744fdd77b 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/PlatformCommandLineProvider.cs @@ -143,7 +143,7 @@ public Task ValidateOptionArgumentsAsync(CommandLineOption com public static int GetMinimumExpectedTests(ICommandLineOptions commandLineOptions) { bool hasMinimumExpectedTestsOptionKey = commandLineOptions.TryGetOptionArgumentList(MinimumExpectedTestsOptionKey, out string[]? minimumExpectedTests); - if (!hasMinimumExpectedTestsOptionKey || !IsMinimumExpectedTestsOptionValidAsync(MinimumExpectedTests, minimumExpectedTests ?? Array.Empty()).Result.IsValid) + if (!hasMinimumExpectedTestsOptionKey || !IsMinimumExpectedTestsOptionValidAsync(MinimumExpectedTests, minimumExpectedTests ?? []).Result.IsValid) { return 0; } diff --git a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs index 1b9d4c057b..a0d5965447 100644 --- a/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs +++ b/src/Platform/Microsoft.Testing.Platform/CommandLine/ResponseFileHelper.cs @@ -12,7 +12,7 @@ internal static bool TryReadResponseFile(string rspFilePath, ICollection { try { - newArguments = ExpandResponseFile(rspFilePath).ToArray(); + newArguments = [.. ExpandResponseFile(rspFilePath)]; return true; } catch (FileNotFoundException) diff --git a/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs b/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs index 5a4861b9b0..4336f6c4e8 100644 --- a/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Configurations/ConfigurationManager.cs @@ -58,6 +58,6 @@ internal async Task BuildAsync(IFileLoggerProvider? syncFileLogg return defaultJsonConfiguration is null ? throw new InvalidOperationException(PlatformResources.ConfigurationManagerCannotFindDefaultJsonConfigurationErrorMessage) - : new AggregatedConfiguration(configurationProviders.OrderBy(x => x.Order).Select(x => x.ConfigurationProvider).ToArray(), _testApplicationModuleInfo, _fileSystem, commandLineParseResult); + : new AggregatedConfiguration([.. configurationProviders.OrderBy(x => x.Order).Select(x => x.ConfigurationProvider)], _testApplicationModuleInfo, _fileSystem, commandLineParseResult); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs index be8ff2dd95..1292534fa5 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/ServerTestHost.cs @@ -556,7 +556,7 @@ await ExecuteRequestAsync( await _telemetryService.LogEventAsync(TelemetryEvents.TestsRunEventName, metadata); return method == JsonRpcMethods.TestingRunTests - ? new RunResponseArgs(testNodeUpdateProcessor.Artifacts.ToArray()) + ? new RunResponseArgs([.. testNodeUpdateProcessor.Artifacts]) : method == JsonRpcMethods.TestingDiscoverTests ? (ResponseArgsBase)new DiscoverResponseArgs() : throw new NotImplementedException($"Request not implemented '{method}'"); diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs index 3f7f116f16..ac796585c4 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostBuilder.cs @@ -727,7 +727,7 @@ private static async Task BuildTestFrameworkAsync(TestFrameworkB dataConsumersBuilder.Add(abortForMaxFailedTestsExtension); } - IDataConsumer[] dataConsumerServices = dataConsumersBuilder.ToArray(); + IDataConsumer[] dataConsumerServices = [.. dataConsumersBuilder]; AsynchronousMessageBus concreteMessageBusService = new( dataConsumerServices, diff --git a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs index 601ea403d2..5fb3719f64 100644 --- a/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs +++ b/src/Platform/Microsoft.Testing.Platform/Hosts/TestHostControllersTestHost.cs @@ -157,7 +157,7 @@ protected override async Task InternalRunAsync() } AsynchronousMessageBus concreteMessageBusService = new( - dataConsumersBuilder.ToArray(), + [.. dataConsumersBuilder], ServiceProvider.GetTestApplicationCancellationTokenSource(), ServiceProvider.GetTask(), ServiceProvider.GetLoggerFactory(), diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs b/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs index 951e264d23..796f009c74 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs @@ -41,7 +41,7 @@ private ILogger[] CreateLoggers(string categoryName) loggers.Add(loggerProvider.CreateLogger(categoryName)); } - return loggers.ToArray(); + return [.. loggers]; } public void Dispose() diff --git a/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs b/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs index 5ce732043a..43c32ecbb2 100644 --- a/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/Logging/LoggingManager.cs @@ -33,6 +33,6 @@ internal async Task BuildAsync(IServiceProvider serviceProvider, loggerProviders.Add(serviceInstance); } - return new LoggerFactory(loggerProviders.ToArray(), logLevel, monitor); + return new LoggerFactory([.. loggerProviders], logLevel, monitor); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs index 0594ffa307..c0401e55a1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.Property.cs @@ -147,6 +147,6 @@ public PropertyDebugView(Property property) } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public IProperty[] Items => _property.AsEnumerable().ToArray(); + public IProperty[] Items => [.. _property.AsEnumerable()]; } } diff --git a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs index c3d1e03d24..b8c0905ce1 100644 --- a/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs +++ b/src/Platform/Microsoft.Testing.Platform/Messages/PropertyBag.cs @@ -230,7 +230,7 @@ public TProperty Single() throw new InvalidOperationException($"Could not find a property of type '{typeof(TProperty)}'."); } - IEnumerable matchingValues = _property is null ? Array.Empty() : _property.OfType(); + IEnumerable matchingValues = _property is null ? [] : _property.OfType(); return !matchingValues.Any() ? throw new InvalidOperationException($"Could not find a property of type '{typeof(TProperty)}'.") @@ -255,7 +255,7 @@ public TProperty[] OfType() // We don't want to allocate an array if we know that we're looking for a TestNodeStateProperty return typeof(TestNodeStateProperty).IsAssignableFrom(typeof(TProperty)) ? [] - : _property is null ? [] : _property.OfType().ToArray(); + : _property is null ? [] : [.. _property.OfType()]; } /// diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs index 5dd4b3e884..9c1b06e283 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiDetector.cs @@ -13,7 +13,7 @@ namespace Microsoft.Testing.Platform.OutputDevice.Terminal; internal static class AnsiDetector { private static readonly Regex[] TerminalsRegexes = - { + [ new("^xterm"), // xterm, PuTTY, Mintty new("^rxvt"), // RXVT new("^(?!eterm-color).*eterm.*"), // Accepts eterm, but not eterm-color, which does not support moving the cursor, see #9950. @@ -30,8 +30,8 @@ internal static class AnsiDetector new("konsole"), // Konsole new("bvterm"), // Bitvise SSH Client new("^st-256color"), // Suckless Simple Terminal, st - new("alacritty"), // Alacritty - }; + new("alacritty") // Alacritty + ]; public static bool IsAnsiSupported(string? termType) => !RoslynString.IsNullOrEmpty(termType) && TerminalsRegexes.Any(regex => regex.IsMatch(termType)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs index 4e8e511e22..abc28c3ea2 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminal.cs @@ -16,8 +16,8 @@ internal sealed class AnsiTerminal : ITerminal /// File extensions that we will link to directly, all other files /// are linked to their directory, to avoid opening dlls, or executables. /// - private static readonly string[] KnownFileExtensions = new string[] - { + private static readonly string[] KnownFileExtensions = + [ // code files ".cs", ".vb", @@ -33,8 +33,8 @@ internal sealed class AnsiTerminal : ITerminal ".nunit", ".trx", ".xml", - ".xunit", - }; + ".xunit" + ]; private readonly IConsole _console; private readonly string? _baseDirectory; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs index 6489512a6b..71649d1dea 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/AnsiTerminalTestProgressFrame.cs @@ -308,7 +308,7 @@ private List GenerateLinesToRender(TestProgressState?[] progress) // Note: We want to render the list of active tests, but this can easily fill up the full screen. // As such, we should balance the number of active tests shown per project. // We do this by distributing the remaining lines for each projects. - TestProgressState[] progressItems = progress.OfType().ToArray(); + TestProgressState[] progressItems = [.. progress.OfType()]; int linesToDistribute = (int)(Height * 0.7) - 1 - progressItems.Length; var detailItems = new IEnumerable[progressItems.Length]; IEnumerable sortedItemsIndices = Enumerable.Range(0, progressItems.Length).OrderBy(i => progressItems[i].TestNodeResultsState?.Count ?? 0); @@ -317,7 +317,7 @@ private List GenerateLinesToRender(TestProgressState?[] progress) { detailItems[sortedItemIndex] = progressItems[sortedItemIndex].TestNodeResultsState?.GetRunningTasks( linesToDistribute / progressItems.Length) - ?? Array.Empty(); + ?? []; } for (int progressI = 0; progressI < progressItems.Length; progressI++) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs index 5e0a406ab8..929a2d6ed4 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/ExceptionFlattener.cs @@ -9,7 +9,7 @@ internal static FlatException[] Flatten(string? errorMessage, Exception? excepti { if (errorMessage is null && exception is null) { - return Array.Empty(); + return []; } string? message = !RoslynString.IsNullOrWhiteSpace(errorMessage) ? errorMessage : exception?.Message; @@ -17,10 +17,7 @@ internal static FlatException[] Flatten(string? errorMessage, Exception? excepti string? stackTrace = exception?.StackTrace; var flatException = new FlatException(message, type, stackTrace); - List flatExceptions = new() - { - flatException, - }; + List flatExceptions = [flatException]; // Add all inner exceptions. This will flatten top level AggregateExceptions, // and all AggregateExceptions that are directly in AggregateExceptions, but won't expand @@ -45,7 +42,7 @@ internal static FlatException[] Flatten(string? errorMessage, Exception? excepti } } - return flatExceptions.ToArray(); + return [.. flatExceptions]; } } diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs index 905fc50137..834156bbef 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TerminalTestReporter.cs @@ -15,7 +15,7 @@ internal sealed partial class TerminalTestReporter : IDisposable /// /// The two directory separator characters to be passed to methods like . /// - private static readonly string[] NewLineStrings = { "\r\n", "\n" }; + private static readonly string[] NewLineStrings = ["\r\n", "\n"]; internal const string SingleIndentation = " "; @@ -37,7 +37,7 @@ internal event EventHandler OnProgressStopUpdate private readonly ConcurrentDictionary _assemblies = new(); - private readonly List _artifacts = new(); + private readonly List _artifacts = []; private readonly TerminalTestReporterOptions _options; diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs index db574dfa97..f14fecc7aa 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestNodeResultsState.cs @@ -45,7 +45,7 @@ public IEnumerable GetRunningTasks(int maxCount) ? string.Format(CultureInfo.CurrentCulture, PlatformResources.ActiveTestsRunning_FullTestsCount, sortedDetails.Count) // If itemsToTake is larger, then we show the project summary, active tests, and the number of active tests that are not shown. : $"... {string.Format(CultureInfo.CurrentCulture, PlatformResources.ActiveTestsRunning_MoreTestsCount, sortedDetails.Count - itemsToTake)}"; - sortedDetails = sortedDetails.Take(itemsToTake).ToList(); + sortedDetails = [.. sortedDetails.Take(itemsToTake)]; } foreach (TestDetailState? detail in sortedDetails) diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs index afc5d8d7cf..73a8aff848 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/TestProgressState.cs @@ -27,7 +27,7 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public IStopwatch Stopwatch { get; } - public List Messages { get; } = new(); + public List Messages { get; } = []; public int FailedTests { get; internal set; } @@ -45,7 +45,7 @@ public TestProgressState(long id, string assembly, string? targetFramework, stri public long Version { get; internal set; } - public List<(string? DisplayName, string? UID)> DiscoveredTests { get; internal set; } = new(); + public List<(string? DisplayName, string? UID)> DiscoveredTests { get; internal set; } = []; internal void AddError(string text) => Messages.Add(new ErrorMessage(text)); diff --git a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs index ac46b81654..30da68d0ef 100644 --- a/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/OutputDevice/TerminalOutputDevice.cs @@ -51,7 +51,7 @@ internal sealed partial class TerminalOutputDevice : IHotReloadPlatformOutputDev // The targeted framework, .NET 8 when application specifies net8.0 private readonly string? _targetFramework; private readonly string _assemblyName; - private readonly char[] _dash = new char[] { '-' }; + private readonly char[] _dash = ['-']; private TerminalTestReporter? _terminalTestReporter; private bool _firstCallTo_OnSessionStartingAsync = true; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs index 8b1d908167..b6cba24fa5 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/DotnetTestConnection.cs @@ -69,7 +69,7 @@ public async Task HelpInvokedAsync() { RoslynDebug.Assert(_dotnetTestPipeClient is not null); - List commandLineHelpOptions = new(); + List commandLineHelpOptions = []; foreach (ICommandLineOptionsProvider commandLineOptionProvider in _commandLineHandler.CommandLineOptionsProviders) { if (commandLineOptionProvider is IToolCommandLineOptionsProvider) @@ -87,7 +87,7 @@ public async Task HelpInvokedAsync() } } - await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), commandLineHelpOptions.OrderBy(option => option.Name).ToArray()), _cancellationTokenSource.CancellationToken); + await _dotnetTestPipeClient.RequestReplyAsync(new CommandLineOptionMessages(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath(), [.. commandLineHelpOptions.OrderBy(option => option.Name)]), _cancellationTokenSource.CancellationToken); } public async Task IsCompatibleProtocolAsync(string hostType) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs index 702a3bd9be..1c23eb623e 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/DotnetTestDataConsumer.cs @@ -21,13 +21,13 @@ public DotnetTestDataConsumer(DotnetTestConnection dotnetTestConnection, IEnviro _environment = environment; } - public Type[] DataTypesConsumed => new[] - { + public Type[] DataTypesConsumed => + [ typeof(TestNodeUpdateMessage), typeof(SessionFileArtifact), typeof(FileArtifact), - typeof(TestRequestExecutionTimeInfo), - }; + typeof(TestRequestExecutionTimeInfo) + ]; public string Uid => nameof(DotnetTestDataConsumer); @@ -59,12 +59,11 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella DiscoveredTestMessages discoveredTestMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new DiscoveredTestMessage( testNodeUpdateMessage.TestNode.Uid.Value, - testNodeUpdateMessage.TestNode.DisplayName), - }); + testNodeUpdateMessage.TestNode.DisplayName) + ]); await _dotnetTestConnection.SendMessageAsync(discoveredTestMessages); break; @@ -74,8 +73,7 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella TestResultMessages testResultMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new SuccessfulTestResultMessage( testNodeUpdateMessage.TestNode.Uid.Value, testNodeUpdateMessage.TestNode.DisplayName, @@ -84,9 +82,9 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeDetails.Reason ?? string.Empty, testNodeDetails.StandardOutput ?? string.Empty, testNodeDetails.StandardError ?? string.Empty, - testNodeUpdateMessage.SessionUid.Value), - }, - Array.Empty()); + testNodeUpdateMessage.SessionUid.Value) + ], + []); await _dotnetTestConnection.SendMessageAsync(testResultMessages); break; @@ -98,9 +96,8 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testResultMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - Array.Empty(), - new[] - { + [], + [ new FailedTestResultMessage( testNodeUpdateMessage.TestNode.Uid.Value, testNodeUpdateMessage.TestNode.DisplayName, @@ -110,8 +107,8 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella testNodeDetails.Exceptions, testNodeDetails.StandardOutput ?? string.Empty, testNodeDetails.StandardError ?? string.Empty, - testNodeUpdateMessage.SessionUid.Value), - }); + testNodeUpdateMessage.SessionUid.Value) + ]); await _dotnetTestConnection.SendMessageAsync(testResultMessages); break; @@ -122,16 +119,15 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella FileArtifactMessages testFileArtifactMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { - new FileArtifactMessage( - artifact.FileInfo.FullName, - artifact.DisplayName, - artifact.Description ?? string.Empty, - testNodeUpdateMessage.TestNode.Uid.Value, - testNodeUpdateMessage.TestNode.DisplayName, - testNodeUpdateMessage.SessionUid.Value), - }); + [ + new FileArtifactMessage( + artifact.FileInfo.FullName, + artifact.DisplayName, + artifact.Description ?? string.Empty, + testNodeUpdateMessage.TestNode.Uid.Value, + testNodeUpdateMessage.TestNode.DisplayName, + testNodeUpdateMessage.SessionUid.Value) + ]); await _dotnetTestConnection.SendMessageAsync(testFileArtifactMessages); } @@ -142,16 +138,15 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella var fileArtifactMessages = new FileArtifactMessages( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new FileArtifactMessage( sessionFileArtifact.FileInfo.FullName, sessionFileArtifact.DisplayName, sessionFileArtifact.Description ?? string.Empty, string.Empty, string.Empty, - sessionFileArtifact.SessionUid.Value), - }); + sessionFileArtifact.SessionUid.Value) + ]); await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages); break; @@ -160,16 +155,15 @@ public async Task ConsumeAsync(IDataProducer dataProducer, IData value, Cancella fileArtifactMessages = new( ExecutionId, DotnetTestConnection.InstanceId, - new[] - { + [ new FileArtifactMessage( fileArtifact.FileInfo.FullName, fileArtifact.DisplayName, fileArtifact.Description ?? string.Empty, string.Empty, string.Empty, - string.Empty), - }); + string.Empty) + ]); await _dotnetTestConnection.SendMessageAsync(fileArtifactMessages); break; diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs index 9940477af9..9571f8f7a4 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/HandshakeMessageSerializer.cs @@ -11,7 +11,7 @@ internal sealed class HandshakeMessageSerializer : BaseSerializer, INamedPipeSer public object Deserialize(Stream stream) { - Dictionary properties = new(); + Dictionary properties = []; ushort fieldCount = ReadShort(stream); diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs index 4472ddbaea..3bc7cc8965 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Serializers/TestResultMessagesSerializer.cs @@ -323,7 +323,7 @@ private static ExceptionMessage[] ReadExceptionMessagesPayload(Stream stream) exceptionMessages.Add(new ExceptionMessage(errorMessage, errorType, stackTrace)); } - return exceptionMessages.ToArray(); + return [.. exceptionMessages]; } public void Serialize(object objectToSerialize, Stream stream) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs index 0e540ef32e..f5a40ec03f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/FormatterUtilities.cs @@ -34,13 +34,13 @@ internal sealed class MessageFormatter : IMessageFormatter public MessageFormatter() { - Dictionary serializers = new(); - Dictionary deserializers = new(); + Dictionary serializers = []; + Dictionary deserializers = []; foreach (Type serializableType in SerializerUtilities.SerializerTypes) { serializers[serializableType] = new JsonObjectSerializer( - o => SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value)).ToArray()); + o => [.. SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value))]); } foreach (Type deserializableType in SerializerUtilities.DeserializerTypes) diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs index 43bf9d41bd..c6a35fe518 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/Json/Json.cs @@ -19,28 +19,27 @@ public Json(Dictionary? serializers = null, Dictionary(request => new[] - { - (JsonRpcStrings.JsonRpc, "2.0"), + _serializers[typeof(RequestMessage)] = new JsonObjectSerializer(request => + [ + (JsonRpcStrings.JsonRpc, "2.0"), (JsonRpcStrings.Id, request.Id), (JsonRpcStrings.Method, request.Method), - (JsonRpcStrings.Params, request.Params), - }); + (JsonRpcStrings.Params, request.Params) + ]); - _serializers[typeof(ResponseMessage)] = new JsonObjectSerializer(response => new[] - { - (JsonRpcStrings.JsonRpc, "2.0"), + _serializers[typeof(ResponseMessage)] = new JsonObjectSerializer(response => + [ + (JsonRpcStrings.JsonRpc, "2.0"), (JsonRpcStrings.Id, response.Id), - (JsonRpcStrings.Result, response.Result), - }); + (JsonRpcStrings.Result, response.Result) + ]); _serializers[typeof(NotificationMessage)] = new JsonObjectSerializer(notification => - new[] - { - (JsonRpcStrings.JsonRpc, "2.0"), + [ + (JsonRpcStrings.JsonRpc, "2.0"), (JsonRpcStrings.Method, notification.Method), - (JsonRpcStrings.Params, notification.Params), - }); + (JsonRpcStrings.Params, notification.Params) + ]); _serializers[typeof(ErrorMessage)] = new JsonObjectSerializer(error => { @@ -51,76 +50,69 @@ public Json(Dictionary? serializers = null, Dictionary(response => - new (string, object?)[] - { - (JsonRpcStrings.ProcessId, response.ProcessId), + [ + (JsonRpcStrings.ProcessId, response.ProcessId), (JsonRpcStrings.ServerInfo, response.ServerInfo), - (JsonRpcStrings.Capabilities, response.Capabilities), - }); + (JsonRpcStrings.Capabilities, response.Capabilities) + ]); - _serializers[typeof(ServerInfo)] = new JsonObjectSerializer(info => new (string, object?)[] - { - (JsonRpcStrings.Name, info.Name), - (JsonRpcStrings.Version, info.Version), - }); + _serializers[typeof(ServerInfo)] = new JsonObjectSerializer(info => + [ + (JsonRpcStrings.Name, info.Name), + (JsonRpcStrings.Version, info.Version) + ]); _serializers[typeof(ServerCapabilities)] = new JsonObjectSerializer(capabilities => - new (string, object?)[] - { - (JsonRpcStrings.Testing, capabilities.TestingCapabilities), - }); + [ + (JsonRpcStrings.Testing, capabilities.TestingCapabilities) + ]); _serializers[typeof(ServerTestingCapabilities)] = new JsonObjectSerializer(capabilities => - new (string, object?)[] - { - (JsonRpcStrings.SupportsDiscovery, capabilities.SupportsDiscovery), + [ + (JsonRpcStrings.SupportsDiscovery, capabilities.SupportsDiscovery), (JsonRpcStrings.MultiRequestSupport, capabilities.MultiRequestSupport), (JsonRpcStrings.VSTestProviderSupport, capabilities.VSTestProviderSupport), (JsonRpcStrings.AttachmentsSupport, capabilities.SupportsAttachments), - (JsonRpcStrings.MultiConnectionProvider, capabilities.MultiConnectionProvider), - }); + (JsonRpcStrings.MultiConnectionProvider, capabilities.MultiConnectionProvider) + ]); _serializers[typeof(Artifact)] = new JsonObjectSerializer(artifact => - new (string, object?)[] - { - (JsonRpcStrings.Uri, artifact.Uri), + [ + (JsonRpcStrings.Uri, artifact.Uri), (JsonRpcStrings.Producer, artifact.Producer), (JsonRpcStrings.Type, artifact.Type), (JsonRpcStrings.DisplayName, artifact.DisplayName), - (JsonRpcStrings.Description, artifact.Description), - }); + (JsonRpcStrings.Description, artifact.Description) + ]); _serializers[typeof(DiscoverResponseArgs)] = new JsonObjectSerializer(response => []); _serializers[typeof(RunResponseArgs)] = new JsonObjectSerializer(response => - new (string, object?)[] - { - (JsonRpcStrings.Attachments, response.Artifacts), - }); + [ + (JsonRpcStrings.Attachments, response.Artifacts) + ]); _serializers[typeof(TestNodeUpdateMessage)] = new JsonObjectSerializer(message => - new (string, object?)[] - { - (JsonRpcStrings.Node, message.TestNode), - (JsonRpcStrings.Parent, message.ParentTestNodeUid?.Value), - }); + [ + (JsonRpcStrings.Node, message.TestNode), + (JsonRpcStrings.Parent, message.ParentTestNodeUid?.Value) + ]); _serializers[typeof(TestNodeStateChangedEventArgs)] = new JsonObjectSerializer(message => - new (string, object?)[] - { - (JsonRpcStrings.RunId, message.RunId), - (JsonRpcStrings.Changes, message.Changes), - }); + [ + (JsonRpcStrings.RunId, message.RunId), + (JsonRpcStrings.Changes, message.Changes) + ]); _serializers[typeof(TestNode)] = new JsonObjectSerializer(message => { @@ -299,59 +291,52 @@ public Json(Dictionary? serializers = null, Dictionary(message => - new (string, object?)[] - { - (JsonRpcStrings.Level, message.LogMessage.Level.ToString()), - (JsonRpcStrings.Message, message.LogMessage.Message), - }); + [ + (JsonRpcStrings.Level, message.LogMessage.Level.ToString()), + (JsonRpcStrings.Message, message.LogMessage.Message) + ]); _serializers[typeof(CancelRequestArgs)] = new JsonObjectSerializer(request => - new (string, object?)[] - { - (JsonRpcStrings.Id, request.CancelRequestId), - }); + [ + (JsonRpcStrings.Id, request.CancelRequestId) + ]); _serializers[typeof(TelemetryEventArgs)] = new JsonObjectSerializer(ev => - new (string, object?)[] - { - (JsonRpcStrings.EventName, ev.EventName), - (JsonRpcStrings.Metrics, ev.Metrics), - }); + [ + (JsonRpcStrings.EventName, ev.EventName), + (JsonRpcStrings.Metrics, ev.Metrics) + ]); _serializers[typeof(ProcessInfoArgs)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.Program, info.Program), + [ + (JsonRpcStrings.Program, info.Program), (JsonRpcStrings.Args, info.Args), (JsonRpcStrings.WorkingDirectory, info.WorkingDirectory), - (JsonRpcStrings.EnvironmentVariables, info.EnvironmentVariables), - }); + (JsonRpcStrings.EnvironmentVariables, info.EnvironmentVariables) + ]); _serializers[typeof(AttachDebuggerInfoArgs)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.ProcessId, info.ProcessId), - }); + [ + (JsonRpcStrings.ProcessId, info.ProcessId) + ]); _serializers[typeof(TestsAttachments)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.Attachments, info.Attachments), - }); + [ + (JsonRpcStrings.Attachments, info.Attachments) + ]); _serializers[typeof(RunTestAttachment)] = new JsonObjectSerializer(info => - new (string, object?)[] - { - (JsonRpcStrings.Uri, info.Uri), + [ + (JsonRpcStrings.Uri, info.Uri), (JsonRpcStrings.Producer, info.Producer), (JsonRpcStrings.Type, info.Type), (JsonRpcStrings.DisplayName, info.DisplayName), - (JsonRpcStrings.Description, info.Description), - }); + (JsonRpcStrings.Description, info.Description) + ]); // Serializers _serializers[typeof(string)] = new JsonValueSerializer((w, v) => w.WriteStringValue(v)); @@ -368,7 +353,7 @@ public Json(Dictionary? serializers = null, Dictionary((w, v) => w.WriteStringValue(v.ToString())); // Remove for now _serializers[typeof((string, object?)[])] = new JsonObjectSerializer<(string, object?)[]>(n => n); - _serializers[typeof(Dictionary)] = new JsonObjectSerializer>(d => d.Select(kvp => (kvp.Key, (object?)kvp.Value)).ToArray()); + _serializers[typeof(Dictionary)] = new JsonObjectSerializer>(d => [.. d.Select(kvp => (kvp.Key, (object?)kvp.Value))]); // Deserializers _deserializers[typeof(string)] = new JsonElementDeserializer((json, jsonDocument) => jsonDocument.GetString()!); @@ -379,7 +364,7 @@ public Json(Dictionary? serializers = null, Dictionary)] = new JsonElementDeserializer>((json, jsonDocument) => { - Dictionary items = new(); + Dictionary items = []; foreach (JsonProperty kvp in jsonDocument.EnumerateObject()) { switch (kvp.Value.ValueKind) @@ -672,7 +657,7 @@ internal bool TryArrayBind(JsonElement element, out T[]? value, string? prope return false; } - value = element.EnumerateArray().Select(Deserialize).ToArray(); + value = [.. element.EnumerateArray().Select(Deserialize)]; return true; } diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs index 1ae054fcbd..d15e47b46f 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/ServerModePerCallOutputDevice.cs @@ -15,11 +15,11 @@ internal sealed class ServerModePerCallOutputDevice : IPlatformOutputDevice, IOu { private readonly FileLoggerProvider? _fileLoggerProvider; private readonly IStopPoliciesService _policiesService; - private readonly ConcurrentBag _messages = new(); + private readonly ConcurrentBag _messages = []; private IServerTestHost? _serverTestHost; - private static readonly string[] NewLineStrings = { "\r\n", "\n" }; + private static readonly string[] NewLineStrings = ["\r\n", "\n"]; public ServerModePerCallOutputDevice(FileLoggerProvider? fileLoggerProvider, IStopPoliciesService policiesService) { diff --git a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs index 0c26a1c096..91a23ad4f7 100644 --- a/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs +++ b/src/Platform/Microsoft.Testing.Platform/ServerMode/JsonRpc/TestNodeStateChangeAggregator.cs @@ -29,6 +29,6 @@ public void OnStateChange(TestNodeUpdateMessage stateChangedMessage) => _stateChanges.Add(stateChangedMessage); public TestNodeStateChangedEventArgs BuildAggregatedChange() - => new(RunId, _stateChanges.ToArray()); + => new(RunId, [.. _stateChanges]); } } diff --git a/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs b/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs index c69e617b8a..79a71c1489 100644 --- a/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs +++ b/src/Platform/Microsoft.Testing.Platform/Services/StopPoliciesService.cs @@ -31,7 +31,7 @@ public StopPoliciesService(ITestApplicationCancellationTokenSource testApplicati private static void RegisterCallback(ref BlockingCollection? callbacks, T callback) #pragma warning disable CA1416 // Validate platform compatibility - => (callbacks ??= new()).Add(callback); + => (callbacks ??= []).Add(callback); #pragma warning restore CA1416 public async Task ExecuteMaxFailedTestsCallbacksAsync(int maxFailedTests, CancellationToken cancellationToken) diff --git a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs index 684e3cfeec..a9a6f7ce61 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHost/TestHostManager.cs @@ -118,7 +118,7 @@ internal async Task BuildTestApplicationLi } } - return testApplicationLifecycleCallbacks.ToArray(); + return [.. testApplicationLifecycleCallbacks]; } public void AddDataConsumer(Func dataConsumerFactory) @@ -212,7 +212,7 @@ public void AddDataConsumer(CompositeExtensionFactory compositeServiceFact } } - return dataConsumers.ToArray(); + return [.. dataConsumers]; } public void AddTestSessionLifetimeHandle(Func testSessionLifetimeHandleFactory) @@ -307,6 +307,6 @@ public void AddTestSessionLifetimeHandle(CompositeExtensionFactory composi } } - return testSessionLifetimeHandlers.ToArray(); + return [.. testSessionLifetimeHandlers]; } } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs index f04985b9db..3422551b69 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostControllers/TestHostControllersManager.cs @@ -286,9 +286,9 @@ internal async Task BuildAsync(ServiceProvider bool requireProcessRestart = environmentVariableProviders.Count > 0 || lifetimeHandlers.Count > 0 || dataConsumers.Count > 0; return new TestHostControllerConfiguration( - environmentVariableProviders.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostEnvironmentVariableProvider).ToArray(), - lifetimeHandlers.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostProcessLifetimeHandler).ToArray(), - dataConsumers.OrderBy(x => x.RegistrationOrder).Select(x => x.Consumer).ToArray(), + [.. environmentVariableProviders.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostEnvironmentVariableProvider)], + [.. lifetimeHandlers.OrderBy(x => x.RegistrationOrder).Select(x => x.TestHostProcessLifetimeHandler)], + [.. dataConsumers.OrderBy(x => x.RegistrationOrder).Select(x => x.Consumer)], requireProcessRestart); } } diff --git a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs index d6f7a628bf..a4015025af 100644 --- a/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs +++ b/src/Platform/Microsoft.Testing.Platform/TestHostOrcherstrator/TestHostOrchestratorManager.cs @@ -46,6 +46,6 @@ public async Task BuildAsync(ServiceProvider } } - return new TestHostOrchestratorConfiguration(orchestrators.ToArray()); + return new TestHostOrchestratorConfiguration([.. orchestrators]); } } diff --git a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs index 1c91754b59..664e9bad37 100644 --- a/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs +++ b/src/TestFramework/TestFramework/Attributes/DataSource/DynamicDataOperations.cs @@ -115,7 +115,7 @@ private static bool TryGetData(object dataSource, [NotNullWhen(true)] out IEnume if (dataSource is IEnumerable enumerable and not string) { - List objects = new(); + List objects = []; foreach (object? entry in enumerable) { if (entry is null) @@ -124,7 +124,7 @@ private static bool TryGetData(object dataSource, [NotNullWhen(true)] out IEnume return false; } - objects.Add(new[] { entry }); + objects.Add([entry]); } data = objects; diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs index 60dc976cf9..855893fc95 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/RetryResult.cs @@ -9,7 +9,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting; [Experimental("MSTESTEXP", UrlFormat = "https://aka.ms/mstest/diagnostics#{0}")] public sealed class RetryResult { - private readonly List _testResults = new(); + private readonly List _testResults = []; /// /// Adds a set of test results to the retry result. diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs index 3260b69c61..4d6885fd96 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/SdkTests.cs @@ -428,7 +428,7 @@ public async Task SettingIsTestApplicationToFalseReducesAddedExtensionsAndMakesP SL.Build binLog = SL.Serialization.Read(compilationResult.BinlogPath!); SL.Task cscTask = binLog.FindChildrenRecursive(task => task.Name == "Csc").Single(); - SL.Item[] references = cscTask.FindChildrenRecursive(p => p.Name == "References").Single().Children.OfType().ToArray(); + SL.Item[] references = [.. cscTask.FindChildrenRecursive(p => p.Name == "References").Single().Children.OfType()]; // Ensure that MSTest.Framework is referenced Assert.IsTrue(references.Any(r => r.Text.EndsWith("Microsoft.VisualStudio.TestPlatform.TestFramework.dll", StringComparison.OrdinalIgnoreCase))); diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs index b79c30d152..1405d7ad71 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/ServerModeTests.cs @@ -16,9 +16,9 @@ public sealed class ServerModeTests : ServerModeTestsBase testResults = await RunTestsAsync(testCases); // Assert - VerifyE2E.ContainsTestsFailed(testResults, new string[] { null! }); + VerifyE2E.ContainsTestsFailed(testResults, [null!]); } public async Task AssertExtensibilityTests() diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs index 7cf6b875ab..4b9b678643 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/CLITestBase.discovery.cs @@ -54,7 +54,7 @@ private sealed class InternalSink : ITestCaseDiscoverySink { private readonly List _testCases = []; - public ImmutableArray DiscoveredTests => _testCases.ToImmutableArray(); + public ImmutableArray DiscoveredTests => [.. _testCases]; public void SendTestCase(TestCase discoveredTest) => _testCases.Add(discoveredTest); } @@ -92,11 +92,11 @@ private sealed class InternalFrameworkHandle : IFrameworkHandle private readonly List _messageList = []; private readonly ConcurrentDictionary> _testResults = new(); - private ConcurrentBag _activeResults = new(); + private ConcurrentBag _activeResults = []; public bool EnableShutdownAfterTestRun { get; set; } - public void RecordStart(TestCase testCase) => _activeResults = _testResults.GetOrAdd(testCase, _ => new()); + public void RecordStart(TestCase testCase) => _activeResults = _testResults.GetOrAdd(testCase, _ => []); public void RecordEnd(TestCase testCase, TestOutcome outcome) => _activeResults = _testResults[testCase]; diff --git a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs index ef809a9bb7..8c4d4f96dd 100644 --- a/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs +++ b/test/IntegrationTests/MSTest.IntegrationTests/Utilities/TestCaseFilterFactory.cs @@ -288,7 +288,7 @@ private static bool ContainsComparer(string[] values, string value) { Guard.NotNull(conditionString); - string[] condition = TokenizeCondition(conditionString).ToArray(); + string[] condition = [.. TokenizeCondition(conditionString)]; Expression parameterName, expectedValue, parameterValueProvider, expression; string op; diff --git a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs index b7e513c82b..d48e07480c 100644 --- a/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs +++ b/test/IntegrationTests/MSTest.VstestConsoleWrapper.IntegrationTests/TimeoutTests.cs @@ -34,7 +34,7 @@ private void ValidateTimeoutTests(string targetFramework) failedTests.Add("TimeoutTestProject.TimeoutTestClass.TimeoutTest_WhenUserCallsThreadAbort_AbortTest"); } - ValidateFailedTestsContain(false, failedTests.ToArray()); + ValidateFailedTestsContain(false, [.. failedTests]); // We should find the /TimeoutTestOutput.txt file, as it's our way to validate // that when the timeout expires it cancels the test context token. diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs index 8e7ae8bb7f..060a342a1a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ExitOnProcessExitTests.cs @@ -25,7 +25,7 @@ public void ExitOnProcessExit_Succeed(string tfm) Thread.Sleep(500); // Look for the pid file created by the test host. - string[] pidFile = Directory.GetFiles(Path.GetDirectoryName(testHost.FullName)!, "PID").ToArray(); + string[] pidFile = [.. Directory.GetFiles(Path.GetDirectoryName(testHost.FullName)!, "PID")]; if (pidFile.Length > 0) { string pid = File.ReadAllText(pidFile[0]); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs index 2c3afc4387..ee62060cb3 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs @@ -180,14 +180,13 @@ private static string ExtractVersionFromPackage(string rootFolder, string packag // Microsoft.Testing.Platform.Extensions.1.0.0.nupkg // So we need to find a package that contains a number after the prefix. // Ideally, we would want to do a full validation to check this is a nuget version number, but that's too much work for now. - matches = matches + matches = [.. matches // (full path, file name without prefix) .Select(path => (path, fileName: Path.GetFileName(path)[packagePrefixName.Length..])) // check if first character of file name without prefix is number .Where(tuple => int.TryParse(tuple.fileName[0].ToString(), CultureInfo.InvariantCulture, out _)) // take the full path - .Select(tuple => tuple.path) - .ToArray(); + .Select(tuple => tuple.path)]; } if (matches.Length != 1) diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs index d971231e9b..c4f229af9d 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/RetryFailedTestsTests.cs @@ -158,9 +158,7 @@ await RetryHelper.RetryAsync( testHostResult.AssertExitCodeIs(ExitCodes.TestHostProcessExitedNonGracefully); - string[] entries = Directory.GetFiles(resultDirectory, "*.*", SearchOption.AllDirectories) - .Where(x => !x.Contains("Retries", StringComparison.OrdinalIgnoreCase)) - .ToArray(); + string[] entries = [.. Directory.GetFiles(resultDirectory, "*.*", SearchOption.AllDirectories).Where(x => !x.Contains("Retries", StringComparison.OrdinalIgnoreCase))]; // 1 trx file Assert.AreEqual(1, entries.Count(x => x.EndsWith("trx", StringComparison.OrdinalIgnoreCase))); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs index 3bfd65e5ea..16c19ea78a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerLoggingTests.cs @@ -17,7 +17,7 @@ public async Task RunningInServerJsonRpcModeShouldHaveOutputDeviceLogsPushedToTe string resultDirectory = Path.Combine(AssetFixture.TargetAssetPath, Guid.NewGuid().ToString("N"), tfm); var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, "ServerLoggingTests", tfm); using TestingPlatformClient jsonClient = await StartAsServerAndConnectToTheClientAsync(testHost); - LogsCollector logs = new(); + LogsCollector logs = []; jsonClient.RegisterLogListener(logs); InitializeResponse initializeResponseArgs = await jsonClient.Initialize(); diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs index 4df559bc05..18efef8eae 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/TestNodeUpdateCollector.cs @@ -10,7 +10,7 @@ public class TestNodeUpdateCollector private readonly TaskCompletionSource _taskCompletionSource = new(); private readonly Func? _completeCollector; - public ConcurrentBag TestNodeUpdates { get; } = new(); + public ConcurrentBag TestNodeUpdates { get; } = []; public TestNodeUpdateCollector(Func? completeCollectorWhen = null) => _completeCollector = completeCollectorWhen; diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs index 6dda46477f..e1abd7b78a 100644 --- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs +++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/ServerMode/v1.0.0/TestingPlatformClient.cs @@ -157,14 +157,11 @@ public record Log(LogLevel LogLevel, string Message); private sealed class TargetHandler { - private readonly ConcurrentDictionary _listeners - = new(); + private readonly ConcurrentDictionary _listeners = new(); - private readonly ConcurrentBag _logListeners - = new(); + private readonly ConcurrentBag _logListeners = []; - private readonly ConcurrentBag _telemetryPayloads - = new(); + private readonly ConcurrentBag _telemetryPayloads = []; public void RegisterTelemetryListener(TelemetryCollector listener) => _telemetryPayloads.Add(listener); diff --git a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs index 4e2ee52753..bb1425fb6d 100644 --- a/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs +++ b/test/IntegrationTests/PlatformServices.Desktop.IntegrationTests/ReflectionUtilityTests.cs @@ -275,6 +275,6 @@ private static string[] GetAttributeValuePairs(IEnumerable attributes) } } - return attributeValuePairs.ToArray(); + return [.. attributeValuePairs]; } } diff --git a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs index b8c2e49da3..bcd6a6bffc 100644 --- a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs +++ b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_OverriddenGetDisplayName.cs @@ -34,7 +34,7 @@ public static IEnumerable Data { get { - yield return new object[] { "SomeData" }; + yield return ["SomeData"]; } } } diff --git a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs index 6f6e1ae3ef..cf397b5972 100644 --- a/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs +++ b/test/IntegrationTests/TestAssets/DataRowTestProject/DataRowTests_Regular.cs @@ -68,7 +68,9 @@ public void NullValueInData(string email, string password, string returnUrl) public void NullValue(object o) => Assert.IsNull(o); [TestMethod] - [DataRow(new string[] { "" })] +#pragma warning disable SA1122 // Use string.Empty for empty strings + [DataRow([""])] +#pragma warning restore SA1122 // Use string.Empty for empty strings public void OneStringArray(string[] lines) => Assert.AreEqual(1, lines.Length); [TestMethod] @@ -80,7 +82,9 @@ public void TwoStringArrays(string[] input1, string[] input2) } [TestMethod] - [DataRow(new object[] { "", 1 })] +#pragma warning disable SA1122 // Use string.Empty for empty strings + [DataRow(["", 1])] +#pragma warning restore SA1122 // Use string.Empty for empty strings public void OneObjectArray(object[] objects) => Assert.AreEqual(2, objects.Length); [TestMethod] diff --git a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs index c22a047e3f..97f8dc09f4 100644 --- a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs +++ b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DisableExpansionTests.cs @@ -50,8 +50,8 @@ public void TestPropertyWithTwoSourcesAndSecondDisablesExpansion(int a, string s private static IEnumerable MethodSource() { - yield return new object[] { 1, "a" }; - yield return new object[] { 2, "b" }; + yield return [1, "a"]; + yield return [2, "b"]; } } @@ -61,7 +61,7 @@ public class DataSourceHelper public static IEnumerable MethodSource() { - yield return new object[] { 3, "c" }; - yield return new object[] { 4, "d" }; + yield return [3, "c"]; + yield return [4, "d"]; } } diff --git a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs index 8fdeb44f88..5e0149815c 100644 --- a/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs +++ b/test/IntegrationTests/TestAssets/DynamicDataTestProject/DynamicDataTests.cs @@ -253,14 +253,14 @@ public class ExampleTestCase private static IEnumerable StringAndInt32() { - yield return new object[] { "1", 1 }; - yield return new object[] { "2", 1 }; + yield return ["1", 1]; + yield return ["2", 1]; } private static IEnumerable Int32AndString() { - yield return new object[] { 1, "0" }; - yield return new object[] { 2, "2" }; + yield return [1, "0"]; + yield return [2, "2"]; } private static IEnumerable SimpleCollection diff --git a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs index fe39499599..48d882ece8 100644 --- a/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs +++ b/test/IntegrationTests/TestAssets/FxExtensibilityTestProject/CustomTestExTests.cs @@ -53,7 +53,7 @@ public override TestResult[] Execute(ITestMethod testMethod) results.AddRange(testResults); } - return results.ToArray(); + return [.. results]; } } diff --git a/test/Performance/MSTest.Performance.Runner/Context.cs b/test/Performance/MSTest.Performance.Runner/Context.cs index a3bd69a829..ab4a7a76d3 100644 --- a/test/Performance/MSTest.Performance.Runner/Context.cs +++ b/test/Performance/MSTest.Performance.Runner/Context.cs @@ -5,13 +5,13 @@ namespace MSTest.Performance.Runner; internal class Context : IContext, IDisposable { - private List _disposables = new(); + private List _disposables = []; public IDictionary Properties { get; private set; } = new Dictionary(); public void Init(IDictionary properties) { - _disposables = new(); + _disposables = []; Properties = properties; } diff --git a/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs b/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs index bcc2153539..ad75d304d4 100644 --- a/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs +++ b/test/Performance/MSTest.Performance.Runner/PipelinesRunner.cs @@ -7,7 +7,7 @@ namespace MSTest.Performance.Runner; internal class PipelinesRunner { - private readonly List _pipelines = new(); + private readonly List _pipelines = []; public void AddPipeline(string groupName, string pipelineName, OSPlatform[] oSPlatform, Action> func, Action>? updatePropertyBag = null, string[]? traits = null) => _pipelines.Add(new PipelineInfo(groupName, pipelineName, oSPlatform, func, updatePropertyBag, traits)); diff --git a/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs b/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs index b1f1af50d9..691ffb6a74 100644 --- a/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs +++ b/test/Performance/MSTest.Performance.Runner/Steps/PlainProcess.cs @@ -36,7 +36,7 @@ public async Task ExecuteAsync(BuildArtifact payload, IContext context) Console.WriteLine($"Process command: '{processStartInfo.FileName} {processStartInfo.Arguments.Trim()}' for {_numberOfRun} times"); - List results = new(); + List results = []; for (int i = 0; i < _numberOfRun; i++) { using Process process = Process.Start(processStartInfo)!; diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs index 23d263569a..7f553df797 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/NonNullableReferenceNotInitializedSuppressorTests.cs @@ -79,7 +79,7 @@ public class DoNothingAnalyzer : DiagnosticAnalyzer [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] public static readonly DiagnosticDescriptor Rule = new(NonNullableReferenceNotInitializedSuppressor.Rule.SuppressedDiagnosticId, "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs index 069d599c3e..b75ac12800 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestFixtureMethodSuppressorTests.cs @@ -104,7 +104,7 @@ public class WarnForMissingAsyncSuffix : DiagnosticAnalyzer [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] public static readonly DiagnosticDescriptor Rule = new(UseAsyncSuffixTestFixtureMethodSuppressor.Rule.SuppressedDiagnosticId, "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs index ba566c293c..1bd51439f4 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAsyncSuffixTestMethodSuppressorTests.cs @@ -107,7 +107,7 @@ public class WarnForMissingAsyncSuffix : DiagnosticAnalyzer [SuppressMessage("MicrosoftCodeAnalysisDesign", "RS1017:DiagnosticId for analyzers must be a non-null constant.", Justification = "For suppression test only.")] public static readonly DiagnosticDescriptor Rule = new(UseAsyncSuffixTestMethodSuppressor.Rule.SuppressedDiagnosticId, "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs index f7353183ad..8ddb170745 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseAttributeOnTestMethodAnalyzerTests.cs @@ -91,7 +91,7 @@ public void TestMethod() string fixedCode = $$""" using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] @@ -118,7 +118,7 @@ public async Task WhenMethodIsMarkedWithMultipleTestAttributesButNotWithTestMeth { string code = $$""" using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] @@ -134,7 +134,7 @@ public void TestMethod() string fixedCode = $$""" using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] @@ -149,7 +149,7 @@ public void TestMethod() } """; - await VerifyCS.VerifyCodeFixAsync(code, new[] { VerifyCS.Diagnostic(rule1).WithLocation(0), VerifyCS.Diagnostic(rule2).WithLocation(1) }, fixedCode); + await VerifyCS.VerifyCodeFixAsync(code, [VerifyCS.Diagnostic(rule1).WithLocation(0), VerifyCS.Diagnostic(rule2).WithLocation(1)], fixedCode); } [DynamicData(nameof(GetAttributeUsageExamples), DynamicDataSourceType.Method)] @@ -159,7 +159,7 @@ public async Task WhenMethodIsMarkedWithTestAttributeAndCustomTestMethod_NoDiagn string code = $$""" using System; using Microsoft.VisualStudio.TestTools.UnitTesting; - + {{MyExpectedExceptionAttributeDeclaration}} [TestClass] diff --git a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs index 5100e968e7..5b7e1a422b 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/Adapter_ExecuteRequestAsyncTests.cs @@ -27,7 +27,7 @@ public async Task ExecutableNode_ThatDoesNotThrow_ShouldReportPassed() }; var services = new Services(); - var adapter = new TestFramework(new(), new[] { new FactoryTestNodesBuilder(() => new[] { testNode }) }, new(), + var adapter = new TestFramework(new(), [new FactoryTestNodesBuilder(() => [testNode])], new(), services.ServiceProvider.GetSystemClock(), services.ServiceProvider.GetTask(), services.ServiceProvider.GetConfiguration(), new Platform.Capabilities.TestFramework.TestFrameworkCapabilities()); CancellationToken cancellationToken = CancellationToken.None; @@ -62,7 +62,7 @@ public async Task ExecutableNode_ThatThrows_ShouldReportError() var services = new Services(); var fakeClock = (FakeClock)services.ServiceProvider.GetService(typeof(FakeClock))!; - var adapter = new TestFramework(new(), new[] { new FactoryTestNodesBuilder(() => new[] { testNode }) }, new(), + var adapter = new TestFramework(new(), [new FactoryTestNodesBuilder(() => [testNode])], new(), services.ServiceProvider.GetSystemClock(), services.ServiceProvider.GetTask(), services.ServiceProvider.GetConfiguration(), new Platform.Capabilities.TestFramework.TestFrameworkCapabilities()); CancellationToken cancellationToken = CancellationToken.None; @@ -93,7 +93,7 @@ await adapter.ExecuteRequestAsync(new( private sealed class FakeClock : IClock { - public List UsedTimes { get; } = new(); + public List UsedTimes { get; } = []; public DateTimeOffset UtcNow { @@ -116,7 +116,7 @@ public Services() ServiceProvider.AddService(new FakeClock()); ServiceProvider.AddService(new SystemTask()); #pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. - ServiceProvider.AddService(new AggregatedConfiguration(Array.Empty(), new CurrentTestApplicationModuleInfo(new SystemEnvironment(), new SystemProcessHandler()), new SystemFileSystem(), new(null, [], []))); + ServiceProvider.AddService(new AggregatedConfiguration([], new CurrentTestApplicationModuleInfo(new SystemEnvironment(), new SystemProcessHandler()), new SystemFileSystem(), new(null, [], []))); #pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. } @@ -127,7 +127,7 @@ public Services() private sealed class MessageBus : IMessageBus { - public List Messages { get; } = new(); + public List Messages { get; } = []; public Task PublishAsync(IDataProducer dataProducer, IData data) { diff --git a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs index 847ecdf276..6ff2840b2a 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/BFSTestNodeVisitorTests.cs @@ -18,21 +18,21 @@ public async Task Visit_WhenFilterDoesNotUseEncodedSlash_NodeIsNotIncluded() { StableUid = "ID1", DisplayName = "A", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "ID2", DisplayName = "B/C", }, - }, + ], }; var filter = new TreeNodeFilter("/A/B/C"); var visitor = new BFSTestNodeVisitor(new[] { rootNode }, filter, null!); // Act - List includedTestNodes = new(); + List includedTestNodes = []; await visitor.VisitAsync((testNode, _) => { includedTestNodes.Add(testNode); @@ -55,21 +55,21 @@ public async Task Visit_WhenFilterUsesEncodedEntry_NodeIsIncluded(string nodeSpe { StableUid = "ID1", DisplayName = "A", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "ID2", DisplayName = "B" + nodeSpecialString + "C", }, - }, + ], }; var filter = new TreeNodeFilter("/A/B" + filterEncodedSpecialString + "C"); var visitor = new BFSTestNodeVisitor(new[] { rootNode }, filter, null!); // Act - List includedTestNodes = new(); + List includedTestNodes = []; await visitor.VisitAsync((testNode, _) => { includedTestNodes.Add(testNode); @@ -107,7 +107,7 @@ public async Task Visit_WhenNodeIsNotParameterizedNode_DoesNotExpand(string nonP var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), null!); // Act - List includedTestNodes = new(); + List includedTestNodes = []; await visitor.VisitAsync((testNode, _) => { includedTestNodes.Add(testNode); @@ -129,7 +129,7 @@ public async Task Visit_WhenNodeIsParameterizedNodeAndPropertyIsAbsentOrTrue_Exp var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), new TestArgumentsManager()); // Act - List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = new(); + List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = []; await visitor.VisitAsync((testNode, parentNodeUid) => { includedTestNodes.Add((testNode, parentNodeUid)); @@ -158,7 +158,7 @@ public async Task Visit_WhenNodeIsParameterizedNodeAndDoesNotAllowExpansion_Does var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), new TestArgumentsManager()); // Act - List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = new(); + List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = []; await visitor.VisitAsync((testNode, parentNodeUid) => { includedTestNodes.Add((testNode, parentNodeUid)); @@ -177,14 +177,14 @@ public async Task Visit_WithModuleNamespaceClassMethodLevelAndExpansion_Discover { StableUid = "MyModule", DisplayName = "MyModule", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "MyNamespace", DisplayName = "MyNamespace", - Tests = new[] - { + Tests = + [ new TestNode { StableUid = "MyType", @@ -200,14 +200,14 @@ public async Task Visit_WithModuleNamespaceClassMethodLevelAndExpansion_Discover }, }, }, - }, + ], }, - }, + ], }; var visitor = new BFSTestNodeVisitor(new[] { rootNode }, new NopFilter(), new TestArgumentsManager()); // Act - List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = new(); + List<(TestNode Node, TestNodeUid? ParentNodeUid)> includedTestNodes = []; await visitor.VisitAsync((testNode, parentNodeUid) => { includedTestNodes.Add((testNode, parentNodeUid)); @@ -267,13 +267,13 @@ private static TestNode CreateParameterizedTestNode(string parameterizedTestNode static IEnumerable GetArguments() => new byte[] { 0, 1 }; static IProperty[] GetProperties(bool? hasExpansionProperty) => hasExpansionProperty.HasValue - ? new IProperty[1] - { + ? + [ new FrameworkEngineMetadataProperty { PreventArgumentsExpansion = hasExpansionProperty.Value, }, - } - : Array.Empty(); + ] + : []; } } diff --git a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs index f511c2ff51..d7d29cca7a 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataNameProviderTests.cs @@ -15,7 +15,7 @@ public void NullTranslatesToNullString() // you will get empty string while with the call you will get "null,a". // // check that this is still true: - string fragment = DynamicDataNameProvider.GetUidFragment(["parameter1", "parameter2"], new object?[] { null, "a" }, 0); + string fragment = DynamicDataNameProvider.GetUidFragment(["parameter1", "parameter2"], [null, "a"], 0); Assert.AreEqual("(parameter1: null, parameter2: a)[0]", fragment); } @@ -28,7 +28,7 @@ public void ParameterMismatchShowsDataInMessage() // you will get empty string while with the call you will get "null,a". // // check that this is still true: - ArgumentException exception = Assert.ThrowsException(() => DynamicDataNameProvider.GetUidFragment(["parameter1"], new object?[] { null, "a" }, 0)); + ArgumentException exception = Assert.ThrowsException(() => DynamicDataNameProvider.GetUidFragment(["parameter1"], [null, "a"], 0)); Assert.AreEqual("Parameter count mismatch. The provided data (null, a) have 2 items, but there are 1 parameters.", exception.Message); } } diff --git a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs index ea608a39d3..1fa1ce4990 100644 --- a/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs +++ b/test/UnitTests/MSTest.Engine.UnitTests/DynamicDataTests.cs @@ -10,11 +10,11 @@ namespace Microsoft.Testing.Framework.UnitTests; public class DynamicDataTests { public static IEnumerable IntDataProperty - => new[] - { - new object[] { 1, 2 }, - new object[] { 2, 3 }, - }; + => + [ + [1, 2], + [2, 3] + ]; [DynamicData(nameof(IntDataProperty))] [TestMethod] @@ -37,11 +37,11 @@ public void DynamicDataWithIntMethodAndExplicitSourceType(int expected, int actu => Assert.AreEqual(expected, actualPlus1 - 1); public static IEnumerable IntDataMethod() - => new[] - { - new object[] { 1, 2 }, - new object[] { 2, 3 }, - }; + => + [ + [1, 2], + [2, 3] + ]; [DynamicData(nameof(IntDataProperty), typeof(DataClass))] [TestMethod] @@ -60,11 +60,11 @@ public void DynamicDataWithUserProperty(User _, User _2) } public static IEnumerable UserDataProperty - => new[] - { - new object[] { new User("Jakub"), new User("Amaury") }, - new object[] { new User("Marco"), new User("Pavel") }, - }; + => + [ + [new User("Jakub"), new User("Amaury")], + [new User("Marco"), new User("Pavel")] + ]; [DynamicData(nameof(UserDataMethod), DynamicDataSourceType.Method)] [TestMethod] @@ -73,28 +73,28 @@ public void DynamicDataWithUserMethod(User _, User _2) } public static IEnumerable UserDataMethod() - => new[] - { - new object[] { new User("Jakub"), new User("Amaury") }, - new object[] { new User("Marco"), new User("Pavel") }, - }; + => + [ + [new User("Jakub"), new User("Amaury")], + [new User("Marco"), new User("Pavel")] + ]; } public class DataClass { public static IEnumerable IntDataProperty - => new[] - { - new object[] { 1, 3 }, - new object[] { 2, 4 }, - }; + => + [ + [1, 3], + [2, 4] + ]; public static IEnumerable IntDataMethod() - => new[] - { - new object[] { 1, 3 }, - new object[] { 2, 4 }, - }; + => + [ + [1, 3], + [2, 4] + ]; } public class User diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs index 7695466e03..7d3c831a9b 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Generators/TestNodesGeneratorTests.cs @@ -626,25 +626,24 @@ public Task TestMethod() public async Task When_MultipleClassesFromSameNamespace_ItGeneratesASingleNamespaceTestNode() { GeneratorCompilationResult generatorResult = await GeneratorTester.TestGraph.CompileAndExecuteAsync( - new[] - { - $$""" - using System.Threading.Tasks; - using Microsoft.VisualStudio.TestTools.UnitTesting; - - namespace MyNamespace - { - [TestClass] - public class MyType1 - { - [TestMethod] - public Task TestMethod() - { - return Task.CompletedTask; - } - } - } - """, + [ + $$""" + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + namespace MyNamespace + { + [TestClass] + public class MyType1 + { + [TestMethod] + public Task TestMethod() + { + return Task.CompletedTask; + } + } + } + """, $$""" using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -661,8 +660,8 @@ public Task TestMethod() } } } - """, - }, CancellationToken.None); + """ + ], CancellationToken.None); generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(4); @@ -1154,27 +1153,26 @@ public void GenerateValidNamespaceName_WithGivenAssemblyName_ReturnsExpectedName public async Task When_APartialTypeIsMarkedWithTestClass_ItGeneratesAGraphWithAssemblyNamespaceTypeAndMethods() { GeneratorCompilationResult generatorResult = await GeneratorTester.TestGraph.CompileAndExecuteAsync( - new string[] - { - $$""" - using System.Threading.Tasks; - using Microsoft.VisualStudio.TestTools.UnitTesting; - - namespace MyNamespace - { - [TestClass] - public partial class MyType - { - public MyType(int a) { } - - [TestMethod] - public Task TestMethod1() - { - return Task.CompletedTask; - } - } - } - """, + [ + $$""" + using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + namespace MyNamespace + { + [TestClass] + public partial class MyType + { + public MyType(int a) { } + + [TestMethod] + public Task TestMethod1() + { + return Task.CompletedTask; + } + } + } + """, $$""" using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -1196,8 +1194,8 @@ public Task TestMethod2() } } } - """, - }, CancellationToken.None); + """ + ], CancellationToken.None); generatorResult.AssertSuccessfulGeneration(); generatorResult.GeneratedTrees.Should().HaveCount(3); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs index e00e391545..5537de1ad2 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/Helpers/MinimalTestRunner.cs @@ -11,7 +11,7 @@ public static async Task RunAllAsync(string? testNameContainsFilter = null) #pragma warning disable IL2026 // Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code IEnumerable classes = Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsPublic); #pragma warning restore IL2026 // Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code - object[][] emptyRow = new[] { Array.Empty() }; + object[][] emptyRow = [[]]; int total = 0; int failed = 0; @@ -63,7 +63,7 @@ public static async Task RunAllAsync(string? testNameContainsFilter = null) object?[][]? rows = null; if (methodAttributes.Any(a => a.AttributeType == typeof(DataRowAttribute))) { - rows = methodAttributes + rows = [.. methodAttributes .Where(a => a.AttributeType == typeof(DataRowAttribute)) .SelectMany(a => a.ConstructorArguments.Select(arg => { @@ -79,8 +79,7 @@ public static async Task RunAllAsync(string? testNameContainsFilter = null) return [arg.Value]; } #pragma warning restore IDE0046 // Convert to conditional expression - })) - .ToArray(); + }))]; } foreach (object?[]? row in rows ?? emptyRow) diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs index 83f1290dcc..1bbd56f15a 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/GeneratorTester.cs @@ -30,8 +30,7 @@ public GeneratorTester(Func incrementalGeneratorFactory, public static GeneratorTester TestGraph { get; } = new( () => new TestNodesGenerator(), - new[] - { + [ // Microsoft.Testing.Platform dll Assembly.GetAssembly(typeof(IProperty))!.Location, @@ -45,13 +44,13 @@ public GeneratorTester(Func incrementalGeneratorFactory, Assembly.GetAssembly(typeof(TrxExceptionProperty))!.Location, // MSTest.TestFramework dll - Assembly.GetAssembly(typeof(TestClassAttribute))!.Location, - }); + Assembly.GetAssembly(typeof(TestClassAttribute))!.Location + ]); public static ImmutableArray? Net60MetadataReferences { get; set; } public async Task CompileAndExecuteAsync(string source, CancellationToken cancellationToken) - => await CompileAndExecuteAsync(new[] { source }, cancellationToken); + => await CompileAndExecuteAsync([source], cancellationToken); public async Task CompileAndExecuteAsync(string[] sources, CancellationToken cancellationToken) { @@ -79,10 +78,7 @@ public async Task CompileAndExecuteAsync(string[] so } } - MetadataReference[] metadataReferences = - Net60MetadataReferences.Value - .Concat(_additionalReferences.Select(loc => MetadataReference.CreateFromFile(loc))) - .ToArray(); + MetadataReference[] metadataReferences = [.. Net60MetadataReferences.Value, .. _additionalReferences.Select(loc => MetadataReference.CreateFromFile(loc))]; var compilation = CSharpCompilation.Create( "TestAssembly", @@ -92,7 +88,7 @@ public async Task CompileAndExecuteAsync(string[] so ISourceGenerator generator = _incrementalGeneratorFactory().AsSourceGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create( - generators: new ISourceGenerator[] { generator }); + generators: [generator]); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out Compilation? outputCompilation, out ImmutableArray diagnostics, cancellationToken); diff --git a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs index c870abcfe3..39c3e026ba 100644 --- a/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs +++ b/test/UnitTests/MSTest.SourceGeneration.UnitTests/TestUtilities/TestingFrameworkVerifier.cs @@ -11,7 +11,7 @@ namespace Microsoft.Testing.Framework.SourceGeneration.UnitTests.TestUtilities; internal sealed class TestingFrameworkVerifier : IVerifier { public TestingFrameworkVerifier() - : this(ImmutableStack.Empty) + : this([]) { } diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs index 4e5035c30c..3af7639fa0 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/AssemblyResolverTests.cs @@ -24,7 +24,7 @@ public void AddSubDirectoriesShouldReturnSubDirectoriesInDfsOrder() @"C:\unitTesting\b", ]; - TestableAssemblyResolver assemblyResolver = new(new List { @"c:\dummy" }) + TestableAssemblyResolver assemblyResolver = new([@"c:\dummy"]) { DoesDirectoryExistSetter = (str) => true, GetDirectoriesSetter = (str) => @@ -42,7 +42,7 @@ public void AddSubDirectoriesShouldReturnSubDirectoriesInDfsOrder() return [@"C:\unitTesting\a\c\d"]; } - return new List().ToArray(); + return []; }, }; @@ -88,7 +88,7 @@ public void OnResolveShouldAddSearchDirectoryListOnANeedToBasis() return [@"C:\FunctionalTesting\c"]; } - return new List().ToArray(); + return []; }; assemblyResolver.SearchAssemblySetter = @@ -147,7 +147,7 @@ public void ReflectionOnlyOnResolveShouldNotReturnACachedDefaultLoadedAssembly() { Assembly currentAssembly = typeof(AssemblyResolverTests).Assembly; string currentAssemblyPath = Path.GetDirectoryName(currentAssembly.Location); - var assemblyResolver = new TestableAssemblyResolver(new List { currentAssemblyPath }); + var assemblyResolver = new TestableAssemblyResolver([currentAssemblyPath]); bool isAssemblyLoaded = false; bool isAssemblyReflectionOnlyLoaded = false; diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs index f7f7883ca2..d436619ee5 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/DesktopTestDeploymentTests.cs @@ -32,7 +32,7 @@ public DesktopTestDeploymentTests() { _mockReflectionUtility = new Mock(); _mockFileUtility = new Mock(); - _warnings = new List(); + _warnings = []; // Reset adapter settings. MSTestSettingsProvider.Reset(); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs index dfd8626b64..97159226f6 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/ReflectionOperationsTests.cs @@ -67,9 +67,7 @@ public void GetCustomAttributesOnTypeShouldReturnAllAttributes() } private object[] GetMemberAttributes(Type type, bool inherit) - => _reflectionOperations.GetCustomAttributes(type, inherit) - .Where(x => x.GetType().FullName != "System.Runtime.CompilerServices.NullableContextAttribute") - .ToArray(); + => [.. _reflectionOperations.GetCustomAttributes(type, inherit).Where(x => x.GetType().FullName != "System.Runtime.CompilerServices.NullableContextAttribute")]; public void GetCustomAttributesOnTypeShouldReturnAllAttributesIgnoringBaseInheritance() { @@ -203,7 +201,7 @@ private static string[] GetAttributeValuePairs(object[] attributes) } } - return attribValuePairs.ToArray(); + return [.. attribValuePairs]; } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs index 49b2bf0e66..37cf9f5605 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Services/TestDeploymentTests.cs @@ -33,7 +33,7 @@ public TestDeploymentTests() { _mockReflectionUtility = new Mock(); _mockFileUtility = new Mock(); - _warnings = new List(); + _warnings = []; // Reset adapter settings. MSTestSettingsProvider.Reset(); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs index 673c1159d9..928a13ca44 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DeploymentUtilityTests.cs @@ -42,7 +42,7 @@ public DeploymentUtilityTests() _mockReflectionUtility = new Mock(); _mockFileUtility = new Mock(); _mockAssemblyUtility = new Mock(); - _warnings = new List(); + _warnings = []; _deploymentUtility = new DeploymentUtility( new DeploymentItemUtility(_mockReflectionUtility.Object), diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs index 2e7348f8e9..80b9663729 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/DesktopReflectionUtilityTests.cs @@ -40,7 +40,7 @@ internal static string[] GetAttributeValuePairs(IEnumerable attributes) } } - return attribValuePairs.ToArray(); + return [.. attribValuePairs]; } [DummyA("ba")] diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs index adea291520..5f83427888 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns10FileUtilityTests.cs @@ -105,10 +105,10 @@ public void AddFilesWithIgnoreDirectory() _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns(directory => { IEnumerable directories = allFiles.Where(file => IsFileUnderDirectory(directory, file)).Select(file => Path.GetDirectoryName(file)!).Distinct(); - return directories.ToArray(); + return [.. directories]; }); - _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct().ToArray()); + _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => [.. allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct()]); // Act List files = _fileUtility.Object.AddFilesFromDirectory("C:\\MainClock", directory => directory.Contains("Results"), false); @@ -145,10 +145,10 @@ public void AddFilesWithNoIgnoreDirectory() _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns(directory => { IEnumerable directories = allFiles.Where(file => IsFileUnderDirectory(directory, file)).Select(file => Path.GetDirectoryName(file)!).Distinct(); - return directories.ToArray(); + return [.. directories]; }); - _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct().ToArray()); + _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns(directory => [.. allFiles.Where(file => Path.GetDirectoryName(file)!.Equals(directory, StringComparison.OrdinalIgnoreCase)).Distinct()]); // Act List files = _fileUtility.Object.AddFilesFromDirectory("C:\\MainClock", false); @@ -171,9 +171,8 @@ private void SetupMockFileAPIs(string[] files) { _fileUtility.Setup(fu => fu.GetFilesInADirectory(It.IsAny())).Returns((string dp) => #pragma warning disable CA1865 // Use char overload - files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') == (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length) && !f.EndsWith("\\", StringComparison.Ordinal)) - .ToArray()); - _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns((string dp) => files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') > (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length)) + [.. files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') == (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length) && !f.EndsWith("\\", StringComparison.Ordinal))]); + _fileUtility.Setup(fu => fu.GetDirectoriesInADirectory(It.IsAny())).Returns((string dp) => [.. files.Where(f => f.Contains(dp) && f.LastIndexOf('\\') > (f.IndexOf(dp, StringComparison.Ordinal) + dp.Length)) .Select(f => { #pragma warning disable IDE0057 // Use range operator @@ -183,8 +182,7 @@ private void SetupMockFileAPIs(string[] files) return f.Substring(0, dp.Length + 1 + val.IndexOf('\\')); #pragma warning restore IDE0057 // Use range operator }) - .Distinct() - .ToArray()); + .Distinct()]); } #endregion diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs index 06ee4478ee..0cdb0d537d 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Utilities/ns13DeploymentItemUtilityTests.cs @@ -34,7 +34,7 @@ public DeploymentItemUtilityTests() { _mockReflectionUtility = new Mock(); _deploymentItemUtility = new DeploymentItemUtility(_mockReflectionUtility.Object); - _warnings = new List(); + _warnings = []; } #region GetClassLevelDeploymentItems tests diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs index 4a34f4c0bb..41443f243f 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorTests.cs @@ -26,7 +26,7 @@ public class AssemblyEnumeratorTests : TestContainer public AssemblyEnumeratorTests() { _assemblyEnumerator = new AssemblyEnumerator(); - _warnings = new List(); + _warnings = []; _testablePlatformServiceProvider = new TestablePlatformServiceProvider(); PlatformServiceProvider.Instance = _testablePlatformServiceProvider; @@ -256,7 +256,7 @@ public void EnumerateAssemblyShouldReturnTestElementsForAType() _testablePlatformServiceProvider.MockFileOperations.Setup(fo => fo.LoadAssembly("DummyAssembly", false)) .Returns(mockAssembly.Object); testableAssemblyEnumerator.MockTypeEnumerator.Setup(te => te.Enumerate(_warnings)) - .Returns(new List { unitTestElement }); + .Returns([unitTestElement]); AssemblyEnumerationResult result = testableAssemblyEnumerator.EnumerateAssembly("DummyAssembly"); _warnings.AddRange(result.Warnings); @@ -389,6 +389,9 @@ private static Mock CreateMockTestableAssembly() // The mock must be configured with a return value for GetCustomAttributes for this attribute type, but the // actual return value is irrelevant for these tests. + // NOTE: Don't convert Array.Empty() to [] as it will cause an InvalidCastException. + // [] will produce `object[]`, then it will fail to cast here: + // https://github.com/dotnet/runtime/blob/4252c8d09b2ec537928f34dad269f02f167c8ce5/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs#L710 mockAssembly .Setup(a => a.GetCustomAttributes( typeof(DiscoverInternalsAttribute), diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs index e652995ef1..95d6da8f50 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/AssemblyEnumeratorWrapperTests.cs @@ -23,7 +23,7 @@ public class AssemblyEnumeratorWrapperTests : TestContainer public AssemblyEnumeratorWrapperTests() { _testableAssemblyEnumeratorWrapper = new AssemblyEnumeratorWrapper(); - _warnings = new List(); + _warnings = []; _testablePlatformServiceProvider = new TestablePlatformServiceProvider(); PlatformServiceProvider.Instance = _testablePlatformServiceProvider; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs index 43d39526a2..a6f584291e 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeEnumeratorTests.cs @@ -33,7 +33,7 @@ public TypeEnumeratorTests() _mockTypeValidator = new Mock(MockBehavior.Default, _mockReflectHelper.Object); _mockTestMethodValidator = new Mock(MockBehavior.Default, _mockReflectHelper.Object, false); - _warnings = new List(); + _warnings = []; _mockMessageLogger = new Mock(); _testablePlatformServiceProvider = new TestablePlatformServiceProvider(); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs index 8c4de47c06..3e15bc8c09 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Discovery/TypeValidatorTests.cs @@ -240,8 +240,8 @@ public void AllTypesContainAllPrivateClasses() { // The names of private types are not accessible by nameof or typeof, ensure that we have them in the // list of our test types, to avoid bugs caused by typos. - string[] allTypes = GetAllTestTypes().Select(t => t.Name).ToArray(); - string[] privateTypes = typeof(PrivateClassNames).GetProperties().Select(n => n.Name).ToArray(); + string[] allTypes = [.. GetAllTestTypes().Select(t => t.Name)]; + string[] privateTypes = [.. typeof(PrivateClassNames).GetProperties().Select(n => n.Name)]; Verify(privateTypes.Length >= 1); foreach (string type in privateTypes) @@ -264,9 +264,9 @@ public void TypeHasValidAccessibilityShouldReturnTrueForAllPublicTypesIncludingN ]; bool discoverInternal = false; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedDiscoveredTypes); @@ -307,9 +307,9 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli ]; bool discoverInternal = false; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => !TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedNonDiscoveredTypes); @@ -342,9 +342,9 @@ public void TypeHasValidAccessibilityShouldReturnTrueForAllPublicAndInternalType ]; bool discoverInternal = true; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedDiscoveredTypes); @@ -372,9 +372,9 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli ]; bool discoverInternal = true; - string[] actualDiscoveredTypes = allTypes + string[] actualDiscoveredTypes = [.. allTypes .Where(t => !TypeValidator.TypeHasValidAccessibility(t, discoverInternal)) - .Select(t => t.Name).ToArray(); + .Select(t => t.Name)]; Array.Sort(actualDiscoveredTypes); Array.Sort(expectedNonDiscoveredTypes); @@ -384,9 +384,9 @@ public void TypeHasValidAccessibilityShouldReturnFalseForAllTypesThatAreNotPubli private static Type[] GetAllTestTypes() { Type[] types = [typeof(PublicClass2), typeof(PublicClass3), typeof(InternalClass), typeof(InternalClass2)]; - Type[] nestedTypes = types.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)).ToArray(); - Type[] nestedNestedTypes = nestedTypes.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)).ToArray(); - Type[] allTypes = new[] { types, nestedTypes, nestedNestedTypes }.SelectMany(t => t).ToArray(); + Type[] nestedTypes = [.. types.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))]; + Type[] nestedNestedTypes = [.. nestedTypes.SelectMany(t => t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))]; + Type[] allTypes = [.. new[] { types, nestedTypes, nestedNestedTypes }.SelectMany(t => t)]; return allTypes; } #endregion diff --git a/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs index dce014fc52..8bc201d4ec 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/DynamicDataAttributeTests.cs @@ -285,7 +285,7 @@ internal class DummyTestClass /// /// Gets the empty test data property. /// - public static IEnumerable EmptyProperty => Array.Empty(); + public static IEnumerable EmptyProperty => []; /// /// Gets the wrong test data property i.e. Property returning something other than diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs index 50d3f59707..055e52f37c 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/ClassCleanupManagerTests.cs @@ -24,11 +24,11 @@ public void AssemblyCleanupRunsAfterAllTestsFinishEvenIfWeScheduleTheSameTestMul // Setting 2 of the same test to run, we should run assembly cleanup after both these tests // finish, not after the first one finishes. - List testsToRun = new() - { - new(testMethod), + List testsToRun = + [ new(testMethod), - }; + new(testMethod) + ]; var classCleanupManager = new ClassCleanupManager(testsToRun, ClassCleanupBehavior.EndOfClass, ClassCleanupBehavior.EndOfClass, reflectHelper); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs index cea2718a3b..2f1fe65132 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestExecutionManagerTests.cs @@ -48,7 +48,7 @@ public class TestExecutionManagerTests : TestContainer ]; private TestableRunContextTestExecutionTests _runContext; - private List _callers = new(); + private List _callers = []; private int _enqueuedParallelTestsCount; public TestExecutionManagerTests() diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs index b935c23c3b..b91c041b66 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodInfoTests.cs @@ -344,7 +344,7 @@ public void TestMethodInfoInvokeShouldSetStackTraceInformationIfTestClassConstru public void TestMethodInfoInvokeShouldSetResultFilesIfTestContextHasAttachments() { Mock testContext = new(); - testContext.Setup(tc => tc.GetResultFiles()).Returns(new List { "C:\\temp.txt" }); + testContext.Setup(tc => tc.GetResultFiles()).Returns(["C:\\temp.txt"]); var mockInnerContext = new Mock(); testContext.SetupGet(tc => tc.Context).Returns(mockInnerContext.Object); mockInnerContext.SetupGet(tc => tc.CancellationTokenSource).Returns(new CancellationTokenSource()); @@ -1398,7 +1398,7 @@ public void ResolveExpectedExceptionShouldThrowWhenAttributeIsDefinedTwice_Diffe MethodInfo testMethodInfo = typeof(DummyTestClassForExpectedException).GetMethod(nameof(DummyTestClassForExpectedException.DummyTestMethod1))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); @@ -1416,7 +1416,7 @@ public void ResolveExpectedExceptionShouldThrowWhenAttributeIsDefinedTwice_SameC MethodInfo testMethodInfo = typeof(DummyTestClassForExpectedException).GetMethod(nameof(DummyTestClassForExpectedException.DummyTestMethod1))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); @@ -1435,7 +1435,7 @@ public void ResolveExpectedExceptionHelperShouldReturnExpectedExceptionAttribute MethodInfo methodInfo = type.GetMethod(nameof(DummyTestClassForExpectedException.TestMethodWithExpectedException))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); @@ -1456,7 +1456,7 @@ public void ResolveExpectedExceptionHelperShouldReturnNullIfExpectedExceptionAtt MethodInfo methodInfo = type.GetMethod(nameof(DummyTestClassForExpectedException.TestMethodWithoutExpectedException))!; TestClassInfo classInfo = new( typeof(DummyTestClassForExpectedException), - typeof(DummyTestClassForExpectedException).GetConstructor(Array.Empty())!, + typeof(DummyTestClassForExpectedException).GetConstructor([])!, isParameterlessConstructor: true, new UTF.TestClassAttribute(), new TestAssemblyInfo(typeof(DummyTestClassForExpectedException).Assembly)); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs index edb63ea7ab..4c9f11f909 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestMethodRunnerTests.cs @@ -359,7 +359,7 @@ public async Task RunTestMethodShouldSetResultFilesIfPresentForDataDrivenTests() { TestResult testResult = new() { - ResultFiles = new List { "C:\\temp.txt" }, + ResultFiles = ["C:\\temp.txt"], }; int dummyIntData1 = 1; @@ -537,7 +537,7 @@ public class DummyTestClassWithTestContextWithoutSetter public class DummyTestClassEmptyDataSource { - public static IEnumerable EmptyProperty => Array.Empty(); + public static IEnumerable EmptyProperty => []; [DynamicData("EmptyProperty")] public void TestMethod(int x) diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs index a61975dfb5..a2c6b1aafe 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/TestPropertyAttributeTests.cs @@ -60,7 +60,7 @@ public void GetTestMethodInfoShouldAddPropertiesFromContainingClassCorrectly() Assert.IsTrue(testContext.TryGetPropertyValue("DummyTestClassBaseKey2", out object? value3)); Assert.AreEqual("DummyTestClassBaseValue2", value3); - TestPlatform.ObjectModel.Trait[] traits = ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassBase).GetMethod(nameof(DummyTestClassBase.VirtualTestMethodInBaseAndDerived))!).ToArray(); + TestPlatform.ObjectModel.Trait[] traits = [.. ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassBase).GetMethod(nameof(DummyTestClassBase.VirtualTestMethodInBaseAndDerived))!)]; Assert.AreEqual(3, traits.Length); Assert.AreEqual("TestMethodKeyFromBase", traits[0].Name); Assert.AreEqual("TestMethodValueFromBase", traits[0].Value); @@ -99,7 +99,7 @@ public void GetTestMethodInfoShouldAddPropertiesFromContainingClassAndBaseClasse Assert.IsTrue(testContext.TryGetPropertyValue("DummyTestClassBaseKey2", out object? value6)); Assert.AreEqual("DummyTestClassBaseValue2", value6); - TestPlatform.ObjectModel.Trait[] traits = ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInBaseAndDerived))!).ToArray(); + TestPlatform.ObjectModel.Trait[] traits = [.. ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInBaseAndDerived))!)]; Assert.AreEqual(6, traits.Length); Assert.AreEqual("DerivedMethod1Key", traits[0].Name); Assert.AreEqual("DerivedMethod1Value", traits[0].Value); @@ -144,7 +144,7 @@ public void GetTestMethodInfoShouldAddPropertiesFromContainingClassAndBaseClasse Assert.IsTrue(testContext.TryGetPropertyValue("DummyTestClassBaseKey2", out object? value6)); Assert.AreEqual("DummyTestClassBaseValue2", value6); - TestPlatform.ObjectModel.Trait[] traits = ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInDerivedButNotTestMethodInBase))!).ToArray(); + TestPlatform.ObjectModel.Trait[] traits = [.. ReflectHelper.Instance.GetTestPropertiesAsTraits(typeof(DummyTestClassDerived).GetMethod(nameof(DummyTestClassDerived.VirtualTestMethodInDerivedButNotTestMethodInBase))!)]; Assert.AreEqual(6, traits.Length); Assert.AreEqual("DerivedMethod2Key", traits[0].Name); Assert.AreEqual("DerivedMethod2Value", traits[0].Value); diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs index 142ff3dffc..fec3b90852 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Execution/UnitTestRunnerTests.cs @@ -31,7 +31,7 @@ public UnitTestRunnerTests() _mockMessageLogger = new Mock(); PlatformServiceProvider.Instance = _testablePlatformServiceProvider; - _unitTestRunner = new UnitTestRunner(GetSettingsWithDebugTrace(false)!, Array.Empty(), null); + _unitTestRunner = new UnitTestRunner(GetSettingsWithDebugTrace(false)!, [], null); } protected override void Dispose(bool disposing) @@ -65,7 +65,7 @@ public void ConstructorShouldPopulateSettings() }); MSTestSettings adapterSettings = MSTestSettings.GetSettings(runSettingsXml, MSTestSettings.SettingsName, _mockMessageLogger.Object)!; - var assemblyEnumerator = new UnitTestRunner(adapterSettings, Array.Empty(), null); + var assemblyEnumerator = new UnitTestRunner(adapterSettings, [], null); Verify(MSTestSettings.CurrentSettings.ForcedLegacyMode); Verify(MSTestSettings.CurrentSettings.TestSettingsFile == "DummyPath\\TestSettings1.testsettings"); @@ -283,7 +283,7 @@ public async Task RunSingleTestShouldSetTestsAsInProgressInTestContext() public async Task RunSingleTestShouldCallAssemblyInitializeAndClassInitializeMethodsInOrder() { var mockReflectHelper = new Mock(); - _unitTestRunner = new UnitTestRunner(new MSTestSettings(), Array.Empty(), null, mockReflectHelper.Object); + _unitTestRunner = new UnitTestRunner(new MSTestSettings(), [], null, mockReflectHelper.Object); Type type = typeof(DummyTestClassWithInitializeMethods); MethodInfo methodInfo = type.GetMethod("TestMethod")!; diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs index 0b116fc5a8..0f9877ebca 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Extensions/TestResultExtensionsTests.cs @@ -43,7 +43,7 @@ public void ToUnitTestResultsForTestResultShouldSetLoggingDataForConvertedUnitTe }; var convertedResult = result.ToTestResult(new() { DisplayName = result.DisplayName }, default, default, string.Empty, new()); - VSTestTestResultMessage[] stdOutMessages = convertedResult.Messages.Where(m => m.Category == VSTestTestResultMessage.StandardOutCategory).ToArray(); + VSTestTestResultMessage[] stdOutMessages = [.. convertedResult.Messages.Where(m => m.Category == VSTestTestResultMessage.StandardOutCategory)]; Verify(stdOutMessages[0].Text == "logOutput"); Verify(convertedResult.Messages.Single(m => m.Category == VSTestTestResultMessage.StandardErrorCategory).Text == "logError"); Verify(convertedResult.DisplayName == "displayName (Data Row 1)"); @@ -177,7 +177,7 @@ public void ToUnitTestResultsShouldHaveResultsFileProvidedToTestResult() // Otherwise, ToTestResult will crash because it calls new Uri on the result file. string resultFile = Path.GetFullPath("DummyFile.txt"); - var result = new TestResult { ResultFiles = new List() { resultFile } }; + var result = new TestResult { ResultFiles = [resultFile] }; var convertedResult = result.ToTestResult(new(), default, default, string.Empty, new()); Verify(convertedResult.Attachments[0].Attachments[0].Description == resultFile); } diff --git a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs index 16cde8c2bb..f77540b6f9 100644 --- a/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs +++ b/test/UnitTests/MSTestAdapter.UnitTests/Helpers/ReflectHelperTests.cs @@ -49,7 +49,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtClassLevel() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("ClassLevel")], MemberTypes.TypeInfo); string[] expected = ["ClassLevel"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -64,7 +64,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtAllLevels() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("ClassLevel")], MemberTypes.TypeInfo); _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel")], MemberTypes.Method); - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; string[] expected = ["MethodLevel", "ClassLevel", "AsmLevel1", "AsmLevel2", "AsmLevel3"]; Verify(expected.SequenceEqual(actual)); @@ -82,7 +82,7 @@ public void GetTestCategoryAttributeShouldConcatCustomAttributeOfSameType() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel1")], MemberTypes.Method); _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel2")], MemberTypes.Method); - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; string[] expected = ["MethodLevel1", "MethodLevel2", "ClassLevel1", "ClassLevel2", "AsmLevel1", "AsmLevel2"]; Verify(expected.SequenceEqual(actual)); @@ -97,7 +97,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtAssemblyLevel() string[] expected = ["AsmLevel"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -110,7 +110,7 @@ public void GetTestCategoryAttributeShouldIncludeMultipleTestCategoriesAtClassLe _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("ClassLevel"), new TestCategoryAttribute("ClassLevel1")], MemberTypes.TypeInfo); string[] expected = ["ClassLevel", "ClassLevel1"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -123,7 +123,7 @@ public void GetTestCategoryAttributeShouldIncludeMultipleTestCategoriesAtAssembl _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("AsmLevel"), new TestCategoryAttribute("AsmLevel1")], MemberTypes.All); string[] expected = ["AsmLevel", "AsmLevel1"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -135,7 +135,7 @@ public void GetTestCategoryAttributeShouldIncludeTestCategoriesAtMethodLevel() _attributeMockingHelper.SetCustomAttribute(typeof(TestCategoryBaseAttribute), [new TestCategoryAttribute("MethodLevel")], MemberTypes.Method); string[] expected = ["MethodLevel"]; - string[] actual = _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests)).ToArray(); + string[] actual = [.. _reflectHelper.GetTestCategories(_method.Object, typeof(ReflectHelperTests))]; Verify(expected.SequenceEqual(actual)); } @@ -274,8 +274,8 @@ public void GettingAttributesShouldNotReturnInheritedAttributesWhenAskingForNonI Setup(ro => ro.GetCustomAttributes(It.IsAny(), /* inherit */ false)). Returns([new TestClassAttribute()]); - TestClassAttribute[] inheritedAttributes = rh.GetAttributes(typeof(object), inherit: true).ToArray(); - TestClassAttribute[] nonInheritedAttributes = rh.GetAttributes(typeof(object), inherit: false).ToArray(); + TestClassAttribute[] inheritedAttributes = [.. rh.GetAttributes(typeof(object), inherit: true)]; + TestClassAttribute[] nonInheritedAttributes = [.. rh.GetAttributes(typeof(object), inherit: false)]; Verify(inheritedAttributes.Length == 2); Verify(nonInheritedAttributes.Length == 1); @@ -291,7 +291,7 @@ internal class AttributeMockingHelper /// MemberTypes.TypeInfo for class level /// MemberTypes.Method for method level. /// - private readonly List<(Type Type, Attribute Attribute, MemberTypes MemberType)> _data = new(); + private readonly List<(Type Type, Attribute Attribute, MemberTypes MemberType)> _data = []; private readonly Mock _mockReflectionOperations; public void SetCustomAttribute(Type type, Attribute[] values, MemberTypes memberTypes) diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs index 95068374c5..c281ef4a14 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AppInsightsProviderTests.cs @@ -32,7 +32,7 @@ public void Platform_CancellationToken_Cancellation_Should_Exit_Gracefully() Mock testApplicationCancellationTokenSource = new(); testApplicationCancellationTokenSource.Setup(x => x.CancellationToken).Returns(cancellationTokenSource.Token); - List events = new(); + List events = []; Mock testTelemetryClient = new(); testTelemetryClient.Setup(x => x.TrackEvent(It.IsAny(), It.IsAny>(), It.IsAny>())) .Callback((string eventName, Dictionary properties, Dictionary metrics) => diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs index 0f1a96c59d..6e94f8fe07 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/TrxTests.cs @@ -27,7 +27,7 @@ public class TrxTests private readonly Mock _testFrameworkMock = new(); private readonly Mock _testApplicationModuleInfoMock = new(); private readonly Mock _fileSystem = new(); - private readonly Dictionary> _artifactsByExtension = new(); + private readonly Dictionary> _artifactsByExtension = []; [TestMethod] public async Task TrxReportEngine_GenerateReportAsyncWithNullAdapterSupportTrxCapability_TrxDoesNotContainClassName() diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs index 14d64e2688..d5971e5cb8 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/ObjectModelConvertersTests.cs @@ -65,7 +65,7 @@ public void ToTestNode_WhenTestResultOutcomeIsFailed_TestNodePropertiesContainFa }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - FailedTestNodeStateProperty[] failedTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + FailedTestNodeStateProperty[] failedTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, failedTestNodeStateProperties.Length); Assert.IsTrue(failedTestNodeStateProperties[0].Exception is VSTestException); Assert.AreEqual(testResult.ErrorStackTrace, failedTestNodeStateProperties[0].Exception!.StackTrace); @@ -83,7 +83,7 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - TestMetadataProperty[] testMetadatas = testNode.Properties.OfType().ToArray(); + TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, testMetadatas.Length); Assert.AreEqual("category1", testMetadatas[0].Key); Assert.AreEqual(string.Empty, testMetadatas[0].Value); @@ -100,7 +100,7 @@ public void ToTestNode_WhenTestResultHasMSTestDiscovererTestCategoryTestProperty var testNode = testResult.ToTestNode(true, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - TrxCategoriesProperty[] trxCategoriesProperty = testNode.Properties.OfType().ToArray(); + TrxCategoriesProperty[] trxCategoriesProperty = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, trxCategoriesProperty.Length); Assert.AreEqual(1, trxCategoriesProperty[0].Categories.Length); Assert.AreEqual("category1", trxCategoriesProperty[0].Categories[0]); @@ -117,7 +117,7 @@ public void ToTestNode_WhenTestCaseHasOriginalExecutorUriProperty_TestNodeProper var testNode = testCase.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - SerializableKeyValuePairStringProperty[] serializableKeyValuePairStringProperty = testNode.Properties.OfType().ToArray(); + SerializableKeyValuePairStringProperty[] serializableKeyValuePairStringProperty = [.. testNode.Properties.OfType()]; Assert.AreEqual(3, serializableKeyValuePairStringProperty.Length); Assert.AreEqual(VSTestTestNodeProperties.OriginalExecutorUriPropertyName, serializableKeyValuePairStringProperty[0].Key); Assert.AreEqual("https://vs.com/", serializableKeyValuePairStringProperty[0].Value); @@ -173,7 +173,7 @@ public void ToTestNode_WhenTestResultOutcomeIsNotFoundWithoutSetErrorMessage_Tes }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - ErrorTestNodeStateProperty[] errorTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + ErrorTestNodeStateProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, errorTestNodeStateProperties.Length); Assert.IsTrue(errorTestNodeStateProperties[0].Exception is VSTestException); Assert.AreEqual(testResult.ErrorStackTrace, errorTestNodeStateProperties[0].Exception!.StackTrace); @@ -189,7 +189,7 @@ public void ToTestNode_WhenTestResultOutcomeIsSkipped_TestNodePropertiesContainS }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - SkippedTestNodeStateProperty[] skipTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, skipTestNodeStateProperties.Length); } @@ -202,7 +202,7 @@ public void ToTestNode_WhenTestResultOutcomeIsNone_TestNodePropertiesContainSkip }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - SkippedTestNodeStateProperty[] skipTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + SkippedTestNodeStateProperty[] skipTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, skipTestNodeStateProperties.Length); } @@ -215,7 +215,7 @@ public void ToTestNode_WhenTestResultOutcomeIsPassed_TestNodePropertiesContainPa }; var testNode = testResult.ToTestNode(false, null, new ConsoleCommandLineOptions(), ClientInfo); - PassedTestNodeStateProperty[] passedTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + PassedTestNodeStateProperty[] passedTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, passedTestNodeStateProperties.Length); } @@ -226,7 +226,7 @@ public void ToTestNode_WhenTestCaseHasUidAndDisplayNameWithWellKnownClient_TestN var testNode = testCase.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - SerializableKeyValuePairStringProperty[] errorTestNodeStateProperties = testNode.Properties.OfType().ToArray(); + SerializableKeyValuePairStringProperty[] errorTestNodeStateProperties = [.. testNode.Properties.OfType()]; Assert.AreEqual(2, errorTestNodeStateProperties.Length, "Expected 2 SerializableKeyValuePairStringProperty"); Assert.AreEqual("vstest.TestCase.FullyQualifiedName", errorTestNodeStateProperties[0].Key); Assert.AreEqual("SomeFqn", errorTestNodeStateProperties[0].Value); @@ -244,7 +244,7 @@ public void ToTestNode_WhenTestResultHasTraits_TestNodePropertiesContainIt() var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - TestMetadataProperty[] testMetadatas = testNode.Properties.OfType().ToArray(); + TestMetadataProperty[] testMetadatas = [.. testNode.Properties.OfType()]; Assert.AreEqual(1, testMetadatas.Length); Assert.AreEqual("key", testMetadatas[0].Key); Assert.AreEqual("value", testMetadatas[0].Value); @@ -265,7 +265,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardOutputMessages_TestNodeP var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - StandardOutputProperty[] standardOutputProperties = testNode.Properties.OfType().ToArray(); + StandardOutputProperty[] standardOutputProperties = [.. testNode.Properties.OfType()]; Assert.IsTrue(standardOutputProperties.Length == 1); Assert.AreEqual($"message1{Environment.NewLine}message2", standardOutputProperties[0].StandardOutput); } @@ -285,7 +285,7 @@ public void ToTestNode_WhenTestResultHasMultipleStandardErrorMessages_TestNodePr var testNode = testResult.ToTestNode(false, new NamedFeatureCapabilityWithVSTestProvider(), new ServerModeCommandLineOptions(), ClientInfo); - StandardErrorProperty[] standardErrorProperties = testNode.Properties.OfType().ToArray(); + StandardErrorProperty[] standardErrorProperties = [.. testNode.Properties.OfType()]; Assert.IsTrue(standardErrorProperties.Length == 1); Assert.AreEqual($"message1{Environment.NewLine}message2", standardErrorProperties[0].StandardError); } diff --git a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs index 92c52dbde1..262f7bc9ae 100644 --- a/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs +++ b/test/UnitTests/Microsoft.Testing.Extensions.VSTestBridge.UnitTests/ObjectModel/RunSettingsPatcherTests.cs @@ -94,7 +94,7 @@ public void Patch_WhenRunSettingsExists_MergesParameters() XDocument runSettingsDocument = RunSettingsPatcher.Patch(runSettings, _configuration.Object, new ClientInfoService(string.Empty, string.Empty), _commandLineOptions.Object); - XElement[] testRunParameters = runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter").ToArray(); + XElement[] testRunParameters = [.. runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter")]; Assert.AreEqual("key1", testRunParameters[0].Attribute("name")!.Value); Assert.AreEqual("value1", testRunParameters[0].Attribute("value")!.Value); Assert.AreEqual("key2", testRunParameters[1].Attribute("name")!.Value); @@ -118,7 +118,7 @@ public void Patch_WhenRunSettingsDoesNotExist_AddParameters() XDocument runSettingsDocument = RunSettingsPatcher.Patch(null, _configuration.Object, new ClientInfoService(string.Empty, string.Empty), _commandLineOptions.Object); - XElement[] testRunParameters = runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter").ToArray(); + XElement[] testRunParameters = [.. runSettingsDocument.XPathSelectElements("RunSettings/TestRunParameters/Parameter")]; Assert.AreEqual("key1", testRunParameters[0].Attribute("name")!.Value); Assert.AreEqual("value1", testRunParameters[0].Attribute("value")!.Value); Assert.AreEqual("key2", testRunParameters[1].Attribute("name")!.Value); diff --git a/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs b/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs index ad5f780f08..e9762332bd 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/MSBuildTests.cs @@ -10,15 +10,11 @@ namespace Microsoft.Testing.Platform.MSBuild.UnitTests; [TestClass] public sealed class MSBuildTests { - private readonly Mock _buildEngine; - private readonly List _errors; + private readonly Mock _buildEngine = new(); + private readonly List _errors = []; - public MSBuildTests() - { - _buildEngine = new Mock(); - _errors = new List(); + public MSBuildTests() => _buildEngine.Setup(x => x.LogErrorEvent(It.IsAny())).Callback(e => _errors.Add(e)); - } [TestMethod] public void Verify_Correct_Registration_Order_For_WellKnown_Extensions() @@ -65,7 +61,7 @@ internal sealed class MicrosoftTestingPlatformEntryPoint private sealed class InMemoryFileSystem : IFileSystem { - public Dictionary Files { get; } = new(); + public Dictionary Files { get; } = []; public void CopyFile(string source, string destination) => throw new NotImplementedException(); @@ -80,7 +76,7 @@ private sealed class InMemoryFileSystem : IFileSystem private sealed class CustomTaskItem : ITaskItem { - private readonly Dictionary _keyValuePairs = new(); + private readonly Dictionary _keyValuePairs = []; public CustomTaskItem(string itemSpec) => ItemSpec = itemSpec; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs index aaf9b02821..2465f64839 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Configuration/ConfigurationManagerTests.cs @@ -29,7 +29,7 @@ public async ValueTask GetConfigurationValueFromJson(string jsonFileConfig, stri CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(new SystemEnvironment(), new SystemProcessHandler()); ConfigurationManager configurationManager = new(fileSystem.Object, testApplicationModuleInfo); configurationManager.AddConfigurationSource(() => new JsonConfigurationSource(testApplicationModuleInfo, fileSystem.Object, null)); - IConfiguration configuration = await configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty())); + IConfiguration configuration = await configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), [])); Assert.AreEqual(result, configuration[key], $"Expected '{result}' found '{configuration[key]}'"); } @@ -63,9 +63,9 @@ public async ValueTask InvalidJson_Fail() // The behavior difference is System.Text.Json vs Jsonite #if NETFRAMEWORK - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty())), ex => ex?.ToString() ?? "No exception was thrown"); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), [])), ex => ex?.ToString() ?? "No exception was thrown"); #else - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty())), ex => ex?.ToString() ?? "No exception was thrown"); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), [])), ex => ex?.ToString() ?? "No exception was thrown"); #endif } @@ -91,7 +91,7 @@ public async ValueTask GetConfigurationValueFromJsonWithFileLoggerProvider(strin configurationManager.AddConfigurationSource(() => new JsonConfigurationSource(testApplicationModuleInfo, fileSystem.Object, null)); - IConfiguration configuration = await configurationManager.BuildAsync(loggerProviderMock.Object, new CommandLineParseResult(null, new List(), Array.Empty())); + IConfiguration configuration = await configurationManager.BuildAsync(loggerProviderMock.Object, new CommandLineParseResult(null, new List(), [])); Assert.AreEqual(result, configuration[key], $"Expected '{result}' found '{configuration[key]}'"); loggerMock.Verify(x => x.LogAsync(LogLevel.Trace, It.IsAny(), null, LoggingExtensions.Formatter), Times.Once); @@ -102,7 +102,7 @@ public async ValueTask BuildAsync_EmptyConfigurationSources_ThrowsException() { CurrentTestApplicationModuleInfo testApplicationModuleInfo = new(new SystemEnvironment(), new SystemProcessHandler()); ConfigurationManager configurationManager = new(new SystemFileSystem(), testApplicationModuleInfo); - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty()))); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), []))); } [TestMethod] @@ -115,7 +115,7 @@ public async ValueTask BuildAsync_ConfigurationSourcesNotEnabledAsync_ThrowsExce ConfigurationManager configurationManager = new(new SystemFileSystem(), testApplicationModuleInfo); configurationManager.AddConfigurationSource(() => mockConfigurationSource.Object); - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty()))); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), []))); mockConfigurationSource.Verify(x => x.IsEnabledAsync(), Times.Once); } @@ -135,7 +135,7 @@ public async ValueTask BuildAsync_ConfigurationSourceIsAsyncInitializableExtensi ConfigurationManager configurationManager = new(new SystemFileSystem(), testApplicationModuleInfo); configurationManager.AddConfigurationSource(() => fakeConfigurationSource); - await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), Array.Empty()))); + await Assert.ThrowsAsync(() => configurationManager.BuildAsync(null, new CommandLineParseResult(null, new List(), []))); } private class FakeConfigurationSource : IConfigurationSource, IAsyncInitializableExtension diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs index d6d0daaa03..aaf9ec1547 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Helpers/SystemAsyncMonitorTests.cs @@ -20,7 +20,7 @@ public async Task AsyncMonitor_ShouldCorrectlyLock() tasks.Add(Task.Run(TestLock)); } - await Task.WhenAll(tasks.ToArray()); + await Task.WhenAll([.. tasks]); // Give more time to be above 3s Thread.Sleep(500); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs index 78beb1d004..e36d719839 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/IPCTests.cs @@ -172,7 +172,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() { PipeNameDescription pipeNameDescription = NamedPipeServer.GetPipeName(Guid.NewGuid().ToString("N")); - List pipes = new(); + List pipes = []; for (int i = 0; i < 3; i++) { pipes.Add(new( @@ -196,7 +196,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() _testContext.CancellationTokenSource.Token)); StringAssert.Contains(exception.Message, "All pipe instances are busy."); - List waitConnectionTask = new(); + List waitConnectionTask = []; int connectionCompleted = 0; foreach (NamedPipeServer namedPipeServer in pipes) { @@ -207,7 +207,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() })); } - List connectedClients = new(); + List connectedClients = []; for (int i = 0; i < waitConnectionTask.Count; i++) { NamedPipeClient namedPipeClient = new(pipeNameDescription.Name); @@ -215,7 +215,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() await namedPipeClient.ConnectAsync(_testContext.CancellationTokenSource.Token); } - await Task.WhenAll(waitConnectionTask.ToArray()); + await Task.WhenAll([.. waitConnectionTask]); Assert.AreEqual(3, connectionCompleted); @@ -235,8 +235,7 @@ public async Task ConnectionNamedPipeServer_MultipleConnection_Succeeds() private static string RandomString(int length, Random random) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - return new string(Enumerable.Repeat(chars, length) - .Select(s => s[random.Next(s.Length)]).ToArray()); + return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); } private abstract record BaseMessage : IRequest; diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs index 019aa5219a..73f4309e2f 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/IPC/ProtocolTests.cs @@ -14,7 +14,7 @@ public void TestResultMessagesSerializeDeserialize() { var success = new SuccessfulTestResultMessage("uid", "displayName", 1, 100, "reason", "standardOutput", "errorOutput", "sessionUid"); var fail = new FailedTestResultMessage("uid", "displayName", 2, 200, "reason", [new ExceptionMessage("errorMessage", "errorType", "stackTrace")], "standardOutput", "errorOutput", "sessionUid"); - var message = new TestResultMessages("executionId", "instanceId", new[] { success }, new[] { fail }); + var message = new TestResultMessages("executionId", "instanceId", [success], [fail]); var stream = new MemoryStream(); new TestResultMessagesSerializer().Serialize(message, stream); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs index 571f312dff..cc3883e67b 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Logging/LogTestHelpers.cs @@ -21,8 +21,8 @@ public static IEnumerable GetLogLevelsForDynamicData() public static IEnumerable<(LogLevel DefaultLevel, LogLevel CurrentLevel)> GetLogLevelCombinations() { - List<(LogLevel, LogLevel)> logLevelCombinations = new(); - LogLevel[] logLevels = GetLogLevels().ToArray(); + List<(LogLevel, LogLevel)> logLevelCombinations = []; + LogLevel[] logLevels = [.. GetLogLevels()]; for (int i = 0; i < logLevels.Length; i++) { diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs index 2d6ba5076e..af1b5c2ab0 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/AsynchronousMessageBusTests.cs @@ -120,8 +120,7 @@ public async Task Consumers_ConsumeData_ShouldNotMissAnyPayload() proxy.SetBuiltMessageBus(asynchronousMessageBus); DummyConsumer.DummyProducer producer = new(); - await Task.WhenAll(Enumerable.Range(1, totalPayloads) - .Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i }))).ToArray()); + await Task.WhenAll([.. Enumerable.Range(1, totalPayloads).Select(i => Task.Run(async () => await proxy.PublishAsync(producer, new DummyConsumer.DummyData { Data = i })))]); await proxy.DrainDataAsync(); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs index 12f4ad6b23..43805d2171 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Messages/PropertyBagTests.cs @@ -143,7 +143,7 @@ public void AsEnumerable_Should_Return_CorrectItems() Assert.AreEqual(0, list.Count); - list = property.AsEnumerable().ToList(); + list = [.. property.AsEnumerable()]; foreach (IProperty prop in property) { list.Remove(prop); diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs index 75b6c6ee89..b400dcd61a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/FormatterUtilitiesTests.cs @@ -363,7 +363,7 @@ private static object CreateInstance(Type type) if (type == typeof(TestsAttachments)) { - return new TestsAttachments(new RunTestAttachment[] { new("Uri", "Producer", "Type", "DisplayName", "Description") }); + return new TestsAttachments([new("Uri", "Producer", "Type", "DisplayName", "Description")]); } if (type == typeof(RunTestAttachment)) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs index e7afcf77ec..f3e0ffd468 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsonTests.cs @@ -16,13 +16,13 @@ public sealed class JsonTests public JsonTests() { - Dictionary serializers = new(); - Dictionary deserializers = new(); + Dictionary serializers = []; + Dictionary deserializers = []; foreach (Type serializableType in SerializerUtilities.SerializerTypes) { serializers[serializableType] = new JsonObjectSerializer( - o => SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value)).ToArray()); + o => [.. SerializerUtilities.Serialize(serializableType, o).Select(kvp => (kvp.Key, kvp.Value))]); } foreach (Type deserializableType in SerializerUtilities.DeserializerTypes) diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs index d2aa862511..ebc6fac83b 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/ServerMode/JsoniteTests.cs @@ -22,7 +22,7 @@ public void Serialize_SpecialCharacters() { // This test is testing if we can serialize the range 0x0000 - 0x001FF correctly, this range contains special characters like NUL. // This is a fix for Jsonite, which throws when such characters are found in a string (but does not fail when we provide them as character). - List errors = new(); + List errors = []; // This could be converted to Data source, but this way we have more control about where in the result message the // special characters will be (hopefully nowhere) so in case of failure, we can still serialize the message to IDE diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs index 580fd28310..1d74be935a 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/TestApplicationResultTests.cs @@ -214,10 +214,10 @@ public void GetProcessExitCodeAsync_IgnoreExitCodes(string? argument, int expect internal static IEnumerable FailedState() { - yield return new[] { new FailedTestNodeStateProperty() }; - yield return new[] { new ErrorTestNodeStateProperty() }; - yield return new[] { new CancelledTestNodeStateProperty() }; - yield return new[] { new TimeoutTestNodeStateProperty() }; + yield return [new FailedTestNodeStateProperty()]; + yield return [new ErrorTestNodeStateProperty()]; + yield return [new CancelledTestNodeStateProperty()]; + yield return [new TimeoutTestNodeStateProperty()]; } private sealed class CommandLineOption : ICommandLineOptions diff --git a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs index d35d3d8e62..152e35d6e3 100644 --- a/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs +++ b/test/UnitTests/Microsoft.Testing.Platform.UnitTests/TestApplicationBuilderTests.cs @@ -91,8 +91,8 @@ public async Task TestHost_ComposeFactory_ShouldSucceed(bool withParameter) testHostManager.AddTestSessionLifetimeHandle(compositeExtensionFactory); testHostManager.AddDataConsumer(compositeExtensionFactory); List compositeExtensions = []; - IDataConsumer[] consumers = (await testHostManager.BuildDataConsumersAsync(_serviceProvider, compositeExtensions)).Select(x => (IDataConsumer)x.Consumer).ToArray(); - ITestSessionLifetimeHandler[] sessionLifetimeHandle = (await testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, compositeExtensions)).Select(x => (ITestSessionLifetimeHandler)x.TestSessionLifetimeHandler).ToArray(); + IDataConsumer[] consumers = [.. (await testHostManager.BuildDataConsumersAsync(_serviceProvider, compositeExtensions)).Select(x => (IDataConsumer)x.Consumer)]; + ITestSessionLifetimeHandler[] sessionLifetimeHandle = [.. (await testHostManager.BuildTestSessionLifetimeHandleAsync(_serviceProvider, compositeExtensions)).Select(x => (ITestSessionLifetimeHandler)x.TestSessionLifetimeHandler)]; Assert.AreEqual(1, consumers.Length); Assert.AreEqual(1, sessionLifetimeHandle.Length); Assert.AreEqual(compositeExtensions[0].GetInstance(), consumers[0]); diff --git a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs index 877e51b57a..4c32ca18af 100644 --- a/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/Assertions/CollectionAssertTests.cs @@ -488,7 +488,7 @@ private static List GenerateDeeplyNestedCollection(int depth) { if (depth == 0) { - return new List { new ReadOnlyCollection(Enumerable.Range(1, 10).ToList()) }; + return [new ReadOnlyCollection([.. Enumerable.Range(1, 10)])]; } var nestedCollection = new List(); @@ -528,14 +528,14 @@ private static List GenerateDeeplyNestedCollection(int depth) private ICollection? GetNonICollectionInnerCollection() => new List> { - new(new List { 1, 2 }), - new(new List { 3, 4 }), + new([1, 2]), + new([3, 4]), }; private ICollection? GetNotMatchingGetNonICollectionInnerCollection() => new List> { - new(new List { 6, 5 }), - new(new List { 3, 4 }), + new([6, 5]), + new([3, 4]), }; private Type? GetStringType() => typeof(string); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs index 3fd02adb5b..883e1f367d 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/CommandLine.cs @@ -14,8 +14,8 @@ public sealed class CommandLine : IDisposable public static int TotalProcessesAttempt => s_totalProcessesAttempt; - private readonly List _errorOutputLines = new(); - private readonly List _standardOutputLines = new(); + private readonly List _errorOutputLines = []; + private readonly List _standardOutputLines = []; private IProcessHandle? _process; public ReadOnlyCollection StandardOutputLines => _standardOutputLines.AsReadOnly(); diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs index 0d7c7413a0..03ec18f867 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/DotnetCli.cs @@ -64,7 +64,7 @@ public static async Task RunAsync( await s_maxOutstandingCommands_semaphore.WaitAsync(); try { - environmentVariables ??= new Dictionary(); + environmentVariables ??= []; foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { // Skip all unwanted environment variables. diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs index 91deff4f72..f19bde0388 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/ProjectSystem.cs @@ -46,7 +46,7 @@ public VSSolution(string? solutionFolder, string? solutionName) AddOrUpdateFileContent(_solutionFileName, MergeSolutionContent()); } - public ICollection Projects { get; } = new List(); + public ICollection Projects { get; } = []; public string SolutionFile { get; private set; } diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs index 3d4b2ffb33..6a8e91de1f 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TargetFrameworks.cs @@ -24,7 +24,7 @@ public static class TargetFrameworks public static string[] All { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? Net.Concat(NetFramework).ToArray() + ? [.. Net, .. NetFramework] : Net; public static IEnumerable AllForDynamicData { get; } = diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs index 76dcfca4b6..285a53fe3a 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TempDirectory.cs @@ -131,7 +131,7 @@ public string[] CopyFile(params string[] filePaths) paths.Add(destination); } - return paths.ToArray(); + return [.. paths]; } /// diff --git a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs index 32352b750b..44c7a12894 100644 --- a/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs +++ b/test/Utilities/Microsoft.Testing.TestInfrastructure/TestHost.cs @@ -51,7 +51,7 @@ public async Task ExecuteAsync( throw new InvalidOperationException($"Command should not start with module name '{_testHostModuleName}'."); } - environmentVariables ??= new Dictionary(); + environmentVariables ??= []; if (disableTelemetry) { diff --git a/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs b/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs index 0f26913c36..922dd103ac 100644 --- a/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs +++ b/test/Utilities/TestFramework.ForTestingMSTest/TestFrameworkEngine.cs @@ -20,8 +20,7 @@ public TestFrameworkEngine(TestFrameworkExtension extension, ILoggerFactory logg _logger = loggerFactory.CreateLogger("InternalTestFrameworkEngine"); } - public Type[] DataTypesProduced { get; } - = new Type[1] { typeof(TestNodeUpdateMessage) }; + public Type[] DataTypesProduced { get; } = [typeof(TestNodeUpdateMessage)]; public string Uid => _extension.Uid; @@ -99,7 +98,7 @@ private async Task ExecuteTestNodeRunAsync(RunTestExecutionRequest request, IMes testContainerType.Name, publicMethod.Name, publicMethod.GetGenericArguments().Length, - publicMethod.GetParameters().Select(x => x.ParameterType.FullName!).ToArray(), + [.. publicMethod.GetParameters().Select(x => x.ParameterType.FullName!)], publicMethod.ReturnType.FullName!)); testNode.Properties.Add(new TrxFullyQualifiedTypeNameProperty(testContainerType.FullName!)); @@ -176,7 +175,7 @@ private async Task ExecuteTestNodeDiscoveryAsync(DiscoverTestExecutionRequest re testContainerType.Name, publicMethod.Name, publicMethod.GetGenericArguments().Length, - publicMethod.GetParameters().Select(x => x.ParameterType.FullName!).ToArray(), + [.. publicMethod.GetParameters().Select(x => x.ParameterType.FullName!)], publicMethod.ReturnType.FullName!)); await messageBus.PublishAsync(this, new TestNodeUpdateMessage(request.Session.SessionUid, testNode));