Skip to content

Commit

Permalink
Fix S2701 FP: avoid raising for xUnit Assert.True() (#8823)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristian-ambrosini-sonarsource authored Feb 28, 2024
1 parent beb30d9 commit 95a7dca
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,29 +29,29 @@ public sealed class DoNotUseLiteralBoolInAssertions : SonarDiagnosticAnalyzer
private const string MessageFormat = "Remove or correct this assertion.";

private static readonly Dictionary<KnownType, HashSet<string>> TrackedTypeAndMethods =
new ()
new()
{
[KnownType.Xunit_Assert] = new HashSet<string>
{
// "True" is not here because there was no Assert.Fail in Xunit until 2020 and Assert.True(false) was a way to simulate it.
"Equal", "False", "NotEqual", "Same", "StrictEqual", "NotSame"
},
[KnownType.Xunit_Assert] =
[
// "True" and "False" are not here because there was no Assert.Fail in Xunit until 2020 and Assert.True(false) and Assert.False(true) were some ways to simulate it.
"Equal", "NotEqual", "Same", "StrictEqual", "NotSame"
],

[KnownType.Microsoft_VisualStudio_TestTools_UnitTesting_Assert] = new HashSet<string>
{
[KnownType.Microsoft_VisualStudio_TestTools_UnitTesting_Assert] =
[
"AreEqual", "AreNotEqual", "AreSame", "IsFalse", "IsTrue"
},
],

[KnownType.NUnit_Framework_Assert] = new HashSet<string>
{
[KnownType.NUnit_Framework_Assert] =
[
"AreEqual", "AreNotEqual", "AreNotSame", "AreSame", "False",
"IsFalse", "IsTrue", "That", "True"
},
],

[KnownType.System_Diagnostics_Debug] = new HashSet<string>
{
[KnownType.System_Diagnostics_Debug] =
[
"Assert"
}
]
};

private static readonly ISet<SyntaxKind> BoolLiterals =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ public void Test()
bool b = true;

Xunit.Assert.Equal(true, b); // Noncompliant
Xunit.Assert.False(true); // Noncompliant
Xunit.Assert.NotEqual(true, b); // Noncompliant
Xunit.Assert.Same(true, b); // Noncompliant
Xunit.Assert.StrictEqual(true, b); // Noncompliant
Expand All @@ -19,9 +18,12 @@ public void Test()
Xunit.Assert.Equal(true, false); // Noncompliant

Xunit.Assert.Equal(b, b);
Xunit.Assert.True(true);
// There is no Assert.Fail in Xunit. Assert.True(false) is way to simulate it.
Xunit.Assert.True(false);
Xunit.Assert.True(true); // FN
Xunit.Assert.False(false); // FN

// There is no Assert.Fail in Xunit. Assert.True(false) or Assert.False(true) are ways to simulate it.
Xunit.Assert.True(false); // Compliant
Xunit.Assert.False(true); // Compliant

bool? x = false;
Xunit.Assert.Equal(false, x); // Compliant, since the comparison triggers a conversion
Expand Down

0 comments on commit 95a7dca

Please sign in to comment.