using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Tau.Acuvim.Console.Data; namespace Tau.Acuvim.Console.Tests; /// /// A subclass of AppDbContext that adds a ValueConverter for JsonDocument properties, /// which the InMemory provider does not natively support. /// public class TestAppDbContext : AppDbContext { public TestAppDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // The InMemory provider cannot handle JsonDocument types. // Add a value converter that serialises JsonDocument to/from string. var jsonDocConverter = new ValueConverter( v => v == null ? null : v.RootElement.GetRawText(), v => v == null ? null : JsonDocument.Parse(v, new JsonDocumentOptions())); foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { if (property.ClrType == typeof(JsonDocument)) { property.SetValueConverter(jsonDocConverter); } } } } } public static class TestHelpers { public static AppDbContext CreateDbContext([System.Runtime.CompilerServices.CallerMemberName] string? name = null) { var options = new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: $"{name}_{Guid.NewGuid():N}") .Options; return new TestAppDbContext(options); } public static ILogger CreateLogger() => NullLogger.Instance; }