2020-12-19 10:55:47 +03:00
|
|
|
|
using System;
|
2021-01-03 12:26:07 +03:00
|
|
|
|
using System.Collections.Generic;
|
2020-12-19 10:55:47 +03:00
|
|
|
|
using System.Collections.Immutable;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using Microsoft.CodeAnalysis;
|
|
|
|
|
using Microsoft.CodeAnalysis.CSharp;
|
|
|
|
|
using Xunit;
|
|
|
|
|
|
2021-01-03 12:26:07 +03:00
|
|
|
|
namespace MapTo.Tests.Infrastructure
|
2020-12-19 10:55:47 +03:00
|
|
|
|
{
|
|
|
|
|
internal static class CSharpGenerator
|
|
|
|
|
{
|
|
|
|
|
internal static void ShouldBeSuccessful(this ImmutableArray<Diagnostic> diagnostics)
|
|
|
|
|
{
|
2020-12-21 13:20:29 +03:00
|
|
|
|
Assert.False(diagnostics.Any(d => d.Severity >= DiagnosticSeverity.Warning), $"Failed: {Environment.NewLine}{string.Join($"{Environment.NewLine}- ", diagnostics.Select(c => c.GetMessage()))}");
|
2020-12-19 10:55:47 +03:00
|
|
|
|
}
|
|
|
|
|
|
2021-01-03 12:26:07 +03:00
|
|
|
|
internal static (Compilation compilation, ImmutableArray<Diagnostic> diagnostics) GetOutputCompilation(string source, bool assertCompilation = false, IDictionary<string, string> analyzerConfigOptions = null)
|
2020-12-19 10:55:47 +03:00
|
|
|
|
{
|
|
|
|
|
var syntaxTree = CSharpSyntaxTree.ParseText(source);
|
|
|
|
|
var references = AppDomain.CurrentDomain.GetAssemblies()
|
|
|
|
|
.Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location))
|
|
|
|
|
.Select(a => MetadataReference.CreateFromFile(a.Location))
|
|
|
|
|
.ToList();
|
|
|
|
|
|
|
|
|
|
var compilation = CSharpCompilation.Create("foo", new[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
|
|
|
|
|
|
2020-12-21 13:20:29 +03:00
|
|
|
|
if (assertCompilation)
|
|
|
|
|
{
|
|
|
|
|
// NB: 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: {Environment.NewLine}{string.Join($"{Environment.NewLine}- ", compileDiagnostics.Select(c => c.GetMessage()))}");
|
|
|
|
|
}
|
2020-12-19 10:55:47 +03:00
|
|
|
|
|
2021-01-03 12:26:07 +03:00
|
|
|
|
var driver = CSharpGeneratorDriver.Create(
|
|
|
|
|
new[] { new MapToGenerator() },
|
|
|
|
|
optionsProvider: new TestAnalyzerConfigOptionsProvider(analyzerConfigOptions)
|
|
|
|
|
);
|
2020-12-21 19:34:53 +03:00
|
|
|
|
|
2021-01-03 12:26:07 +03:00
|
|
|
|
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generateDiagnostics);
|
2020-12-19 10:55:47 +03:00
|
|
|
|
return (outputCompilation, generateDiagnostics);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|