/Verify.SourceGenerators

Extends Verify to allow verification of C# Source Generators.

Primary LanguageC#MIT LicenseMIT

Verify.SourceGenerators

Build status NuGet Status

Extends Verify to allow verification of C# Source Generators.


Part of the .NET Foundation

NuGet package

https://nuget.org/packages/Verify.SourceGenerators/

Initialize

Call VerifySourceGenerators.Enable() once at assembly load time.

Generator

Given a Source Generator:

using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

[Generator]
public class HelloWorldGenerator :
    ISourceGenerator
{
    public void Execute(GeneratorExecutionContext context)
    {
        var source = @"using System;
public static class HelloWorld
{
    public static void SayHello()
    {
        Console.WriteLine(""Hello from generated code!"");
    }
}";
        context.AddSource("helloWorldGenerator", SourceText.From(source, Encoding.UTF8));

        var descriptor = new DiagnosticDescriptor(
            id: "theId",
            title: "the title",
            messageFormat: "the descriptor",
            category: "the category",
            DiagnosticSeverity.Info,
            isEnabledByDefault: true);

        var location = Location.Create(
            "theFile",
            new TextSpan(1, 2),
            new LinePositionSpan(
                new LinePosition(1, 2),
                new LinePosition(3, 4)));
        var diagnostic = Diagnostic.Create(descriptor, location);
        context.ReportDiagnostic(diagnostic);
    }

    public void Initialize(GeneratorInitializationContext context)
    {
    }
}

snippet source | anchor

Test

Can be tested as follows:

using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using VerifyXunit;
using Xunit;

[UsesVerify]
public class SampleTest
{
    [Fact]
    public Task Run()
    {
        var compilation = CSharpCompilation.Create("name");
        HelloWorldGenerator generator = new();

        GeneratorDriver driver = CSharpGeneratorDriver.Create(generator);

        driver = driver.RunGenerators(compilation);

        return Verifier.Verify(driver);
    }
}

snippet source | anchor

Results

And will result in the following verified files:

Info file

An info file containing all metadata about the current state. eg any Diagnostics.

{
  Diagnostics: [
    {
      Id: theId,
      Title: the title,
      Severity: Info,
      WarningLevel: 1,
      Location: theFile: (1,2)-(3,4),
      MessageFormat: the descriptor,
      Category: the category
    }
  ]
}

snippet source | anchor

Source FIles

Multiple source files. One for each GeneratorDriverRunResult.Results.GeneratedSources.

//HintName: helloWorldGenerator.cs
using System;
public static class HelloWorld
{
    public static void SayHello()
    {
        Console.WriteLine("Hello from generated code!");
    }
}

snippet source | anchor

Notes:

Icon

Sauce designed by April Hsuan from The Noun Project.