using System;
using System.Threading.Tasks;
using Kyoo.SqLite;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Kyoo.Tests
{
public sealed class SqLiteTestContext : TestContext
{
///
/// The internal sqlite connection used by all context returned by this class.
///
private readonly SqliteConnection _connection;
public SqLiteTestContext()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
Context = new DbContextOptionsBuilder()
.UseSqlite(_connection)
.Options;
using DatabaseContext context = New();
context.Database.Migrate();
}
public override void Dispose()
{
_connection.Close();
}
public override async ValueTask DisposeAsync()
{
await _connection.CloseAsync();
}
public override DatabaseContext New()
{
return new SqLiteContext(Context);
}
}
[CollectionDefinition(nameof(Postgresql))]
public class PostgresCollection : ICollectionFixture
{}
public class PostgresFixture
{
}
public sealed class PostgresTestContext : TestContext
{
private readonly PostgresFixture _template;
public PostgresTestContext(PostgresFixture template)
{
_template = template;
}
public override void Dispose()
{
throw new NotImplementedException();
}
public override ValueTask DisposeAsync()
{
throw new NotImplementedException();
}
public override DatabaseContext New()
{
throw new NotImplementedException();
}
}
///
/// Class responsible to fill and create in memory databases for unit tests.
///
public abstract class TestContext : IDisposable, IAsyncDisposable
{
///
/// The context's options that specify to use an in memory Sqlite database.
///
protected DbContextOptions Context;
///
/// 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();
}
///
/// 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();
}
///
/// Add an arbitrary data to the test context.
///
public void Add(T obj)
where T : class
{
using DatabaseContext context = New();
context.Set().Add(obj);
context.SaveChanges();
}
///
/// Add an arbitrary data to the test context.
///
public async Task AddAsync(T obj)
where T : class
{
await using DatabaseContext context = New();
await context.Set().AddAsync(obj);
await context.SaveChangesAsync();
}
///
/// Get a new database context connected to a in memory Sqlite database.
///
/// A valid DatabaseContext
public abstract DatabaseContext New();
public abstract void Dispose();
public abstract ValueTask DisposeAsync();
}
}