using System.Collections.Generic; using System.IO; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json.Linq; using LCU.Api.Internal.DispatcherLib.Persistence; namespace LCU.Api.Internal.DispatcherTests.RepositoryTests; public class DbContextTestSet { public IReadOnlyCollection Jobs { get; set; } public IReadOnlyCollection WorkItems { get; set; } } public abstract class DbContextFromJsonTest { public DbContextTestSet GetTestAccounts(string filePath) { var testSet = new DbContextTestSet(); // Get the absolute path to the JSON file var path = Path.IsPathRooted(filePath) ? filePath : Path.GetRelativePath(Directory.GetCurrentDirectory(), filePath); if (!File.Exists(path)) { throw new ArgumentException($"Could not find file at path: {path}"); } var fileData = File.ReadAllText(filePath); var allData = JObject.Parse(fileData); var data = allData["jobs"]; testSet.Jobs = data?.ToObject>(); var events = allData["workitems"]; testSet.WorkItems = events?.ToObject>(); return testSet; } public AppDbContext GetBlankContext() { var options = new DbContextOptionsBuilder() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; return new AppDbContext(options); } public AppDbContext GetContextWithData(string jsonFileName) { var options = new DbContextOptionsBuilder() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; var context = new AppDbContext(options); var testData = GetTestAccounts(jsonFileName); AddTo(context.Jobs, testData.Jobs); AddTo(context.WorkItems, testData.WorkItems); context.SaveChanges(); context.ChangeTracker.Clear(); return context; } private static void AddTo(DbSet collection, IEnumerable range) where T : class { if (range != null) collection.AddRange(range); } }