Skip to content

Commit

Permalink
EncloseInNamespace for ConcurrentAnalysis
Browse files Browse the repository at this point in the history
  • Loading branch information
martin-strecker-sonarsource committed Nov 21, 2022
1 parent 638c7a6 commit 3162916
Show file tree
Hide file tree
Showing 14 changed files with 45 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ public void AsyncVoidMethod_MsTestV2_CSharp11(string testFwkVersion) =>
// The first version of the framework is not compatible with Net 7 so we need to test only v2 with C#11 features
.WithOptions(ParseOptionsHelper.FromCSharp11)
.AddReferences(NuGetMetadataReference.MSTestTestFramework(testFwkVersion))
.WithConcurrentAnalysis(false)
.Verify();

#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ public void CallerInformationParametersShouldBeLast_CSharp11() =>
public void CallerInformationParametersShouldBeLastInvalidSyntax() =>
builder.AddPaths("CallerInformationParametersShouldBeLastInvalidSyntax.cs")
.WithErrorBehavior(CompilationErrorBehavior.Ignore)
.WithConcurrentAnalysis(false)
.Verify();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public class ClassAndMethodNameTest
public void ClassAndMethodName_CS() =>
builderCS.AddPaths("ClassAndMethodName.cs", "ClassAndMethodName.Partial.cs")
.AddReferences(MetadataReferenceFacade.NETStandard21)
.WithConcurrentAnalysis(false)
.WithOptions(ParseOptionsHelper.FromCSharp8)
.Verify();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ public void CognitiveComplexity_CS_CSharp9() =>
public void CognitiveComplexity_CS_CSharp10() =>
builderCS.AddPaths("CognitiveComplexity.CSharp10.cs")
.WithOptions(ParseOptionsHelper.FromCSharp10)
.WithConcurrentAnalysis(false)
.Verify();

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class CommentedOutCodeTest

[TestMethod]
public void CommentedOutCode_Nonconcurrent() =>
builder.AddPaths("CommentedOutCode_Nonconcurrent.cs").WithConcurrentAnalysis(false).Verify();
builder.AddPaths("CommentedOutCode_Nonconcurrent.cs").Verify();

[TestMethod]
public void CommentedOutCode() =>
Expand All @@ -39,7 +39,6 @@ public void CommentedOutCode() =>
[TestMethod]
public void CommentedOutCode_NoDocumentation() =>
builder.AddPaths("CommentedOutCode.cs")
.WithConcurrentAnalysis(false)
.WithOptions(ImmutableArray.Create<ParseOptions>(new CSharpParseOptions(documentationMode: DocumentationMode.None)))
.Verify();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,13 @@ public void EmptyNamespace() =>
public void EmptyNamespace_CSharp10() =>
builder.AddPaths("EmptyNamespace.CSharp10.Empty.cs", "EmptyNamespace.CSharp10.NotEmpty.cs")
.WithOptions(ParseOptionsHelper.FromCSharp10)
.WithConcurrentAnalysis(false)
.Verify();

[TestMethod]
public void EmptyNamespace_CSharp10_CodeFix() =>
builder.AddPaths("EmptyNamespace.CSharp10.Empty.cs")
.WithCodeFix<EmptyNamespaceCodeFix>()
.WithOptions(ParseOptionsHelper.FromCSharp10)
.WithAutogenerateConcurrentFiles(false)
.WithCodeFixedPaths("EmptyNamespace.CSharp10.Fixed.cs")
.VerifyCodeFix();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public void ExtensionMethodShouldBeInSeparateNamespace_CSharp9() =>
public void ExtensionMethodShouldBeInSeparateNamespace_CSharp10() =>
builder
.AddPaths("ExtensionMethodShouldBeInSeparateNamespace.CSharp10.cs")
.WithConcurrentAnalysis(false)
.WithOptions(ParseOptionsHelper.FromCSharp10)
.Verify();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ public void RequestsWithExcessiveLength_Csharp10() =>
public void RequestsWithExcessiveLength_Csharp11() =>
builderCS
.AddPaths(@"RequestsWithExcessiveLength.CSharp11.cs")
.WithConcurrentAnalysis(false)
.WithOptions(ParseOptionsHelper.FromCSharp11).Verify();

#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,12 @@ public void SqlKeywordsDelimitedBySpace_DefaultNamespace() =>
public void SqlKeywordsDelimitedBySpace_CSharp10_GlobalUsings() =>
builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.GlobalUsing.cs", "SqlKeywordsDelimitedBySpace.CSharp10.GlobalUsingConsumer.cs")
.WithOptions(ParseOptionsHelper.FromCSharp10)
.WithConcurrentAnalysis(false)
.Verify();

[TestMethod]
public void SqlKeywordsDelimitedBySpace_CSharp10_FileScopesNamespace() =>
builder.AddPaths("SqlKeywordsDelimitedBySpace.CSharp10.FileScopedNamespaceDeclaration.cs")
.WithOptions(ParseOptionsHelper.FromCSharp10)
.WithConcurrentAnalysis(false)
.Verify();

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ public void StringLiteralShouldNotBeDuplicated_CSharp11() =>
public void StringLiteralShouldNotBeDuplicated_Attributes_CS() =>
new VerifierBuilder().AddAnalyzer(() => new CS.StringLiteralShouldNotBeDuplicated { Threshold = 2 })
.AddPaths("StringLiteralShouldNotBeDuplicated_Attributes.cs")
.WithConcurrentAnalysis(false)
.Verify();

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ private static VerifierBuilder CreateVerifier(Func<DiagnosticAnalyzer> createCon
.AddAnalyzer(createConfiguredAnalyzer)
.WithOnlyDiagnostics(onlyDiagnostics)
.AddReferences(MetadataReferenceFacade.SystemThreading)
.WithBasePath(@"SymbolicExecution\Roslyn")
.WithConcurrentAnalysis(false);
.WithBasePath(@"SymbolicExecution\Roslyn");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public void UnnecessaryUsings_CSharp10_GlobalUsings() =>

[TestMethod]
public void UnnecessaryUsings_CSharp10_FileScopedNamespace() =>
builder.AddPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.cs").WithOptions(ParseOptionsHelper.FromCSharp10).WithConcurrentAnalysis(false).Verify();
builder.AddPaths("UnnecessaryUsings.CSharp10.FileScopedNamespace.cs").WithOptions(ParseOptionsHelper.FromCSharp10).Verify();

[TestMethod]
public void UnnecessaryUsings_CodeFix_CSharp10_FileScopedNamespace() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,21 +226,24 @@ public void Verify_TwoPaths() =>
[TestMethod]
public void Verify_AutogenerateConcurrentFiles()
{
var builder = WithSnippetCS("// Noncompliant - FN");
var builder = WithSnippetCS(
@"namespace N1 {
// Noncompliant - FN
}");
// Concurrent analysis by-default automatically generates concurrent files - File.Concurrent.cs
builder.Invoking(x => x.Verify()).Should().Throw<AssertFailedException>().WithMessage(
@"CSharp7: Issue(s) expected but not raised in file(s):
File: File.cs
Line: 1, Type: primary, Id: ''
Line: 2, Type: primary, Id: ''
File: File.Concurrent.cs
Line: 1, Type: primary, Id: ''
Line: 2, Type: primary, Id: ''
");
// When AutogenerateConcurrentFiles is turned off, only the provided snippet is analyzed
builder.WithAutogenerateConcurrentFiles(false).Invoking(x => x.Verify()).Should().Throw<AssertFailedException>().WithMessage(
@"CSharp7: Issue(s) expected but not raised in file(s):
File: File.cs
Line: 1, Type: primary, Id: ''
Line: 2, Type: primary, Id: ''
");
}

Expand Down
36 changes: 35 additions & 1 deletion analyzers/tests/SonarAnalyzer.UnitTest/TestFramework/Verifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@
using System.Text;
using System.Text.RegularExpressions;
using Google.Protobuf;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SonarAnalyzer.Common;
using SonarAnalyzer.Rules;
using SonarAnalyzer.UnitTest.Helpers;
Expand Down Expand Up @@ -181,7 +184,7 @@ private string InsertConcurrentNamespace(string content)
{
return language.LanguageName switch
{
LanguageNames.CSharp => $"namespace AppendedNamespaceForConcurrencyTest {{ {content} {Environment.NewLine}}}", // Last line can be a comment
LanguageNames.CSharp => EncloseInNamespace(content),
LanguageNames.VisualBasic => content.Insert(ImportsIndexVB(), "Namespace AppendedNamespaceForConcurrencyTest : ") + Environment.NewLine + " : End Namespace",
_ => throw new UnexpectedLanguageException(language)
};
Expand All @@ -190,6 +193,37 @@ int ImportsIndexVB() =>
ImportsRegexVB.Match(content) is { Success: true } match ? match.Index + match.Length + 1 : 0;
}

private static string EncloseInNamespace(string content)
{
var tree = CSharpSyntaxTree.ParseText(content);
if (tree.TryGetRoot(out var root) && root is CompilationUnitSyntax { Members: { } members } compilationUnit)
{
if (members.OfType<FileScopedNamespaceDeclarationSyntax>().FirstOrDefault() is { } fileScoped)
{
root = root.ReplaceNode(fileScoped, fileScoped.WithName(SyntaxFactory.ParseName($"ConcurrencyTest.{CSharpSyntaxHelper.GetName(fileScoped.Name)}")));
}
else
{
var newNamespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(" AppendedNamespaceForConcurrencyTest"))
.WithMembers(compilationUnit.Members)
.WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken).WithLeadingTrivia(SyntaxFactory.Whitespace("\n")));
if (newNamespace.Members.Any() && newNamespace.Members[0] is NamespaceDeclarationSyntax)
{
// Move the leading trivia of the first member to newNamespace
newNamespace = newNamespace.WithLeadingTrivia(newNamespace.Members[0].GetLeadingTrivia());
newNamespace = newNamespace.WithMembers(newNamespace.Members.Replace(newNamespace.Members[0], newNamespace.Members[0].WithoutLeadingTrivia()));
}
root = compilationUnit.WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(new[] { newNamespace }));
}

return root.ToFullString();
}
else
{
return $"namespace AppendedNamespaceForConcurrencyTest {{ {content} {Environment.NewLine}}}";
}
}

private string TestCasePath(string fileName) =>
Path.GetFullPath(builder.BasePath == null ? Path.Combine(TestCases, fileName) : Path.Combine(TestCases, builder.BasePath, fileName));

Expand Down

0 comments on commit 3162916

Please sign in to comment.