CodeLiturgy.Dashboard/include/BlueWest.MapTo/test/BlueWest.MapTo.Tests/MappingContextTests.cs

102 lines
2.9 KiB
C#
Raw Normal View History

2022-08-17 23:17:37 +03:00
using MapTo.Sources;
using MapTo.Tests.Extensions;
using MapTo.Tests.Infrastructure;
using Xunit;
using static MapTo.Tests.Common;
namespace MapTo.Tests
{
public class MappingContextTests
{
[Fact]
public void VerifyMappingContextSource()
{
// Arrange
const string source = "";
var expected = @"
// <auto-generated />
using System;
using System.Collections.Generic;
using System.Reflection;
namespace MapTo
{
internal sealed class MappingContext
{
private readonly Dictionary<object, object> _cache;
internal MappingContext()
{
_cache = new Dictionary<object, object>(1);
}
internal static TMapped Create<TOriginal, TMapped>(TOriginal original)
{
if (original == null) throw new ArgumentNullException(nameof(original));
var context = new MappingContext();
var mapped = context.MapFromWithContext<TOriginal, TMapped>(original);
if (mapped == null)
{
throw new InvalidOperationException();
}
return mapped;
}
internal TMapped MapFromWithContext<TOriginal, TMapped>(TOriginal original)
{
if (original == null)
{
return default(TMapped);
}
if (!TryGetValue<TOriginal, TMapped>(original, out var mapped))
{
var instance = Activator.CreateInstance(typeof(TMapped), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { this, original }, null);
if (instance != null)
{
mapped = (TMapped)instance;
}
}
return mapped;
}
internal void Register<TOriginal, TMapped>(TOriginal original, TMapped mapped)
{
if (original == null) throw new ArgumentNullException(nameof(original));
if (mapped == null) throw new ArgumentNullException(nameof(mapped));
if (!_cache.ContainsKey(original))
{
_cache.Add(original, mapped);
}
}
private bool TryGetValue<TOriginal, TMapped>(TOriginal original, out TMapped mapped)
{
if (original != null && _cache.TryGetValue(original, out var value))
{
mapped = (TMapped)value;
return true;
}
mapped = default(TMapped);
return false;
}
}
}
".Trim();
// Act
var (compilation, diagnostics) = CSharpGenerator.GetOutputCompilation(source, analyzerConfigOptions: DefaultAnalyzerOptions);
// Assert
diagnostics.ShouldBeSuccessful();
compilation.SyntaxTrees.ShouldContainSource(MappingContextSource.ClassName, expected);
}
}
}