Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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,130 @@ 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(GetComparedType(operation, expectedOrNotExpectedParameterName));

/// <summary>
/// Returns <see langword="true"/> when the invoked <c>Assert</c> overload is passed a non-default
/// <see cref="System.Collections.Generic.IEqualityComparer{T}"/> argument, in which case the comparison can
/// return any result and must not be treated as an always-true/always-false condition. A <see langword="null"/>
/// comparer is treated by MSTest as <see cref="System.Collections.Generic.EqualityComparer{T}.Default"/>, so it
/// does not change the equality semantics and is not considered a custom comparer here.
/// </summary>
internal static bool HasNonDefaultEqualityComparerArgument(IInvocationOperation operation)
{
IParameterSymbol? comparerParameter = operation.TargetMethod.Parameters.FirstOrDefault(static parameter =>
parameter.Type is INamedTypeSymbol
{
Name: "IEqualityComparer",
ContainingNamespace: { Name: "Generic", ContainingNamespace: { Name: "Collections", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } } },
});

if (comparerParameter is null)
{
return false;
}

// A null (or omitted) comparer is equivalent to EqualityComparer<T>.Default, so it does not change the
// equality semantics. Any other comparer (including a non-constant one) can return an arbitrary result.
// Strip only built-in conversions so a user-defined conversion cannot hide a null source that it turns
// into a non-null comparer.
return GetRawArgumentValueWithName(operation, comparerParameter.Name)?.WalkDownBuiltInConversion() is { } comparerArgument
&& comparerArgument.ConstantValue is not { HasValue: true, Value: null };
}
Comment thread
Evangelink marked this conversation as resolved.
Resolved

/// <summary>
/// Gets the type <c>T</c> whose <see cref="System.Collections.Generic.EqualityComparer{T}.Default"/> the
/// invoked <c>Assert.AreEqual</c>/<c>AreNotEqual</c> overload uses to compare the values. For the generic
/// overloads this is the method type argument (not the operand's static type, which may differ through an
/// implicit conversion); for non-generic overloads it is the declared parameter type.
/// </summary>
private static ITypeSymbol? GetComparedType(IInvocationOperation operation, string expectedOrNotExpectedParameterName)
=> operation.TargetMethod.TypeArguments is [{ } typeArgument]
? typeArgument
: operation.TargetMethod.Parameters.FirstOrDefault(parameter => parameter.Name == expectedOrNotExpectedParameterName)?.Type;

/// <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)"/>. Reflexivity can only be proven conservatively:
/// <list type="bullet">
/// <item>primitives, <see cref="string"/>, and enums have reflexive built-in equality;</item>
/// <item>arrays and sealed reference types without customized equality use reflexive reference equality;</item>
/// <item>a non-sealed reference type, an interface, or a type parameter can hold an instance whose overridden
/// equality is not reflexive;</item>
/// <item>a non-primitive value type relying on the default field-based <c>ValueType.Equals</c> (or <c>Nullable&lt;T&gt;</c>,
/// which delegates to the underlying type) may compare a field whose equality is not reflexive, and a custom struct
/// override could itself be non-reflexive.</item>
/// </list>
/// </remarks>
private static bool IsProvablyReflexiveSelfEquality(ITypeSymbol? type)
{
if (type is null || type.TypeKind is TypeKind.TypeParameter)
{
return false;
}

if (type.IsReferenceType)
{
// Arrays always use reflexive reference equality (they never override Equals). Any other reference
// type is only provable when its runtime type is known exactly (sealed) and it does not customize
// equality with a potentially non-reflexive override. Non-sealed types, interfaces, and object can
// hold a derived instance whose overridden Equals is not reflexive.
return type.TypeKind is TypeKind.Array
|| (type.IsSealed && !HasUserDefinedEquality(type));
}

// Value types: only primitives (and enums) have provably reflexive built-in equality. Nullable<T> and
// structs relying on the default (or a custom) equality could be non-reflexive.
return type.OriginalDefinition.SpecialType is not SpecialType.System_Nullable_T
&& (type.SpecialType is not SpecialType.None || type.TypeKind is TypeKind.Enum);
}

private static bool HasUserDefinedEquality(ITypeSymbol type)
{
// string overrides Equals but its equality is reflexive; it is handled as a primitive by the caller.
if (type.SpecialType != SpecialType.None)
{
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(nameof(object.Equals)))
{
if (member is IMethodSymbol { IsOverride: true, Parameters: [{ Type.SpecialType: SpecialType.System_Object }] })
{
return true;
}
}
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.HasNonDefaultEqualityComparerArgument(operation)
&& AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.ExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.NotEqual,
"AreNotEqual" => !AssertConditionAnalyzerHelper.HasNonDefaultEqualityComparerArgument(operation)
&& (AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.Equal
|| AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActualWithBuiltInEquality(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName)),
"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.HasNonDefaultEqualityComparerArgument(operation)
&& (AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.ExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.Equal
|| AssertConditionAnalyzerHelper.HasIdenticalExpectedAndActualWithBuiltInEquality(operation, AssertConditionAnalyzerHelper.ExpectedParameterName)),
"AreNotEqual" => !AssertConditionAnalyzerHelper.HasNonDefaultEqualityComparerArgument(operation)
&& AssertConditionAnalyzerHelper.GetEqualityStatus(operation, AssertConditionAnalyzerHelper.NotExpectedParameterName) == AssertConditionAnalyzerHelper.EqualityStatus.NotEqual,
"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,171 @@ 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);
}

[TestMethod]
public async Task WhenAssertAreNotEqualIsPassedSameLocalWithNullComparer_Diagnostic()
{
// MSTest treats a null comparer as EqualityComparer<T>.Default, so the self-comparison is still
// provably always false and must be flagged.
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, (IEqualityComparer<int>)null)|];
}
}
""";
string fixedCode = """
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestMethod()
{
int x = 1;
Assert.Fail();
}
}
""";

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