71 lines
2.1 KiB
C#
71 lines
2.1 KiB
C#
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<Job> Jobs { get; set; }
|
|
public IReadOnlyCollection<WorkItem> 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<List<Job>>();
|
|
|
|
var events = allData["workitems"];
|
|
testSet.WorkItems = events?.ToObject<List<WorkItem>>();
|
|
|
|
return testSet;
|
|
}
|
|
|
|
public AppDbContext GetBlankContext()
|
|
{
|
|
var options = new DbContextOptionsBuilder<AppDbContext>()
|
|
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
|
.Options;
|
|
return new AppDbContext(options);
|
|
}
|
|
|
|
public AppDbContext GetContextWithData(string jsonFileName)
|
|
{
|
|
var options = new DbContextOptionsBuilder<AppDbContext>()
|
|
.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<T>(DbSet<T> collection, IEnumerable<T> range) where T : class
|
|
{
|
|
if (range != null) collection.AddRange(range);
|
|
}
|
|
} |