using System; using System.Threading.Tasks; using Kyoo.SqLite; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; namespace Kyoo.Tests { /// /// Class responsible to fill and create in memory databases for unit tests. /// public class TestContext : IDisposable, IAsyncDisposable { /// /// The context's options that specify to use an in memory Sqlite database. /// private readonly DbContextOptions _context; /// /// The internal sqlite connection used by all context returned by this class. /// private readonly SqliteConnection _connection; /// /// Create a new database and fill it with information. /// public TestContext() { _connection = new SqliteConnection("DataSource=:memory:"); _connection.Open(); _context = new DbContextOptionsBuilder() .UseSqlite(_connection) .Options; using DatabaseContext context = New(); context.Database.Migrate(); } /// /// Fill the database with pre defined values using a clean context. /// public async Task AddTestAsync() where T : class { await using DatabaseContext context = New(); await context.Set().AddAsync(TestSample.Get()); await context.SaveChangesAsync(); } /// /// Fill the database with pre defined values using a clean context. /// public void AddTest() where T : class { using DatabaseContext context = New(); context.Set().Add(TestSample.Get()); context.SaveChanges(); } /// /// Get a new database context connected to a in memory Sqlite database. /// /// A valid DatabaseContext public DatabaseContext New() { return new SqLiteContext(_context); } public void Dispose() { _connection.Close(); } public async ValueTask DisposeAsync() { await _connection.CloseAsync(); } } }