dotnet/roslyn-sdk

Still unable to test compiler diagnostic suppressors

DoctorKrolic opened this issue · 0 comments

Suppressor:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class MySuppressor : DiagnosticSuppressor
{
    private static readonly SuppressionDescriptor _descriptor = new SuppressionDescriptor(
        id: "MYSPR001",
        suppressedDiagnosticId: "CS8618",
        justification: "test");

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

    public override void ReportSuppressions(SuppressionAnalysisContext context)
    {
        foreach (var diagnostic in context.ReportedDiagnostics)
        {
            context.ReportSuppression(Suppression.Create(SupportedSuppressions[0], diagnostic));
        }
    }
}

Test:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;

namespace TestSuppressors;
public class SuppressorTests
{
    [Fact]
    public async Task Test1()
    {
        var source = """
            class C
            {
                public string {|#0:Prop|} { get; set; }
            }
            """;

        await new MyAnalyzerVerifier<MySuppressor>.Test
        {
            TestCode = source,
            ExpectedDiagnostics =
            {
                DiagnosticResult
                    .CompilerWarning("CS8618")
                    .WithLocation(0)
                    .WithLocation(0)
                    .WithIsSuppressed(true)
            },
            CompilerDiagnostics = CompilerDiagnostics.Warnings
        }.RunAsync();
    }
}

public static class MyAnalyzerVerifier<TAnalyzer>
    where TAnalyzer : DiagnosticAnalyzer, new()
{
    public class Test : CSharpAnalyzerTest<TAnalyzer, XUnitVerifier>
    {
        protected override CompilationOptions CreateCompilationOptions()
        {
            return ((CSharpCompilationOptions)base.CreateCompilationOptions())
                .WithNullableContextOptions(NullableContextOptions.Enable);
        }

        protected override ParseOptions CreateParseOptions()
        {
            return ((CSharpParseOptions)base.CreateParseOptions())
                .WithLanguageVersion(LanguageVersion.Latest);
        }
    }
}

Expected behavior:
Test passes.

Actual behavior:
Test fails. If you comment .WithIsSuppressed(true) line it passes showing that diagnostic isn't actually suppressed. If you set breakpoints in SupportedSuppressions initializer and ReportSuppressions method you will actually see, that the first one is triggered while the second one is not. So the suppressor's method isn't even called.

Solution:
TestSuppressors.zip