MapTo/test/BlueWest.MapTo.Tests/Infrastructure/CSharpGenerator.cs

66 lines
3.1 KiB
C#
Raw Normal View History

2021-12-24 20:06:06 +03:00
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
2022-08-24 19:56:44 +03:00
using System.Diagnostics;
2021-12-24 20:06:06 +03:00
using System.Linq;
2022-08-24 19:56:44 +03:00
using System.Threading;
2021-12-24 20:06:06 +03:00
using MapTo.Tests.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace MapTo.Tests.Infrastructure
{
internal static class CSharpGenerator
{
internal static (Compilation compilation, ImmutableArray<Diagnostic> diagnostics) GetOutputCompilation(
string source,
bool assertCompilation = false,
IDictionary<string, string>? analyzerConfigOptions = null,
NullableContextOptions nullableContextOptions = NullableContextOptions.Disable,
LanguageVersion languageVersion = LanguageVersion.CSharp7_3) =>
GetOutputCompilation(
new[] { source },
assertCompilation,
analyzerConfigOptions,
nullableContextOptions,
languageVersion);
internal static (Compilation compilation, ImmutableArray<Diagnostic> diagnostics) GetOutputCompilation(
IEnumerable<string> sources,
bool assertCompilation = false,
IDictionary<string, string>? analyzerConfigOptions = null,
NullableContextOptions nullableContextOptions = NullableContextOptions.Disable,
LanguageVersion languageVersion = LanguageVersion.CSharp7_3)
{
var references = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location))
.Select(a => MetadataReference.CreateFromFile(a.Location))
.ToList();
var compilation = CSharpCompilation.Create(
$"{typeof(CSharpGenerator).Assembly.GetName().Name}.Dynamic",
sources.Select((source, index) => CSharpSyntaxTree.ParseText(source, path: $"Test{index:00}.g.cs", options: new CSharpParseOptions(languageVersion))),
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: nullableContextOptions));
if (assertCompilation)
{
// NB: fail tests when the injected program isn't valid _before_ running generators
compilation.GetDiagnostics().ShouldBeSuccessful();
}
2022-08-24 19:56:44 +03:00
2021-12-24 20:06:06 +03:00
var driver = CSharpGeneratorDriver.Create(
2022-08-27 06:19:43 +03:00
new List<ISourceGenerator>() { new MapToGenerator(), new EfAddMethodsGenerator() },
2021-12-24 20:06:06 +03:00
optionsProvider: new TestAnalyzerConfigOptionsProvider(analyzerConfigOptions),
parseOptions: new CSharpParseOptions(languageVersion)
);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generateDiagnostics);
generateDiagnostics.ShouldBeSuccessful(ignoreDiagnosticsIds: new[] { "MT" });
outputCompilation.GetDiagnostics().ShouldBeSuccessful(outputCompilation);
return (outputCompilation, generateDiagnostics);
}
}
}