diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs index 1336545d01..f6ba7d7089 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs @@ -46,8 +46,8 @@ internal static class WellKnownTypeNames public const string MicrosoftVisualStudioTestToolsUnitTestingWorkItemAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.WorkItemAttribute"; public const string System = "System"; - public const string SystemRuntimeInteropServicesRuntimeInformation = "System.Runtime.InteropServices.RuntimeInformation"; public const string SystemCollectionsGenericIEnumerable1 = "System.Collections.Generic.IEnumerable`1"; + public const string SystemCollectionsIDictionary = "System.Collections.IDictionary"; public const string SystemDescriptionAttribute = "System.ComponentModel.DescriptionAttribute"; public const string SystemFunc1 = "System.Func`1"; public const string SystemIAsyncDisposable = "System.IAsyncDisposable"; @@ -58,6 +58,7 @@ internal static class WellKnownTypeNames public const string SystemReflectionMethodInfo = "System.Reflection.MethodInfo"; public const string SystemRuntimeCompilerServicesCallerFilePathAttribute = "System.Runtime.CompilerServices.CallerFilePathAttribute"; public const string SystemRuntimeCompilerServicesCallerLineNumberAttribute = "System.Runtime.CompilerServices.CallerLineNumberAttribute"; + public const string SystemRuntimeInteropServicesRuntimeInformation = "System.Runtime.InteropServices.RuntimeInformation"; public const string SystemThreadingCancellationToken = "System.Threading.CancellationToken"; public const string SystemThreadingCancellationTokenSource = "System.Threading.CancellationTokenSource"; public const string SystemThreadingTasksTask = "System.Threading.Tasks.Task"; diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.Collection.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.Collection.cs index b5be1ed7aa..cc5ced3ffc 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.Collection.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.Collection.cs @@ -37,6 +37,47 @@ private static bool IsBCLCollectionType(ITypeSymbol type, INamedTypeSymbol objec i.OriginalDefinition.SpecialType == SpecialType.System_Collections_IEnumerable) && IsBCLSymbol(type, objectTypeSymbol); + /// + /// Returns when the invoked Contains method is the non-generic + /// (or an implementation of it). + /// That method checks for a matching key, whereas Assert.Contains enumerates the + /// dictionary (yielding items), so the two are not + /// equivalent and the code fix would silently change behavior. + /// + private static bool IsNonGenericDictionaryContains(IMethodSymbol containsMethod, INamedTypeSymbol? iDictionaryTypeSymbol) + { + if (iDictionaryTypeSymbol is null) + { + return false; + } + + INamedTypeSymbol containingType = containsMethod.ContainingType; + + // Direct call through the interface, e.g. 'IDictionary dict; dict.Contains(key)'. + if (SymbolEqualityComparer.Default.Equals(containingType.OriginalDefinition, iDictionaryTypeSymbol)) + { + return true; + } + + // Call through a concrete type that implements IDictionary (e.g. Hashtable), where the invoked + // 'Contains' is the implementation of 'IDictionary.Contains'. + if (!containingType.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i.OriginalDefinition, iDictionaryTypeSymbol))) + { + return false; + } + + foreach (IMethodSymbol dictionaryContains in iDictionaryTypeSymbol.GetMembers("Contains").OfType()) + { + if (containingType.FindImplementationForInterfaceMember(dictionaryContains) is IMethodSymbol implementation && + SymbolEqualityComparer.Default.Equals(implementation.OriginalDefinition, containsMethod.OriginalDefinition)) + { + return true; + } + } + + return false; + } + /// /// Returns when is one of , /// , or . @@ -69,6 +110,7 @@ private static CollectionCheckStatus RecognizeCollectionMethodCheck( IOperation operation, INamedTypeSymbol objectTypeSymbol, INamedTypeSymbol? enumerableTypeSymbol, + INamedTypeSymbol? iDictionaryTypeSymbol, out SyntaxNode? collectionExpression, out SyntaxNode? itemExpression, out SyntaxNode? comparerExpression) @@ -89,6 +131,17 @@ private static CollectionCheckStatus RecognizeCollectionMethodCheck( ITypeSymbol? enumerableElementType = invocation.TargetMethod.ContainingType.OriginalDefinition.AllInterfaces.FirstOrDefault( i => i.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)?.TypeArguments[0]; + if (enumerableElementType is null && IsNonGenericDictionaryContains(invocation.TargetMethod, iDictionaryTypeSymbol)) + { + // Non-generic 'System.Collections.IDictionary.Contains(object key)' checks for a matching *key*, + // whereas 'Assert.Contains' enumerates the dictionary (yielding 'DictionaryEntry' items). + // These have different semantics, so suggesting 'Assert.Contains' here would change behavior. + collectionExpression = null; + itemExpression = null; + comparerExpression = null; + return CollectionCheckStatus.Unknown; + } + if (enumerableElementType is null || enumerableElementType.Equals(containsParameterType, SymbolEqualityComparer.Default)) { // If enumerableElementType is null, we expect that this is a non-generic IEnumerable. So we simply report the diagnostic. diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.IsTrueIsFalse.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.IsTrueIsFalse.cs index 70ec333b30..eca644dc2f 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.IsTrueIsFalse.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.IsTrueIsFalse.cs @@ -16,7 +16,7 @@ namespace MSTest.Analyzers; public sealed partial class UseProperAssertMethodsAnalyzer { - private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext context, IOperation conditionArgument, bool isTrueInvocation, INamedTypeSymbol objectTypeSymbol, INamedTypeSymbol? enumerableTypeSymbol, INamedTypeSymbol? iComparableOfTSymbol) + private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext context, IOperation conditionArgument, bool isTrueInvocation, INamedTypeSymbol objectTypeSymbol, INamedTypeSymbol? enumerableTypeSymbol, INamedTypeSymbol? iComparableOfTSymbol, INamedTypeSymbol? iDictionaryTypeSymbol) { RoslynDebug.Assert(context.Operation is IInvocationOperation, "Expected IInvocationOperation."); @@ -107,7 +107,7 @@ private static void AnalyzeIsTrueOrIsFalseInvocation(OperationAnalysisContext co } // Check for collection method patterns: myCollection.Contains(...) - CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, objectTypeSymbol, enumerableTypeSymbol, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr, out SyntaxNode? comparerExpr); + CollectionCheckStatus collectionMethodStatus = RecognizeCollectionMethodCheck(conditionArgument, objectTypeSymbol, enumerableTypeSymbol, iDictionaryTypeSymbol, out SyntaxNode? collectionExpr, out SyntaxNode? itemExpr, out SyntaxNode? comparerExpr); if (collectionMethodStatus != CollectionCheckStatus.Unknown) { if (collectionMethodStatus == CollectionCheckStatus.Contains) diff --git a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs index 0b6a927639..dc2e1776f9 100644 --- a/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs @@ -267,12 +267,13 @@ public override void Initialize(AnalysisContext context) INamedTypeSymbol objectTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_Object); context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqEnumerable, out INamedTypeSymbol? enumerableTypeSymbol); INamedTypeSymbol? iComparableOfTSymbol = context.Compilation.GetTypeByMetadataName("System.IComparable`1"); + context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIDictionary, out INamedTypeSymbol? iDictionaryTypeSymbol); - context.RegisterOperationAction(context => AnalyzeInvocationOperation(context, assertTypeSymbol, objectTypeSymbol, enumerableTypeSymbol, iComparableOfTSymbol), OperationKind.Invocation); + context.RegisterOperationAction(context => AnalyzeInvocationOperation(context, assertTypeSymbol, objectTypeSymbol, enumerableTypeSymbol, iComparableOfTSymbol, iDictionaryTypeSymbol), OperationKind.Invocation); }); } - private static void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol assertTypeSymbol, INamedTypeSymbol objectTypeSymbol, INamedTypeSymbol? enumerableTypeSymbol, INamedTypeSymbol? iComparableOfTSymbol) + private static void AnalyzeInvocationOperation(OperationAnalysisContext context, INamedTypeSymbol assertTypeSymbol, INamedTypeSymbol objectTypeSymbol, INamedTypeSymbol? enumerableTypeSymbol, INamedTypeSymbol? iComparableOfTSymbol, INamedTypeSymbol? iDictionaryTypeSymbol) { var operation = (IInvocationOperation)context.Operation; IMethodSymbol targetMethod = operation.TargetMethod; @@ -289,11 +290,11 @@ private static void AnalyzeInvocationOperation(OperationAnalysisContext context, switch (targetMethod.Name) { case "IsTrue": - AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: true, objectTypeSymbol, enumerableTypeSymbol, iComparableOfTSymbol); + AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: true, objectTypeSymbol, enumerableTypeSymbol, iComparableOfTSymbol, iDictionaryTypeSymbol); break; case "IsFalse": - AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: false, objectTypeSymbol, enumerableTypeSymbol, iComparableOfTSymbol); + AnalyzeIsTrueOrIsFalseInvocation(context, firstArgument, isTrueInvocation: false, objectTypeSymbol, enumerableTypeSymbol, iComparableOfTSymbol, iDictionaryTypeSymbol); break; case "AreEqual": diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs index 884fb920ae..0894639edb 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/UseProperAssertMethodsAnalyzerTests.cs @@ -1395,6 +1395,38 @@ protected override int GetKeyForItem(int item) await VerifyCS.VerifyCodeFixAsync(code, code); } + [TestMethod] + public async Task WhenAssertIsTrueOrIsFalseWithNonGenericIDictionaryContains_NoDiagnostic() + { + // 'System.Collections.IDictionary.Contains(object)' checks for a matching *key*, whereas + // 'Assert.Contains' enumerates the dictionary (yielding 'DictionaryEntry' items). These have + // different semantics, so the analyzer must not suggest 'Assert.Contains' here. + // See https://github.com/microsoft/testfx/issues/9966. + string code = """ + using System.Collections; + using System.Collections.Generic; + + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTests + { + [TestMethod] + public void Contains() + { + IDictionary dict = new Dictionary() { { "a", "b" } }; + Assert.IsTrue(dict.Contains("a")); + Assert.IsFalse(dict.Contains("a")); + + Hashtable hashtable = new Hashtable(); + Assert.IsTrue(hashtable.Contains("a")); + Assert.IsFalse(hashtable.Contains("a")); + } + } + """; + await VerifyCS.VerifyCodeFixAsync(code, code); + } + #region New test cases for string methods [TestMethod]