-
Notifications
You must be signed in to change notification settings - Fork 29
/
Tests.cs
76 lines (62 loc) · 2.39 KB
/
Tests.cs
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using SourceGenerator;
using Xunit;
using Xunit.Abstractions;
namespace SourceGeneratorTests
{
public class Tests
{
private readonly ITestOutputHelper _output;
public Tests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Test1()
{
string source = @"
namespace Foo
{
class C
{
void M()
{
}
}
}";
string output = GetGeneratedOutput(source);
Assert.NotNull(output);
Assert.Equal("// global::Foo.C", output.Trim());
}
private string GetGeneratedOutput(string source)
{
var syntaxTree = CSharpSyntaxTree.ParseText(source);
var references = new List<MetadataReference>();
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
if (!assembly.IsDynamic && !string.IsNullOrWhiteSpace(assembly.Location))
{
references.Add(MetadataReference.CreateFromFile(assembly.Location));
}
}
var compilation = CSharpCompilation.Create("foo", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
// TODO: Uncomment this line if you want to fail tests when the injected program isn't valid _before_ running generators
// var compileDiagnostics = compilation.GetDiagnostics();
// Assert.False(compileDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error), "Failed: " + compileDiagnostics.FirstOrDefault()?.GetMessage());
ISourceGenerator generator = new Generator();
var driver = CSharpGeneratorDriver.Create(generator);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generateDiagnostics);
Assert.False(generateDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error), "Failed: " + generateDiagnostics.FirstOrDefault()?.GetMessage());
string output = outputCompilation.SyntaxTrees.Last().ToString();
_output.WriteLine(output);
return output;
}
}
}