using Chronos.Data.Postgres; using Chronos.Testing; namespace Chronos.Data.Tests.Infrastructure; /// Engine a dialect-parameterised test class runs against. public enum Backend { SqliteMemory, SqliteFile, Postgres, } /// /// The PostgreSQL server named by CHRONOS_TEST_PG. Every test gets its own schema (selected through /// Search Path), so classes run in parallel without seeing each other's tables. /// internal static class PgTestServer { public const string Variable = "CHRONOS_TEST_PG"; private static readonly Lazy Admin = new(() => new PostgresDatabase(PostgresSettings.Parse(ConnectionString) with { MaxPoolSize = 4 })); public static string ConnectionString => Environment.GetEnvironmentVariable(Variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{Variable} not set"); /// A connection string for another role (MD5, cleartext, trust tests), or a skip when not configured. public static string Optional(string variable) => Environment.GetEnvironmentVariable(variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{variable} not set"); /// Set to 1 where the server was set up with TLS (CI): a server that refuses TLS then fails the TLS tests. public const string TlsVariable = "CHRONOS_TEST_PG_TLS"; public static bool TlsExpected => Environment.GetEnvironmentVariable(TlsVariable) is "1" or "true"; public static async Task CreateSchemaAsync(CancellationToken cancellationToken) { var name = "chronos_t_" + Guid.NewGuid().ToString("N")[..16]; await using var session = await Admin.Value.OpenAsync(cancellationToken); await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", cancellationToken); return name; } public static async Task DropSchemaAsync(string name) { await using var session = await Admin.Value.OpenAsync(CancellationToken.None); await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {name} CASCADE", CancellationToken.None); } public static string With(string connectionString, string extra) => connectionString.TrimEnd(';', ' ') + ";" + extra; } /// /// Base of tests that run against a fresh database per test: an in-memory or temporary-file SQLite database, or /// a private schema on the PostgreSQL test server. Everything opened through it is disposed after the test. /// public abstract class DatabaseTest(TestContext context) : IAsyncDisposable { private readonly List _owned = []; private readonly List _schemas = []; protected TestContext Context => context; protected CancellationToken Ct => context.Cancellation; protected abstract Backend Backend { get; } protected Dialect Dialect => Backend == Backend.Postgres ? Dialect.Postgres : Dialect.Sqlite; /// Picks the DDL/SQL variant of the current dialect. protected string ForDialect(string sqlite, string postgres) => Dialect == Dialect.Postgres ? postgres : sqlite; /// Options for a new empty database; forces a SQLite file (pooled readers). protected async Task NewOptionsAsync(bool multiConnection = false, string? extraPostgres = null) { switch (Backend) { case Backend.SqliteMemory when !multiConnection: return DatabaseOptions.SqliteInMemory(); case Backend.SqliteMemory or Backend.SqliteFile: return DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "chronos.db")); default: var schema = await PgTestServer.CreateSchemaAsync(Ct); _schemas.Add(schema); var cs = PgTestServer.With(PgTestServer.ConnectionString, $"Search Path={schema};Maximum Pool Size=12"); return DatabaseOptions.Postgres(extraPostgres is null ? cs : PgTestServer.With(cs, extraPostgres)); } } /// Opens a bare database (no migrations). protected async Task OpenDatabaseAsync(bool multiConnection = false) { var database = DatabaseFactory.Open(await NewOptionsAsync(multiConnection)); return Own(database); } protected T Own(T disposable) where T : IAsyncDisposable { _owned.Add(disposable); return disposable; } public async ValueTask DisposeAsync() { for (var i = _owned.Count - 1; i >= 0; i--) await _owned[i].DisposeAsync(); foreach (var schema in _schemas) await PgTestServer.DropSchemaAsync(schema); } }