Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Analyzers/MSTest.Analyzers/Helpers/WellKnownTypeNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Comment thread
Evangelink marked this conversation as resolved.
Resolved
public const string SystemDescriptionAttribute = "System.ComponentModel.DescriptionAttribute";
public const string SystemFunc1 = "System.Func`1";
public const string SystemIAsyncDisposable = "System.IAsyncDisposable";
Expand All @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,47 @@ private static bool IsBCLCollectionType(ITypeSymbol type, INamedTypeSymbol objec
i.OriginalDefinition.SpecialType == SpecialType.System_Collections_IEnumerable) &&
IsBCLSymbol(type, objectTypeSymbol);

/// <summary>
/// Returns <see langword="true"/> when the invoked <c>Contains</c> method is the non-generic
/// <see cref="System.Collections.IDictionary.Contains(object)"/> (or an implementation of it).
/// That method checks for a matching <em>key</em>, whereas <c>Assert.Contains</c> enumerates the
/// dictionary (yielding <see cref="System.Collections.DictionaryEntry"/> items), so the two are not
/// equivalent and the code fix would silently change behavior.
/// </summary>
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<IMethodSymbol>())
{
if (containingType.FindImplementationForInterfaceMember(dictionaryContains) is IMethodSymbol implementation &&
SymbolEqualityComparer.Default.Equals(implementation.OriginalDefinition, containsMethod.OriginalDefinition))
{
return true;
}
}
Comment thread
Evangelink marked this conversation as resolved.
Resolved

return false;
}

/// <summary>
/// Returns <see langword="true"/> when <paramref name="type"/> is one of <see cref="System.Span{T}"/>,
/// <see cref="System.ReadOnlySpan{T}"/>, <see cref="System.Memory{T}"/> or <see cref="System.ReadOnlyMemory{T}"/>.
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.");

Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>() { { "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]
Expand Down
Loading