Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CA1822 Suppressor #1637

Merged
merged 4 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" Version="1.1.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing" Version="1.1.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.12.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.SourceGenerators.Testing" Version="1.1.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.Workspaces.Common" Version="4.7.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="9.0.1" />
Expand Down
170 changes: 170 additions & 0 deletions TUnit.Analyzers.Tests/AnalyzerTestHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
using Polly.CircuitBreaker;
using TUnit.Core;
using TUnit.TestProject.Library;

namespace TUnit.Analyzers.Tests;

public static class AnalyzerTestHelpers
{
public static CSharpAnalyzerTest<TAnalyzer, DefaultVerifier> CreateAnalyzerTest<TAnalyzer>(
[StringSyntax("c#-test")] string inputSource
)
where TAnalyzer : DiagnosticAnalyzer, new()
{
var csTest = new CSharpAnalyzerTest<TAnalyzer, DefaultVerifier>
{
TestState =
{
Sources = { inputSource },
ReferenceAssemblies = new ReferenceAssemblies(
"net8.0",
new PackageIdentity(
"Microsoft.NETCore.App.Ref",
"8.0.0"),
Path.Combine("ref", "net8.0")),
},
};

csTest.TestState.AdditionalReferences
.AddRange(
[
MetadataReference.CreateFromFile(typeof(TUnitAttribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(CircuitState).Assembly.Location),
MetadataReference.CreateFromFile(typeof(ProjectReferenceEnum).Assembly.Location)
]
);

return csTest;
}

public sealed class CSharpSuppressorTest<TSuppressor, TVerifier> : CSharpAnalyzerTest<TSuppressor, TVerifier>
where TSuppressor : DiagnosticSuppressor, new()
where TVerifier : IVerifier, new()
{
private readonly List<DiagnosticAnalyzer> _analyzers = [];

protected override IEnumerable<DiagnosticAnalyzer> GetDiagnosticAnalyzers()
{
return base.GetDiagnosticAnalyzers().Concat(_analyzers);
}

public CSharpSuppressorTest<TSuppressor, TVerifier> WithAnalyzer<TAnalyzer>(bool enableDiagnostics = false)
where TAnalyzer : DiagnosticAnalyzer, new()
{
var analyzer = new TAnalyzer();
_analyzers.Add(analyzer);

if (enableDiagnostics)
{
var diagnosticOptions = analyzer.SupportedDiagnostics
.ToImmutableDictionary(
descriptor => descriptor.Id,
descriptor => descriptor.DefaultSeverity.ToReportDiagnostic()
);

SolutionTransforms.Clear();
SolutionTransforms.Add(EnableDiagnostics(diagnosticOptions));
}

return this;
}

public CSharpSuppressorTest<TSuppressor, TVerifier> WithSpecificDiagnostics(
params DiagnosticResult[] diagnostics
)
{
var diagnosticOptions = diagnostics
.ToImmutableDictionary(
descriptor => descriptor.Id,
descriptor => descriptor.Severity.ToReportDiagnostic()
);

SolutionTransforms.Clear();
SolutionTransforms.Add(EnableDiagnostics(diagnosticOptions));
return this;
}

private static Func<Solution, ProjectId, Solution> EnableDiagnostics(
ImmutableDictionary<string, ReportDiagnostic> diagnostics
) =>
(solution, id) =>
{
var options = solution.GetProject(id)?.CompilationOptions
?? throw new InvalidOperationException("Compilation options missing.");

return solution
.WithProjectCompilationOptions(
id,
options
.WithSpecificDiagnosticOptions(diagnostics)
);
};

public CSharpSuppressorTest<TSuppressor, TVerifier> WithExpectedDiagnosticsResults(
params DiagnosticResult[] diagnostics
)
{
ExpectedDiagnostics.AddRange(diagnostics);
return this;
}
}

public static CSharpSuppressorTest<TSuppressor, DefaultVerifier> CreateSuppressorTest<TSuppressor>(
[StringSyntax("c#-test")] string inputSource
)
where TSuppressor : DiagnosticSuppressor, new()
{
var currentVersion = Environment.Version.Major;
var test = new CSharpSuppressorTest<TSuppressor, DefaultVerifier>
{
TestCode = inputSource,
ReferenceAssemblies = new ReferenceAssemblies(
$"net{currentVersion}.0",
new PackageIdentity(
"Microsoft.NETCore.App.Ref",
$"{currentVersion}.0.0"),
Path.Combine("ref", $"net{currentVersion}.0")
)
};

test.TestState.AdditionalReferences
.AddRange([
MetadataReference.CreateFromFile(typeof(TUnitAttribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(CircuitState).Assembly.Location),
MetadataReference.CreateFromFile(typeof(ProjectReferenceEnum).Assembly.Location)
]);

return test;
}

public static CSharpSuppressorTest<TSuppressor, DefaultVerifier> CreateSuppressorTest<TSuppressor, TAnalyzer>(
[StringSyntax("c#-test")] string inputSource
)
where TSuppressor : DiagnosticSuppressor, new()
where TAnalyzer : DiagnosticAnalyzer, new()
{
return CreateSuppressorTest<TSuppressor>(inputSource)
.WithAnalyzer<TAnalyzer>(enableDiagnostics: true);
}
}

file static class DiagnosticSeverityExtensions
{
public static ReportDiagnostic ToReportDiagnostic(this DiagnosticSeverity severity)
=> severity switch
{
DiagnosticSeverity.Hidden => ReportDiagnostic.Hidden,
DiagnosticSeverity.Info => ReportDiagnostic.Info,
DiagnosticSeverity.Warning => ReportDiagnostic.Warn,
DiagnosticSeverity.Error => ReportDiagnostic.Error,
_ => throw new InvalidEnumArgumentException(nameof(severity), (int)severity, typeof(DiagnosticSeverity)),
};
}
53 changes: 53 additions & 0 deletions TUnit.Analyzers.Tests/MarkMethodStaticSuppressorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeQuality.Analyzers.QualityGuidelines;
using NUnit.Framework;

namespace TUnit.Analyzers.Tests;

public class MarkMethodStaticSuppressorTests
{
private static readonly DiagnosticResult CA1822 = new("CA1822", DiagnosticSeverity.Info);

[TestCase("Test")]
[TestCase("Before(Test)")]
[TestCase("After(Test)")]
public async Task WarningsInTUnitAreSuppressed(string attribute) =>
await AnalyzerTestHelpers
.CreateSuppressorTest<MarkMethodStaticSuppressor>(
$$"""
using TUnit.Core;
using static TUnit.Core.HookType;

public class MyTests
{
[{{attribute}}]
public void {|#0:Test1|}()
{
}
}
"""
)
.WithAnalyzer<MarkMembersAsStaticAnalyzer>()
.WithSpecificDiagnostics(CA1822)
.WithExpectedDiagnosticsResults(CA1822.WithLocation(0).WithIsSuppressed(true))
.RunAsync();

[Test]
public async Task WarningsAllowedElsewhere() =>
await AnalyzerTestHelpers
.CreateSuppressorTest<MarkMethodStaticSuppressor>(
"""
public class MyTests
{
public void {|#0:DoSomething|}()
{
}
}
"""
)
.WithAnalyzer<MarkMembersAsStaticAnalyzer>()
.WithSpecificDiagnostics(CA1822)
.WithExpectedDiagnosticsResults(CA1822.WithLocation(0).WithIsSuppressed(false))
.RunAsync();
}
8 changes: 7 additions & 1 deletion TUnit.Analyzers.Tests/TUnit.Analyzers.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" VersionOverride="4.12.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" VersionOverride="4.8.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NUnit" />
<PackageReference Include="NUnit.Analyzers">
Expand All @@ -22,4 +22,10 @@
<ProjectReference Include="..\TUnit.Analyzers\TUnit.Analyzers.csproj" />
<ProjectReference Include="..\TUnit.TestProject.Library\TUnit.TestProject.Library.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" PrivateAssets="all" GeneratePathProperty="true" />
<Reference Include="$(PkgMicrosoft_CodeAnalysis_NetAnalyzers)\analyzers\dotnet\cs\Microsoft.CodeAnalysis.NetAnalyzers.dll" />
<Reference Include="$(PkgMicrosoft_CodeAnalysis_NetAnalyzers)\analyzers\dotnet\cs\Microsoft.CodeAnalysis.CSharp.NetAnalyzers.dll" />
</ItemGroup>
</Project>
61 changes: 61 additions & 0 deletions TUnit.Analyzers/MarkMethodStaticSuppressor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using TUnit.Analyzers.Extensions;

namespace TUnit.Analyzers;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class MarkMethodStaticSuppressor : DiagnosticSuppressor
{
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
if (diagnostic.Location.SourceTree?.GetRoot().FindNode(diagnostic.Location.SourceSpan) is not { } node)
{
continue;
}

var semanticModel = context.GetSemanticModel(diagnostic.Location.SourceTree);

if (semanticModel.GetDeclaredSymbol(node) is not IMethodSymbol methodSymbol)
{
continue;
}

if (methodSymbol.IsTestMethod(context.Compilation))
{
Suppress(context, diagnostic);
}
else if (methodSymbol.IsStandardHookMethod(context.Compilation, out _, out var hookLevel, out _)
&& hookLevel is HookLevel.Test)
{
Suppress(context, diagnostic);
}
}
}

private void Suppress(SuppressionAnalysisContext context, Diagnostic diagnostic)
{
var suppression = SupportedSuppressions.First(s => s.SuppressedDiagnosticId == diagnostic.Id);

context.ReportSuppression(
Suppression.Create(
suppression,
diagnostic
)
);
}

public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions { get; } =
ImmutableArray.Create(CreateDescriptor("CA1822"));

private static SuppressionDescriptor CreateDescriptor(string id)
=> new(
id: $"{id}Suppression",
suppressedDiagnosticId: id,
justification: $"Suppress {id} for TUnit instance methods."
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" VersionOverride="4.12.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" VersionOverride="4.8.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NUnit" />
<PackageReference Include="NUnit.Analyzers">
Expand Down
Loading