-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGeneratorTestHelper.cs
More file actions
44 lines (34 loc) · 1.48 KB
/
GeneratorTestHelper.cs
File metadata and controls
44 lines (34 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace CSharpFunctionalExtensions.HttpResults.Generators.Tests;
public static class GeneratorTestHelper
{
public static (IEnumerable<Diagnostic> Diagnostics, string GeneratedSource) RunGenerator(
string sourceCode,
IEnumerable<MetadataReference>? additionalReferences = null
)
{
var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
var references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(typeof(ResultExtensionsGenerator).Assembly.Location),
MetadataReference.CreateFromFile(typeof(IResultErrorMapper<,>).Assembly.Location),
};
if (additionalReferences != null)
references.AddRange(additionalReferences);
var compilation = CSharpCompilation.Create(
"TestAssembly",
[syntaxTree],
references.OfType<PortableExecutableReference>(),
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
var generator = new ResultExtensionsGenerator();
var driver = CSharpGeneratorDriver.Create(generator);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
var sourceFiles = outputCompilation
.SyntaxTrees.Where(tree => tree.FilePath.EndsWith(".g.cs", StringComparison.OrdinalIgnoreCase))
.Select(tree => tree.GetText().ToString());
var generatedSource = string.Join("\n\n", sourceFiles);
return (diagnostics, generatedSource);
}
}