Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,101 @@ internal static bool HasIdenticalExpectedAndActual(IInvocationOperation operatio
&& GetRawArgumentValueWithName(operation, ActualParameterName) is { } actualArgument
&& expectedArgument.IsEquivalentReferenceTo(actualArgument);

/// <summary>
Comment thread
Evangelink marked this conversation as resolved.
Resolved
/// Returns <see langword="true"/> when <c>expected</c>/<c>notExpected</c> and <c>actual</c> are the
/// same side-effect-free reference (see <see cref="HasIdenticalExpectedAndActual"/>) <em>and</em> a
/// self-comparison of that value using the default equality comparer is provably always equal.
/// </summary>
internal static bool HasIdenticalExpectedAndActualWithBuiltInEquality(IInvocationOperation operation, string expectedOrNotExpectedParameterName)
=> HasIdenticalExpectedAndActual(operation, expectedOrNotExpectedParameterName)
&& IsProvablyReflexiveSelfEquality(GetArgumentWithName(operation, expectedOrNotExpectedParameterName)?.Type);
Comment thread
Evangelink marked this conversation as resolved.
Resolved

/// <summary>
/// Returns <see langword="true"/> when the invoked <c>Assert</c> overload accepts a caller-supplied
/// <see cref="System.Collections.Generic.IEqualityComparer{T}"/>, in which case the comparison can
/// return any result and must not be treated as an always-true/always-false condition.
/// </summary>
internal static bool HasEqualityComparerParameter(IInvocationOperation operation)
=> operation.TargetMethod.Parameters.Any(static parameter =>
parameter.Type is INamedTypeSymbol
{
Name: "IEqualityComparer",
ContainingNamespace: { Name: "Generic", ContainingNamespace: { Name: "Collections", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } } },
});

/// <summary>
/// Returns <see langword="true"/> when a self-comparison of a value of <paramref name="type"/> using the
/// default equality comparer is provably always equal.
/// </summary>
/// <remarks>
/// <c>Assert.AreEqual</c>/<c>AreNotEqual</c> compare using <see cref="System.Collections.Generic.EqualityComparer{T}.Default"/>,
/// which dispatches to <see cref="System.IEquatable{T}"/><c>.Equals</c> when the type implements it, otherwise to the
/// virtual <see cref="object.Equals(object)"/>. The result is only provable when the runtime type is known exactly
/// (a value type or a sealed type) and that type does not customize equality with a potentially non-reflexive
/// override. A non-sealed reference type, an interface, or a type parameter can hold an instance whose overridden
/// equality is not reflexive, so nothing can be proven from the static type.
/// </remarks>
private static bool IsProvablyReflexiveSelfEquality(ITypeSymbol? type)
{
if (type is null)
{
return false;
}

// A type parameter can be substituted with a type whose equality is not reflexive.
if (type.TypeKind is TypeKind.TypeParameter)
{
return false;
}

// Arrays are non-sealed reference types but always use reflexive reference equality
// (they never override Equals), so a self-comparison is provably always equal.
if (type.TypeKind is TypeKind.Array)
{
return true;
}

// A non-sealed reference type (including object, base classes, and interfaces) can hold a derived
// instance whose overridden Equals is not reflexive. Only value types and sealed types have an
// exactly-known runtime type.
return type is not { IsReferenceType: true, IsSealed: false }
&& !HasUserDefinedEquality(type);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}

private static bool HasUserDefinedEquality(ITypeSymbol type)
{
// Primitives, enums, and other well-known types have reflexive, built-in equality.
if (type.SpecialType != SpecialType.None || type.TypeKind is TypeKind.Enum)
{
return false;
}

// The == operator is never consulted by EqualityComparer<T>.Default, so it is intentionally not checked here.
for (ITypeSymbol? current = type;
current is { SpecialType: not SpecialType.System_Object and not SpecialType.System_ValueType };
current = current.BaseType)
{
foreach (ISymbol member in current.GetMembers())
{
if (member is IMethodSymbol { IsOverride: true, Name: nameof(object.Equals), Parameters: [{ Type.SpecialType: SpecialType.System_Object }] })
{
return true;
}
}
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
Comment thread
Evangelink marked this conversation as resolved.
Resolved
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}

foreach (INamedTypeSymbol @interface in type.AllInterfaces)
{
if (@interface is { Name: "IEquatable", TypeArguments: [{ } typeArgument], ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } }
&& SymbolEqualityComparer.Default.Equals(typeArgument, type))
{
return true;
}
}
Comment thread
Evangelink marked this conversation as resolved.
Resolved

return false;
}

internal static IOperation? GetArgumentWithName(IInvocationOperation operation, string name)
=> operation.Arguments.FirstOrDefault(arg => arg.Parameter?.Name == name)?.Value.WalkDownConversion();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,11 @@ private static bool IsAlwaysFalse(IInvocationOperation operation)
{
"IsTrue" => AssertConditionAnalyzerHelper.GetConditionArgument(operation) is { ConstantValue: { HasValue: true, Value: false } },
"IsFalse" => AssertConditionAnalyzerHelper.GetConditionArgument(operation) is { ConstantValue: { HasValue: true, Value: true } },
"AreEqual" => AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.ExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.NotEqual,
"AreNotEqual" => AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.Equal
|| AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActual(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName),
"AreEqual" => !AssertConditionAnalyzerHelper.HasEqualityComparerParameter(operation)
&& AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.ExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.NotEqual,
"AreNotEqual" => !AssertConditionAnalyzerHelper.HasEqualityComparerParameter(operation)
&& (AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.Equal
|| AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActualWithBuiltInEquality(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName)),
Comment thread
Evangelink marked this conversation as resolved.
Resolved
"AreNotSame" => AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActual(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName),
"IsNotNull" => AssertConditionAnalyzerHelper.GetValueArgument(operation) is { ConstantValue: { HasValue: true, Value: null } },
"IsNull" => AssertConditionAnalyzerHelper.GetValueArgument(operation) is { } valueArgumentOperation && AssertConditionAnalyzerHelper.IsNotNullableType(valueArgumentOperation),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,11 @@ private static bool IsAlwaysTrue(IInvocationOperation operation)
{
"IsTrue" => AssertConditionAnalyzerHelper.GetConditionArgument(operation) is { ConstantValue: { HasValue: true, Value: true } },
"IsFalse" => AssertConditionAnalyzerHelper.GetConditionArgument(operation) is { ConstantValue: { HasValue: true, Value: false } },
"AreEqual" => AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.ExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.Equal
|| AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActual(operation, AssertConditionAnalyzerHelper.ExpectedParameterName),
"AreNotEqual" => AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.NotEqual,
"AreEqual" => !AssertConditionAnalyzerHelper.HasEqualityComparerParameter(operation)
&& (AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.ExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.Equal
|| AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActualWithBuiltInEquality(operation, AssertConditionAnalyzerHelper.ExpectedParameterName)),
"AreNotEqual" => !AssertConditionAnalyzerHelper.HasEqualityComparerParameter(operation)
&& AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.NotEqual,
Comment thread
Evangelink marked this conversation as resolved.
Resolved
"AreSame" => AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActual(operation, AssertConditionAnalyzerHelper.ExpectedParameterName),
"IsNull" => AssertConditionAnalyzerHelper.GetValueArgument(operation) is { ConstantValue: { HasValue: true, Value: null } },
"IsNotNull" => AssertConditionAnalyzerHelper.GetValueArgument(operation) is { } valueArgumentOperation && AssertConditionAnalyzerHelper.IsNotNullableType(valueArgumentOperation),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1951,4 +1951,132 @@ private sealed class Wrapper

await VerifyCS.VerifyCodeFixAsync(code, code);
}

[TestMethod]
public async Task WhenAssertAreNotEqualIsPassedSameLocalWithOverriddenEquals_NoDiagnostic()
{
// The type overrides object.Equals, so Assert.AreNotEqual routes through user code and the
// self-comparison is a legitimate way to exercise the equality contract (see issue #9972).
string code = """
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestMethod()
{
var x = new MyType();
Assert.AreNotEqual(x, x);
}

private sealed class MyType
{
public override bool Equals(object obj) => false;
public override int GetHashCode() => 0;
}
}
""";

await VerifyCS.VerifyCodeFixAsync(code, code);
}

[TestMethod]
public async Task WhenAssertAreNotEqualIsPassedSameLocalWithoutCustomEquality_Diagnostic()
{
string code = """
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestMethod()
{
var x = new MyType();
[|Assert.AreNotEqual(x, x)|];
}

private sealed class MyType
{
}
}
""";
string fixedCode = """
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestMethod()
{
var x = new MyType();
Assert.Fail();
}

private sealed class MyType
{
}
}
""";

await VerifyCS.VerifyCodeFixAsync(code, fixedCode);
}

[TestMethod]
public async Task WhenAssertAreEqualIsPassedNonEqualConstantsWithCustomComparer_NoDiagnostic()
{
// A caller-supplied comparer can return any result, so the comparison is not provably always false.
string code = """
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestMethod()
{
Assert.AreEqual(1, 2, new AlwaysEqualComparer());
}

private sealed class AlwaysEqualComparer : IEqualityComparer<int>
{
public bool Equals(int x, int y) => true;
public int GetHashCode(int obj) => 0;
}
}
""";

await VerifyCS.VerifyCodeFixAsync(code, code);
}

[TestMethod]
public async Task WhenAssertAreNotEqualIsPassedSameLocalWithCustomComparer_NoDiagnostic()
{
string code = """
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestMethod()
{
int x = 1;
Assert.AreNotEqual(x, x, new AlwaysEqualComparer());
}

private sealed class AlwaysEqualComparer : IEqualityComparer<int>
{
public bool Equals(int x, int y) => true;
public int GetHashCode(int obj) => 0;
}
}
""";

await VerifyCS.VerifyCodeFixAsync(code, code);
}
}
Loading
Loading