71 lines
2.8 KiB
C#
71 lines
2.8 KiB
C#
using AutoMapPropertyHelper;
|
|
using Microsoft.CodeAnalysis;
|
|
using Microsoft.CodeAnalysis.CSharp;
|
|
using System.Reflection;
|
|
using Xunit;
|
|
|
|
namespace AutoMapProperty.Tests;
|
|
|
|
internal sealed class GeneratorTestCompilation
|
|
{
|
|
private static readonly MetadataReference[] References = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
|
|
.Split(Path.PathSeparator)
|
|
.Append(typeof(AutoMapPropertyAttribute).Assembly.Location)
|
|
.Append(typeof(LinqKit.PredicateBuilder).Assembly.Location)
|
|
.Distinct()
|
|
.Select(path => MetadataReference.CreateFromFile(path))
|
|
.ToArray();
|
|
|
|
private const string Support = """
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using AutoMapPropertyHelper;
|
|
|
|
namespace AutoMapProperty
|
|
{
|
|
public static class AutoMapPropertyUtils
|
|
{
|
|
public static T Create<T>(IServiceProvider providers) where T : class => Activator.CreateInstance<T>();
|
|
public static T Create<T, TParent>(IServiceProvider providers, TParent parent, string name)
|
|
where T : class, new() where TParent : class => new T();
|
|
}
|
|
}
|
|
""";
|
|
|
|
public Compilation Output { get; }
|
|
public GeneratorDriverRunResult RunResult { get; }
|
|
|
|
public GeneratorTestCompilation(string source)
|
|
{
|
|
var compilation = CSharpCompilation.Create("MappingTests_" + Guid.NewGuid().ToString("N"),
|
|
new[] { CSharpSyntaxTree.ParseText(Support + "\n" + source) }, References,
|
|
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable));
|
|
|
|
GeneratorDriver driver = CSharpGeneratorDriver.Create(new AutoMapPropertyGenerator());
|
|
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out _);
|
|
Output = output;
|
|
RunResult = driver.GetRunResult();
|
|
Assert.All(RunResult.Results, result => Assert.Null(result.Exception));
|
|
}
|
|
|
|
public void AssertCompiles()
|
|
{
|
|
var errors = Output.GetDiagnostics().Concat(RunResult.Diagnostics)
|
|
.Where(x => x.Severity == DiagnosticSeverity.Error).ToArray();
|
|
Assert.True(errors.Length == 0, string.Join(Environment.NewLine, errors.Select(x => x.ToString())));
|
|
}
|
|
|
|
public IPropertySymbol Property(string type, string property) =>
|
|
Assert.IsAssignableFrom<IPropertySymbol>(Assert.Single(Output.GetTypeByMetadataName(type)!.GetMembers(property)));
|
|
|
|
public object? Evaluate()
|
|
{
|
|
AssertCompiles();
|
|
using var stream = new MemoryStream();
|
|
var result = Output.Emit(stream);
|
|
Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics));
|
|
return Assembly.Load(stream.ToArray()).GetType("Fixtures.Check")!.GetMethod("Run")!.Invoke(null, null);
|
|
}
|
|
}
|