Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add a basic xunit runner generator that generates a top-level-stateme…
…nt Main method that runs all static parameterless [Fact] attributes in sequence, wrapped in a simple try-catch.
  • Loading branch information
jkoritzinsky authored and trylek committed Nov 4, 2021
commit fd6d4e42b43dbbd7a8fe407119f91d7f7cd0b49a
39 changes: 39 additions & 0 deletions src/tests/Common/XUnitWrapperGenerator/XUnitWrapperGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace XUnitWrapperGenerator
{
[Generator]
public sealed class XUnitWrapperGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterImplementationSourceOutput(
context.SyntaxProvider.CreateSyntaxProvider(
static (node, ct) =>
node.IsKind(SyntaxKind.MethodDeclaration)
&& node is MethodDeclarationSyntax method
&& method.AttributeLists.Count > 0,
static (context, ct) => (IMethodSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!)
.Where(method => method.IsStatic && method.Parameters.IsEmpty && method.GetAttributes().Any(attr => attr.AttributeClass!.ToDisplayString() == "Xunit.FactAttribute"))
.Select((method, ct) => method.ToDisplayString())
.Collect(),
static (context, methods) =>
{
// For simplicity, we'll use top-level statements for the generated Main method.
StringBuilder builder = new();
builder.AppendLine("try {");
builder.Append(string.Join("\n", methods.Select(m => $"{m}();")));
builder.AppendLine("} catch(Exception) { return 101; }");
builder.AppendLine("return 100;");
context.AddSource("Main.g.cs", builder.ToString());
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<EnableDefaultItems>true</EnableDefaultItems>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis" Version="$(MicrosoftCodeAnalysisVersion)" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="$(MicrosoftCodeAnalysisCSharpVersion)" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="$(MicrosoftCodeAnalysisAnalyzersVersion)" />
</ItemGroup>
</Project>