Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
1 parent
55e769c
commit a0336ce
Showing
18 changed files
with
840 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
<p>It is very easy to write incomplete assertions when using some test frameworks. This rule enforces complete assertions in the following cases:</p> | ||
<ul> | ||
<li> Fluent Assertions: <a href="https://fluentassertions.com/introduction"><code>Should()</code></a> is not followed by an assertion invocation. | ||
</li> | ||
<li> NFluent: <a href="https://www.n-fluent.net"><code>Check.That()</code></a> is not followed by an assertion invocation. </li> | ||
<li> NSubstitute: <a href="https://nsubstitute.github.io/help/received-calls"><code>Received()</code></a> is not followed by an invocation. </li> | ||
</ul> | ||
<p>In such cases, what is intended to be a test doesn’t actually verify anything.</p> | ||
<h2>Noncompliant Code Example</h2> | ||
<pre> | ||
string actual = "Hello World!"; | ||
// Fluent Assertions | ||
actual.Should(); // Noncompliant | ||
// NFluent | ||
Check.That(actual); // Noncompliant | ||
// NSubstitute | ||
command.Received(); // Noncompliant | ||
</pre> | ||
<h2>Compliant Solution</h2> | ||
<pre> | ||
string actual = "Hello World!"; | ||
// Fluent Assertions | ||
actual.Should().Contain("Hello"); | ||
// NFluent | ||
Check.That(actual).Contains("Hello"); | ||
// NSubstitute | ||
command.Received().Execute(); | ||
</pre> | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
{ | ||
"title": "Assertions should be complete", | ||
"type": "CODE_SMELL", | ||
"status": "ready", | ||
"remediation": { | ||
"func": "Constant\/Issue", | ||
"constantCost": "5min" | ||
}, | ||
"tags": [ | ||
"tests" | ||
], | ||
"defaultSeverity": "Blocker", | ||
"ruleSpecification": "RSPEC-2970", | ||
"sqKey": "S2970", | ||
"scope": "Tests", | ||
"quickfix": "unknown" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -120,6 +120,7 @@ | |
"S2933", | ||
"S2934", | ||
"S2953", | ||
"S2970", | ||
"S2971", | ||
"S2995", | ||
"S2996", | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
analyzers/src/SonarAnalyzer.CSharp/Rules/AssertionsShouldBeComplete.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* | ||
* SonarAnalyzer for .NET | ||
* Copyright (C) 2015-2023 SonarSource SA | ||
* mailto: contact AT sonarsource DOT com | ||
* | ||
* This program is free software; you can redistribute it and/or | ||
* modify it under the terms of the GNU Lesser General Public | ||
* License as published by the Free Software Foundation; either | ||
* version 3 of the License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
* Lesser General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public License | ||
* along with this program; if not, write to the Free Software Foundation, | ||
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
*/ | ||
|
||
namespace SonarAnalyzer.Rules.CSharp; | ||
|
||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public sealed class AssertionsShouldBeComplete : SonarDiagnosticAnalyzer | ||
{ | ||
private const string DiagnosticId = "S2970"; | ||
private const string MessageFormat = "Complete the assertion"; | ||
|
||
private static readonly DiagnosticDescriptor Rule = DescriptorFactory.Create(DiagnosticId, MessageFormat); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); | ||
|
||
protected override void Initialize(SonarAnalysisContext context) => | ||
context.RegisterCompilationStartAction(start => | ||
{ | ||
if (start.Compilation.References(KnownAssembly.FluentAssertions)) | ||
{ | ||
start.RegisterNodeAction(c => | ||
CheckInvocation(c, invocation => | ||
invocation.NameIs("Should") | ||
&& c.SemanticModel.GetSymbolInfo(invocation).AllSymbols().Any(x => | ||
x is IMethodSymbol | ||
{ | ||
IsExtensionMethod: true, | ||
ReturnsVoid: false, | ||
ContainingType: { } container, | ||
ReturnType: { } returnType, | ||
} | ||
&& (container.Is(KnownType.FluentAssertions_AssertionExtensions) | ||
// ⬆️ Built in assertions. ⬇️ Custom assertions (the majority at least). | ||
|| returnType.DerivesFrom(KnownType.FluentAssertions_Primitives_ReferenceTypeAssertions)))), | ||
SyntaxKind.InvocationExpression); | ||
} | ||
if (start.Compilation.References(KnownAssembly.NFluent)) | ||
{ | ||
start.RegisterNodeAction(c => | ||
CheckInvocation(c, invocation => | ||
invocation.NameIs("That", "ThatEnum", "ThatCode", "ThatAsyncCode", "ThatDynamic") | ||
&& c.SemanticModel.GetSymbolInfo(invocation) is | ||
{ | ||
Symbol: IMethodSymbol | ||
{ | ||
IsStatic: true, | ||
ReturnsVoid: false, | ||
ContainingType: { IsStatic: true } container | ||
} | ||
} | ||
&& container.Is(KnownType.NFluent_Check)), | ||
SyntaxKind.InvocationExpression); | ||
} | ||
if (start.Compilation.References(KnownAssembly.NSubstitute)) | ||
{ | ||
start.RegisterNodeAction(c => | ||
CheckInvocation(c, invocation => | ||
invocation.NameIs("Received", "DidNotReceive", "ReceivedWithAnyArgs", "DidNotReceiveWithAnyArgs", "ReceivedCalls") | ||
&& c.SemanticModel.GetSymbolInfo(invocation) is | ||
{ | ||
Symbol: IMethodSymbol | ||
{ | ||
IsExtensionMethod: true, | ||
ReturnsVoid: false, | ||
ContainingType: { } container, | ||
} | ||
} | ||
&& container.Is(KnownType.NSubstitute_SubstituteExtensions)), | ||
SyntaxKind.InvocationExpression); | ||
} | ||
}); | ||
|
||
private static void CheckInvocation(SonarSyntaxNodeReportingContext c, Func<InvocationExpressionSyntax, bool> isAssertionMethod) | ||
{ | ||
if (c.Node is InvocationExpressionSyntax invocation | ||
&& isAssertionMethod(invocation) | ||
&& !HasContinuation(invocation)) | ||
{ | ||
c.ReportIssue(Diagnostic.Create(Rule, invocation.GetIdentifier()?.GetLocation())); | ||
} | ||
} | ||
|
||
private static bool HasContinuation(InvocationExpressionSyntax invocation) | ||
{ | ||
var closeParen = invocation.ArgumentList.CloseParenToken; | ||
if (!closeParen.IsKind(SyntaxKind.CloseParenToken) || closeParen.IsMissing || !invocation.GetLastToken().Equals(closeParen)) | ||
{ | ||
// Any invocation should end with ")". We are in unknown territory here. | ||
return true; | ||
} | ||
if (closeParen.GetNextToken() is var nextToken | ||
&& !nextToken.IsKind(SyntaxKind.SemicolonToken)) | ||
{ | ||
// There is something right to the invocation that is not a semicolon. | ||
return true; | ||
} | ||
// We are in some kind of statement context "??? Should();" | ||
// The result might be stored in a variable or returned from the method/property | ||
return nextToken.Parent switch | ||
{ | ||
MethodDeclarationSyntax { ReturnType: { } returnType } => !IsVoid(returnType), | ||
{ } parent when LocalFunctionStatementSyntaxWrapper.IsInstance(parent) => !IsVoid(((LocalFunctionStatementSyntaxWrapper)parent).ReturnType), | ||
PropertyDeclarationSyntax => true, | ||
AccessorDeclarationSyntax { Keyword.RawKind: (int)SyntaxKind.GetKeyword } => true, | ||
ReturnStatementSyntax => true, | ||
LocalDeclarationStatementSyntax => true, | ||
ExpressionStatementSyntax { Expression: AssignmentExpressionSyntax } => true, | ||
_ => false, | ||
}; | ||
} | ||
|
||
private static bool IsVoid(TypeSyntax type) => | ||
type is PredefinedTypeSyntax { Keyword.RawKind: (int)SyntaxKind.VoidKeyword }; | ||
} |
33 changes: 33 additions & 0 deletions
33
analyzers/src/SonarAnalyzer.Common/Extensions/SymbolInfoExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/* | ||
* SonarAnalyzer for .NET | ||
* Copyright (C) 2015-2023 SonarSource SA | ||
* mailto: contact AT sonarsource DOT com | ||
* | ||
* This program is free software; you can redistribute it and/or | ||
* modify it under the terms of the GNU Lesser General Public | ||
* License as published by the Free Software Foundation; either | ||
* version 3 of the License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
* Lesser General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public License | ||
* along with this program; if not, write to the Free Software Foundation, | ||
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
*/ | ||
|
||
namespace SonarAnalyzer.Extensions | ||
{ | ||
public static class SymbolInfoExtensions | ||
{ | ||
/// <summary> | ||
/// Returns the <see cref="SymbolInfo.Symbol"/> or if no symbol could be found the <see cref="SymbolInfo.CandidateSymbols"/>. | ||
/// </summary> | ||
public static IEnumerable<ISymbol> AllSymbols(this SymbolInfo symbolInfo) => | ||
symbolInfo.Symbol == null | ||
? symbolInfo.CandidateSymbols | ||
: new[] { symbolInfo.Symbol }; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.