diff --git a/src/Analyzers/MSTest.Analyzers/Helpers/AssertConditionAnalyzerHelper.cs b/src/Analyzers/MSTest.Analyzers/Helpers/AssertConditionAnalyzerHelper.cs index 695caa312e8..a013a7f7963 100644 --- a/src/Analyzers/MSTest.Analyzers/Helpers/AssertConditionAnalyzerHelper.cs +++ b/src/Analyzers/MSTest.Analyzers/Helpers/AssertConditionAnalyzerHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.CodeAnalysis; @@ -28,6 +28,139 @@ internal static bool HasIdenticalExpectedAndActual(IInvocationOperation operatio && GetRawArgumentValueWithName(operation, ActualParameterName) is { } actualArgument && expectedArgument.IsEquivalentReferenceTo(actualArgument); + /// + /// Returns when expected/notExpected and actual are the + /// same side-effect-free reference (see ) and a + /// self-comparison of that value using the default equality comparer is provably always equal. + /// + internal static bool HasIdenticalExpectedAndActualWithBuiltInEquality(IInvocationOperation operation, string expectedOrNotExpectedParameterName) + => HasIdenticalExpectedAndActual(operation, expectedOrNotExpectedParameterName) + && IsProvablyReflexiveSelfEquality(GetComparedType(operation, expectedOrNotExpectedParameterName)); + + /// + /// Returns when the invoked Assert overload is passed a non-default + /// argument, in which case the comparison can + /// return any result and must not be treated as an always-true/always-false condition. A + /// comparer is treated by MSTest as , so it + /// does not change the equality semantics and is not considered a custom comparer here. + /// + 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 not { Type: INamedTypeSymbol { TypeArguments: [{ } comparerElementType] } }) + { + return false; + } + + // A null (or omitted) comparer, or an explicit EqualityComparer.Default, is equivalent to the default + // comparer and 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. + IOperation? comparerArgument = GetRawArgumentValueWithName(operation, comparerParameter.Name)?.WalkDownBuiltInConversion(); + return comparerArgument is not null + && comparerArgument.ConstantValue is not { HasValue: true, Value: null } + && !IsDefaultEqualityComparerReference(comparerArgument, comparerElementType); + } + + // EqualityComparer.Default is only the default comparer for T when X is T. IEqualityComparer is + // contravariant, so e.g. EqualityComparer.Default can be passed as IEqualityComparer, in + // which case it is a non-default comparer that may return a different result. + private static bool IsDefaultEqualityComparerReference(IOperation operation, ITypeSymbol comparerElementType) + => operation is IPropertyReferenceOperation { Property: { Name: "Default", ContainingType: INamedTypeSymbol { Name: "EqualityComparer", TypeArguments: [{ } elementType], ContainingNamespace: { Name: "Generic", ContainingNamespace: { Name: "Collections", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } } } } } } + && SymbolEqualityComparer.Default.Equals(elementType, comparerElementType); + + /// + /// Gets the type T whose the + /// invoked Assert.AreEqual/AreNotEqual 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. + /// + private static ITypeSymbol? GetComparedType(IInvocationOperation operation, string expectedOrNotExpectedParameterName) + => operation.TargetMethod.TypeArguments is [{ } typeArgument] + ? typeArgument + : operation.TargetMethod.Parameters.FirstOrDefault(parameter => parameter.Name == expectedOrNotExpectedParameterName)?.Type; + + /// + /// Returns when a self-comparison of a value of using the + /// default equality comparer is provably always equal. + /// + /// + /// Assert.AreEqual/AreNotEqual compare using , + /// which dispatches to .Equals when the type implements it, otherwise to the + /// virtual . Reflexivity can only be proven conservatively: + /// + /// primitives, , and enums have reflexive built-in equality; + /// arrays and sealed reference types without customized equality use reflexive reference equality; + /// a non-sealed reference type, an interface, or a type parameter can hold an instance whose overridden + /// equality is not reflexive; + /// a non-primitive value type relying on the default field-based ValueType.Equals (or Nullable<T>, + /// 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. + /// + /// + 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 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.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; + } + } + } + + 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; + } + } + + return false; + } + internal static IOperation? GetArgumentWithName(IInvocationOperation operation, string name) => operation.Arguments.FirstOrDefault(arg => arg.Parameter?.Name == name)?.Value.WalkDownConversion(); diff --git a/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs index 263131a2725..12b9e8ea61d 100644 --- a/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/PreferAssertFailOverAlwaysFalseConditionsAnalyzer.cs @@ -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), diff --git a/src/Analyzers/MSTest.Analyzers/ReviewAlwaysTrueAssertConditionAnalyzer.cs b/src/Analyzers/MSTest.Analyzers/ReviewAlwaysTrueAssertConditionAnalyzer.cs index ed2438ee611..4dfe5b3d40c 100644 --- a/src/Analyzers/MSTest.Analyzers/ReviewAlwaysTrueAssertConditionAnalyzer.cs +++ b/src/Analyzers/MSTest.Analyzers/ReviewAlwaysTrueAssertConditionAnalyzer.cs @@ -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), diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs index ec98e934d36..7eaafadd562 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/PreferAssertFailOverAlwaysFalseConditionsAnalyzerTests.cs @@ -1951,4 +1951,210 @@ 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 + { + 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 + { + 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.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)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); + } + + [TestMethod] + public async Task WhenAssertAreNotEqualIsPassedSameLocalWithDefaultEqualityComparer_Diagnostic() + { + // EqualityComparer.Default passed explicitly is the default comparer, 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, EqualityComparer.Default)|]; + } + } + """; + 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); + } } diff --git a/test/UnitTests/MSTest.Analyzers.UnitTests/ReviewAlwaysTrueAssertConditionAnalyzerTests.cs b/test/UnitTests/MSTest.Analyzers.UnitTests/ReviewAlwaysTrueAssertConditionAnalyzerTests.cs index fa674b91d7f..c93cecb7bd4 100644 --- a/test/UnitTests/MSTest.Analyzers.UnitTests/ReviewAlwaysTrueAssertConditionAnalyzerTests.cs +++ b/test/UnitTests/MSTest.Analyzers.UnitTests/ReviewAlwaysTrueAssertConditionAnalyzerTests.cs @@ -1510,4 +1510,526 @@ public void TestMethod() await VerifyCS.VerifyCodeFixAsync(code, code); } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithOverriddenEquals_NoDiagnostic() + { + // The type overrides object.Equals, so Assert.AreEqual 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.AreEqual(x, x); + } + + private sealed class MyType + { + public override bool Equals(object obj) => obj is MyType; + public override int GetHashCode() => 0; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithEquatable_NoDiagnostic() + { + // A sealed type implementing IEquatable (without overriding object.Equals) routes equality + // through user code, so it must not be flagged. This exercises the IEquatable detection branch. + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new MyType(); + Assert.AreEqual(x, x); + } + + private sealed class MyType : IEquatable + { + public bool Equals(MyType other) => true; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithOnlyEqualityOperator_Diagnostic() + { + // EqualityComparer.Default (used by Assert.AreEqual) never calls operator ==; it uses + // IEquatable.Equals or the virtual object.Equals. A type that only overloads == (without + // overriding Equals or implementing IEquatable) still compares by reference, so the + // self-comparison is genuinely always true and must be flagged. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new MyType(); + [|Assert.AreEqual(x, x)|]; + } + + #pragma warning disable CS0660, CS0661 + private sealed class MyType + { + public static bool operator ==(MyType left, MyType right) => true; + public static bool operator !=(MyType left, MyType right) => false; + } + #pragma warning restore CS0660, CS0661 + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithEquatableOfOtherType_Diagnostic() + { + // The type implements IEquatable, not IEquatable, so EqualityComparer.Default + // falls back to reference equality and the self-comparison is genuinely always true. + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new MyType(); + [|Assert.AreEqual(x, x)|]; + } + + private sealed class MyType : IEquatable + { + public bool Equals(string other) => true; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameGenericTypeParameter_NoDiagnostic() + { + // T can be substituted with a type whose equality is not reflexive, so we cannot prove the + // comparison is always true. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + Helper(1); + } + + private static void Helper(T value) + { + Assert.AreEqual(value, value); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithoutCustomEquality_Diagnostic() + { + // A reference type that does not customize equality falls back to reference equality, + // so a self-comparison is genuinely always true and should still be flagged. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new MyType(); + [|Assert.AreEqual(x, x)|]; + } + + private sealed class MyType + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameArray_Diagnostic() + { + // Arrays use reference equality, so a self-comparison is genuinely always true. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new int[0]; + [|Assert.AreEqual(x, x)|]; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalOfPolymorphicType_NoDiagnostic() + { + // A non-sealed reference type can hold a derived instance whose overridden Equals is not + // reflexive, so equality cannot be proven from the static type. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + object x = new object(); + Assert.AreEqual(x, x); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalOfNonSealedType_NoDiagnostic() + { + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new MyType(); + Assert.AreEqual(x, x); + } + + private class MyType + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedEqualConstantsWithCustomComparer_NoDiagnostic() + { + // A caller-supplied comparer can return any result, so the comparison is not provably always true. + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + Assert.AreEqual(1, 1, new NeverEqualComparer()); + } + + private sealed class NeverEqualComparer : IEqualityComparer + { + public bool Equals(int x, int y) => false; + public int GetHashCode(int obj) => 0; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithCustomComparer_NoDiagnostic() + { + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + int x = 1; + Assert.AreEqual(x, x, new NeverEqualComparer()); + } + + private sealed class NeverEqualComparer : IEqualityComparer + { + public bool Equals(int x, int y) => false; + public int GetHashCode(int obj) => 0; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameDateTime_Diagnostic() + { + // DateTime is a primitive-like value type with reflexive built-in equality, so a self-comparison + // is genuinely always true and should still be flagged. + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + DateTime x = DateTime.Now; + [|Assert.AreEqual(x, x)|]; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameValueWithPolymorphicComparerType_NoDiagnostic() + { + // The comparison uses EqualityComparer.Default (the method type argument), which invokes the + // non-reflexive IEquatable, even though the operand's static type is the sealed Derived. + string code = """ + using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new Derived(); + Assert.AreEqual(x, x); + } + + private class Base : IEquatable + { + public bool Equals(Base other) => false; + } + + private sealed class Derived : Base + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameStructWithNonReflexiveField_NoDiagnostic() + { + // A struct using the default field-based ValueType.Equals compares its fields via their equality, + // so a field whose Equals is not reflexive makes the self-comparison return false. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new Wrapper(); + Assert.AreEqual(x, x); + } + + private struct Wrapper + { + public NeverEqual Field; + } + + private sealed class NeverEqual + { + public override bool Equals(object obj) => false; + public override int GetHashCode() => 0; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameNullable_NoDiagnostic() + { + // Nullable delegates equality to the underlying T, which may not be reflexive, so it is treated + // conservatively. + string code = """ + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + int? x = 1; + Assert.AreEqual(x, x); + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithNullComparer_Diagnostic() + { + // MSTest treats a null comparer as EqualityComparer.Default, so the self-comparison is still + // provably always true 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.AreEqual(x, x, (IEqualityComparer)null)|]; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithDefaultComparer_Diagnostic() + { + // default(IEqualityComparer) is null, which MSTest treats as EqualityComparer.Default, so the + // self-comparison is still provably always true. Only built-in conversions are stripped when inspecting + // the comparer argument. + string code = """ + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + int x = 1; + [|Assert.AreEqual(x, x, default(IEqualityComparer))|]; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedSameLocalWithDefaultEqualityComparer_Diagnostic() + { + // EqualityComparer.Default passed explicitly is the default comparer, so the self-comparison is + // still provably always true 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.AreEqual(x, x, EqualityComparer.Default)|]; + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } + + [TestMethod] + public async Task WhenAssertAreEqualIsPassedContravariantDefaultComparer_NoDiagnostic() + { + // IEqualityComparer is contravariant, so EqualityComparer.Default can be passed where an + // IEqualityComparer is expected. That is NOT EqualityComparer.Default and can return a + // different (non-reflexive) result, so it must not be treated as the default comparer. + string code = """ + using System; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MyTestClass + { + [TestMethod] + public void TestMethod() + { + var x = new Derived(); + Assert.AreEqual(x, x, EqualityComparer.Default); + } + + private class Base : IEquatable + { + public bool Equals(Base other) => false; + } + + private sealed class Derived : Base + { + } + } + """; + + await VerifyCS.VerifyCodeFixAsync(code, code); + } }