From 9f809bf9a5693edc7e5dc7d3d58f883d061a36fd Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 19:11:54 +0200 Subject: [PATCH 01/23] IDE0016 Null check can be simplified --- src/TestFramework/Extension.Desktop/PrivateType.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/TestFramework/Extension.Desktop/PrivateType.cs b/src/TestFramework/Extension.Desktop/PrivateType.cs index 413ff1cba3..78cb3c40f1 100644 --- a/src/TestFramework/Extension.Desktop/PrivateType.cs +++ b/src/TestFramework/Extension.Desktop/PrivateType.cs @@ -46,12 +46,7 @@ public PrivateType(string assemblyName, string typeName) /// The wrapped Type to create. public PrivateType(Type type) { - if (type == null) - { - throw new ArgumentNullException("type"); - } - - this.type = type; + this.type = type ?? throw new ArgumentNullException("type"); } /// From a34277f75e4b062b2bfaecd8436e34f832bcd47e Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 22:28:07 +0200 Subject: [PATCH 02/23] IDE0018 Variable declaration can be inlined --- .../Discovery/AssemblyEnumerator.cs | 4 +-- .../Discovery/UnitTestDiscoverer.cs | 17 +++------- .../Execution/TestAssemblyInfo.cs | 4 +-- .../Execution/TestMethodInfo.cs | 12 ++----- .../RunConfigurationSettings.cs | 3 +- .../MSTest.CoreAdapter/TestMethodFilter.cs | 6 ++-- .../AssemblyResolver.cs | 3 +- .../Data/TestDataConnectionFactory.cs | 3 +- .../Data/TestDataConnectionSql.cs | 4 +-- .../DesktopTestContextImplementation.cs | 3 +- .../Utilities/DesktopDeploymentUtility.cs | 6 ++-- .../NetCoreTestContextImplementation.cs | 6 ++-- .../Services/ns10TestContextImplementation.cs | 3 +- .../Utilities/ns13DeploymentItemUtility.cs | 3 +- .../Utilities/ns13FileUtility.cs | 3 +- .../Extension.Desktop/PrivateObject.cs | 7 ++--- .../Assertions/CollectionAssert.cs | 31 ++++++------------- .../Execution/TestMethodFilterTests.cs | 18 ++++------- .../Execution/TypeCacheTests.cs | 3 +- .../Extensions/ExceptionExtensionsTests.cs | 16 +++------- .../MSTestSettingsTests.cs | 9 ++---- .../Deployment/AssemblyLoadWorkerTests.cs | 6 ++-- .../Services/DesktopFileOperationsTests.cs | 12 +++---- .../Services/DesktopTestContextImplTests.cs | 8 ++--- .../Services/DesktopTestDeploymentTests.cs | 9 ++---- .../DesktopDeploymentUtilityTests.cs | 21 +++++-------- .../NetCoreDeploymentUtilityTests.cs | 6 ++-- .../Services/ns13TestDeploymentTests.cs | 15 +++------ .../ns13DeploymentItemUtilityTests.cs | 21 +++++-------- .../Services/UniversalFileOperationsTests.cs | 5 +-- 30 files changed, 83 insertions(+), 184 deletions(-) diff --git a/src/Adapter/MSTest.CoreAdapter/Discovery/AssemblyEnumerator.cs b/src/Adapter/MSTest.CoreAdapter/Discovery/AssemblyEnumerator.cs index 4c67d2bad3..91744c05a1 100644 --- a/src/Adapter/MSTest.CoreAdapter/Discovery/AssemblyEnumerator.cs +++ b/src/Adapter/MSTest.CoreAdapter/Discovery/AssemblyEnumerator.cs @@ -92,10 +92,8 @@ internal ICollection EnumerateAssembly(string assemblyFileName, try { - ICollection warningsFromTypeEnumerator; - typeFullName = type.FullName; - var unitTestCases = this.GetTypeEnumerator(type, assemblyFileName).Enumerate(out warningsFromTypeEnumerator); + var unitTestCases = this.GetTypeEnumerator(type, assemblyFileName).Enumerate(out var warningsFromTypeEnumerator); if (warningsFromTypeEnumerator != null) { diff --git a/src/Adapter/MSTest.CoreAdapter/Discovery/UnitTestDiscoverer.cs b/src/Adapter/MSTest.CoreAdapter/Discovery/UnitTestDiscoverer.cs index 4a75207da4..dbd6614bb6 100644 --- a/src/Adapter/MSTest.CoreAdapter/Discovery/UnitTestDiscoverer.cs +++ b/src/Adapter/MSTest.CoreAdapter/Discovery/UnitTestDiscoverer.cs @@ -58,9 +58,7 @@ internal virtual void DiscoverTestsInSource( ITestCaseDiscoverySink discoverySink, IDiscoveryContext discoveryContext) { - ICollection warnings; - - var testElements = this.assemblyEnumeratorWrapper.GetTests(source, discoveryContext?.RunSettings, out warnings); + var testElements = this.assemblyEnumeratorWrapper.GetTests(source, discoveryContext?.RunSettings, out var warnings); // log the warnings foreach (var warning in warnings) @@ -100,8 +98,7 @@ internal void SendTestCases(string source, IEnumerable testElem } // Get filter expression and skip discovery in case filter expression has parsing error. - bool filterHasError = false; - ITestCaseFilterExpression filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, logger, out filterHasError); + ITestCaseFilterExpression filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, logger, out var filterHasError); if (filterHasError) { return; @@ -117,12 +114,11 @@ internal void SendTestCases(string source, IEnumerable testElem continue; } - object testNavigationSession; if (shouldCollectSourceInformation) { string testSource = testElement.TestMethod.DeclaringAssemblyName ?? source; - if (!navigationSessions.TryGetValue(testSource, out testNavigationSession)) + if (!navigationSessions.TryGetValue(testSource, out var testNavigationSession)) { testNavigationSession = PlatformServiceProvider.Instance.FileOperations.CreateNavigationSession(testSource); navigationSessions.Add(testSource, testNavigationSession); @@ -144,15 +140,12 @@ internal void SendTestCases(string source, IEnumerable testElem methodName = "MoveNext"; } - int minLineNumber; - string fileName; - PlatformServiceProvider.Instance.FileOperations.GetNavigationData( testNavigationSession, className, methodName, - out minLineNumber, - out fileName); + out var minLineNumber, + out var fileName); if (!string.IsNullOrEmpty(fileName)) { diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/TestAssemblyInfo.cs b/src/Adapter/MSTest.CoreAdapter/Execution/TestAssemblyInfo.cs index b197afcdaf..ca3ff03b9c 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/TestAssemblyInfo.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/TestAssemblyInfo.cs @@ -173,9 +173,7 @@ public void RunAssemblyInitialize(TestContext testContext) ?? this.AssemblyInitializationException; var outcome = UnitTestOutcome.Failed; - string errorMessage = null; - StackTraceInformation stackTraceInfo = null; - if (!realException.TryGetUnitTestAssertException(out outcome, out errorMessage, out stackTraceInfo)) + if (!realException.TryGetUnitTestAssertException(out outcome, out var errorMessage, out var stackTraceInfo)) { var exception = realException.GetType().ToString(); var message = StackTraceHelper.GetExceptionMessage(realException); diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs index fd918bd17d..98f249c7ce 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs @@ -453,11 +453,9 @@ private Exception HandleMethodException(Exception ex, string className, string m // Get the real exception thrown by the test method Exception realException = this.GetRealException(ex); - string exceptionMessage = null; - StackTraceInformation exceptionStackTraceInfo = null; var outcome = TestTools.UnitTesting.UnitTestOutcome.Failed; - if (realException.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out exceptionStackTraceInfo)) + if (realException.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var exceptionStackTraceInfo)) { return new TestFailedException(outcome.ToUnitTestOutcome(), exceptionMessage, exceptionStackTraceInfo, realException); } @@ -546,11 +544,9 @@ private void RunTestCleanupMethod(object classInstance, TestResult result) } Exception realException = ex.GetInnerExceptionOrDefault(); - string exceptionMessage = null; - StackTraceInformation realExceptionStackTraceInfo = null; // special case UnitTestAssertException to trim off part of the stack trace - if (!realException.TryGetUnitTestAssertException(out cleanupOutcome, out exceptionMessage, out realExceptionStackTraceInfo)) + if (!realException.TryGetUnitTestAssertException(out cleanupOutcome, out var exceptionMessage, out var realExceptionStackTraceInfo)) { cleanupOutcome = UTF.UnitTestOutcome.Failed; exceptionMessage = this.GetTestCleanUpExceptionMessage(testCleanupMethod, realException); @@ -632,11 +628,9 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result) catch (Exception ex) { var innerException = ex.GetInnerExceptionOrDefault(); - string exceptionMessage = null; - StackTraceInformation exceptionStackTraceInfo = null; var outcome = TestTools.UnitTesting.UnitTestOutcome.Failed; - if (innerException.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out exceptionStackTraceInfo)) + if (innerException.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var exceptionStackTraceInfo)) { result.Outcome = outcome; result.TestFailureException = new TestFailedException( diff --git a/src/Adapter/MSTest.CoreAdapter/RunConfigurationSettings.cs b/src/Adapter/MSTest.CoreAdapter/RunConfigurationSettings.cs index 86bf7829ac..1a5aeb4179 100644 --- a/src/Adapter/MSTest.CoreAdapter/RunConfigurationSettings.cs +++ b/src/Adapter/MSTest.CoreAdapter/RunConfigurationSettings.cs @@ -117,13 +117,12 @@ private static RunConfigurationSettings ToSettings(XmlReader reader) while (reader.NodeType == XmlNodeType.Element) { - bool result; string elementName = reader.Name.ToUpperInvariant(); switch (elementName) { case "COLLECTSOURCEINFORMATION": { - if (bool.TryParse(reader.ReadInnerXml(), out result)) + if (bool.TryParse(reader.ReadInnerXml(), out var result)) { settings.CollectSourceInformation = result; PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo( diff --git a/src/Adapter/MSTest.CoreAdapter/TestMethodFilter.cs b/src/Adapter/MSTest.CoreAdapter/TestMethodFilter.cs index afc795f50d..70f033f87c 100644 --- a/src/Adapter/MSTest.CoreAdapter/TestMethodFilter.cs +++ b/src/Adapter/MSTest.CoreAdapter/TestMethodFilter.cs @@ -65,8 +65,7 @@ internal ITestCaseFilterExpression GetFilterExpression(IDiscoveryContext context /// a TestProperty instance. internal TestProperty PropertyProvider(string propertyName) { - TestProperty testProperty; - this.supportedProperties.TryGetValue(propertyName, out testProperty); + this.supportedProperties.TryGetValue(propertyName, out var testProperty); Debug.Assert(testProperty != null, "Invalid property queried"); return testProperty; } @@ -81,8 +80,7 @@ internal object PropertyValueProvider(TestCase currentTest, string propertyName) { if (currentTest != null && propertyName != null) { - TestProperty testProperty; - if (this.supportedProperties.TryGetValue(propertyName, out testProperty)) + if (this.supportedProperties.TryGetValue(propertyName, out var testProperty)) { // Test case might not have defined this property. In that case GetPropertyValue() // would return default value. For filtering, if property is not defined return null. diff --git a/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs b/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs index 96c6262c50..045a33c8c7 100644 --- a/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs +++ b/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs @@ -424,9 +424,8 @@ private Assembly OnResolveInternal(object senderAppDomain, ResolveEventArgs args lock (this.syncLock) { // Since both normal and reflection only cache are accessed in same block, putting only one lock should be sufficient. - Assembly assembly = null; - if (this.TryLoadFromCache(assemblyNameToLoad, isReflectionOnly, out assembly)) + if (this.TryLoadFromCache(assemblyNameToLoad, isReflectionOnly, out var assembly)) { return assembly; } diff --git a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionFactory.cs b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionFactory.cs index 0331f0c504..c7351a7237 100644 --- a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionFactory.cs +++ b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionFactory.cs @@ -49,8 +49,7 @@ public virtual TestDataConnection Create(string invariantProviderName, string co // Most, but not all, connections are actually database based, // here we look for special cases - TestDataConnectionFactory factory; - if (specializedProviders.TryGetValue(invariantProviderName, out factory)) + if (specializedProviders.TryGetValue(invariantProviderName, out var factory)) { Debug.Assert(factory != null, "factory"); return factory.Create(invariantProviderName, connectionString, dataFolders); diff --git a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs index 0593e22fcf..c506a311e7 100644 --- a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs +++ b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs @@ -601,9 +601,7 @@ public override List GetColumns(string tableName) WriteDiagnostics("GetColumns for {0}", tableName); try { - string targetSchema; - string targetName; - this.SplitTableName(tableName, out targetSchema, out targetName); + this.SplitTableName(tableName, out var targetSchema, out var targetName); // This lets us specifically query for columns from the appropriate table name // but assumes all databases have the same restrictions on all the column diff --git a/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs b/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs index 7d7245bde1..9cf304ed5c 100644 --- a/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs +++ b/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs @@ -490,8 +490,7 @@ private static UTF.UnitTestOutcome ToUTF(UTF.UnitTestOutcome outcome) /// Property value private string GetStringPropertyValue(string propertyName) { - object propertyValue = null; - this.properties.TryGetValue(propertyName, out propertyValue); + this.properties.TryGetValue(propertyName, out var propertyValue); return propertyValue as string; } diff --git a/src/Adapter/PlatformServices.Desktop/Utilities/DesktopDeploymentUtility.cs b/src/Adapter/PlatformServices.Desktop/Utilities/DesktopDeploymentUtility.cs index 1f708d0124..d37d72431a 100644 --- a/src/Adapter/PlatformServices.Desktop/Utilities/DesktopDeploymentUtility.cs +++ b/src/Adapter/PlatformServices.Desktop/Utilities/DesktopDeploymentUtility.cs @@ -68,8 +68,7 @@ public override string GetRootDeploymentDirectory(string baseDirectory) protected void ProcessNewStorage(string testSource, IList deploymentItems, IList warnings) { // Add deployment items and process .config files only for storages we have not processed before. - string errorMessage; - if (!this.DeploymentItemUtility.IsValidDeploymentItem(testSource, string.Empty, out errorMessage)) + if (!this.DeploymentItemUtility.IsValidDeploymentItem(testSource, string.Empty, out var errorMessage)) { warnings.Add(errorMessage); return; @@ -222,8 +221,7 @@ private void AddDependencies(string testSource, string configFile, IList warningList; - string[] references = this.AssemblyUtility.GetFullPathToDependentAssemblies(testSource, configFile, out warningList); + string[] references = this.AssemblyUtility.GetFullPathToDependentAssemblies(testSource, configFile, out var warningList); if (warningList != null && warningList.Count > 0) { warnings = warnings.Concat(warningList).ToList(); diff --git a/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs b/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs index 23eeebd7d2..11793e332a 100644 --- a/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs +++ b/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs @@ -422,8 +422,7 @@ public void SetDataConnection(object dbConnection) /// Property value private object GetPropertyValue(string propertyName) { - object propertyValue = null; - this.properties.TryGetValue(propertyName, out propertyValue); + this.properties.TryGetValue(propertyName, out var propertyValue); return propertyValue; } @@ -435,8 +434,7 @@ private object GetPropertyValue(string propertyName) /// Property value private string GetStringPropertyValue(string propertyName) { - object propertyValue = null; - this.properties.TryGetValue(propertyName, out propertyValue); + this.properties.TryGetValue(propertyName, out var propertyValue); return propertyValue as string; } diff --git a/src/Adapter/PlatformServices.Shared/netstandard1.0/Services/ns10TestContextImplementation.cs b/src/Adapter/PlatformServices.Shared/netstandard1.0/Services/ns10TestContextImplementation.cs index b444ccb6b2..db9d7e2fe3 100644 --- a/src/Adapter/PlatformServices.Shared/netstandard1.0/Services/ns10TestContextImplementation.cs +++ b/src/Adapter/PlatformServices.Shared/netstandard1.0/Services/ns10TestContextImplementation.cs @@ -329,8 +329,7 @@ public void SetDataConnection(object dbConnection) /// Property value private object GetPropertyValue(string propertyName) { - object propertyValue = null; - this.properties.TryGetValue(propertyName, out propertyValue); + this.properties.TryGetValue(propertyName, out var propertyValue); return propertyValue; } diff --git a/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13DeploymentItemUtility.cs b/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13DeploymentItemUtility.cs index ce37f29a42..6565c5348f 100644 --- a/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13DeploymentItemUtility.cs +++ b/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13DeploymentItemUtility.cs @@ -181,8 +181,7 @@ private IList GetDeploymentItems(object[] deploymentItemAttribut foreach (DeploymentItemAttribute deploymentItemAttribute in deploymentItemAttributes) { - string warning; - if (this.IsValidDeploymentItem(deploymentItemAttribute.Path, deploymentItemAttribute.OutputDirectory, out warning)) + if (this.IsValidDeploymentItem(deploymentItemAttribute.Path, deploymentItemAttribute.OutputDirectory, out var warning)) { this.AddDeploymentItem(deploymentItems, new DeploymentItem(deploymentItemAttribute.Path, deploymentItemAttribute.OutputDirectory)); } diff --git a/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13FileUtility.cs b/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13FileUtility.cs index 8f672b3194..f8d845fba7 100644 --- a/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13FileUtility.cs +++ b/src/Adapter/PlatformServices.Shared/netstandard1.3/Utilities/ns13FileUtility.cs @@ -170,8 +170,7 @@ public string FindAndDeployPdb(string destinationFile, string relativeDestinatio { if (this.DoesFileExist(pdbSource)) { - string warning; - pdbDestination = this.CopyFileOverwrite(pdbSource, pdbDestination, out warning); + pdbDestination = this.CopyFileOverwrite(pdbSource, pdbDestination, out var warning); if (!string.IsNullOrEmpty(pdbDestination)) { destToSource.Add(relativePdbDestination, pdbSource); diff --git a/src/TestFramework/Extension.Desktop/PrivateObject.cs b/src/TestFramework/Extension.Desktop/PrivateObject.cs index a6c656affc..08f8b57a70 100644 --- a/src/TestFramework/Extension.Desktop/PrivateObject.cs +++ b/src/TestFramework/Extension.Desktop/PrivateObject.cs @@ -770,13 +770,13 @@ private void BuildGenericMethodCacheForType(Type t) this.methodCache = new Dictionary>(); MethodInfo[] members = t.GetMethods(BindToEveryThing); - LinkedList listByName; // automatically initialized to null foreach (MethodInfo member in members) { if (member.IsGenericMethod || member.IsGenericMethodDefinition) { - if (!this.GenericMethodCache.TryGetValue(member.Name, out listByName)) + // automatically initialized to null + if (!this.GenericMethodCache.TryGetValue(member.Name, out LinkedList listByName)) { listByName = new LinkedList(); this.GenericMethodCache.Add(member.Name, listByName); @@ -837,9 +837,8 @@ private LinkedList GetMethodCandidates(string methodName, Type[] par Debug.Assert(typeArguments != null, "typeArguments should not be null."); LinkedList methodCandidates = new LinkedList(); - LinkedList methods = null; - if (!this.GenericMethodCache.TryGetValue(methodName, out methods)) + if (!this.GenericMethodCache.TryGetValue(methodName, out var methods)) { return methodCandidates; } diff --git a/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs b/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs index ea84a4a6f6..00734a9ceb 100644 --- a/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs +++ b/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs @@ -648,10 +648,7 @@ public static void AreEquivalent(ICollection expected, ICollection actual, strin } // Search for a mismatched element. - int expectedCount; - int actualCount; - object mismatchedElement; - if (FindMismatchedElement(expected, actual, out expectedCount, out actualCount, out mismatchedElement)) + if (FindMismatchedElement(expected, actual, out var expectedCount, out var actualCount, out var mismatchedElement)) { var finalMessage = string.Format( CultureInfo.CurrentCulture, @@ -776,10 +773,7 @@ public static void AreNotEquivalent(ICollection expected, ICollection actual, st } // Search for a mismatched element. - int expectedCount; - int actualCount; - object mismatchedElement; - if (!FindMismatchedElement(expected, actual, out expectedCount, out actualCount, out mismatchedElement)) + if (!FindMismatchedElement(expected, actual, out var expectedCount, out var actualCount, out var mismatchedElement)) { var finalMessage = string.Format( CultureInfo.CurrentCulture, @@ -1282,10 +1276,8 @@ internal static bool IsSubsetOfHelper(ICollection subset, ICollection superset) // $ CONSIDER: comparison, which should result in ~n*log(n) + m*log(m) + n. // Count the occurrences of each object in both collections. - int subsetNulls; - Dictionary subsetElements = GetElementCounts(subset, out subsetNulls); - int supersetNulls; - Dictionary supersetElements = GetElementCounts(superset, out supersetNulls); + Dictionary subsetElements = GetElementCounts(subset, out var subsetNulls); + Dictionary supersetElements = GetElementCounts(superset, out var supersetNulls); if (subsetNulls > supersetNulls) { @@ -1296,10 +1288,8 @@ internal static bool IsSubsetOfHelper(ICollection subset, ICollection superset) // in the superset. foreach (object element in subsetElements.Keys) { - int subsetCount; - subsetElements.TryGetValue(element, out subsetCount); - int supersetCount; - supersetElements.TryGetValue(element, out supersetCount); + subsetElements.TryGetValue(element, out var subsetCount); + supersetElements.TryGetValue(element, out var supersetCount); if (subsetCount > supersetCount) { @@ -1340,8 +1330,7 @@ private static Dictionary GetElementCounts(ICollection collection, continue; } - int value; - elementCounts.TryGetValue(element, out value); + elementCounts.TryGetValue(element, out var value); value++; elementCounts[element] = value; } @@ -1390,10 +1379,8 @@ private static bool FindMismatchedElement(ICollection expected, ICollection actu // $ CONSIDER: comparison, which should result in ~n*log(n) + m*log(m) + n. // Count the occurrences of each object in the both collections - int expectedNulls; - Dictionary expectedElements = GetElementCounts(expected, out expectedNulls); - int actualNulls; - Dictionary actualElements = GetElementCounts(actual, out actualNulls); + Dictionary expectedElements = GetElementCounts(expected, out var expectedNulls); + Dictionary actualElements = GetElementCounts(actual, out var actualNulls); if (actualNulls != expectedNulls) { diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodFilterTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodFilterTests.cs index 3759a38a9f..cfbf7545ed 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodFilterTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TestMethodFilterTests.cs @@ -112,8 +112,7 @@ public void PropertyProviderValueForValidTestAndSupportedPropertyNameReturnsValu public void GetFilterExpressionForNullRunContextReturnsNull() { TestableTestExecutionRecorder recorder = new TestableTestExecutionRecorder(); - bool filterHasError; - var filterExpression = this.TestMethodFilter.GetFilterExpression(null, recorder, out filterHasError); + var filterExpression = this.TestMethodFilter.GetFilterExpression(null, recorder, out var filterHasError); Assert.IsNull(filterExpression); Assert.IsFalse(filterHasError); @@ -125,8 +124,7 @@ public void GetFilterExpressionForValidRunContextReturnsValidTestCaseFilterExpre TestableTestExecutionRecorder recorder = new TestableTestExecutionRecorder(); var dummyFilterExpression = new TestableTestCaseFilterExpression(); TestableRunContext runContext = new TestableRunContext(() => dummyFilterExpression); - bool filterHasError; - var filterExpression = this.TestMethodFilter.GetFilterExpression(runContext, recorder, out filterHasError); + var filterExpression = this.TestMethodFilter.GetFilterExpression(runContext, recorder, out var filterHasError); Assert.AreEqual(dummyFilterExpression, filterExpression); Assert.IsFalse(filterHasError); @@ -141,8 +139,7 @@ public void GetFilterExpressionForDiscoveryContextWithGetTestCaseFilterReturnsVa TestableTestExecutionRecorder recorder = new TestableTestExecutionRecorder(); var dummyFilterExpression = new TestableTestCaseFilterExpression(); TestableDiscoveryContextWithGetTestCaseFilter discoveryContext = new TestableDiscoveryContextWithGetTestCaseFilter(() => dummyFilterExpression); - bool filterHasError; - var filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, recorder, out filterHasError); + var filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, recorder, out var filterHasError); Assert.AreEqual(dummyFilterExpression, filterExpression); Assert.IsFalse(filterHasError); @@ -156,8 +153,7 @@ public void GetFilterExpressionForDiscoveryContextWithoutGetTestCaseFilterReturn { TestableTestExecutionRecorder recorder = new TestableTestExecutionRecorder(); TestableDiscoveryContextWithoutGetTestCaseFilter discoveryContext = new TestableDiscoveryContextWithoutGetTestCaseFilter(); - bool filterHasError; - var filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, recorder, out filterHasError); + var filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, recorder, out var filterHasError); Assert.IsNull(filterExpression); Assert.IsFalse(filterHasError); @@ -168,8 +164,7 @@ public void GetFilterExpressionForRunContextGetTestCaseFilterThrowingExceptionRe { TestableTestExecutionRecorder recorder = new TestableTestExecutionRecorder(); TestableRunContext runContext = new TestableRunContext(() => { throw new TestPlatformFormatException("DummyException"); }); - bool filterHasError; - var filterExpression = this.TestMethodFilter.GetFilterExpression(runContext, recorder, out filterHasError); + var filterExpression = this.TestMethodFilter.GetFilterExpression(runContext, recorder, out var filterHasError); Assert.IsNull(filterExpression); Assert.IsTrue(filterHasError); @@ -185,8 +180,7 @@ public void GetFilterExpressionForDiscoveryContextWithGetTestCaseFilterThrowingE { TestableTestExecutionRecorder recorder = new TestableTestExecutionRecorder(); TestableDiscoveryContextWithGetTestCaseFilter discoveryContext = new TestableDiscoveryContextWithGetTestCaseFilter(() => { throw new TestPlatformFormatException("DummyException"); }); - bool filterHasError; - var filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, recorder, out filterHasError); + var filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, recorder, out var filterHasError); Assert.IsNull(filterExpression); Assert.IsTrue(filterHasError); diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs index ea7be9e8ca..596d1856ac 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs @@ -1181,8 +1181,7 @@ public void GetTestMethodInfoShouldNotAddDuplicateTestPropertiesToTestContext() Assert.IsNotNull(testMethodInfo); // Verify that the first value gets set. - object value; - Assert.IsTrue(((IDictionary)testContext.Properties).TryGetValue("WhoAmI", out value)); + Assert.IsTrue(((IDictionary)testContext.Properties).TryGetValue("WhoAmI", out var value)); Assert.AreEqual("Me", value); } diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/ExceptionExtensionsTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/ExceptionExtensionsTests.cs index 5b4209afa7..05251d0a55 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/ExceptionExtensionsTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/ExceptionExtensionsTests.cs @@ -177,10 +177,8 @@ public void IsUnitTestAssertExceptionReturnsTrueIfExceptionIsAssertException() { var exception = new UTF.AssertInconclusiveException(); UTF.UnitTestOutcome outcome = UTF.UnitTestOutcome.Unknown; - string exceptionMessage = null; - StackTraceInformation stackTraceInfo = null; - Assert.IsTrue(exception.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out stackTraceInfo)); + Assert.IsTrue(exception.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var stackTraceInfo)); } [TestMethod] @@ -188,10 +186,8 @@ public void IsUnitTestAssertExceptionReturnsFalseIfExceptionIsNotAssertException { var exception = new NotImplementedException(); UTF.UnitTestOutcome outcome = UTF.UnitTestOutcome.Unknown; - string exceptionMessage = null; - StackTraceInformation stackTraceInfo = null; - Assert.IsFalse(exception.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out stackTraceInfo)); + Assert.IsFalse(exception.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var stackTraceInfo)); } [TestMethod] @@ -199,10 +195,8 @@ public void IsUnitTestAssertExceptionSetsOutcomeAsInconclusiveIfAssertInconclusi { var exception = new UTF.AssertInconclusiveException("Dummy Message", new NotImplementedException("notImplementedException")); UTF.UnitTestOutcome outcome = UTF.UnitTestOutcome.Unknown; - string exceptionMessage = null; - StackTraceInformation stackTraceInfo = null; - exception.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out stackTraceInfo); + exception.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var stackTraceInfo); Assert.AreEqual(UTF.UnitTestOutcome.Inconclusive, outcome); Assert.AreEqual("Dummy Message", exceptionMessage); @@ -213,10 +207,8 @@ public void IsUnitTestAssertExceptionSetsOutcomeAsFailedIfAssertFailedException( { var exception = new UTF.AssertFailedException("Dummy Message", new NotImplementedException("notImplementedException")); UTF.UnitTestOutcome outcome = UTF.UnitTestOutcome.Unknown; - string exceptionMessage = null; - StackTraceInformation stackTraceInfo = null; - exception.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out stackTraceInfo); + exception.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var stackTraceInfo); Assert.AreEqual(UTF.UnitTestOutcome.Failed, outcome); Assert.AreEqual("Dummy Message", exceptionMessage); diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs index 61d031aebe..8c21743e2a 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs @@ -640,13 +640,12 @@ public void GetSettingsShouldBeAbleToReadSettingsAfterThePlatformServiceReadsIts reader.Read(); while (reader.NodeType == XmlNodeType.Element) { - bool result; string elementName = reader.Name.ToUpperInvariant(); switch (elementName) { case "DUMMYPLATFORMSPECIFICSETTING": { - if (bool.TryParse(reader.ReadInnerXml(), out result)) + if (bool.TryParse(reader.ReadInnerXml(), out var result)) { dummyPlatformSpecificSetting = result; } @@ -697,13 +696,12 @@ public void GetSettingsShouldBeAbleToReadSettingsIfThePlatformServiceDoesNotUnde reader.Read(); while (reader.NodeType == XmlNodeType.Element) { - bool result; string elementName = reader.Name.ToUpperInvariant(); switch (elementName) { case "DUMMYPLATFORMSPECIFICSETTING": { - if (bool.TryParse(reader.ReadInnerXml(), out result)) + if (bool.TryParse(reader.ReadInnerXml(), out var result)) { dummyPlatformSpecificSetting = result; } @@ -806,13 +804,12 @@ public void GetSettingsShouldWorkIfThereAreCommentsInTheXML() reader.Read(); while (reader.NodeType == XmlNodeType.Element) { - bool result; string elementName = reader.Name.ToUpperInvariant(); switch (elementName) { case "DUMMYPLATFORMSPECIFICSETTING": { - if (bool.TryParse(reader.ReadInnerXml(), out result)) + if (bool.TryParse(reader.ReadInnerXml(), out var result)) { dummyPlatformSpecificSetting = result; } diff --git a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Deployment/AssemblyLoadWorkerTests.cs b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Deployment/AssemblyLoadWorkerTests.cs index 76c0546e5f..d34d4fd7fd 100644 --- a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Deployment/AssemblyLoadWorkerTests.cs +++ b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Deployment/AssemblyLoadWorkerTests.cs @@ -40,10 +40,9 @@ public void GetFullPathToDependentAssembliesShouldReturnV1FrameworkAssembly() .Returns(new TestableAssembly(v1AssemblyName.Name)); var worker = new AssemblyLoadWorker(mockAssemblyUtility.Object); - IList warnings; // Act. - var dependentAssemblies = worker.GetFullPathToDependentAssemblies("C:\\temp\\test3424.dll", out warnings); + var dependentAssemblies = worker.GetFullPathToDependentAssemblies("C:\\temp\\test3424.dll", out var warnings); // Assert. var utfassembly = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll"); @@ -103,10 +102,9 @@ public void GetFullPathToDependentAssembliesShouldReturnV1FrameworkReferencedInA }); var worker = new AssemblyLoadWorker(mockAssemblyUtility.Object); - IList warnings; // Act. - var dependentAssemblies = worker.GetFullPathToDependentAssemblies("C:\\temp\\test3424.dll", out warnings); + var dependentAssemblies = worker.GetFullPathToDependentAssemblies("C:\\temp\\test3424.dll", out var warnings); // Assert. var utfassembly = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll"); diff --git a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopFileOperationsTests.cs b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopFileOperationsTests.cs index b02a82db63..013f5e5432 100644 --- a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopFileOperationsTests.cs +++ b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopFileOperationsTests.cs @@ -45,14 +45,12 @@ public void CreateNavigationSessionShouldReturnDiaSession() public void GetNavigationDataShouldReturnDataFromNavigationSession() { var diaSession = this.fileOperations.CreateNavigationSession(Assembly.GetExecutingAssembly().Location); - int minLineNumber; - string fileName; this.fileOperations.GetNavigationData( diaSession, typeof(DesktopFileOperationsTests).FullName, "GetNavigationDataShouldReturnDataFromNavigationSession", - out minLineNumber, - out fileName); + out var minLineNumber, + out var fileName); Assert.AreNotEqual(-1, minLineNumber); Assert.IsNotNull(fileName); @@ -61,14 +59,12 @@ public void GetNavigationDataShouldReturnDataFromNavigationSession() [TestMethod] public void GetNavigationDataShouldNotThrowOnNullNavigationSession() { - int minLineNumber; - string fileName; this.fileOperations.GetNavigationData( null, typeof(DesktopFileOperationsTests).FullName, "GetNavigationDataShouldReturnDataFromNavigationSession", - out minLineNumber, - out fileName); + out var minLineNumber, + out var fileName); Assert.AreEqual(-1, minLineNumber); Assert.IsNull(fileName); diff --git a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestContextImplTests.cs b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestContextImplTests.cs index e164d16f5b..6d3faa6e4a 100644 --- a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestContextImplTests.cs +++ b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestContextImplTests.cs @@ -137,9 +137,7 @@ public void TryGetPropertyValueShouldReturnTrueIfPropertyIsPresent() this.testContextImplementation = new TestContextImplementation(this.testMethod.Object, new System.IO.StringWriter(), this.properties); - object propValue; - - Assert.IsTrue(this.testContextImplementation.TryGetPropertyValue("TestName", out propValue)); + Assert.IsTrue(this.testContextImplementation.TryGetPropertyValue("TestName", out var propValue)); Assert.AreEqual("M", propValue); } @@ -148,9 +146,7 @@ public void TryGetPropertyValueShouldReturnFalseIfPropertyIsNotPresent() { this.testContextImplementation = new TestContextImplementation(this.testMethod.Object, new System.IO.StringWriter(), this.properties); - object propValue; - - Assert.IsFalse(this.testContextImplementation.TryGetPropertyValue("Random", out propValue)); + Assert.IsFalse(this.testContextImplementation.TryGetPropertyValue("Random", out var propValue)); Assert.IsNull(propValue); } diff --git a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDeploymentTests.cs b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDeploymentTests.cs index 8a6f4bea99..292beaaa47 100644 --- a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDeploymentTests.cs +++ b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDeploymentTests.cs @@ -54,11 +54,10 @@ public void TestInit() [TestMethod] public void DeployShouldDeployFilesInASourceAndReturnTrue() { - TestRunDirectories testRunDirectories; var testCase = this.GetTestCase(Assembly.GetExecutingAssembly().Location); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); @@ -79,13 +78,12 @@ public void DeployShouldDeployFilesInASourceAndReturnTrue() [TestMethod] public void DeployShouldDeployFilesInMultipleSourcesAndReturnTrue() { - TestRunDirectories testRunDirectories; var testCase1 = this.GetTestCase(Assembly.GetExecutingAssembly().Location); var sourceFile2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "a.dll"); var testCase2 = this.GetTestCase(sourceFile2); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); @@ -113,11 +111,10 @@ public void DeployShouldDeployFilesInMultipleSourcesAndReturnTrue() [TestMethod] public void DeployShouldCreateDeploymentDirectories() { - TestRunDirectories testRunDirectories; var testCase = this.GetTestCase(typeof(DesktopTestDeploymentTests).GetTypeInfo().Assembly.Location); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); diff --git a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Utilities/DesktopDeploymentUtilityTests.cs b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Utilities/DesktopDeploymentUtilityTests.cs index c80f7a8d18..0f7a023d1b 100644 --- a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Utilities/DesktopDeploymentUtilityTests.cs +++ b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Utilities/DesktopDeploymentUtilityTests.cs @@ -92,8 +92,7 @@ public void DeployShouldReturnFalseWhenNoDeploymentItemsOnTestCase() [TestMethod] public void DeployShouldDeploySourceAndItsConfigFile() { - TestRunDirectories testRunDirectories; - var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out var testRunDirectories); // Setup mocks. this.mockFileUtility.Setup(fu => fu.DoesDirectoryExist(It.Is(s => !(s.EndsWith(".dll") || s.EndsWith(".config"))))).Returns(true); @@ -139,8 +138,7 @@ public void DeployShouldDeployDependentFiles() { var dependencyFile = "C:\\temp\\dependency.dll"; - TestRunDirectories testRunDirectories; - var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out var testRunDirectories); // Setup mocks. this.mockFileUtility.Setup(fu => fu.DoesDirectoryExist(It.Is(s => !(s.EndsWith(".dll") || s.EndsWith(".config"))))).Returns(true); @@ -176,8 +174,7 @@ public void DeployShouldDeployDependentFiles() [TestMethod] public void DeployShouldDeploySatelliteAssemblies() { - TestRunDirectories testRunDirectories; - var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out var testRunDirectories); var assemblyFullPath = Assembly.GetExecutingAssembly().Location; var satelliteFullPath = Path.Combine(Path.GetDirectoryName(assemblyFullPath), "de", "satellite.dll"); @@ -215,12 +212,11 @@ public void DeployShouldDeploySatelliteAssemblies() [TestMethod] public void DeployShouldNotDeployIfOutputDirectoryIsInvalid() { - TestRunDirectories testRunDirectories; var assemblyFullPath = Assembly.GetExecutingAssembly().Location; var deploymentItemPath = "C:\\temp\\sample.dll"; var deploymentItemOutputDirectory = "..\\..\\out"; - var testCase = this.GetTestCaseAndTestRunDirectories(deploymentItemPath, deploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(deploymentItemPath, deploymentItemOutputDirectory, out var testRunDirectories); // Setup mocks. this.mockFileUtility.Setup(fu => fu.DoesDirectoryExist(It.Is(s => !(s.EndsWith(".dll") || s.EndsWith(".config"))))).Returns(true); @@ -267,10 +263,9 @@ public void DeployShouldNotDeployIfOutputDirectoryIsInvalid() [TestMethod] public void DeployShouldDeployContentsOfADirectoryIfSpecified() { - TestRunDirectories testRunDirectories; var assemblyFullPath = Assembly.GetExecutingAssembly().Location; - var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out var testRunDirectories); var content1 = Path.Combine(DefaultDeploymentItemPath, "directoryContents.dll"); var directoryContentFiles = new List { content1 }; @@ -312,8 +307,7 @@ public void DeployShouldDeployContentsOfADirectoryIfSpecified() [TestMethod] public void DeployShouldDeployPdbWithSourceIfPdbFileIsPresentInSourceDirectory() { - TestRunDirectories testRunDirectories; - var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out var testRunDirectories); // Setup mocks. this.mockFileUtility.Setup(fu => fu.DoesDirectoryExist(It.Is(s => !s.EndsWith(".dll")))).Returns(true); @@ -369,8 +363,7 @@ public void DeployShouldNotDeployPdbFileOfAssemblyIfPdbFileIsNotPresentInAssembl // Path for pdb file of dependent assembly if pdb file is present. var pdbFile = Path.ChangeExtension(dependencyFile, "pdb"); - TestRunDirectories testRunDirectories; - var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out var testRunDirectories); // Setup mocks. this.mockFileUtility.Setup(fu => fu.DoesDirectoryExist(It.Is(s => !s.EndsWith(".dll")))).Returns(true); diff --git a/test/UnitTests/PlatformServices.NetCore.Unit.Tests/Utilities/NetCoreDeploymentUtilityTests.cs b/test/UnitTests/PlatformServices.NetCore.Unit.Tests/Utilities/NetCoreDeploymentUtilityTests.cs index f048a99ca6..0c355af393 100644 --- a/test/UnitTests/PlatformServices.NetCore.Unit.Tests/Utilities/NetCoreDeploymentUtilityTests.cs +++ b/test/UnitTests/PlatformServices.NetCore.Unit.Tests/Utilities/NetCoreDeploymentUtilityTests.cs @@ -76,12 +76,11 @@ public void DeployShouldReturnFalseWhenNoDeploymentItemsOnTestCase() [TestMethod] public void DeployShouldNotDeployIfOutputDirectoryIsInvalid() { - TestRunDirectories testRunDirectories; var assemblyFullPath = Assembly.GetEntryAssembly().Location; var deploymentItemPath = "C:\\temp\\sample.dll"; var deploymentItemOutputDirectory = "..\\..\\out"; - var testCase = this.GetTestCaseAndTestRunDirectories(deploymentItemPath, deploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(deploymentItemPath, deploymentItemOutputDirectory, out var testRunDirectories); // Setup mocks. this.mockFileUtility.Setup(fu => fu.DoesDirectoryExist(It.Is(s => !(s.EndsWith(".dll") || s.EndsWith(".config"))))).Returns(true); @@ -122,10 +121,9 @@ public void DeployShouldNotDeployIfOutputDirectoryIsInvalid() [TestMethod] public void DeployShouldDeployContentsOfADirectoryIfSpecified() { - TestRunDirectories testRunDirectories; var assemblyFullPath = Assembly.GetEntryAssembly().Location; - var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out testRunDirectories); + var testCase = this.GetTestCaseAndTestRunDirectories(DefaultDeploymentItemPath, DefaultDeploymentItemOutputDirectory, out var testRunDirectories); var content1 = Path.Combine(DefaultDeploymentItemPath, "directoryContents.dll"); var directoryContentFiles = new List { content1 }; diff --git a/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs b/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs index 82eef2e92f..79542d4972 100644 --- a/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs +++ b/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs @@ -134,11 +134,10 @@ public void CleanupShouldNotDeleteDirectoriesIfRunSettingsSpecifiesSo() MSTestSettingsProvider mstestSettingsProvider = new MSTestSettingsProvider(); mstestSettingsProvider.Load(reader); - TestRunDirectories testRunDirectories; var testCase = this.GetTestCase(typeof(TestDeploymentTests).GetTypeInfo().Assembly.Location); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); @@ -153,11 +152,10 @@ public void CleanupShouldNotDeleteDirectoriesIfRunSettingsSpecifiesSo() [TestMethod] public void CleanupShouldDeleteRootDeploymentDirectory() { - TestRunDirectories testRunDirectories; var testCase = this.GetTestCase(typeof(DeploymentUtilityTests).GetTypeInfo().Assembly.Location); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); @@ -183,11 +181,10 @@ public void GetDeploymentDirectoryShouldReturnNullIfDeploymentDirectoryIsNull() [TestMethod] public void GetDeploymentDirectoryShouldReturnDeploymentOutputDirectory() { - TestRunDirectories testRunDirectories; var testCase = this.GetTestCase(typeof(TestDeploymentTests).GetTypeInfo().Assembly.Location); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); @@ -369,11 +366,10 @@ public void GetDeploymentInformationShouldReturnAppBaseDirectoryIfRunDirectoryIs public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceIsNull() { // Arrange. - TestRunDirectories testRunDirectories; var testCase = this.GetTestCase(typeof(TestDeploymentTests).GetTypeInfo().Assembly.Location); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); @@ -430,11 +426,10 @@ public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceI public void GetDeploymentInformationShouldReturnRunDirectoryInformationIfSourceIsNotNull() { // Arrange. - TestRunDirectories testRunDirectories; var testCase = this.GetTestCase(typeof(TestDeploymentTests).GetTypeInfo().Assembly.Location); // Setup mocks. - var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out testRunDirectories); + var testDeployment = this.CreateAndSetupDeploymentRelatedUtilities(out var testRunDirectories); var mockRunContext = new Mock(); mockRunContext.Setup(rc => rc.TestRunDirectory).Returns(testRunDirectories.RootDeploymentDirectory); diff --git a/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Utilities/ns13DeploymentItemUtilityTests.cs b/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Utilities/ns13DeploymentItemUtilityTests.cs index dd038907f6..adfd360c85 100644 --- a/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Utilities/ns13DeploymentItemUtilityTests.cs +++ b/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Utilities/ns13DeploymentItemUtilityTests.cs @@ -354,8 +354,7 @@ public void GetDeploymentItemsShouldReturnClassAndMethodLevelDeploymentItemsWith [TestMethod] public void IsValidDeploymentItemShouldReportWarningIfSourcePathIsNull() { - string warning; - Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(null, this.defaultDeploymentItemOutputDirectory, out warning)); + Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(null, this.defaultDeploymentItemOutputDirectory, out var warning)); StringAssert.Contains(Resource.DeploymentItemPathCannotBeNullOrEmpty, warning); } @@ -363,8 +362,7 @@ public void IsValidDeploymentItemShouldReportWarningIfSourcePathIsNull() [TestMethod] public void IsValidDeploymentItemShouldReportWarningIfSourcePathIsEmpty() { - string warning; - Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(string.Empty, this.defaultDeploymentItemOutputDirectory, out warning)); + Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(string.Empty, this.defaultDeploymentItemOutputDirectory, out var warning)); StringAssert.Contains(Resource.DeploymentItemPathCannotBeNullOrEmpty, warning); } @@ -372,8 +370,7 @@ public void IsValidDeploymentItemShouldReportWarningIfSourcePathIsEmpty() [TestMethod] public void IsValidDeploymentItemShouldReportWarningIfDeploymentOutputDirectoryIsNull() { - string warning; - Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, null, out warning)); + Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, null, out var warning)); StringAssert.Contains(Resource.DeploymentItemOutputDirectoryCannotBeNull, warning); } @@ -381,8 +378,7 @@ public void IsValidDeploymentItemShouldReportWarningIfDeploymentOutputDirectoryI [TestMethod] public void IsValidDeploymentItemShouldReportWarningIfSourcePathHasInvalidCharacters() { - string warning; - Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem("C:<>", this.defaultDeploymentItemOutputDirectory, out warning)); + Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem("C:<>", this.defaultDeploymentItemOutputDirectory, out var warning)); StringAssert.Contains( string.Format( @@ -395,8 +391,7 @@ public void IsValidDeploymentItemShouldReportWarningIfSourcePathHasInvalidCharac [TestMethod] public void IsValidDeploymentItemShouldReportWarningIfOutputDirectoryHasInvalidCharacters() { - string warning; - Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, "<>", out warning)); + Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, "<>", out var warning)); StringAssert.Contains( string.Format( @@ -409,8 +404,7 @@ public void IsValidDeploymentItemShouldReportWarningIfOutputDirectoryHasInvalidC [TestMethod] public void IsValidDeploymentItemShouldReportWarningIfDeploymentOutputDirectoryIsRooted() { - string warning; - Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, "C:\\temp", out warning)); + Assert.IsFalse(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, "C:\\temp", out var warning)); StringAssert.Contains( string.Format( @@ -422,8 +416,7 @@ public void IsValidDeploymentItemShouldReportWarningIfDeploymentOutputDirectoryI [TestMethod] public void IsValidDeploymentItemShouldReturnTrueForAValidDeploymentItem() { - string warning; - Assert.IsTrue(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, this.defaultDeploymentItemOutputDirectory, out warning)); + Assert.IsTrue(this.deploymentItemUtility.IsValidDeploymentItem(this.defaultDeploymentItemPath, this.defaultDeploymentItemOutputDirectory, out var warning)); Assert.IsTrue(string.Empty.Equals(warning)); } diff --git a/test/UnitTests/PlatformServices.Universal.Unit.Tests/Services/UniversalFileOperationsTests.cs b/test/UnitTests/PlatformServices.Universal.Unit.Tests/Services/UniversalFileOperationsTests.cs index 33c19a64d9..a51fa7305e 100644 --- a/test/UnitTests/PlatformServices.Universal.Unit.Tests/Services/UniversalFileOperationsTests.cs +++ b/test/UnitTests/PlatformServices.Universal.Unit.Tests/Services/UniversalFileOperationsTests.cs @@ -108,10 +108,7 @@ public void CreateNavigationSessionShouldReturnNullForAllSources() [TestMethod] public void GetNavigationDataShouldReturnNullFileName() { - int minLineNumber; - string fileName; - - this.fileOperations.GetNavigationData(null, null, null, out minLineNumber, out fileName); + this.fileOperations.GetNavigationData(null, null, null, out var minLineNumber, out var fileName); Assert.IsNull(fileName); Assert.AreEqual(-1, minLineNumber); } From c13d7b693d52fe058d0effc38111f3cbe0da0f47 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 22:35:41 +0200 Subject: [PATCH 03/23] IDE0019 Use pattern matching --- src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs | 6 ++---- src/TestFramework/MSTest.Core/Assertions/Assert.cs | 6 ++---- src/TestFramework/MSTest.Core/GenericParameterHelper.cs | 3 +-- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs b/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs index 98f249c7ce..c508f35efe 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs @@ -95,8 +95,7 @@ public TAttributeType[] GetAttributes(bool inherit) { Attribute[] attributeArray = ReflectHelper.GetCustomAttributes(this.TestMethod, typeof(TAttributeType), inherit); - TAttributeType[] tAttributeArray = attributeArray as TAttributeType[]; - if (tAttributeArray != null) + if (attributeArray is TAttributeType[] tAttributeArray) { return tAttributeArray; } @@ -106,8 +105,7 @@ public TAttributeType[] GetAttributes(bool inherit) { foreach (Attribute attribute in attributeArray) { - TAttributeType tAttribute = attribute as TAttributeType; - if (tAttribute != null) + if (attribute is TAttributeType tAttribute) { tAttributeList.Add(tAttribute); } diff --git a/src/TestFramework/MSTest.Core/Assertions/Assert.cs b/src/TestFramework/MSTest.Core/Assertions/Assert.cs index 2b0126dc72..8af6bf20c9 100644 --- a/src/TestFramework/MSTest.Core/Assertions/Assert.cs +++ b/src/TestFramework/MSTest.Core/Assertions/Assert.cs @@ -483,11 +483,9 @@ public static void AreSame(object expected, object actual, string message, param { string finalMessage = message; - ValueType valExpected = expected as ValueType; - if (valExpected != null) + if (expected is ValueType valExpected) { - ValueType valActual = actual as ValueType; - if (valActual != null) + if (actual is ValueType valActual) { finalMessage = string.Format( CultureInfo.CurrentCulture, diff --git a/src/TestFramework/MSTest.Core/GenericParameterHelper.cs b/src/TestFramework/MSTest.Core/GenericParameterHelper.cs index 1d4c40459b..dd70833cd9 100644 --- a/src/TestFramework/MSTest.Core/GenericParameterHelper.cs +++ b/src/TestFramework/MSTest.Core/GenericParameterHelper.cs @@ -106,8 +106,7 @@ public override int GetHashCode() /// public int CompareTo(object obj) { - GenericParameterHelper gpf = obj as GenericParameterHelper; - if (gpf != null) + if (obj is GenericParameterHelper gpf) { return this.Data.CompareTo(gpf.Data); } From cc75b2d3874877ce4a29ae50739a86d31b5c4881 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 22:41:52 +0200 Subject: [PATCH 04/23] IDE0054 Use '++' operator --- .../PlatformServices.Desktop/Data/TestDataConnectionSql.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs index c506a311e7..8b262cbf7d 100644 --- a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs +++ b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs @@ -443,7 +443,7 @@ private int FindIdentifierEnd(string text, int start) } // Skip the quote we just found - here = here + 1; + here++; // If this the end? if (here == end || text[here] != suffixChar) @@ -453,7 +453,7 @@ private int FindIdentifierEnd(string text, int start) } // We have a double quote, skip the second one, then keep looking - here = here + 1; + here++; } // If we fall off end of loop, From a89f2f63b77241dc6bf43c6b397a3f7433ebe10c Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 22:45:57 +0200 Subject: [PATCH 05/23] IDE0029 Null check can be simplified --- .../MSTest.Core/Assertions/CollectionAssert.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs b/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs index 00734a9ceb..d1d9a3dd8d 100644 --- a/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs +++ b/src/TestFramework/MSTest.Core/Assertions/CollectionAssert.cs @@ -350,7 +350,7 @@ public static void AllItemsAreUnique(ICollection collection, string message, par var finalMessage = string.Format( CultureInfo.CurrentCulture, FrameworkMessages.AllItemsAreUniqueFailMsg, - message == null ? string.Empty : message, + message ?? string.Empty, FrameworkMessages.Common_NullInMessages); Assert.HandleFail("CollectionAssert.AllItemsAreUnique", finalMessage, parameters); @@ -363,7 +363,7 @@ public static void AllItemsAreUnique(ICollection collection, string message, par string finalMessage = string.Format( CultureInfo.CurrentCulture, FrameworkMessages.AllItemsAreUniqueFailMsg, - message == null ? string.Empty : message, + message ?? string.Empty, Assert.ReplaceNulls(current)); Assert.HandleFail("CollectionAssert.AllItemsAreUnique", finalMessage, parameters); @@ -868,8 +868,8 @@ public static void AllItemsAreInstancesOfType(ICollection collection, Type expec int i = 0; foreach (object element in collection) { - var elementTypeInfo = element != null ? element.GetType().GetTypeInfo() : null; - var expectedTypeInfo = expectedType != null ? expectedType.GetTypeInfo() : null; + var elementTypeInfo = element?.GetType().GetTypeInfo(); + var expectedTypeInfo = expectedType?.GetTypeInfo(); if (expectedTypeInfo != null && elementTypeInfo != null && !expectedTypeInfo.IsAssignableFrom(elementTypeInfo)) { var finalMessage = string.Format( From 4262d2bfa4121488b8ebe99ea1b71e587e2c4c7e Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 22:50:00 +0200 Subject: [PATCH 06/23] S1155 Use '.Any()' to test whether this 'IEnumerable' is empty or not. --- .../Services/DesktopTestContextImplementation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs b/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs index 9cf304ed5c..be4226606c 100644 --- a/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs +++ b/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs @@ -427,7 +427,7 @@ public void AddProperty(string propertyName, string propertyValue) /// Results files generated in run. public IList GetResultFiles() { - if (this.testResultFiles.Count() == 0) + if (!this.testResultFiles.Any()) { return null; } From 3079ccee23eaf1379e2574bf5bda7d005c14c73b Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 23:02:00 +0200 Subject: [PATCH 07/23] S3415 Make sure these 2 arguments are in the correct order: expected value, actual value. --- .../Execution/UnitTestRunnerTests.cs | 2 +- .../Services/DesktopTestDataSourceTests.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs index e7795818a5..048fa8200f 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs @@ -294,7 +294,7 @@ public void RunCleanupShouldReturnCleanupResultsWithDebugTraceLogsSetIfDebugTrac this.unitTestRunner.RunSingleTest(testMethod, this.testRunParameters); var cleanupresult = this.unitTestRunner.RunCleanup(); - Assert.AreEqual(cleanupresult.DebugTrace, "DummyTrace"); + Assert.AreEqual("DummyTrace", cleanupresult.DebugTrace); } [TestMethodV1] diff --git a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDataSourceTests.cs b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDataSourceTests.cs index e69e75cbf2..c412c718bf 100644 --- a/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDataSourceTests.cs +++ b/test/UnitTests/PlatformServices.Desktop.Unit.Tests/Services/DesktopTestDataSourceTests.cs @@ -89,15 +89,15 @@ public DesktopTestFrameworkV2.TestContext TestContext [TestFrameworkV2.TestMethod] public void PassingTest() { - Assert.AreEqual(this.testContextInstance.DataRow["adapter"].ToString(), "v1"); - Assert.AreEqual(this.testContextInstance.DataRow["targetPlatform"].ToString(), "x86"); + Assert.AreEqual("v1", this.testContextInstance.DataRow["adapter"].ToString()); + Assert.AreEqual("x86", this.testContextInstance.DataRow["targetPlatform"].ToString()); this.TestContext.AddResultFile("C:\\temp.txt"); } [TestFrameworkV2.TestMethod] public void FailingTest() { - Assert.AreEqual(this.testContextInstance.DataRow["configuration"].ToString(), "Release"); + Assert.AreEqual("Release", this.testContextInstance.DataRow["configuration"].ToString()); } } From e742b1d80c43677aab9289a1de92cbecebbde0a8 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 23:04:57 +0200 Subject: [PATCH 08/23] S2971 Drop 'Where' and move the condition into the 'Count'. --- .../MSTestDiscovererTests.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestDiscovererTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestDiscovererTests.cs index 395e8c1f84..c910ee5f03 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestDiscovererTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestDiscovererTests.cs @@ -71,7 +71,7 @@ public void MSTestDiscovererHasXapAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetTypeInfo().GetCustomAttributes(typeof(FileExtensionAttribute)).Cast(); Assert.IsNotNull(attributes); - Assert.AreEqual(1, attributes.Where(attribute => attribute.FileExtension == ".xap").Count()); + Assert.AreEqual(1, attributes.Count(attribute => attribute.FileExtension == ".xap")); } [TestMethod] @@ -79,7 +79,7 @@ public void MSTestDiscovererHasAppxAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetTypeInfo().GetCustomAttributes(typeof(FileExtensionAttribute)).Cast(); Assert.IsNotNull(attributes); - Assert.AreEqual(1, attributes.Where(attribute => attribute.FileExtension == ".appx").Count()); + Assert.AreEqual(1, attributes.Count(attribute => attribute.FileExtension == ".appx")); } [TestMethod] @@ -87,7 +87,7 @@ public void MSTestDiscovererHasDllAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetTypeInfo().GetCustomAttributes(typeof(FileExtensionAttribute)).Cast(); Assert.IsNotNull(attributes); - Assert.AreEqual(1, attributes.Where(attribute => attribute.FileExtension == ".dll").Count()); + Assert.AreEqual(1, attributes.Count(attribute => attribute.FileExtension == ".dll")); } [TestMethod] @@ -95,7 +95,7 @@ public void MSTestDiscovererHasExeAsFileExtension() { IEnumerable attributes = typeof(MSTestDiscoverer).GetTypeInfo().GetCustomAttributes(typeof(FileExtensionAttribute)).Cast(); Assert.IsNotNull(attributes); - Assert.AreEqual(1, attributes.Where(attribute => attribute.FileExtension == ".exe").Count()); + Assert.AreEqual(1, attributes.Count(attribute => attribute.FileExtension == ".exe")); } [TestMethod] From 14b5d6cc55b3ac58d811eeb5142e060cef11f4b9 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 23:08:09 +0200 Subject: [PATCH 09/23] IDE0054 Use compound assignment --- .../Execution/UnitTestRunnerTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs index 048fa8200f..ef23905920 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs @@ -224,8 +224,8 @@ public void RunSingleTestShouldCallAssemblyInitializeAndClassInitializeMethodsIn It.IsAny())).Returns(true); var validator = 1; - DummyTestClassWithInitializeMethods.AssemblyInitializeMethodBody = () => { validator = validator << 2; }; - DummyTestClassWithInitializeMethods.ClassInitializeMethodBody = () => { validator = validator >> 2; }; + DummyTestClassWithInitializeMethods.AssemblyInitializeMethodBody = () => { validator <<= 2; }; + DummyTestClassWithInitializeMethods.ClassInitializeMethodBody = () => { validator >>= 2; }; this.unitTestRunner.RunSingleTest(testMethod, this.testRunParameters); From 9289601c978852b4ef4a860a9c8b1afc6bd0038f Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 23:09:19 +0200 Subject: [PATCH 10/23] SA1512 Single-line comments must not be followed by blank line --- src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs b/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs index 045a33c8c7..13f35426a1 100644 --- a/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs +++ b/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs @@ -424,7 +424,6 @@ private Assembly OnResolveInternal(object senderAppDomain, ResolveEventArgs args lock (this.syncLock) { // Since both normal and reflection only cache are accessed in same block, putting only one lock should be sufficient. - if (this.TryLoadFromCache(assemblyNameToLoad, isReflectionOnly, out var assembly)) { return assembly; From 6195c80aee0567c79d30b8f7eddabf13413bef81 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 23:09:54 +0200 Subject: [PATCH 11/23] SA1611 The documentation for parameter 'runSettingsXml' is missing --- src/Adapter/MSTest.CoreAdapter/MSTestSettings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Adapter/MSTest.CoreAdapter/MSTestSettings.cs b/src/Adapter/MSTest.CoreAdapter/MSTestSettings.cs index a6fd562431..351491782b 100644 --- a/src/Adapter/MSTest.CoreAdapter/MSTestSettings.cs +++ b/src/Adapter/MSTest.CoreAdapter/MSTestSettings.cs @@ -245,7 +245,7 @@ public static bool IsLegacyScenario(IMessageLogger logger) /// /// Gets the adapter specific settings from the xml. /// - /// The xml with the settings passed from the test platform. + /// The xml with the settings passed from the test platform. /// The name of the adapter settings to fetch - Its either MSTest or MSTestV2 /// The settings if found. Null otherwise. internal static MSTestSettings GetSettings(string runSettingsXml, string settingName) From 4cf8b78cee6bf207f1ee491050c896eae03e8698 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 23:26:22 +0200 Subject: [PATCH 12/23] IDE0075 Conditional expression can be simplified --- .../PlatformServices.Desktop/Data/TestDataConnectionSql.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs index 8b262cbf7d..d849b19923 100644 --- a/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs +++ b/src/Adapter/PlatformServices.Desktop/Data/TestDataConnectionSql.cs @@ -726,7 +726,7 @@ private static bool IsInArray(string candidate, string[] values) public bool IsOpen() #pragma warning restore SA1202 // Elements must be ordered by access { - return this.connection != null ? this.connection.State == ConnectionState.Open : false; + return this.connection != null && this.connection.State == ConnectionState.Open; } /// From 619acfb4f50865716c81829df0202d2b2a7a5e03 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Sun, 4 Apr 2021 23:37:14 +0200 Subject: [PATCH 13/23] IDE0075 Conditional expression can be simplified --- src/Adapter/PlatformServices.Desktop/Data/OdbcDataConnection.cs | 2 +- src/Adapter/PlatformServices.Desktop/Data/OleDataConnection.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Adapter/PlatformServices.Desktop/Data/OdbcDataConnection.cs b/src/Adapter/PlatformServices.Desktop/Data/OdbcDataConnection.cs index 6280c485bb..13af29c8ff 100644 --- a/src/Adapter/PlatformServices.Desktop/Data/OdbcDataConnection.cs +++ b/src/Adapter/PlatformServices.Desktop/Data/OdbcDataConnection.cs @@ -21,7 +21,7 @@ public OdbcDataConnection(string invariantProviderName, string connectionString, // Need open connection to get Connection.Driver. Debug.Assert(this.IsOpen(), "The connection must be open!"); - this.isMSSql = this.Connection != null ? IsMSSql(this.Connection.Driver) : false; + this.isMSSql = this.Connection != null && IsMSSql(this.Connection.Driver); } public new OdbcCommandBuilder CommandBuilder diff --git a/src/Adapter/PlatformServices.Desktop/Data/OleDataConnection.cs b/src/Adapter/PlatformServices.Desktop/Data/OleDataConnection.cs index e4019c8777..35c4fcb89b 100644 --- a/src/Adapter/PlatformServices.Desktop/Data/OleDataConnection.cs +++ b/src/Adapter/PlatformServices.Desktop/Data/OleDataConnection.cs @@ -23,7 +23,7 @@ public OleDataConnection(string invariantProviderName, string connectionString, Debug.Assert(this.IsOpen(), "The connection must be open!"); // Fill m_isMSSql. - this.isMSSql = this.Connection != null ? IsMSSql(this.Connection.Provider) : false; + this.isMSSql = this.Connection != null && IsMSSql(this.Connection.Provider); } public new OleDbCommandBuilder CommandBuilder From a2c11b14f5f679003e5e256e80ae1b65c1b8d22e Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 12:33:56 +0200 Subject: [PATCH 14/23] CA1507 Use nameof in place of string literal. --- src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs | 4 ++-- .../MSTest.CoreAdapter/Execution/UnitTestRunner.cs | 2 +- src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs | 2 +- .../Services/DesktopTestContextImplementation.cs | 2 +- .../Utilities/RandomIntPermutation.cs | 2 +- .../Utilities/SequentialIntPermutation.cs | 2 +- .../PlatformServices.Desktop/Utilities/XmlUtilities.cs | 2 +- .../Services/NetCoreTestContextImplementation.cs | 2 +- src/TestFramework/Extension.Desktop/PrivateType.cs | 2 +- src/TestFramework/Extension.Desktop/RuntimeTypeHelper.cs | 2 +- src/TestFramework/MSTest.Core/Assertions/Assert.cs | 8 ++++---- .../MSTest.Core/Attributes/ExpectedExceptionAttribute.cs | 4 ++-- src/TestFramework/MSTest.Core/Logger.cs | 2 +- 13 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs b/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs index 074845f5fc..51baa6e7ce 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs @@ -100,12 +100,12 @@ public TestMethodInfo GetTestMethodInfo(TestMethod testMethod, ITestContext test { if (testMethod == null) { - throw new ArgumentNullException("testMethod"); + throw new ArgumentNullException(nameof(testMethod)); } if (testContext == null) { - throw new ArgumentNullException("testContext"); + throw new ArgumentNullException(nameof(testContext)); } // Get the classInfo (This may throw as GetType calls assembly.GetType(..,true);) diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/UnitTestRunner.cs b/src/Adapter/MSTest.CoreAdapter/Execution/UnitTestRunner.cs index 679d5a8971..597e2a6ca8 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/UnitTestRunner.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/UnitTestRunner.cs @@ -68,7 +68,7 @@ internal UnitTestResult[] RunSingleTest(TestMethod testMethod, IDictionary directories) { if (directories == null || directories.Count == 0) { - throw new ArgumentNullException("directories"); + throw new ArgumentNullException(nameof(directories)); } this.searchDirectories = new List(directories); diff --git a/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs b/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs index be4226606c..e103c48149 100644 --- a/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs +++ b/src/Adapter/PlatformServices.Desktop/Services/DesktopTestContextImplementation.cs @@ -250,7 +250,7 @@ public override void AddResultFile(string fileName) { if (string.IsNullOrEmpty(fileName)) { - throw new ArgumentException(Resource.Common_CannotBeNullOrEmpty, "fileName"); + throw new ArgumentException(Resource.Common_CannotBeNullOrEmpty, nameof(fileName)); } this.testResultFiles.Add(Path.GetFullPath(fileName)); diff --git a/src/Adapter/PlatformServices.Desktop/Utilities/RandomIntPermutation.cs b/src/Adapter/PlatformServices.Desktop/Utilities/RandomIntPermutation.cs index 56b2ffd83b..9b713cc486 100644 --- a/src/Adapter/PlatformServices.Desktop/Utilities/RandomIntPermutation.cs +++ b/src/Adapter/PlatformServices.Desktop/Utilities/RandomIntPermutation.cs @@ -19,7 +19,7 @@ public RandomIntPermutation(int numberOfObjects) { if (numberOfObjects < 0) { - throw new ArgumentException(Resource.WrongNumberOfObjects, "numberOfObjects"); + throw new ArgumentException(Resource.WrongNumberOfObjects, nameof(numberOfObjects)); } this.objects = new int[numberOfObjects]; diff --git a/src/Adapter/PlatformServices.Desktop/Utilities/SequentialIntPermutation.cs b/src/Adapter/PlatformServices.Desktop/Utilities/SequentialIntPermutation.cs index 7d345e7e0b..921c4e5cf8 100644 --- a/src/Adapter/PlatformServices.Desktop/Utilities/SequentialIntPermutation.cs +++ b/src/Adapter/PlatformServices.Desktop/Utilities/SequentialIntPermutation.cs @@ -19,7 +19,7 @@ public SequentialIntPermutation(int numberOfObjects) { if (numberOfObjects < 0) { - throw new ArgumentException(Resource.WrongNumberOfObjects, "numberOfObjects"); + throw new ArgumentException(Resource.WrongNumberOfObjects, nameof(numberOfObjects)); } this.numberOfObjects = numberOfObjects; diff --git a/src/Adapter/PlatformServices.Desktop/Utilities/XmlUtilities.cs b/src/Adapter/PlatformServices.Desktop/Utilities/XmlUtilities.cs index 6d5d829f34..5a0871cdd7 100644 --- a/src/Adapter/PlatformServices.Desktop/Utilities/XmlUtilities.cs +++ b/src/Adapter/PlatformServices.Desktop/Utilities/XmlUtilities.cs @@ -109,7 +109,7 @@ private static void AddAssemblyBindingRedirect( Debug.Assert(assemblyName != null, "assemblyName should not be null."); if (assemblyName == null) { - throw new ArgumentNullException("assemblyName"); + throw new ArgumentNullException(nameof(assemblyName)); } // Convert the public key token into a string. diff --git a/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs b/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs index 11793e332a..108268ce23 100644 --- a/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs +++ b/src/Adapter/PlatformServices.NetCore/Services/NetCoreTestContextImplementation.cs @@ -226,7 +226,7 @@ public override void AddResultFile(string fileName) { if (string.IsNullOrEmpty(fileName)) { - throw new ArgumentException(Resource.Common_CannotBeNullOrEmpty, "fileName"); + throw new ArgumentException(Resource.Common_CannotBeNullOrEmpty, nameof(fileName)); } this.testResultFiles.Add(Path.GetFullPath(fileName)); diff --git a/src/TestFramework/Extension.Desktop/PrivateType.cs b/src/TestFramework/Extension.Desktop/PrivateType.cs index 78cb3c40f1..2cb5c15d89 100644 --- a/src/TestFramework/Extension.Desktop/PrivateType.cs +++ b/src/TestFramework/Extension.Desktop/PrivateType.cs @@ -46,7 +46,7 @@ public PrivateType(string assemblyName, string typeName) /// The wrapped Type to create. public PrivateType(Type type) { - this.type = type ?? throw new ArgumentNullException("type"); + this.type = type ?? throw new ArgumentNullException(nameof(type)); } /// diff --git a/src/TestFramework/Extension.Desktop/RuntimeTypeHelper.cs b/src/TestFramework/Extension.Desktop/RuntimeTypeHelper.cs index 987a27cf94..078cb90fee 100644 --- a/src/TestFramework/Extension.Desktop/RuntimeTypeHelper.cs +++ b/src/TestFramework/Extension.Desktop/RuntimeTypeHelper.cs @@ -120,7 +120,7 @@ internal static MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] m { if (match == null) { - throw new ArgumentNullException("match"); + throw new ArgumentNullException(nameof(match)); } int i; diff --git a/src/TestFramework/MSTest.Core/Assertions/Assert.cs b/src/TestFramework/MSTest.Core/Assertions/Assert.cs index 8af6bf20c9..4d9671909e 100644 --- a/src/TestFramework/MSTest.Core/Assertions/Assert.cs +++ b/src/TestFramework/MSTest.Core/Assertions/Assert.cs @@ -2184,12 +2184,12 @@ public static T ThrowsException(Action action, string message, params object[ if (action == null) { - throw new ArgumentNullException("action"); + throw new ArgumentNullException(nameof(action)); } if (message == null) { - throw new ArgumentNullException("message"); + throw new ArgumentNullException(nameof(message)); } try @@ -2295,12 +2295,12 @@ public static async Task ThrowsExceptionAsync(Func action, string me if (action == null) { - throw new ArgumentNullException("action"); + throw new ArgumentNullException(nameof(action)); } if (message == null) { - throw new ArgumentNullException("message"); + throw new ArgumentNullException(nameof(message)); } try diff --git a/src/TestFramework/MSTest.Core/Attributes/ExpectedExceptionAttribute.cs b/src/TestFramework/MSTest.Core/Attributes/ExpectedExceptionAttribute.cs index 274d322c39..a7eb801c50 100644 --- a/src/TestFramework/MSTest.Core/Attributes/ExpectedExceptionAttribute.cs +++ b/src/TestFramework/MSTest.Core/Attributes/ExpectedExceptionAttribute.cs @@ -38,14 +38,14 @@ public ExpectedExceptionAttribute(Type exceptionType, string noExceptionMessage) { if (exceptionType == null) { - throw new ArgumentNullException("exceptionType"); + throw new ArgumentNullException(nameof(exceptionType)); } if (!typeof(Exception).GetTypeInfo().IsAssignableFrom(exceptionType.GetTypeInfo())) { throw new ArgumentException( FrameworkMessages.UTF_ExpectedExceptionTypeMustDeriveFromException, - "exceptionType"); + nameof(exceptionType)); } this.ExceptionType = exceptionType; diff --git a/src/TestFramework/MSTest.Core/Logger.cs b/src/TestFramework/MSTest.Core/Logger.cs index c0c3739931..81cc0d1569 100644 --- a/src/TestFramework/MSTest.Core/Logger.cs +++ b/src/TestFramework/MSTest.Core/Logger.cs @@ -37,7 +37,7 @@ public static void LogMessage(string format, params object[] args) { if (format == null) { - throw new ArgumentNullException("format"); + throw new ArgumentNullException(nameof(format)); } string message = string.Format(CultureInfo.InvariantCulture, format, args); From 8540c3048c2f5172add8fd5efbba659fc7082f41 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 12:44:09 +0200 Subject: [PATCH 15/23] RCS1077 Optimize LINQ method call. --- .../MSTest.CoreAdapter/Execution/TypeCache.cs | 4 ++-- test/E2ETests/Automation.CLI/CLITestBase.cs | 2 +- .../Discovery/AssemblyEnumeratorTests.cs | 6 +++--- .../Execution/TypeCacheTests.cs | 12 ++++++------ .../Execution/UnitTestRunnerTests.cs | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs b/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs index 51baa6e7ce..f95be41da7 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs @@ -682,9 +682,9 @@ private MethodInfo GetMethodInfoUsingRuntimeMethods(TestMethod testMethod, TestC { // Only find methods that match the given declaring name. testMethodInfo = - methodsInClass.Where(method => method.Name.Equals(testMethod.Name) + Array.Find(methodsInClass, method => method.Name.Equals(testMethod.Name) && method.DeclaringType.FullName.Equals(testMethod.DeclaringClassFullName) - && method.HasCorrectTestMethodSignature(true)).FirstOrDefault(); + && method.HasCorrectTestMethodSignature(true)); } else { diff --git a/test/E2ETests/Automation.CLI/CLITestBase.cs b/test/E2ETests/Automation.CLI/CLITestBase.cs index 9c6f5b85ef..3624c7c89e 100644 --- a/test/E2ETests/Automation.CLI/CLITestBase.cs +++ b/test/E2ETests/Automation.CLI/CLITestBase.cs @@ -343,7 +343,7 @@ private static string GetTestMethodName(string testFullName) string testMethodName = string.Empty; var splits = testFullName.Split('.'); - if (splits.Count() >= 3) + if (splits.Length >= 3) { testMethodName = splits[2]; } diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs index 17a9edda4f..7040106c65 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs @@ -94,7 +94,7 @@ public void GetTypesShouldReturnEmptyArrayWhenNoDeclaredTypes() // Setup mocks mockAssembly.Setup(a => a.DefinedTypes).Returns(new List()); - Assert.AreEqual(0, this.assemblyEnumerator.GetTypes(mockAssembly.Object, string.Empty, this.warnings).Count()); + Assert.AreEqual(0, this.assemblyEnumerator.GetTypes(mockAssembly.Object, string.Empty, this.warnings).Length); } [TestMethodV1] @@ -243,7 +243,7 @@ public void EnumerateAssemblyShouldReturnEmptyListWhenNoDeclaredTypes() this.testablePlatformServiceProvider.MockFileOperations.Setup(fo => fo.LoadAssembly("DummyAssembly", false)) .Returns(mockAssembly.Object); - Assert.AreEqual(0, this.assemblyEnumerator.EnumerateAssembly("DummyAssembly", out this.warnings).Count()); + Assert.AreEqual(0, this.assemblyEnumerator.EnumerateAssembly("DummyAssembly", out this.warnings).Count); } [TestMethodV1] @@ -260,7 +260,7 @@ public void EnumerateAssemblyShouldReturnEmptyListWhenNoTestElementsInAType() testableAssemblyEnumerator.MockTypeEnumerator.Setup(te => te.Enumerate(out this.warnings)) .Returns((ICollection)null); - Assert.AreEqual(0, this.assemblyEnumerator.EnumerateAssembly("DummyAssembly", out this.warnings).Count()); + Assert.AreEqual(0, this.assemblyEnumerator.EnumerateAssembly("DummyAssembly", out this.warnings).Count); } [TestMethodV1] diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs index 596d1856ac..70d9436c46 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/TypeCacheTests.cs @@ -495,8 +495,8 @@ public void GetTestMethodInfoShouldCacheBaseClassInitializeAttributes() Assert.AreEqual(1, this.typeCache.ClassInfoCache.Count()); Assert.AreEqual(1, this.typeCache.ClassInfoCache.ToArray()[0].BaseClassInitAndCleanupMethods.Count); - Assert.IsNull(this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.First().Item2, "No base class cleanup"); - Assert.AreEqual(baseType.GetMethod("AssemblyInit"), this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.First().Item1); + Assert.IsNull(this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.Peek().Item2, "No base class cleanup"); + Assert.AreEqual(baseType.GetMethod("AssemblyInit"), this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.Peek().Item1); } [TestMethodV1] @@ -543,8 +543,8 @@ public void GetTestMethodInfoShouldCacheBaseClassCleanupAttributes() Assert.AreEqual(1, this.typeCache.ClassInfoCache.Count()); Assert.AreEqual(1, this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.Count); - Assert.IsNull(this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.First().Item1, "No base class init"); - Assert.AreEqual(baseType.GetMethod("AssemblyCleanup"), this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.First().Item2); + Assert.IsNull(this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.Peek().Item1, "No base class init"); + Assert.AreEqual(baseType.GetMethod("AssemblyCleanup"), this.typeCache.ClassInfoCache.First().BaseClassInitAndCleanupMethods.Peek().Item2); } [TestMethodV1] @@ -610,8 +610,8 @@ public void GetTestMethodInfoShouldCacheBaseClassInitAndCleanupAttributes() Assert.AreEqual(type.GetMethod("AssemblyCleanup"), this.typeCache.ClassInfoCache.ToArray()[0].ClassCleanupMethod); Assert.AreEqual(1, this.typeCache.ClassInfoCache.ToArray()[0].BaseClassInitAndCleanupMethods.Count); - Assert.AreEqual(baseInitializeMethod, this.typeCache.ClassInfoCache.ToArray()[0].BaseClassInitAndCleanupMethods.First().Item1); - Assert.AreEqual(baseCleanupMethod, this.typeCache.ClassInfoCache.ToArray()[0].BaseClassInitAndCleanupMethods.First().Item2); + Assert.AreEqual(baseInitializeMethod, this.typeCache.ClassInfoCache.ToArray()[0].BaseClassInitAndCleanupMethods.Peek().Item1); + Assert.AreEqual(baseCleanupMethod, this.typeCache.ClassInfoCache.ToArray()[0].BaseClassInitAndCleanupMethods.Peek().Item2); } [TestMethodV1] diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs index ef23905920..b4efbb5be9 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Execution/UnitTestRunnerTests.cs @@ -273,7 +273,7 @@ public void RunCleanupShouldReturnCleanupResultsForAssemblyAndClassCleanupMethod Assert.AreEqual(1, assemblyCleanupCount); Assert.AreEqual(1, classCleanupCount); - Assert.AreEqual(2, cleanupresult.Warnings.Count()); + Assert.AreEqual(2, cleanupresult.Warnings.Count); Assert.IsTrue(cleanupresult.Warnings.All(w => w.Contains("NotImplemented"))); } From f5621da582addf11fc908b8c25e1dca92ec0d248 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 12:53:28 +0200 Subject: [PATCH 16/23] RCS1090 Add call to 'ConfigureAwait'. --- .../MSTest.Core/Assertions/Assert.cs | 6 +++--- .../Assertions/AssertTests.cs | 18 +++++++++--------- .../Extensions/MethodInfoExtensionsTests.cs | 14 +++++++------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/TestFramework/MSTest.Core/Assertions/Assert.cs b/src/TestFramework/MSTest.Core/Assertions/Assert.cs index 4d9671909e..ed83d9e097 100644 --- a/src/TestFramework/MSTest.Core/Assertions/Assert.cs +++ b/src/TestFramework/MSTest.Core/Assertions/Assert.cs @@ -2244,7 +2244,7 @@ public static T ThrowsException(Action action, string message, params object[ public static async Task ThrowsExceptionAsync(Func action) where T : Exception { - return await ThrowsExceptionAsync(action, string.Empty, null); + return await ThrowsExceptionAsync(action, string.Empty, null).ConfigureAwait(false); } /// @@ -2266,7 +2266,7 @@ public static async Task ThrowsExceptionAsync(Func action) public static async Task ThrowsExceptionAsync(Func action, string message) where T : Exception { - return await ThrowsExceptionAsync(action, message, null); + return await ThrowsExceptionAsync(action, message, null).ConfigureAwait(false); } /// @@ -2305,7 +2305,7 @@ public static async Task ThrowsExceptionAsync(Func action, string me try { - await action(); + await action().ConfigureAwait(false); } catch (Exception ex) { diff --git a/test/UnitTests/MSTest.Core.Unit.Tests/Assertions/AssertTests.cs b/test/UnitTests/MSTest.Core.Unit.Tests/Assertions/AssertTests.cs index 6cabbc06ce..effd1393d9 100644 --- a/test/UnitTests/MSTest.Core.Unit.Tests/Assertions/AssertTests.cs +++ b/test/UnitTests/MSTest.Core.Unit.Tests/Assertions/AssertTests.cs @@ -71,12 +71,12 @@ public async Task ThrowsExceptionAsyncShouldNotThrowAssertionOnRightException() Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync( async () => { - await Task.Delay(5); + await Task.Delay(5).ConfigureAwait(false); throw new ArgumentException(); }); // Should not throw an exception. - await t; + await t.ConfigureAwait(false); } [TestMethod] @@ -85,7 +85,7 @@ public void ThrowsExceptionAsyncShouldThrowAssertionOnNoException() Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync( async () => { - await Task.Delay(5); + await Task.Delay(5).ConfigureAwait(false); }); var ex = ActionUtility.PerformActionAndReturnException(() => t.Wait()); @@ -104,7 +104,7 @@ public void ThrowsExceptionAsyncShouldThrowAssertionOnWrongException() Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync( async () => { - await Task.Delay(5); + await Task.Delay(5).ConfigureAwait(false); throw new FormatException(); }); var ex = ActionUtility.PerformActionAndReturnException(() => t.Wait()); @@ -124,7 +124,7 @@ public void ThrowsExceptionAsyncWithMessageShouldThrowAssertionOnNoException() Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync( async () => { - await Task.Delay(5); + await Task.Delay(5).ConfigureAwait(false); }, "The world is not on fire."); var ex = ActionUtility.PerformActionAndReturnException(() => t.Wait()); @@ -144,7 +144,7 @@ public void ThrowsExceptionAsyncWithMessageShouldThrowAssertionOnWrongException( Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync( async () => { - await Task.Delay(5); + await Task.Delay(5).ConfigureAwait(false); throw new FormatException(); }, "Happily ever after."); @@ -175,7 +175,7 @@ public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowOnNullMessage() { Action a = () => { - Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync(async () => { await Task.FromResult(true); }, null, null); + Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync(async () => { await Task.FromResult(true).ConfigureAwait(false); }, null, null); t.Wait(); }; ActionUtility.ActionShouldThrowInnerExceptionOfType(a, typeof(ArgumentNullException)); @@ -187,7 +187,7 @@ public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowAssertionOnNoExce Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync( async () => { - await Task.Delay(5); + await Task.Delay(5).ConfigureAwait(false); }, "The world is not on fire {0}.{1}-{2}.", "ta", @@ -210,7 +210,7 @@ public void ThrowsExceptionAsyncWithMessageAndParamsShouldThrowAssertionOnWrongE Task t = TestFrameworkV2.Assert.ThrowsExceptionAsync( async () => { - await Task.Delay(5); + await Task.Delay(5).ConfigureAwait(false); throw new FormatException(); }, "Happily ever after. {0} {1}.", diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/MethodInfoExtensionsTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/MethodInfoExtensionsTests.cs index c9d27f5e42..ae9adf8f61 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/MethodInfoExtensionsTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Extensions/MethodInfoExtensionsTests.cs @@ -454,7 +454,7 @@ public bool DummyMethod(int x, int y) public async Task DummyAsyncMethod(int x, int y) { - await DummyAsyncMethodBody(x, y); + await DummyAsyncMethodBody(x, y).ConfigureAwait(false); } public void PublicMethodWithParameters(int x, int y) @@ -485,7 +485,7 @@ public static void PublicStaticMethodWithTC(UTFExtension.TestContext tc) public static async Task PublicStaticAsyncTaskMethodWithTC(UTFExtension.TestContext tc) { - await Task.FromResult(true); + await Task.FromResult(true).ConfigureAwait(false); } public static Task PublicStaticNonAsyncTaskMethodWithTC(UTFExtension.TestContext tc) @@ -495,7 +495,7 @@ public static Task PublicStaticNonAsyncTaskMethodWithTC(UTFExtension.TestContext public static async void PublicStaticAsyncVoidMethodWithTC(UTFExtension.TestContext tc) { - await Task.FromResult(true); + await Task.FromResult(true).ConfigureAwait(false); } public static int PublicStaticMethodReturningInt() @@ -505,12 +505,12 @@ public static int PublicStaticMethodReturningInt() public static async Task PublicStaticAsyncTaskMethod() { - await Task.FromResult(true); + await Task.FromResult(true).ConfigureAwait(false); } public static async void PublicStaticAsyncVoidMethod() { - await Task.FromResult(true); + await Task.FromResult(true).ConfigureAwait(false); } public static Task PublicStaticNonAsyncTaskMethod() @@ -539,12 +539,12 @@ public int PublicMethodReturningInt() public async Task PublicAsyncTaskMethod() { - await Task.FromResult(true); + await Task.FromResult(true).ConfigureAwait(false); } public async void PublicAsyncVoidMethod() { - await Task.FromResult(true); + await Task.FromResult(true).ConfigureAwait(false); } public Task PublicNonAsyncTaskMethod() From e19a83dedd85349d3e03db2e8edbbe87968d4d87 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 12:57:03 +0200 Subject: [PATCH 17/23] RCS1235 Optimize 'string.Compare' call. --- src/Adapter/MSTest.CoreAdapter/MSTestDiscoverer.cs | 2 +- .../netstandard1.3/Services/ns13MSTestAdapterSettings.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Adapter/MSTest.CoreAdapter/MSTestDiscoverer.cs b/src/Adapter/MSTest.CoreAdapter/MSTestDiscoverer.cs index 8179dd273d..5ccfab7184 100644 --- a/src/Adapter/MSTest.CoreAdapter/MSTestDiscoverer.cs +++ b/src/Adapter/MSTest.CoreAdapter/MSTestDiscoverer.cs @@ -80,7 +80,7 @@ internal bool AreValidSources(IEnumerable sources) source => PlatformServiceProvider.Instance.TestSource.ValidSourceExtensions.Any( extension => - string.Compare(Path.GetExtension(source), extension, StringComparison.OrdinalIgnoreCase) == 0)); + string.Equals(Path.GetExtension(source), extension, StringComparison.OrdinalIgnoreCase))); } } } diff --git a/src/Adapter/PlatformServices.Shared/netstandard1.3/Services/ns13MSTestAdapterSettings.cs b/src/Adapter/PlatformServices.Shared/netstandard1.3/Services/ns13MSTestAdapterSettings.cs index 00b2fb7945..e6ebf63883 100644 --- a/src/Adapter/PlatformServices.Shared/netstandard1.3/Services/ns13MSTestAdapterSettings.cs +++ b/src/Adapter/PlatformServices.Shared/netstandard1.3/Services/ns13MSTestAdapterSettings.cs @@ -282,7 +282,7 @@ private void ReadAssemblyResolutionPath(XmlReader reader) { while (reader.NodeType == XmlNodeType.Element) { - if (string.Compare("Directory", reader.Name, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals("Directory", reader.Name, StringComparison.OrdinalIgnoreCase)) { string recursiveAttribute = reader.GetAttribute("includeSubDirectories"); @@ -292,7 +292,7 @@ private void ReadAssemblyResolutionPath(XmlReader reader) if (!string.IsNullOrEmpty(path)) { // Do we have to look in sub directory for dependent dll. - var includeSubDirectories = string.Compare(recursiveAttribute, "true", StringComparison.OrdinalIgnoreCase) == 0; + var includeSubDirectories = string.Equals(recursiveAttribute, "true", StringComparison.OrdinalIgnoreCase); this.SearchDirectories.Add(new RecursiveDirectoryPath(path, includeSubDirectories)); } } From fcbc2181a8ced029095f69cd97918a6323928f88 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 12:57:31 +0200 Subject: [PATCH 18/23] RCS1235 Optimize 'Debug.Assert' call. --- src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs b/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs index 09ce562979..af2a6fe54a 100644 --- a/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs +++ b/src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs @@ -395,7 +395,7 @@ private Assembly OnResolveInternal(object senderAppDomain, ResolveEventArgs args { if (string.IsNullOrEmpty(args?.Name)) { - Debug.Assert(false, "AssemblyResolver.OnResolve: args.Name is null or empty."); + Debug.Fail("AssemblyResolver.OnResolve: args.Name is null or empty."); return null; } From a007801a8b6c12506c0b8324a2041abf70511789 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 20:51:39 +0200 Subject: [PATCH 19/23] RCS1197 Optimize StringBuilder.Append call. --- .../MSTest.CoreAdapter/Execution/StackTraceHelper.cs | 10 ++++------ src/TestFramework/MSTest.Core/Internal/UtfHelper.cs | 5 ++--- .../Discovery/AssemblyEnumeratorTests.cs | 10 ++++------ 3 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs b/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs index 6b7fded5e5..611abc2855 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs @@ -97,13 +97,12 @@ internal static StackTraceInformation GetStackTraceInformation(Exception ex) bool first = true; while (stackTraces.Count != 0) { - result.Append( - string.Format( + result.AppendFormat( CultureInfo.CurrentCulture, "{0} {1}{2}", first ? string.Empty : (Resource.UTA_EndOfInnerExceptionTrace + Environment.NewLine), stackTraces.Pop(), - Environment.NewLine)); + Environment.NewLine); first = false; } @@ -179,13 +178,12 @@ internal static string GetExceptionMessage(Exception ex) msg = string.Format(CultureInfo.CurrentCulture, Resource.UTF_FailedToGetExceptionMessage, curException.GetType()); } - result.Append( - string.Format( + result.AppendFormat( CultureInfo.CurrentCulture, "{0}{1}: {2}", first ? string.Empty : " ---> ", curException.GetType(), - msg)); + msg); first = false; } diff --git a/src/TestFramework/MSTest.Core/Internal/UtfHelper.cs b/src/TestFramework/MSTest.Core/Internal/UtfHelper.cs index 8d5dec5cf3..6797597eb1 100644 --- a/src/TestFramework/MSTest.Core/Internal/UtfHelper.cs +++ b/src/TestFramework/MSTest.Core/Internal/UtfHelper.cs @@ -46,13 +46,12 @@ internal static string GetExceptionMsg(Exception ex) curException.GetType()); } - result.Append( - string.Format( + result.AppendFormat( CultureInfo.CurrentCulture, "{0}{1}: {2}", first ? string.Empty : " ---> ", curException.GetType(), - msg)); + msg); first = false; } diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs index 7040106c65..119edbe000 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/Discovery/AssemblyEnumeratorTests.cs @@ -196,18 +196,16 @@ public void GetLoadExceptionDetailsShouldReturnLoaderExceptionMessagesForMoreTha new Exception[] { loaderException1, loaderException2 }); StringBuilder errorDetails = new StringBuilder(); - errorDetails.AppendLine( - string.Format( + errorDetails.AppendFormat( CultureInfo.CurrentCulture, Resource.EnumeratorLoadTypeErrorFormat, loaderException1.GetType(), - loaderException1.Message)); - errorDetails.AppendLine( - string.Format( + loaderException1.Message).AppendLine(); + errorDetails.AppendFormat( CultureInfo.CurrentCulture, Resource.EnumeratorLoadTypeErrorFormat, loaderException2.GetType(), - loaderException2.Message)); + loaderException2.Message).AppendLine(); Assert.AreEqual(errorDetails.ToString(), this.assemblyEnumerator.GetLoadExceptionDetails(exceptions)); } From e164c36af714c3205ee950fdb9123266842b6c90 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 20:54:24 +0200 Subject: [PATCH 20/23] RCS1247 Fix documentation comment tag. --- .../PlatformServices.Interface/ObjectModel/ITestMethod.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Adapter/PlatformServices.Interface/ObjectModel/ITestMethod.cs b/src/Adapter/PlatformServices.Interface/ObjectModel/ITestMethod.cs index 5fa8b3a2b0..abd883c7cc 100644 --- a/src/Adapter/PlatformServices.Interface/ObjectModel/ITestMethod.cs +++ b/src/Adapter/PlatformServices.Interface/ObjectModel/ITestMethod.cs @@ -39,7 +39,7 @@ public interface ITestMethod /// Gets the fully specified type name metadata format. /// /// - /// NamespaceA.NamespaceB.ClassName`1+InnerClass`2 + /// NamespaceA.NamespaceB.ClassName`1+InnerClass`2 /// string ManagedTypeName { get; } @@ -47,7 +47,7 @@ public interface ITestMethod /// Gets the fully specified method name metadata format. /// /// - /// MethodName`2(ParamTypeA,ParamTypeB,...) + /// MethodName`2(ParamTypeA,ParamTypeB,...) /// string ManagedMethodName { get; } From 2467bd967cb4704fc860a5f29983707304de399b Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 21:01:11 +0200 Subject: [PATCH 21/23] RCS1192 Unnecessary usage of verbatim string literal. --- test/E2ETests/Automation.CLI/CLITestBase.cs | 4 ++-- .../MSTestSettingsTests.cs | 2 +- .../netstandard1.3/Services/ns13TestDeploymentTests.cs | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/E2ETests/Automation.CLI/CLITestBase.cs b/test/E2ETests/Automation.CLI/CLITestBase.cs index 3624c7c89e..ec67f62064 100644 --- a/test/E2ETests/Automation.CLI/CLITestBase.cs +++ b/test/E2ETests/Automation.CLI/CLITestBase.cs @@ -20,7 +20,7 @@ public class CLITestBase private const string PackagesFolder = "packages"; // This value is automatically updated by "build.ps1" script. - private const string TestPlatformCLIPackage = @"Microsoft.TestPlatform.16.9.1"; + private const string TestPlatformCLIPackage = "Microsoft.TestPlatform.16.9.1"; private const string VstestConsoleRelativePath = @"tools\net451\Common7\IDE\Extensions\TestPlatform\vstest.console.exe"; private static VsTestConsoleWrapper vsTestConsoleWrapper; @@ -227,7 +227,7 @@ public void ValidateFailedTestsContain(string source, bool validateStackTraceInf { if (string.IsNullOrWhiteSpace(testFound.ErrorStackTrace)) { - Assert.Fail($@"The test failure {testFound.DisplayName ?? testFound.TestCase.FullyQualifiedName} with message {testFound.ErrorMessage} lacks stacktrace."); + Assert.Fail($"The test failure {testFound.DisplayName ?? testFound.TestCase.FullyQualifiedName} with message {testFound.ErrorMessage} lacks stacktrace."); } // Verify stack information as well. diff --git a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs index 8c21743e2a..752487788e 100644 --- a/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs +++ b/test/UnitTests/MSTest.CoreAdapter.Unit.Tests/MSTestSettingsTests.cs @@ -600,7 +600,7 @@ public void GetSettingsShouldOnlyPassTheElementSubTreeToPlatformService() "; - string expectedrunSettingxml = @"True"; + string expectedrunSettingxml = "True"; string observedxml = null; this.testablePlatformServiceProvider.MockSettingsProvider.Setup(sp => sp.Load(It.IsAny())) diff --git a/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs b/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs index 79542d4972..042d8b6fe4 100644 --- a/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs +++ b/test/UnitTests/PlatformServices.Shared.Unit.Tests/netstandard1.3/Services/ns13TestDeploymentTests.cs @@ -128,7 +128,7 @@ public void CleanupShouldNotDeleteDirectoriesIfRunDirectoiresIsNull() public void CleanupShouldNotDeleteDirectoriesIfRunSettingsSpecifiesSo() { string runSettingxml = - @"False"; + "False"; StringReader stringReader = new StringReader(runSettingxml); XmlReader reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); MSTestSettingsProvider mstestSettingsProvider = new MSTestSettingsProvider(); @@ -217,7 +217,7 @@ public void DeployShouldReturnFalseWhenDeploymentEnabledSetToFalseButHasDeployme this.mockFileUtility.Object); string runSettingxml = - @"False"; + "False"; StringReader stringReader = new StringReader(runSettingxml); XmlReader reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); MSTestSettingsProvider mstestSettingsProvider = new MSTestSettingsProvider(); @@ -241,7 +241,7 @@ public void DeployShouldReturnFalseWhenDeploymentEnabledSetToFalseAndHasNoDeploy this.mockFileUtility.Object); string runSettingxml = - @"False"; + "False"; StringReader stringReader = new StringReader(runSettingxml); XmlReader reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); MSTestSettingsProvider mstestSettingsProvider = new MSTestSettingsProvider(); @@ -265,7 +265,7 @@ public void DeployShouldReturnFalseWhenDeploymentEnabledSetToTrueButHasNoDeploym this.mockFileUtility.Object); string runSettingxml = - @"True"; + "True"; StringReader stringReader = new StringReader(runSettingxml); XmlReader reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); MSTestSettingsProvider mstestSettingsProvider = new MSTestSettingsProvider(); @@ -297,7 +297,7 @@ public void DeployShouldReturnTrueWhenDeploymentEnabledSetToTrueAndHasDeployment this.mockFileUtility.Object); string runSettingxml = - @"True"; + "True"; StringReader stringReader = new StringReader(runSettingxml); XmlReader reader = XmlReader.Create(stringReader, XmlRunSettingsUtilities.ReaderSettings); MSTestSettingsProvider mstestSettingsProvider = new MSTestSettingsProvider(); From fcc6480aeaa8e28e7f60cd36e19095f1b9622aa9 Mon Sep 17 00:00:00 2001 From: Maximilian Chaplin Date: Mon, 5 Apr 2021 21:14:48 +0200 Subject: [PATCH 22/23] RCS1113 Use 'string.IsNullOrEmpty' method. --- src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs b/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs index 611abc2855..d9cd047216 100644 --- a/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs +++ b/src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs @@ -120,7 +120,7 @@ internal static StackTraceInformation GetStackTraceInformation(Exception ex) /// internal static string TrimStackTrace(string stackTrace) { - Debug.Assert(stackTrace != null && stackTrace.Length > 0, "stack trace should be non-empty."); + Debug.Assert(!string.IsNullOrEmpty(stackTrace), "stack trace should be non-empty."); StringBuilder result = new StringBuilder(stackTrace.Length); string[] stackFrames = Regex.Split(stackTrace, Environment.NewLine); From 56fa1659f2f3ca16c81b79443e189f79ff067761 Mon Sep 17 00:00:00 2001 From: Medeni Baykal <433724+Haplois@users.noreply.github.com> Date: Thu, 8 Apr 2021 11:46:46 +0200 Subject: [PATCH 23/23] Fixed `build.ps1` to accommodate the refactoring. --- scripts/Build.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/Build.ps1 b/scripts/Build.ps1 index 2f6aa55ed4..fd060482f6 100644 --- a/scripts/Build.ps1 +++ b/scripts/Build.ps1 @@ -312,7 +312,7 @@ function Replace-InFile($File, $RegEx, $ReplaceWith) { function Sync-PackageVersions { $versionsRegex = '(?mi)<(TestPlatformVersion.*?)>(.*?)<\/TestPlatformVersion>' $packageRegex = '(?mi)